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/ASTFwd.h"
19 #include "clang/AST/Attr.h"
20 #include "clang/AST/Availability.h"
21 #include "clang/AST/ComparisonCategories.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/DeclarationName.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprConcepts.h"
27 #include "clang/AST/ExprObjC.h"
28 #include "clang/AST/ExprOpenMP.h"
29 #include "clang/AST/ExternalASTSource.h"
30 #include "clang/AST/LocInfoType.h"
31 #include "clang/AST/MangleNumberingContext.h"
32 #include "clang/AST/NSAPI.h"
33 #include "clang/AST/PrettyPrinter.h"
34 #include "clang/AST/StmtCXX.h"
35 #include "clang/AST/StmtOpenMP.h"
36 #include "clang/AST/TypeLoc.h"
37 #include "clang/AST/TypeOrdering.h"
38 #include "clang/Basic/BitmaskEnum.h"
39 #include "clang/Basic/Builtins.h"
40 #include "clang/Basic/DarwinSDKInfo.h"
41 #include "clang/Basic/ExpressionTraits.h"
42 #include "clang/Basic/Module.h"
43 #include "clang/Basic/OpenCLOptions.h"
44 #include "clang/Basic/OpenMPKinds.h"
45 #include "clang/Basic/PragmaKinds.h"
46 #include "clang/Basic/Specifiers.h"
47 #include "clang/Basic/TemplateKinds.h"
48 #include "clang/Basic/TypeTraits.h"
49 #include "clang/Sema/AnalysisBasedWarnings.h"
50 #include "clang/Sema/CleanupInfo.h"
51 #include "clang/Sema/DeclSpec.h"
52 #include "clang/Sema/ExternalSemaSource.h"
53 #include "clang/Sema/IdentifierResolver.h"
54 #include "clang/Sema/ObjCMethodList.h"
55 #include "clang/Sema/Ownership.h"
56 #include "clang/Sema/Scope.h"
57 #include "clang/Sema/SemaConcept.h"
58 #include "clang/Sema/TypoCorrection.h"
59 #include "clang/Sema/Weak.h"
60 #include "llvm/ADT/ArrayRef.h"
61 #include "llvm/ADT/Optional.h"
62 #include "llvm/ADT/SetVector.h"
63 #include "llvm/ADT/SmallBitVector.h"
64 #include "llvm/ADT/SmallPtrSet.h"
65 #include "llvm/ADT/SmallSet.h"
66 #include "llvm/ADT/SmallVector.h"
67 #include "llvm/ADT/TinyPtrVector.h"
68 #include "llvm/Frontend/OpenMP/OMPConstants.h"
69 #include <deque>
70 #include <memory>
71 #include <string>
72 #include <tuple>
73 #include <vector>
74 
75 namespace llvm {
76   class APSInt;
77   template <typename ValueT, typename ValueInfoT> class DenseSet;
78   class SmallBitVector;
79   struct InlineAsmIdentifierInfo;
80 }
81 
82 namespace clang {
83   class ADLResult;
84   class ASTConsumer;
85   class ASTContext;
86   class ASTMutationListener;
87   class ASTReader;
88   class ASTWriter;
89   class ArrayType;
90   class ParsedAttr;
91   class BindingDecl;
92   class BlockDecl;
93   class CapturedDecl;
94   class CXXBasePath;
95   class CXXBasePaths;
96   class CXXBindTemporaryExpr;
97   typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
98   class CXXConstructorDecl;
99   class CXXConversionDecl;
100   class CXXDeleteExpr;
101   class CXXDestructorDecl;
102   class CXXFieldCollector;
103   class CXXMemberCallExpr;
104   class CXXMethodDecl;
105   class CXXScopeSpec;
106   class CXXTemporary;
107   class CXXTryStmt;
108   class CallExpr;
109   class ClassTemplateDecl;
110   class ClassTemplatePartialSpecializationDecl;
111   class ClassTemplateSpecializationDecl;
112   class VarTemplatePartialSpecializationDecl;
113   class CodeCompleteConsumer;
114   class CodeCompletionAllocator;
115   class CodeCompletionTUInfo;
116   class CodeCompletionResult;
117   class CoroutineBodyStmt;
118   class Decl;
119   class DeclAccessPair;
120   class DeclContext;
121   class DeclRefExpr;
122   class DeclaratorDecl;
123   class DeducedTemplateArgument;
124   class DependentDiagnostic;
125   class DesignatedInitExpr;
126   class Designation;
127   class EnableIfAttr;
128   class EnumConstantDecl;
129   class Expr;
130   class ExtVectorType;
131   class FormatAttr;
132   class FriendDecl;
133   class FunctionDecl;
134   class FunctionProtoType;
135   class FunctionTemplateDecl;
136   class ImplicitConversionSequence;
137   typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
138   class InitListExpr;
139   class InitializationKind;
140   class InitializationSequence;
141   class InitializedEntity;
142   class IntegerLiteral;
143   class LabelStmt;
144   class LambdaExpr;
145   class LangOptions;
146   class LocalInstantiationScope;
147   class LookupResult;
148   class MacroInfo;
149   typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
150   class ModuleLoader;
151   class MultiLevelTemplateArgumentList;
152   class NamedDecl;
153   class ObjCCategoryDecl;
154   class ObjCCategoryImplDecl;
155   class ObjCCompatibleAliasDecl;
156   class ObjCContainerDecl;
157   class ObjCImplDecl;
158   class ObjCImplementationDecl;
159   class ObjCInterfaceDecl;
160   class ObjCIvarDecl;
161   template <class T> class ObjCList;
162   class ObjCMessageExpr;
163   class ObjCMethodDecl;
164   class ObjCPropertyDecl;
165   class ObjCProtocolDecl;
166   class OMPThreadPrivateDecl;
167   class OMPRequiresDecl;
168   class OMPDeclareReductionDecl;
169   class OMPDeclareSimdDecl;
170   class OMPClause;
171   struct OMPVarListLocTy;
172   struct OverloadCandidate;
173   enum class OverloadCandidateParamOrder : char;
174   enum OverloadCandidateRewriteKind : unsigned;
175   class OverloadCandidateSet;
176   class OverloadExpr;
177   class ParenListExpr;
178   class ParmVarDecl;
179   class Preprocessor;
180   class PseudoDestructorTypeStorage;
181   class PseudoObjectExpr;
182   class QualType;
183   class StandardConversionSequence;
184   class Stmt;
185   class StringLiteral;
186   class SwitchStmt;
187   class TemplateArgument;
188   class TemplateArgumentList;
189   class TemplateArgumentLoc;
190   class TemplateDecl;
191   class TemplateInstantiationCallback;
192   class TemplateParameterList;
193   class TemplatePartialOrderingContext;
194   class TemplateTemplateParmDecl;
195   class Token;
196   class TypeAliasDecl;
197   class TypedefDecl;
198   class TypedefNameDecl;
199   class TypeLoc;
200   class TypoCorrectionConsumer;
201   class UnqualifiedId;
202   class UnresolvedLookupExpr;
203   class UnresolvedMemberExpr;
204   class UnresolvedSetImpl;
205   class UnresolvedSetIterator;
206   class UsingDecl;
207   class UsingShadowDecl;
208   class ValueDecl;
209   class VarDecl;
210   class VarTemplateSpecializationDecl;
211   class VisibilityAttr;
212   class VisibleDeclConsumer;
213   class IndirectFieldDecl;
214   struct DeductionFailureInfo;
215   class TemplateSpecCandidateSet;
216 
217 namespace sema {
218   class AccessedEntity;
219   class BlockScopeInfo;
220   class Capture;
221   class CapturedRegionScopeInfo;
222   class CapturingScopeInfo;
223   class CompoundScopeInfo;
224   class DelayedDiagnostic;
225   class DelayedDiagnosticPool;
226   class FunctionScopeInfo;
227   class LambdaScopeInfo;
228   class PossiblyUnreachableDiag;
229   class RISCVIntrinsicManager;
230   class SemaPPCallbacks;
231   class TemplateDeductionInfo;
232 }
233 
234 namespace threadSafety {
235   class BeforeSet;
236   void threadSafetyCleanup(BeforeSet* Cache);
237 }
238 
239 // FIXME: No way to easily map from TemplateTypeParmTypes to
240 // TemplateTypeParmDecls, so we have this horrible PointerUnion.
241 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
242                   SourceLocation> UnexpandedParameterPack;
243 
244 /// Describes whether we've seen any nullability information for the given
245 /// file.
246 struct FileNullability {
247   /// The first pointer declarator (of any pointer kind) in the file that does
248   /// not have a corresponding nullability annotation.
249   SourceLocation PointerLoc;
250 
251   /// The end location for the first pointer declarator in the file. Used for
252   /// placing fix-its.
253   SourceLocation PointerEndLoc;
254 
255   /// Which kind of pointer declarator we saw.
256   uint8_t PointerKind;
257 
258   /// Whether we saw any type nullability annotations in the given file.
259   bool SawTypeNullability = false;
260 };
261 
262 /// A mapping from file IDs to a record of whether we've seen nullability
263 /// information in that file.
264 class FileNullabilityMap {
265   /// A mapping from file IDs to the nullability information for each file ID.
266   llvm::DenseMap<FileID, FileNullability> Map;
267 
268   /// A single-element cache based on the file ID.
269   struct {
270     FileID File;
271     FileNullability Nullability;
272   } Cache;
273 
274 public:
275   FileNullability &operator[](FileID file) {
276     // Check the single-element cache.
277     if (file == Cache.File)
278       return Cache.Nullability;
279 
280     // It's not in the single-element cache; flush the cache if we have one.
281     if (!Cache.File.isInvalid()) {
282       Map[Cache.File] = Cache.Nullability;
283     }
284 
285     // Pull this entry into the cache.
286     Cache.File = file;
287     Cache.Nullability = Map[file];
288     return Cache.Nullability;
289   }
290 };
291 
292 /// Tracks expected type during expression parsing, for use in code completion.
293 /// The type is tied to a particular token, all functions that update or consume
294 /// the type take a start location of the token they are looking at as a
295 /// parameter. This avoids updating the type on hot paths in the parser.
296 class PreferredTypeBuilder {
297 public:
298   PreferredTypeBuilder(bool Enabled) : Enabled(Enabled) {}
299 
300   void enterCondition(Sema &S, SourceLocation Tok);
301   void enterReturn(Sema &S, SourceLocation Tok);
302   void enterVariableInit(SourceLocation Tok, Decl *D);
303   /// Handles e.g. BaseType{ .D = Tok...
304   void enterDesignatedInitializer(SourceLocation Tok, QualType BaseType,
305                                   const Designation &D);
306   /// Computing a type for the function argument may require running
307   /// overloading, so we postpone its computation until it is actually needed.
308   ///
309   /// Clients should be very careful when using this funciton, as it stores a
310   /// function_ref, clients should make sure all calls to get() with the same
311   /// location happen while function_ref is alive.
312   ///
313   /// The callback should also emit signature help as a side-effect, but only
314   /// if the completion point has been reached.
315   void enterFunctionArgument(SourceLocation Tok,
316                              llvm::function_ref<QualType()> ComputeType);
317 
318   void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
319   void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
320                   SourceLocation OpLoc);
321   void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
322   void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
323   void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
324   /// Handles all type casts, including C-style cast, C++ casts, etc.
325   void enterTypeCast(SourceLocation Tok, QualType CastType);
326 
327   /// Get the expected type associated with this location, if any.
328   ///
329   /// If the location is a function argument, determining the expected type
330   /// involves considering all function overloads and the arguments so far.
331   /// In this case, signature help for these function overloads will be reported
332   /// as a side-effect (only if the completion point has been reached).
333   QualType get(SourceLocation Tok) const {
334     if (!Enabled || Tok != ExpectedLoc)
335       return QualType();
336     if (!Type.isNull())
337       return Type;
338     if (ComputeType)
339       return ComputeType();
340     return QualType();
341   }
342 
343 private:
344   bool Enabled;
345   /// Start position of a token for which we store expected type.
346   SourceLocation ExpectedLoc;
347   /// Expected type for a token starting at ExpectedLoc.
348   QualType Type;
349   /// A function to compute expected type at ExpectedLoc. It is only considered
350   /// if Type is null.
351   llvm::function_ref<QualType()> ComputeType;
352 };
353 
354 /// Sema - This implements semantic analysis and AST building for C.
355 class Sema final {
356   Sema(const Sema &) = delete;
357   void operator=(const Sema &) = delete;
358 
359   ///Source of additional semantic information.
360   ExternalSemaSource *ExternalSource;
361 
362   ///Whether Sema has generated a multiplexer and has to delete it.
363   bool isMultiplexExternalSource;
364 
365   static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
366 
367   /// Determine whether two declarations should be linked together, given that
368   /// the old declaration might not be visible and the new declaration might
369   /// not have external linkage.
370   bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
371                                     const NamedDecl *New) {
372     if (isVisible(Old))
373      return true;
374     // See comment in below overload for why it's safe to compute the linkage
375     // of the new declaration here.
376     if (New->isExternallyDeclarable()) {
377       assert(Old->isExternallyDeclarable() &&
378              "should not have found a non-externally-declarable previous decl");
379       return true;
380     }
381     return false;
382   }
383   bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
384 
385   void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
386                                       QualType ResultTy,
387                                       ArrayRef<QualType> Args);
388 
389 public:
390   /// The maximum alignment, same as in llvm::Value. We duplicate them here
391   /// because that allows us not to duplicate the constants in clang code,
392   /// which we must to since we can't directly use the llvm constants.
393   /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
394   ///
395   /// This is the greatest alignment value supported by load, store, and alloca
396   /// instructions, and global values.
397   static const unsigned MaxAlignmentExponent = 32;
398   static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent;
399 
400   typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
401   typedef OpaquePtr<TemplateName> TemplateTy;
402   typedef OpaquePtr<QualType> TypeTy;
403 
404   OpenCLOptions OpenCLFeatures;
405   FPOptions CurFPFeatures;
406 
407   const LangOptions &LangOpts;
408   Preprocessor &PP;
409   ASTContext &Context;
410   ASTConsumer &Consumer;
411   DiagnosticsEngine &Diags;
412   SourceManager &SourceMgr;
413 
414   /// Flag indicating whether or not to collect detailed statistics.
415   bool CollectStats;
416 
417   /// Code-completion consumer.
418   CodeCompleteConsumer *CodeCompleter;
419 
420   /// CurContext - This is the current declaration context of parsing.
421   DeclContext *CurContext;
422 
423   /// Generally null except when we temporarily switch decl contexts,
424   /// like in \see ActOnObjCTemporaryExitContainerContext.
425   DeclContext *OriginalLexicalContext;
426 
427   /// VAListTagName - The declaration name corresponding to __va_list_tag.
428   /// This is used as part of a hack to omit that class from ADL results.
429   DeclarationName VAListTagName;
430 
431   bool MSStructPragmaOn; // True when \#pragma ms_struct on
432 
433   /// Controls member pointer representation format under the MS ABI.
434   LangOptions::PragmaMSPointersToMembersKind
435       MSPointerToMemberRepresentationMethod;
436 
437   /// Stack of active SEH __finally scopes.  Can be empty.
438   SmallVector<Scope*, 2> CurrentSEHFinally;
439 
440   /// Source location for newly created implicit MSInheritanceAttrs
441   SourceLocation ImplicitMSInheritanceAttrLoc;
442 
443   /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
444   /// `TransformTypos` in order to keep track of any TypoExprs that are created
445   /// recursively during typo correction and wipe them away if the correction
446   /// fails.
447   llvm::SmallVector<TypoExpr *, 2> TypoExprs;
448 
449   /// pragma clang section kind
450   enum PragmaClangSectionKind {
451     PCSK_Invalid      = 0,
452     PCSK_BSS          = 1,
453     PCSK_Data         = 2,
454     PCSK_Rodata       = 3,
455     PCSK_Text         = 4,
456     PCSK_Relro        = 5
457    };
458 
459   enum PragmaClangSectionAction {
460     PCSA_Set     = 0,
461     PCSA_Clear   = 1
462   };
463 
464   struct PragmaClangSection {
465     std::string SectionName;
466     bool Valid = false;
467     SourceLocation PragmaLocation;
468   };
469 
470    PragmaClangSection PragmaClangBSSSection;
471    PragmaClangSection PragmaClangDataSection;
472    PragmaClangSection PragmaClangRodataSection;
473    PragmaClangSection PragmaClangRelroSection;
474    PragmaClangSection PragmaClangTextSection;
475 
476   enum PragmaMsStackAction {
477     PSK_Reset     = 0x0,                // #pragma ()
478     PSK_Set       = 0x1,                // #pragma (value)
479     PSK_Push      = 0x2,                // #pragma (push[, id])
480     PSK_Pop       = 0x4,                // #pragma (pop[, id])
481     PSK_Show      = 0x8,                // #pragma (show) -- only for "pack"!
482     PSK_Push_Set  = PSK_Push | PSK_Set, // #pragma (push[, id], value)
483     PSK_Pop_Set   = PSK_Pop | PSK_Set,  // #pragma (pop[, id], value)
484   };
485 
486   // #pragma pack and align.
487   class AlignPackInfo {
488   public:
489     // `Native` represents default align mode, which may vary based on the
490     // platform.
491     enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
492 
493     // #pragma pack info constructor
494     AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
495         : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
496       assert(Num == PackNumber && "The pack number has been truncated.");
497     }
498 
499     // #pragma align info constructor
500     AlignPackInfo(AlignPackInfo::Mode M, bool IsXL)
501         : PackAttr(false), AlignMode(M),
502           PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
503 
504     explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
505 
506     AlignPackInfo() : AlignPackInfo(Native, false) {}
507 
508     // When a AlignPackInfo itself cannot be used, this returns an 32-bit
509     // integer encoding for it. This should only be passed to
510     // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
511     static uint32_t getRawEncoding(const AlignPackInfo &Info) {
512       std::uint32_t Encoding{};
513       if (Info.IsXLStack())
514         Encoding |= IsXLMask;
515 
516       Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
517 
518       if (Info.IsPackAttr())
519         Encoding |= PackAttrMask;
520 
521       Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
522 
523       return Encoding;
524     }
525 
526     static AlignPackInfo getFromRawEncoding(unsigned Encoding) {
527       bool IsXL = static_cast<bool>(Encoding & IsXLMask);
528       AlignPackInfo::Mode M =
529           static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
530       int PackNumber = (Encoding & PackNumMask) >> 4;
531 
532       if (Encoding & PackAttrMask)
533         return AlignPackInfo(M, PackNumber, IsXL);
534 
535       return AlignPackInfo(M, IsXL);
536     }
537 
538     bool IsPackAttr() const { return PackAttr; }
539 
540     bool IsAlignAttr() const { return !PackAttr; }
541 
542     Mode getAlignMode() const { return AlignMode; }
543 
544     unsigned getPackNumber() const { return PackNumber; }
545 
546     bool IsPackSet() const {
547       // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
548       // attriute on a decl.
549       return PackNumber != UninitPackVal && PackNumber != 0;
550     }
551 
552     bool IsXLStack() const { return XLStack; }
553 
554     bool operator==(const AlignPackInfo &Info) const {
555       return std::tie(AlignMode, PackNumber, PackAttr, XLStack) ==
556              std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr,
557                       Info.XLStack);
558     }
559 
560     bool operator!=(const AlignPackInfo &Info) const {
561       return !(*this == Info);
562     }
563 
564   private:
565     /// \brief True if this is a pragma pack attribute,
566     ///         not a pragma align attribute.
567     bool PackAttr;
568 
569     /// \brief The alignment mode that is in effect.
570     Mode AlignMode;
571 
572     /// \brief The pack number of the stack.
573     unsigned char PackNumber;
574 
575     /// \brief True if it is a XL #pragma align/pack stack.
576     bool XLStack;
577 
578     /// \brief Uninitialized pack value.
579     static constexpr unsigned char UninitPackVal = -1;
580 
581     // Masks to encode and decode an AlignPackInfo.
582     static constexpr uint32_t IsXLMask{0x0000'0001};
583     static constexpr uint32_t AlignModeMask{0x0000'0006};
584     static constexpr uint32_t PackAttrMask{0x00000'0008};
585     static constexpr uint32_t PackNumMask{0x0000'01F0};
586   };
587 
588   template<typename ValueType>
589   struct PragmaStack {
590     struct Slot {
591       llvm::StringRef StackSlotLabel;
592       ValueType Value;
593       SourceLocation PragmaLocation;
594       SourceLocation PragmaPushLocation;
595       Slot(llvm::StringRef StackSlotLabel, ValueType Value,
596            SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
597           : StackSlotLabel(StackSlotLabel), Value(Value),
598             PragmaLocation(PragmaLocation),
599             PragmaPushLocation(PragmaPushLocation) {}
600     };
601 
602     void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
603              llvm::StringRef StackSlotLabel, ValueType Value) {
604       if (Action == PSK_Reset) {
605         CurrentValue = DefaultValue;
606         CurrentPragmaLocation = PragmaLocation;
607         return;
608       }
609       if (Action & PSK_Push)
610         Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
611                            PragmaLocation);
612       else if (Action & PSK_Pop) {
613         if (!StackSlotLabel.empty()) {
614           // If we've got a label, try to find it and jump there.
615           auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
616             return x.StackSlotLabel == StackSlotLabel;
617           });
618           // If we found the label so pop from there.
619           if (I != Stack.rend()) {
620             CurrentValue = I->Value;
621             CurrentPragmaLocation = I->PragmaLocation;
622             Stack.erase(std::prev(I.base()), Stack.end());
623           }
624         } else if (!Stack.empty()) {
625           // We do not have a label, just pop the last entry.
626           CurrentValue = Stack.back().Value;
627           CurrentPragmaLocation = Stack.back().PragmaLocation;
628           Stack.pop_back();
629         }
630       }
631       if (Action & PSK_Set) {
632         CurrentValue = Value;
633         CurrentPragmaLocation = PragmaLocation;
634       }
635     }
636 
637     // MSVC seems to add artificial slots to #pragma stacks on entering a C++
638     // method body to restore the stacks on exit, so it works like this:
639     //
640     //   struct S {
641     //     #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
642     //     void Method {}
643     //     #pragma <name>(pop, InternalPragmaSlot)
644     //   };
645     //
646     // It works even with #pragma vtordisp, although MSVC doesn't support
647     //   #pragma vtordisp(push [, id], n)
648     // syntax.
649     //
650     // Push / pop a named sentinel slot.
651     void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
652       assert((Action == PSK_Push || Action == PSK_Pop) &&
653              "Can only push / pop #pragma stack sentinels!");
654       Act(CurrentPragmaLocation, Action, Label, CurrentValue);
655     }
656 
657     // Constructors.
658     explicit PragmaStack(const ValueType &Default)
659         : DefaultValue(Default), CurrentValue(Default) {}
660 
661     bool hasValue() const { return CurrentValue != DefaultValue; }
662 
663     SmallVector<Slot, 2> Stack;
664     ValueType DefaultValue; // Value used for PSK_Reset action.
665     ValueType CurrentValue;
666     SourceLocation CurrentPragmaLocation;
667   };
668   // FIXME: We should serialize / deserialize these if they occur in a PCH (but
669   // we shouldn't do so if they're in a module).
670 
671   /// Whether to insert vtordisps prior to virtual bases in the Microsoft
672   /// C++ ABI.  Possible values are 0, 1, and 2, which mean:
673   ///
674   /// 0: Suppress all vtordisps
675   /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
676   ///    structors
677   /// 2: Always insert vtordisps to support RTTI on partially constructed
678   ///    objects
679   PragmaStack<MSVtorDispMode> VtorDispStack;
680   PragmaStack<AlignPackInfo> AlignPackStack;
681   // The current #pragma align/pack values and locations at each #include.
682   struct AlignPackIncludeState {
683     AlignPackInfo CurrentValue;
684     SourceLocation CurrentPragmaLocation;
685     bool HasNonDefaultValue, ShouldWarnOnInclude;
686   };
687   SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack;
688   // Segment #pragmas.
689   PragmaStack<StringLiteral *> DataSegStack;
690   PragmaStack<StringLiteral *> BSSSegStack;
691   PragmaStack<StringLiteral *> ConstSegStack;
692   PragmaStack<StringLiteral *> CodeSegStack;
693 
694   // This stack tracks the current state of Sema.CurFPFeatures.
695   PragmaStack<FPOptionsOverride> FpPragmaStack;
696   FPOptionsOverride CurFPFeatureOverrides() {
697     FPOptionsOverride result;
698     if (!FpPragmaStack.hasValue()) {
699       result = FPOptionsOverride();
700     } else {
701       result = FpPragmaStack.CurrentValue;
702     }
703     return result;
704   }
705 
706   // RAII object to push / pop sentinel slots for all MS #pragma stacks.
707   // Actions should be performed only if we enter / exit a C++ method body.
708   class PragmaStackSentinelRAII {
709   public:
710     PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
711     ~PragmaStackSentinelRAII();
712 
713   private:
714     Sema &S;
715     StringRef SlotLabel;
716     bool ShouldAct;
717   };
718 
719   /// A mapping that describes the nullability we've seen in each header file.
720   FileNullabilityMap NullabilityMap;
721 
722   /// Last section used with #pragma init_seg.
723   StringLiteral *CurInitSeg;
724   SourceLocation CurInitSegLoc;
725 
726   /// Sections used with #pragma alloc_text.
727   llvm::StringMap<std::tuple<StringRef, SourceLocation>> FunctionToSectionMap;
728 
729   /// VisContext - Manages the stack for \#pragma GCC visibility.
730   void *VisContext; // Really a "PragmaVisStack*"
731 
732   /// This an attribute introduced by \#pragma clang attribute.
733   struct PragmaAttributeEntry {
734     SourceLocation Loc;
735     ParsedAttr *Attribute;
736     SmallVector<attr::SubjectMatchRule, 4> MatchRules;
737     bool IsUsed;
738   };
739 
740   /// A push'd group of PragmaAttributeEntries.
741   struct PragmaAttributeGroup {
742     /// The location of the push attribute.
743     SourceLocation Loc;
744     /// The namespace of this push group.
745     const IdentifierInfo *Namespace;
746     SmallVector<PragmaAttributeEntry, 2> Entries;
747   };
748 
749   SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
750 
751   /// The declaration that is currently receiving an attribute from the
752   /// #pragma attribute stack.
753   const Decl *PragmaAttributeCurrentTargetDecl;
754 
755   /// This represents the last location of a "#pragma clang optimize off"
756   /// directive if such a directive has not been closed by an "on" yet. If
757   /// optimizations are currently "on", this is set to an invalid location.
758   SourceLocation OptimizeOffPragmaLocation;
759 
760   /// The "on" or "off" argument passed by \#pragma optimize, that denotes
761   /// whether the optimizations in the list passed to the pragma should be
762   /// turned off or on. This boolean is true by default because command line
763   /// options are honored when `#pragma optimize("", on)`.
764   /// (i.e. `ModifyFnAttributeMSPragmaOptimze()` does nothing)
765   bool MSPragmaOptimizeIsOn = true;
766 
767   /// Set of no-builtin functions listed by \#pragma function.
768   llvm::SmallSetVector<StringRef, 4> MSFunctionNoBuiltins;
769 
770   /// Flag indicating if Sema is building a recovery call expression.
771   ///
772   /// This flag is used to avoid building recovery call expressions
773   /// if Sema is already doing so, which would cause infinite recursions.
774   bool IsBuildingRecoveryCallExpr;
775 
776   /// Used to control the generation of ExprWithCleanups.
777   CleanupInfo Cleanup;
778 
779   /// ExprCleanupObjects - This is the stack of objects requiring
780   /// cleanup that are created by the current full expression.
781   SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects;
782 
783   /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
784   /// to a variable (constant) that may or may not be odr-used in this Expr, and
785   /// we won't know until all lvalue-to-rvalue and discarded value conversions
786   /// have been applied to all subexpressions of the enclosing full expression.
787   /// This is cleared at the end of each full expression.
788   using MaybeODRUseExprSet = llvm::SetVector<Expr *, SmallVector<Expr *, 4>,
789                                              llvm::SmallPtrSet<Expr *, 4>>;
790   MaybeODRUseExprSet MaybeODRUseExprs;
791 
792   std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
793 
794   /// Stack containing information about each of the nested
795   /// function, block, and method scopes that are currently active.
796   SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
797 
798   /// The index of the first FunctionScope that corresponds to the current
799   /// context.
800   unsigned FunctionScopesStart = 0;
801 
802   ArrayRef<sema::FunctionScopeInfo*> getFunctionScopes() const {
803     return llvm::makeArrayRef(FunctionScopes.begin() + FunctionScopesStart,
804                               FunctionScopes.end());
805   }
806 
807   /// Stack containing information needed when in C++2a an 'auto' is encountered
808   /// in a function declaration parameter type specifier in order to invent a
809   /// corresponding template parameter in the enclosing abbreviated function
810   /// template. This information is also present in LambdaScopeInfo, stored in
811   /// the FunctionScopes stack.
812   SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos;
813 
814   /// The index of the first InventedParameterInfo that refers to the current
815   /// context.
816   unsigned InventedParameterInfosStart = 0;
817 
818   ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const {
819     return llvm::makeArrayRef(InventedParameterInfos.begin() +
820                                   InventedParameterInfosStart,
821                               InventedParameterInfos.end());
822   }
823 
824   typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
825                      &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
826     ExtVectorDeclsType;
827 
828   /// ExtVectorDecls - This is a list all the extended vector types. This allows
829   /// us to associate a raw vector type with one of the ext_vector type names.
830   /// This is only necessary for issuing pretty diagnostics.
831   ExtVectorDeclsType ExtVectorDecls;
832 
833   /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
834   std::unique_ptr<CXXFieldCollector> FieldCollector;
835 
836   typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType;
837 
838   /// Set containing all declared private fields that are not used.
839   NamedDeclSetType UnusedPrivateFields;
840 
841   /// Set containing all typedefs that are likely unused.
842   llvm::SmallSetVector<const TypedefNameDecl *, 4>
843       UnusedLocalTypedefNameCandidates;
844 
845   /// Delete-expressions to be analyzed at the end of translation unit
846   ///
847   /// This list contains class members, and locations of delete-expressions
848   /// that could not be proven as to whether they mismatch with new-expression
849   /// used in initializer of the field.
850   typedef std::pair<SourceLocation, bool> DeleteExprLoc;
851   typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
852   llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
853 
854   typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
855 
856   /// PureVirtualClassDiagSet - a set of class declarations which we have
857   /// emitted a list of pure virtual functions. Used to prevent emitting the
858   /// same list more than once.
859   std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
860 
861   /// ParsingInitForAutoVars - a set of declarations with auto types for which
862   /// we are currently parsing the initializer.
863   llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
864 
865   /// Look for a locally scoped extern "C" declaration by the given name.
866   NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
867 
868   typedef LazyVector<VarDecl *, ExternalSemaSource,
869                      &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
870     TentativeDefinitionsType;
871 
872   /// All the tentative definitions encountered in the TU.
873   TentativeDefinitionsType TentativeDefinitions;
874 
875   /// All the external declarations encoutered and used in the TU.
876   SmallVector<VarDecl *, 4> ExternalDeclarations;
877 
878   typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
879                      &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
880     UnusedFileScopedDeclsType;
881 
882   /// The set of file scoped decls seen so far that have not been used
883   /// and must warn if not used. Only contains the first declaration.
884   UnusedFileScopedDeclsType UnusedFileScopedDecls;
885 
886   typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
887                      &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
888     DelegatingCtorDeclsType;
889 
890   /// All the delegating constructors seen so far in the file, used for
891   /// cycle detection at the end of the TU.
892   DelegatingCtorDeclsType DelegatingCtorDecls;
893 
894   /// All the overriding functions seen during a class definition
895   /// that had their exception spec checks delayed, plus the overridden
896   /// function.
897   SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
898     DelayedOverridingExceptionSpecChecks;
899 
900   /// All the function redeclarations seen during a class definition that had
901   /// their exception spec checks delayed, plus the prior declaration they
902   /// should be checked against. Except during error recovery, the new decl
903   /// should always be a friend declaration, as that's the only valid way to
904   /// redeclare a special member before its class is complete.
905   SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2>
906     DelayedEquivalentExceptionSpecChecks;
907 
908   typedef llvm::MapVector<const FunctionDecl *,
909                           std::unique_ptr<LateParsedTemplate>>
910       LateParsedTemplateMapT;
911   LateParsedTemplateMapT LateParsedTemplateMap;
912 
913   /// Callback to the parser to parse templated functions when needed.
914   typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
915   typedef void LateTemplateParserCleanupCB(void *P);
916   LateTemplateParserCB *LateTemplateParser;
917   LateTemplateParserCleanupCB *LateTemplateParserCleanup;
918   void *OpaqueParser;
919 
920   void SetLateTemplateParser(LateTemplateParserCB *LTP,
921                              LateTemplateParserCleanupCB *LTPCleanup,
922                              void *P) {
923     LateTemplateParser = LTP;
924     LateTemplateParserCleanup = LTPCleanup;
925     OpaqueParser = P;
926   }
927 
928   class DelayedDiagnostics;
929 
930   class DelayedDiagnosticsState {
931     sema::DelayedDiagnosticPool *SavedPool;
932     friend class Sema::DelayedDiagnostics;
933   };
934   typedef DelayedDiagnosticsState ParsingDeclState;
935   typedef DelayedDiagnosticsState ProcessingContextState;
936 
937   /// A class which encapsulates the logic for delaying diagnostics
938   /// during parsing and other processing.
939   class DelayedDiagnostics {
940     /// The current pool of diagnostics into which delayed
941     /// diagnostics should go.
942     sema::DelayedDiagnosticPool *CurPool;
943 
944   public:
945     DelayedDiagnostics() : CurPool(nullptr) {}
946 
947     /// Adds a delayed diagnostic.
948     void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
949 
950     /// Determines whether diagnostics should be delayed.
951     bool shouldDelayDiagnostics() { return CurPool != nullptr; }
952 
953     /// Returns the current delayed-diagnostics pool.
954     sema::DelayedDiagnosticPool *getCurrentPool() const {
955       return CurPool;
956     }
957 
958     /// Enter a new scope.  Access and deprecation diagnostics will be
959     /// collected in this pool.
960     DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
961       DelayedDiagnosticsState state;
962       state.SavedPool = CurPool;
963       CurPool = &pool;
964       return state;
965     }
966 
967     /// Leave a delayed-diagnostic state that was previously pushed.
968     /// Do not emit any of the diagnostics.  This is performed as part
969     /// of the bookkeeping of popping a pool "properly".
970     void popWithoutEmitting(DelayedDiagnosticsState state) {
971       CurPool = state.SavedPool;
972     }
973 
974     /// Enter a new scope where access and deprecation diagnostics are
975     /// not delayed.
976     DelayedDiagnosticsState pushUndelayed() {
977       DelayedDiagnosticsState state;
978       state.SavedPool = CurPool;
979       CurPool = nullptr;
980       return state;
981     }
982 
983     /// Undo a previous pushUndelayed().
984     void popUndelayed(DelayedDiagnosticsState state) {
985       assert(CurPool == nullptr);
986       CurPool = state.SavedPool;
987     }
988   } DelayedDiagnostics;
989 
990   /// A RAII object to temporarily push a declaration context.
991   class ContextRAII {
992   private:
993     Sema &S;
994     DeclContext *SavedContext;
995     ProcessingContextState SavedContextState;
996     QualType SavedCXXThisTypeOverride;
997     unsigned SavedFunctionScopesStart;
998     unsigned SavedInventedParameterInfosStart;
999 
1000   public:
1001     ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
1002       : S(S), SavedContext(S.CurContext),
1003         SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
1004         SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
1005         SavedFunctionScopesStart(S.FunctionScopesStart),
1006         SavedInventedParameterInfosStart(S.InventedParameterInfosStart)
1007     {
1008       assert(ContextToPush && "pushing null context");
1009       S.CurContext = ContextToPush;
1010       if (NewThisContext)
1011         S.CXXThisTypeOverride = QualType();
1012       // Any saved FunctionScopes do not refer to this context.
1013       S.FunctionScopesStart = S.FunctionScopes.size();
1014       S.InventedParameterInfosStart = S.InventedParameterInfos.size();
1015     }
1016 
1017     void pop() {
1018       if (!SavedContext) return;
1019       S.CurContext = SavedContext;
1020       S.DelayedDiagnostics.popUndelayed(SavedContextState);
1021       S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
1022       S.FunctionScopesStart = SavedFunctionScopesStart;
1023       S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
1024       SavedContext = nullptr;
1025     }
1026 
1027     ~ContextRAII() {
1028       pop();
1029     }
1030   };
1031 
1032   /// Whether the AST is currently being rebuilt to correct immediate
1033   /// invocations. Immediate invocation candidates and references to consteval
1034   /// functions aren't tracked when this is set.
1035   bool RebuildingImmediateInvocation = false;
1036 
1037   /// Used to change context to isConstantEvaluated without pushing a heavy
1038   /// ExpressionEvaluationContextRecord object.
1039   bool isConstantEvaluatedOverride;
1040 
1041   bool isConstantEvaluated() {
1042     return ExprEvalContexts.back().isConstantEvaluated() ||
1043            isConstantEvaluatedOverride;
1044   }
1045 
1046   /// RAII object to handle the state changes required to synthesize
1047   /// a function body.
1048   class SynthesizedFunctionScope {
1049     Sema &S;
1050     Sema::ContextRAII SavedContext;
1051     bool PushedCodeSynthesisContext = false;
1052 
1053   public:
1054     SynthesizedFunctionScope(Sema &S, DeclContext *DC)
1055         : S(S), SavedContext(S, DC) {
1056       S.PushFunctionScope();
1057       S.PushExpressionEvaluationContext(
1058           Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
1059       if (auto *FD = dyn_cast<FunctionDecl>(DC))
1060         FD->setWillHaveBody(true);
1061       else
1062         assert(isa<ObjCMethodDecl>(DC));
1063     }
1064 
1065     void addContextNote(SourceLocation UseLoc) {
1066       assert(!PushedCodeSynthesisContext);
1067 
1068       Sema::CodeSynthesisContext Ctx;
1069       Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
1070       Ctx.PointOfInstantiation = UseLoc;
1071       Ctx.Entity = cast<Decl>(S.CurContext);
1072       S.pushCodeSynthesisContext(Ctx);
1073 
1074       PushedCodeSynthesisContext = true;
1075     }
1076 
1077     ~SynthesizedFunctionScope() {
1078       if (PushedCodeSynthesisContext)
1079         S.popCodeSynthesisContext();
1080       if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
1081         FD->setWillHaveBody(false);
1082       S.PopExpressionEvaluationContext();
1083       S.PopFunctionScopeInfo();
1084     }
1085   };
1086 
1087   /// WeakUndeclaredIdentifiers - Identifiers contained in \#pragma weak before
1088   /// declared. Rare. May alias another identifier, declared or undeclared.
1089   ///
1090   /// For aliases, the target identifier is used as a key for eventual
1091   /// processing when the target is declared. For the single-identifier form,
1092   /// the sole identifier is used as the key. Each entry is a `SetVector`
1093   /// (ordered by parse order) of aliases (identified by the alias name) in case
1094   /// of multiple aliases to the same undeclared identifier.
1095   llvm::MapVector<
1096       IdentifierInfo *,
1097       llvm::SetVector<
1098           WeakInfo, llvm::SmallVector<WeakInfo, 1u>,
1099           llvm::SmallDenseSet<WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly>>>
1100       WeakUndeclaredIdentifiers;
1101 
1102   /// ExtnameUndeclaredIdentifiers - Identifiers contained in
1103   /// \#pragma redefine_extname before declared.  Used in Solaris system headers
1104   /// to define functions that occur in multiple standards to call the version
1105   /// in the currently selected standard.
1106   llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
1107 
1108 
1109   /// Load weak undeclared identifiers from the external source.
1110   void LoadExternalWeakUndeclaredIdentifiers();
1111 
1112   /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
1113   /// \#pragma weak during processing of other Decls.
1114   /// I couldn't figure out a clean way to generate these in-line, so
1115   /// we store them here and handle separately -- which is a hack.
1116   /// It would be best to refactor this.
1117   SmallVector<Decl*,2> WeakTopLevelDecl;
1118 
1119   IdentifierResolver IdResolver;
1120 
1121   /// Translation Unit Scope - useful to Objective-C actions that need
1122   /// to lookup file scope declarations in the "ordinary" C decl namespace.
1123   /// For example, user-defined classes, built-in "id" type, etc.
1124   Scope *TUScope;
1125 
1126   /// The C++ "std" namespace, where the standard library resides.
1127   LazyDeclPtr StdNamespace;
1128 
1129   /// The C++ "std::bad_alloc" class, which is defined by the C++
1130   /// standard library.
1131   LazyDeclPtr StdBadAlloc;
1132 
1133   /// The C++ "std::align_val_t" enum class, which is defined by the C++
1134   /// standard library.
1135   LazyDeclPtr StdAlignValT;
1136 
1137   /// The C++ "std::experimental" namespace, where the experimental parts
1138   /// of the standard library resides.
1139   NamespaceDecl *StdExperimentalNamespaceCache;
1140 
1141   /// The C++ "std::initializer_list" template, which is defined in
1142   /// \<initializer_list>.
1143   ClassTemplateDecl *StdInitializerList;
1144 
1145   /// The C++ "std::coroutine_traits" template, which is defined in
1146   /// \<coroutine_traits>
1147   ClassTemplateDecl *StdCoroutineTraitsCache;
1148   /// The namespace where coroutine components are defined. In standard,
1149   /// they are defined in std namespace. And in the previous implementation,
1150   /// they are defined in std::experimental namespace.
1151   NamespaceDecl *CoroTraitsNamespaceCache;
1152 
1153   /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
1154   RecordDecl *CXXTypeInfoDecl;
1155 
1156   /// The MSVC "_GUID" struct, which is defined in MSVC header files.
1157   RecordDecl *MSVCGuidDecl;
1158 
1159   /// The C++ "std::source_location::__impl" struct, defined in
1160   /// \<source_location>.
1161   RecordDecl *StdSourceLocationImplDecl;
1162 
1163   /// Caches identifiers/selectors for NSFoundation APIs.
1164   std::unique_ptr<NSAPI> NSAPIObj;
1165 
1166   /// The declaration of the Objective-C NSNumber class.
1167   ObjCInterfaceDecl *NSNumberDecl;
1168 
1169   /// The declaration of the Objective-C NSValue class.
1170   ObjCInterfaceDecl *NSValueDecl;
1171 
1172   /// Pointer to NSNumber type (NSNumber *).
1173   QualType NSNumberPointer;
1174 
1175   /// Pointer to NSValue type (NSValue *).
1176   QualType NSValuePointer;
1177 
1178   /// The Objective-C NSNumber methods used to create NSNumber literals.
1179   ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
1180 
1181   /// The declaration of the Objective-C NSString class.
1182   ObjCInterfaceDecl *NSStringDecl;
1183 
1184   /// Pointer to NSString type (NSString *).
1185   QualType NSStringPointer;
1186 
1187   /// The declaration of the stringWithUTF8String: method.
1188   ObjCMethodDecl *StringWithUTF8StringMethod;
1189 
1190   /// The declaration of the valueWithBytes:objCType: method.
1191   ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
1192 
1193   /// The declaration of the Objective-C NSArray class.
1194   ObjCInterfaceDecl *NSArrayDecl;
1195 
1196   /// The declaration of the arrayWithObjects:count: method.
1197   ObjCMethodDecl *ArrayWithObjectsMethod;
1198 
1199   /// The declaration of the Objective-C NSDictionary class.
1200   ObjCInterfaceDecl *NSDictionaryDecl;
1201 
1202   /// The declaration of the dictionaryWithObjects:forKeys:count: method.
1203   ObjCMethodDecl *DictionaryWithObjectsMethod;
1204 
1205   /// id<NSCopying> type.
1206   QualType QIDNSCopying;
1207 
1208   /// will hold 'respondsToSelector:'
1209   Selector RespondsToSelectorSel;
1210 
1211   /// A flag to remember whether the implicit forms of operator new and delete
1212   /// have been declared.
1213   bool GlobalNewDeleteDeclared;
1214 
1215   /// Describes how the expressions currently being parsed are
1216   /// evaluated at run-time, if at all.
1217   enum class ExpressionEvaluationContext {
1218     /// The current expression and its subexpressions occur within an
1219     /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
1220     /// \c sizeof, where the type of the expression may be significant but
1221     /// no code will be generated to evaluate the value of the expression at
1222     /// run time.
1223     Unevaluated,
1224 
1225     /// The current expression occurs within a braced-init-list within
1226     /// an unevaluated operand. This is mostly like a regular unevaluated
1227     /// context, except that we still instantiate constexpr functions that are
1228     /// referenced here so that we can perform narrowing checks correctly.
1229     UnevaluatedList,
1230 
1231     /// The current expression occurs within a discarded statement.
1232     /// This behaves largely similarly to an unevaluated operand in preventing
1233     /// definitions from being required, but not in other ways.
1234     DiscardedStatement,
1235 
1236     /// The current expression occurs within an unevaluated
1237     /// operand that unconditionally permits abstract references to
1238     /// fields, such as a SIZE operator in MS-style inline assembly.
1239     UnevaluatedAbstract,
1240 
1241     /// The current context is "potentially evaluated" in C++11 terms,
1242     /// but the expression is evaluated at compile-time (like the values of
1243     /// cases in a switch statement).
1244     ConstantEvaluated,
1245 
1246     /// In addition of being constant evaluated, the current expression
1247     /// occurs in an immediate function context - either a consteval function
1248     /// or a consteval if function.
1249     ImmediateFunctionContext,
1250 
1251     /// The current expression is potentially evaluated at run time,
1252     /// which means that code may be generated to evaluate the value of the
1253     /// expression at run time.
1254     PotentiallyEvaluated,
1255 
1256     /// The current expression is potentially evaluated, but any
1257     /// declarations referenced inside that expression are only used if
1258     /// in fact the current expression is used.
1259     ///
1260     /// This value is used when parsing default function arguments, for which
1261     /// we would like to provide diagnostics (e.g., passing non-POD arguments
1262     /// through varargs) but do not want to mark declarations as "referenced"
1263     /// until the default argument is used.
1264     PotentiallyEvaluatedIfUsed
1265   };
1266 
1267   using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
1268 
1269   /// Data structure used to record current or nested
1270   /// expression evaluation contexts.
1271   struct ExpressionEvaluationContextRecord {
1272     /// The expression evaluation context.
1273     ExpressionEvaluationContext Context;
1274 
1275     /// Whether the enclosing context needed a cleanup.
1276     CleanupInfo ParentCleanup;
1277 
1278     /// The number of active cleanup objects when we entered
1279     /// this expression evaluation context.
1280     unsigned NumCleanupObjects;
1281 
1282     /// The number of typos encountered during this expression evaluation
1283     /// context (i.e. the number of TypoExprs created).
1284     unsigned NumTypos;
1285 
1286     MaybeODRUseExprSet SavedMaybeODRUseExprs;
1287 
1288     /// The lambdas that are present within this context, if it
1289     /// is indeed an unevaluated context.
1290     SmallVector<LambdaExpr *, 2> Lambdas;
1291 
1292     /// The declaration that provides context for lambda expressions
1293     /// and block literals if the normal declaration context does not
1294     /// suffice, e.g., in a default function argument.
1295     Decl *ManglingContextDecl;
1296 
1297     /// If we are processing a decltype type, a set of call expressions
1298     /// for which we have deferred checking the completeness of the return type.
1299     SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
1300 
1301     /// If we are processing a decltype type, a set of temporary binding
1302     /// expressions for which we have deferred checking the destructor.
1303     SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
1304 
1305     llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
1306 
1307     /// Expressions appearing as the LHS of a volatile assignment in this
1308     /// context. We produce a warning for these when popping the context if
1309     /// they are not discarded-value expressions nor unevaluated operands.
1310     SmallVector<Expr*, 2> VolatileAssignmentLHSs;
1311 
1312     /// Set of candidates for starting an immediate invocation.
1313     llvm::SmallVector<ImmediateInvocationCandidate, 4> ImmediateInvocationCandidates;
1314 
1315     /// Set of DeclRefExprs referencing a consteval function when used in a
1316     /// context not already known to be immediately invoked.
1317     llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval;
1318 
1319     /// \brief Describes whether we are in an expression constext which we have
1320     /// to handle differently.
1321     enum ExpressionKind {
1322       EK_Decltype, EK_TemplateArgument, EK_Other
1323     } ExprContext;
1324 
1325     // A context can be nested in both a discarded statement context and
1326     // an immediate function context, so they need to be tracked independently.
1327     bool InDiscardedStatement;
1328     bool InImmediateFunctionContext;
1329 
1330     ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
1331                                       unsigned NumCleanupObjects,
1332                                       CleanupInfo ParentCleanup,
1333                                       Decl *ManglingContextDecl,
1334                                       ExpressionKind ExprContext)
1335         : Context(Context), ParentCleanup(ParentCleanup),
1336           NumCleanupObjects(NumCleanupObjects), NumTypos(0),
1337           ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext),
1338           InDiscardedStatement(false), InImmediateFunctionContext(false) {}
1339 
1340     bool isUnevaluated() const {
1341       return Context == ExpressionEvaluationContext::Unevaluated ||
1342              Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
1343              Context == ExpressionEvaluationContext::UnevaluatedList;
1344     }
1345 
1346     bool isConstantEvaluated() const {
1347       return Context == ExpressionEvaluationContext::ConstantEvaluated ||
1348              Context == ExpressionEvaluationContext::ImmediateFunctionContext;
1349     }
1350 
1351     bool isImmediateFunctionContext() const {
1352       return Context == ExpressionEvaluationContext::ImmediateFunctionContext ||
1353              (Context == ExpressionEvaluationContext::DiscardedStatement &&
1354               InImmediateFunctionContext);
1355     }
1356 
1357     bool isDiscardedStatementContext() const {
1358       return Context == ExpressionEvaluationContext::DiscardedStatement ||
1359              (Context ==
1360                   ExpressionEvaluationContext::ImmediateFunctionContext &&
1361               InDiscardedStatement);
1362     }
1363   };
1364 
1365   /// A stack of expression evaluation contexts.
1366   SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
1367 
1368   /// Emit a warning for all pending noderef expressions that we recorded.
1369   void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
1370 
1371   /// Compute the mangling number context for a lambda expression or
1372   /// block literal. Also return the extra mangling decl if any.
1373   ///
1374   /// \param DC - The DeclContext containing the lambda expression or
1375   /// block literal.
1376   std::tuple<MangleNumberingContext *, Decl *>
1377   getCurrentMangleNumberContext(const DeclContext *DC);
1378 
1379 
1380   /// SpecialMemberOverloadResult - The overloading result for a special member
1381   /// function.
1382   ///
1383   /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1384   /// integer are used to determine whether overload resolution succeeded.
1385   class SpecialMemberOverloadResult {
1386   public:
1387     enum Kind {
1388       NoMemberOrDeleted,
1389       Ambiguous,
1390       Success
1391     };
1392 
1393   private:
1394     llvm::PointerIntPair<CXXMethodDecl *, 2> Pair;
1395 
1396   public:
1397     SpecialMemberOverloadResult() {}
1398     SpecialMemberOverloadResult(CXXMethodDecl *MD)
1399         : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1400 
1401     CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1402     void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1403 
1404     Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1405     void setKind(Kind K) { Pair.setInt(K); }
1406   };
1407 
1408   class SpecialMemberOverloadResultEntry
1409       : public llvm::FastFoldingSetNode,
1410         public SpecialMemberOverloadResult {
1411   public:
1412     SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1413       : FastFoldingSetNode(ID)
1414     {}
1415   };
1416 
1417   /// A cache of special member function overload resolution results
1418   /// for C++ records.
1419   llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1420 
1421   /// A cache of the flags available in enumerations with the flag_bits
1422   /// attribute.
1423   mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1424 
1425   /// The kind of translation unit we are processing.
1426   ///
1427   /// When we're processing a complete translation unit, Sema will perform
1428   /// end-of-translation-unit semantic tasks (such as creating
1429   /// initializers for tentative definitions in C) once parsing has
1430   /// completed. Modules and precompiled headers perform different kinds of
1431   /// checks.
1432   const TranslationUnitKind TUKind;
1433 
1434   llvm::BumpPtrAllocator BumpAlloc;
1435 
1436   /// The number of SFINAE diagnostics that have been trapped.
1437   unsigned NumSFINAEErrors;
1438 
1439   typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1440     UnparsedDefaultArgInstantiationsMap;
1441 
1442   /// A mapping from parameters with unparsed default arguments to the
1443   /// set of instantiations of each parameter.
1444   ///
1445   /// This mapping is a temporary data structure used when parsing
1446   /// nested class templates or nested classes of class templates,
1447   /// where we might end up instantiating an inner class before the
1448   /// default arguments of its methods have been parsed.
1449   UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1450 
1451   // Contains the locations of the beginning of unparsed default
1452   // argument locations.
1453   llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1454 
1455   /// UndefinedInternals - all the used, undefined objects which require a
1456   /// definition in this translation unit.
1457   llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1458 
1459   /// Determine if VD, which must be a variable or function, is an external
1460   /// symbol that nonetheless can't be referenced from outside this translation
1461   /// unit because its type has no linkage and it's not extern "C".
1462   bool isExternalWithNoLinkageType(ValueDecl *VD);
1463 
1464   /// Obtain a sorted list of functions that are undefined but ODR-used.
1465   void getUndefinedButUsed(
1466       SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1467 
1468   /// Retrieves list of suspicious delete-expressions that will be checked at
1469   /// the end of translation unit.
1470   const llvm::MapVector<FieldDecl *, DeleteLocs> &
1471   getMismatchingDeleteExpressions() const;
1472 
1473   class GlobalMethodPool {
1474   public:
1475     using Lists = std::pair<ObjCMethodList, ObjCMethodList>;
1476     using iterator = llvm::DenseMap<Selector, Lists>::iterator;
1477     iterator begin() { return Methods.begin(); }
1478     iterator end() { return Methods.end(); }
1479     iterator find(Selector Sel) { return Methods.find(Sel); }
1480     std::pair<iterator, bool> insert(std::pair<Selector, Lists> &&Val) {
1481       return Methods.insert(Val);
1482     }
1483     int count(Selector Sel) const { return Methods.count(Sel); }
1484     bool empty() const { return Methods.empty(); }
1485 
1486   private:
1487     llvm::DenseMap<Selector, Lists> Methods;
1488   };
1489 
1490   /// Method Pool - allows efficient lookup when typechecking messages to "id".
1491   /// We need to maintain a list, since selectors can have differing signatures
1492   /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1493   /// of selectors are "overloaded").
1494   /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1495   /// methods inside categories with a particular selector.
1496   GlobalMethodPool MethodPool;
1497 
1498   /// Method selectors used in a \@selector expression. Used for implementation
1499   /// of -Wselector.
1500   llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1501 
1502   /// List of SourceLocations where 'self' is implicitly retained inside a
1503   /// block.
1504   llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
1505       ImplicitlyRetainedSelfLocs;
1506 
1507   /// Kinds of C++ special members.
1508   enum CXXSpecialMember {
1509     CXXDefaultConstructor,
1510     CXXCopyConstructor,
1511     CXXMoveConstructor,
1512     CXXCopyAssignment,
1513     CXXMoveAssignment,
1514     CXXDestructor,
1515     CXXInvalid
1516   };
1517 
1518   typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1519       SpecialMemberDecl;
1520 
1521   /// The C++ special members which we are currently in the process of
1522   /// declaring. If this process recursively triggers the declaration of the
1523   /// same special member, we should act as if it is not yet declared.
1524   llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1525 
1526   /// Kinds of defaulted comparison operator functions.
1527   enum class DefaultedComparisonKind : unsigned char {
1528     /// This is not a defaultable comparison operator.
1529     None,
1530     /// This is an operator== that should be implemented as a series of
1531     /// subobject comparisons.
1532     Equal,
1533     /// This is an operator<=> that should be implemented as a series of
1534     /// subobject comparisons.
1535     ThreeWay,
1536     /// This is an operator!= that should be implemented as a rewrite in terms
1537     /// of a == comparison.
1538     NotEqual,
1539     /// This is an <, <=, >, or >= that should be implemented as a rewrite in
1540     /// terms of a <=> comparison.
1541     Relational,
1542   };
1543 
1544   /// The function definitions which were renamed as part of typo-correction
1545   /// to match their respective declarations. We want to keep track of them
1546   /// to ensure that we don't emit a "redefinition" error if we encounter a
1547   /// correctly named definition after the renamed definition.
1548   llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1549 
1550   /// Stack of types that correspond to the parameter entities that are
1551   /// currently being copy-initialized. Can be empty.
1552   llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1553 
1554   void ReadMethodPool(Selector Sel);
1555   void updateOutOfDateSelector(Selector Sel);
1556 
1557   /// Private Helper predicate to check for 'self'.
1558   bool isSelfExpr(Expr *RExpr);
1559   bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1560 
1561   /// Cause the active diagnostic on the DiagosticsEngine to be
1562   /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1563   /// should not be used elsewhere.
1564   void EmitCurrentDiagnostic(unsigned DiagID);
1565 
1566   /// Records and restores the CurFPFeatures state on entry/exit of compound
1567   /// statements.
1568   class FPFeaturesStateRAII {
1569   public:
1570     FPFeaturesStateRAII(Sema &S);
1571     ~FPFeaturesStateRAII();
1572     FPOptionsOverride getOverrides() { return OldOverrides; }
1573 
1574   private:
1575     Sema& S;
1576     FPOptions OldFPFeaturesState;
1577     FPOptionsOverride OldOverrides;
1578     LangOptions::FPEvalMethodKind OldEvalMethod;
1579     SourceLocation OldFPPragmaLocation;
1580   };
1581 
1582   void addImplicitTypedef(StringRef Name, QualType T);
1583 
1584   bool WarnedStackExhausted = false;
1585 
1586   /// Increment when we find a reference; decrement when we find an ignored
1587   /// assignment.  Ultimately the value is 0 if every reference is an ignored
1588   /// assignment.
1589   llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments;
1590 
1591   /// Indicate RISC-V vector builtin functions enabled or not.
1592   bool DeclareRISCVVBuiltins = false;
1593 
1594 private:
1595   std::unique_ptr<sema::RISCVIntrinsicManager> RVIntrinsicManager;
1596 
1597   Optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
1598 
1599   bool WarnedDarwinSDKInfoMissing = false;
1600 
1601 public:
1602   Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1603        TranslationUnitKind TUKind = TU_Complete,
1604        CodeCompleteConsumer *CompletionConsumer = nullptr);
1605   ~Sema();
1606 
1607   /// Perform initialization that occurs after the parser has been
1608   /// initialized but before it parses anything.
1609   void Initialize();
1610 
1611   /// This virtual key function only exists to limit the emission of debug info
1612   /// describing the Sema class. GCC and Clang only emit debug info for a class
1613   /// with a vtable when the vtable is emitted. Sema is final and not
1614   /// polymorphic, but the debug info size savings are so significant that it is
1615   /// worth adding a vtable just to take advantage of this optimization.
1616   virtual void anchor();
1617 
1618   const LangOptions &getLangOpts() const { return LangOpts; }
1619   OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1620   FPOptions     &getCurFPFeatures() { return CurFPFeatures; }
1621 
1622   DiagnosticsEngine &getDiagnostics() const { return Diags; }
1623   SourceManager &getSourceManager() const { return SourceMgr; }
1624   Preprocessor &getPreprocessor() const { return PP; }
1625   ASTContext &getASTContext() const { return Context; }
1626   ASTConsumer &getASTConsumer() const { return Consumer; }
1627   ASTMutationListener *getASTMutationListener() const;
1628   ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1629 
1630   DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc,
1631                                                          StringRef Platform);
1632   DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking();
1633 
1634   ///Registers an external source. If an external source already exists,
1635   /// creates a multiplex external source and appends to it.
1636   ///
1637   ///\param[in] E - A non-null external sema source.
1638   ///
1639   void addExternalSource(ExternalSemaSource *E);
1640 
1641   void PrintStats() const;
1642 
1643   /// Warn that the stack is nearly exhausted.
1644   void warnStackExhausted(SourceLocation Loc);
1645 
1646   /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1647   /// guaranteed). Produces a warning if we're low on stack space and allocates
1648   /// more in that case. Use this in code that may recurse deeply (for example,
1649   /// in template instantiation) to avoid stack overflow.
1650   void runWithSufficientStackSpace(SourceLocation Loc,
1651                                    llvm::function_ref<void()> Fn);
1652 
1653   /// Helper class that creates diagnostics with optional
1654   /// template instantiation stacks.
1655   ///
1656   /// This class provides a wrapper around the basic DiagnosticBuilder
1657   /// class that emits diagnostics. ImmediateDiagBuilder is
1658   /// responsible for emitting the diagnostic (as DiagnosticBuilder
1659   /// does) and, if the diagnostic comes from inside a template
1660   /// instantiation, printing the template instantiation stack as
1661   /// well.
1662   class ImmediateDiagBuilder : public DiagnosticBuilder {
1663     Sema &SemaRef;
1664     unsigned DiagID;
1665 
1666   public:
1667     ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1668         : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1669     ImmediateDiagBuilder(DiagnosticBuilder &&DB, Sema &SemaRef, unsigned DiagID)
1670         : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1671 
1672     // This is a cunning lie. DiagnosticBuilder actually performs move
1673     // construction in its copy constructor (but due to varied uses, it's not
1674     // possible to conveniently express this as actual move construction). So
1675     // the default copy ctor here is fine, because the base class disables the
1676     // source anyway, so the user-defined ~ImmediateDiagBuilder is a safe no-op
1677     // in that case anwyay.
1678     ImmediateDiagBuilder(const ImmediateDiagBuilder &) = default;
1679 
1680     ~ImmediateDiagBuilder() {
1681       // If we aren't active, there is nothing to do.
1682       if (!isActive()) return;
1683 
1684       // Otherwise, we need to emit the diagnostic. First clear the diagnostic
1685       // builder itself so it won't emit the diagnostic in its own destructor.
1686       //
1687       // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1688       // do its own needless checks to see if the diagnostic needs to be
1689       // emitted. However, because we take care to ensure that the builder
1690       // objects never escape, a sufficiently smart compiler will be able to
1691       // eliminate that code.
1692       Clear();
1693 
1694       // Dispatch to Sema to emit the diagnostic.
1695       SemaRef.EmitCurrentDiagnostic(DiagID);
1696     }
1697 
1698     /// Teach operator<< to produce an object of the correct type.
1699     template <typename T>
1700     friend const ImmediateDiagBuilder &
1701     operator<<(const ImmediateDiagBuilder &Diag, const T &Value) {
1702       const DiagnosticBuilder &BaseDiag = Diag;
1703       BaseDiag << Value;
1704       return Diag;
1705     }
1706 
1707     // It is necessary to limit this to rvalue reference to avoid calling this
1708     // function with a bitfield lvalue argument since non-const reference to
1709     // bitfield is not allowed.
1710     template <typename T, typename = typename std::enable_if<
1711                               !std::is_lvalue_reference<T>::value>::type>
1712     const ImmediateDiagBuilder &operator<<(T &&V) const {
1713       const DiagnosticBuilder &BaseDiag = *this;
1714       BaseDiag << std::move(V);
1715       return *this;
1716     }
1717   };
1718 
1719   /// A generic diagnostic builder for errors which may or may not be deferred.
1720   ///
1721   /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
1722   /// which are not allowed to appear inside __device__ functions and are
1723   /// allowed to appear in __host__ __device__ functions only if the host+device
1724   /// function is never codegen'ed.
1725   ///
1726   /// To handle this, we use the notion of "deferred diagnostics", where we
1727   /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
1728   ///
1729   /// This class lets you emit either a regular diagnostic, a deferred
1730   /// diagnostic, or no diagnostic at all, according to an argument you pass to
1731   /// its constructor, thus simplifying the process of creating these "maybe
1732   /// deferred" diagnostics.
1733   class SemaDiagnosticBuilder {
1734   public:
1735     enum Kind {
1736       /// Emit no diagnostics.
1737       K_Nop,
1738       /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
1739       K_Immediate,
1740       /// Emit the diagnostic immediately, and, if it's a warning or error, also
1741       /// emit a call stack showing how this function can be reached by an a
1742       /// priori known-emitted function.
1743       K_ImmediateWithCallStack,
1744       /// Create a deferred diagnostic, which is emitted only if the function
1745       /// it's attached to is codegen'ed.  Also emit a call stack as with
1746       /// K_ImmediateWithCallStack.
1747       K_Deferred
1748     };
1749 
1750     SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
1751                           FunctionDecl *Fn, Sema &S);
1752     SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D);
1753     SemaDiagnosticBuilder(const SemaDiagnosticBuilder &) = default;
1754     ~SemaDiagnosticBuilder();
1755 
1756     bool isImmediate() const { return ImmediateDiag.has_value(); }
1757 
1758     /// Convertible to bool: True if we immediately emitted an error, false if
1759     /// we didn't emit an error or we created a deferred error.
1760     ///
1761     /// Example usage:
1762     ///
1763     ///   if (SemaDiagnosticBuilder(...) << foo << bar)
1764     ///     return ExprError();
1765     ///
1766     /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
1767     /// want to use these instead of creating a SemaDiagnosticBuilder yourself.
1768     operator bool() const { return isImmediate(); }
1769 
1770     template <typename T>
1771     friend const SemaDiagnosticBuilder &
1772     operator<<(const SemaDiagnosticBuilder &Diag, const T &Value) {
1773       if (Diag.ImmediateDiag)
1774         *Diag.ImmediateDiag << Value;
1775       else if (Diag.PartialDiagId)
1776         Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
1777             << Value;
1778       return Diag;
1779     }
1780 
1781     // It is necessary to limit this to rvalue reference to avoid calling this
1782     // function with a bitfield lvalue argument since non-const reference to
1783     // bitfield is not allowed.
1784     template <typename T, typename = typename std::enable_if<
1785                               !std::is_lvalue_reference<T>::value>::type>
1786     const SemaDiagnosticBuilder &operator<<(T &&V) const {
1787       if (ImmediateDiag)
1788         *ImmediateDiag << std::move(V);
1789       else if (PartialDiagId)
1790         S.DeviceDeferredDiags[Fn][*PartialDiagId].second << std::move(V);
1791       return *this;
1792     }
1793 
1794     friend const SemaDiagnosticBuilder &
1795     operator<<(const SemaDiagnosticBuilder &Diag, const PartialDiagnostic &PD) {
1796       if (Diag.ImmediateDiag)
1797         PD.Emit(*Diag.ImmediateDiag);
1798       else if (Diag.PartialDiagId)
1799         Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second = PD;
1800       return Diag;
1801     }
1802 
1803     void AddFixItHint(const FixItHint &Hint) const {
1804       if (ImmediateDiag)
1805         ImmediateDiag->AddFixItHint(Hint);
1806       else if (PartialDiagId)
1807         S.DeviceDeferredDiags[Fn][*PartialDiagId].second.AddFixItHint(Hint);
1808     }
1809 
1810     friend ExprResult ExprError(const SemaDiagnosticBuilder &) {
1811       return ExprError();
1812     }
1813     friend StmtResult StmtError(const SemaDiagnosticBuilder &) {
1814       return StmtError();
1815     }
1816     operator ExprResult() const { return ExprError(); }
1817     operator StmtResult() const { return StmtError(); }
1818     operator TypeResult() const { return TypeError(); }
1819     operator DeclResult() const { return DeclResult(true); }
1820     operator MemInitResult() const { return MemInitResult(true); }
1821 
1822   private:
1823     Sema &S;
1824     SourceLocation Loc;
1825     unsigned DiagID;
1826     FunctionDecl *Fn;
1827     bool ShowCallStack;
1828 
1829     // Invariant: At most one of these Optionals has a value.
1830     // FIXME: Switch these to a Variant once that exists.
1831     llvm::Optional<ImmediateDiagBuilder> ImmediateDiag;
1832     llvm::Optional<unsigned> PartialDiagId;
1833   };
1834 
1835   /// Is the last error level diagnostic immediate. This is used to determined
1836   /// whether the next info diagnostic should be immediate.
1837   bool IsLastErrorImmediate = true;
1838 
1839   /// Emit a diagnostic.
1840   SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID,
1841                              bool DeferHint = false);
1842 
1843   /// Emit a partial diagnostic.
1844   SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic &PD,
1845                              bool DeferHint = false);
1846 
1847   /// Build a partial diagnostic.
1848   PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1849 
1850   /// Whether deferrable diagnostics should be deferred.
1851   bool DeferDiags = false;
1852 
1853   /// RAII class to control scope of DeferDiags.
1854   class DeferDiagsRAII {
1855     Sema &S;
1856     bool SavedDeferDiags = false;
1857 
1858   public:
1859     DeferDiagsRAII(Sema &S, bool DeferDiags)
1860         : S(S), SavedDeferDiags(S.DeferDiags) {
1861       S.DeferDiags = DeferDiags;
1862     }
1863     ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; }
1864   };
1865 
1866   /// Whether uncompilable error has occurred. This includes error happens
1867   /// in deferred diagnostics.
1868   bool hasUncompilableErrorOccurred() const;
1869 
1870   bool findMacroSpelling(SourceLocation &loc, StringRef name);
1871 
1872   /// Get a string to suggest for zero-initialization of a type.
1873   std::string
1874   getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1875   std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1876 
1877   /// Calls \c Lexer::getLocForEndOfToken()
1878   SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1879 
1880   /// Retrieve the module loader associated with the preprocessor.
1881   ModuleLoader &getModuleLoader() const;
1882 
1883   /// Invent a new identifier for parameters of abbreviated templates.
1884   IdentifierInfo *
1885   InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName,
1886                                              unsigned Index);
1887 
1888   void emitAndClearUnusedLocalTypedefWarnings();
1889 
1890   private:
1891     /// Function or variable declarations to be checked for whether the deferred
1892     /// diagnostics should be emitted.
1893     llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags;
1894 
1895   public:
1896   // Emit all deferred diagnostics.
1897   void emitDeferredDiags();
1898 
1899   enum TUFragmentKind {
1900     /// The global module fragment, between 'module;' and a module-declaration.
1901     Global,
1902     /// A normal translation unit fragment. For a non-module unit, this is the
1903     /// entire translation unit. Otherwise, it runs from the module-declaration
1904     /// to the private-module-fragment (if any) or the end of the TU (if not).
1905     Normal,
1906     /// The private module fragment, between 'module :private;' and the end of
1907     /// the translation unit.
1908     Private
1909   };
1910 
1911   void ActOnStartOfTranslationUnit();
1912   void ActOnEndOfTranslationUnit();
1913   void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1914 
1915   void CheckDelegatingCtorCycles();
1916 
1917   Scope *getScopeForContext(DeclContext *Ctx);
1918 
1919   void PushFunctionScope();
1920   void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1921   sema::LambdaScopeInfo *PushLambdaScope();
1922 
1923   /// This is used to inform Sema what the current TemplateParameterDepth
1924   /// is during Parsing.  Currently it is used to pass on the depth
1925   /// when parsing generic lambda 'auto' parameters.
1926   void RecordParsingTemplateParameterDepth(unsigned Depth);
1927 
1928   void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1929                                RecordDecl *RD, CapturedRegionKind K,
1930                                unsigned OpenMPCaptureLevel = 0);
1931 
1932   /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1933   /// time after they've been popped.
1934   class PoppedFunctionScopeDeleter {
1935     Sema *Self;
1936 
1937   public:
1938     explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1939     void operator()(sema::FunctionScopeInfo *Scope) const;
1940   };
1941 
1942   using PoppedFunctionScopePtr =
1943       std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1944 
1945   PoppedFunctionScopePtr
1946   PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1947                        const Decl *D = nullptr,
1948                        QualType BlockType = QualType());
1949 
1950   sema::FunctionScopeInfo *getCurFunction() const {
1951     return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1952   }
1953 
1954   sema::FunctionScopeInfo *getEnclosingFunction() const;
1955 
1956   void setFunctionHasBranchIntoScope();
1957   void setFunctionHasBranchProtectedScope();
1958   void setFunctionHasIndirectGoto();
1959   void setFunctionHasMustTail();
1960 
1961   void PushCompoundScope(bool IsStmtExpr);
1962   void PopCompoundScope();
1963 
1964   sema::CompoundScopeInfo &getCurCompoundScope() const;
1965 
1966   bool hasAnyUnrecoverableErrorsInThisFunction() const;
1967 
1968   /// Retrieve the current block, if any.
1969   sema::BlockScopeInfo *getCurBlock();
1970 
1971   /// Get the innermost lambda enclosing the current location, if any. This
1972   /// looks through intervening non-lambda scopes such as local functions and
1973   /// blocks.
1974   sema::LambdaScopeInfo *getEnclosingLambda() const;
1975 
1976   /// Retrieve the current lambda scope info, if any.
1977   /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1978   /// lambda scope info ignoring all inner capturing scopes that are not
1979   /// lambda scopes.
1980   sema::LambdaScopeInfo *
1981   getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1982 
1983   /// Retrieve the current generic lambda info, if any.
1984   sema::LambdaScopeInfo *getCurGenericLambda();
1985 
1986   /// Retrieve the current captured region, if any.
1987   sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1988 
1989   /// Retrieve the current function, if any, that should be analyzed for
1990   /// potential availability violations.
1991   sema::FunctionScopeInfo *getCurFunctionAvailabilityContext();
1992 
1993   /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1994   SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1995 
1996   /// Called before parsing a function declarator belonging to a function
1997   /// declaration.
1998   void ActOnStartFunctionDeclarationDeclarator(Declarator &D,
1999                                                unsigned TemplateParameterDepth);
2000 
2001   /// Called after parsing a function declarator belonging to a function
2002   /// declaration.
2003   void ActOnFinishFunctionDeclarationDeclarator(Declarator &D);
2004 
2005   void ActOnComment(SourceRange Comment);
2006 
2007   //===--------------------------------------------------------------------===//
2008   // Type Analysis / Processing: SemaType.cpp.
2009   //
2010 
2011   QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
2012                               const DeclSpec *DS = nullptr);
2013   QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
2014                               const DeclSpec *DS = nullptr);
2015   QualType BuildPointerType(QualType T,
2016                             SourceLocation Loc, DeclarationName Entity);
2017   QualType BuildReferenceType(QualType T, bool LValueRef,
2018                               SourceLocation Loc, DeclarationName Entity);
2019   QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
2020                           Expr *ArraySize, unsigned Quals,
2021                           SourceRange Brackets, DeclarationName Entity);
2022   QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
2023   QualType BuildExtVectorType(QualType T, Expr *ArraySize,
2024                               SourceLocation AttrLoc);
2025   QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
2026                            SourceLocation AttrLoc);
2027 
2028   QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
2029                                  SourceLocation AttrLoc);
2030 
2031   /// Same as above, but constructs the AddressSpace index if not provided.
2032   QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
2033                                  SourceLocation AttrLoc);
2034 
2035   bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
2036 
2037   bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
2038 
2039   /// Build a function type.
2040   ///
2041   /// This routine checks the function type according to C++ rules and
2042   /// under the assumption that the result type and parameter types have
2043   /// just been instantiated from a template. It therefore duplicates
2044   /// some of the behavior of GetTypeForDeclarator, but in a much
2045   /// simpler form that is only suitable for this narrow use case.
2046   ///
2047   /// \param T The return type of the function.
2048   ///
2049   /// \param ParamTypes The parameter types of the function. This array
2050   /// will be modified to account for adjustments to the types of the
2051   /// function parameters.
2052   ///
2053   /// \param Loc The location of the entity whose type involves this
2054   /// function type or, if there is no such entity, the location of the
2055   /// type that will have function type.
2056   ///
2057   /// \param Entity The name of the entity that involves the function
2058   /// type, if known.
2059   ///
2060   /// \param EPI Extra information about the function type. Usually this will
2061   /// be taken from an existing function with the same prototype.
2062   ///
2063   /// \returns A suitable function type, if there are no errors. The
2064   /// unqualified type will always be a FunctionProtoType.
2065   /// Otherwise, returns a NULL type.
2066   QualType BuildFunctionType(QualType T,
2067                              MutableArrayRef<QualType> ParamTypes,
2068                              SourceLocation Loc, DeclarationName Entity,
2069                              const FunctionProtoType::ExtProtoInfo &EPI);
2070 
2071   QualType BuildMemberPointerType(QualType T, QualType Class,
2072                                   SourceLocation Loc,
2073                                   DeclarationName Entity);
2074   QualType BuildBlockPointerType(QualType T,
2075                                  SourceLocation Loc, DeclarationName Entity);
2076   QualType BuildParenType(QualType T);
2077   QualType BuildAtomicType(QualType T, SourceLocation Loc);
2078   QualType BuildReadPipeType(QualType T,
2079                          SourceLocation Loc);
2080   QualType BuildWritePipeType(QualType T,
2081                          SourceLocation Loc);
2082   QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
2083 
2084   TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
2085   TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
2086 
2087   /// Package the given type and TSI into a ParsedType.
2088   ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
2089   DeclarationNameInfo GetNameForDeclarator(Declarator &D);
2090   DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
2091   static QualType GetTypeFromParser(ParsedType Ty,
2092                                     TypeSourceInfo **TInfo = nullptr);
2093   CanThrowResult canThrow(const Stmt *E);
2094   /// Determine whether the callee of a particular function call can throw.
2095   /// E, D and Loc are all optional.
2096   static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
2097                                        SourceLocation Loc = SourceLocation());
2098   const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
2099                                                 const FunctionProtoType *FPT);
2100   void UpdateExceptionSpec(FunctionDecl *FD,
2101                            const FunctionProtoType::ExceptionSpecInfo &ESI);
2102   bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
2103   bool CheckDistantExceptionSpec(QualType T);
2104   bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
2105   bool CheckEquivalentExceptionSpec(
2106       const FunctionProtoType *Old, SourceLocation OldLoc,
2107       const FunctionProtoType *New, SourceLocation NewLoc);
2108   bool CheckEquivalentExceptionSpec(
2109       const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
2110       const FunctionProtoType *Old, SourceLocation OldLoc,
2111       const FunctionProtoType *New, SourceLocation NewLoc);
2112   bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
2113   bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
2114                                 const PartialDiagnostic &NestedDiagID,
2115                                 const PartialDiagnostic &NoteID,
2116                                 const PartialDiagnostic &NoThrowDiagID,
2117                                 const FunctionProtoType *Superset,
2118                                 SourceLocation SuperLoc,
2119                                 const FunctionProtoType *Subset,
2120                                 SourceLocation SubLoc);
2121   bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
2122                                const PartialDiagnostic &NoteID,
2123                                const FunctionProtoType *Target,
2124                                SourceLocation TargetLoc,
2125                                const FunctionProtoType *Source,
2126                                SourceLocation SourceLoc);
2127 
2128   TypeResult ActOnTypeName(Scope *S, Declarator &D);
2129 
2130   /// The parser has parsed the context-sensitive type 'instancetype'
2131   /// in an Objective-C message declaration. Return the appropriate type.
2132   ParsedType ActOnObjCInstanceType(SourceLocation Loc);
2133 
2134   /// Abstract class used to diagnose incomplete types.
2135   struct TypeDiagnoser {
2136     TypeDiagnoser() {}
2137 
2138     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
2139     virtual ~TypeDiagnoser() {}
2140   };
2141 
2142   static int getPrintable(int I) { return I; }
2143   static unsigned getPrintable(unsigned I) { return I; }
2144   static bool getPrintable(bool B) { return B; }
2145   static const char * getPrintable(const char *S) { return S; }
2146   static StringRef getPrintable(StringRef S) { return S; }
2147   static const std::string &getPrintable(const std::string &S) { return S; }
2148   static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
2149     return II;
2150   }
2151   static DeclarationName getPrintable(DeclarationName N) { return N; }
2152   static QualType getPrintable(QualType T) { return T; }
2153   static SourceRange getPrintable(SourceRange R) { return R; }
2154   static SourceRange getPrintable(SourceLocation L) { return L; }
2155   static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
2156   static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
2157 
2158   template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
2159   protected:
2160     unsigned DiagID;
2161     std::tuple<const Ts &...> Args;
2162 
2163     template <std::size_t... Is>
2164     void emit(const SemaDiagnosticBuilder &DB,
2165               std::index_sequence<Is...>) const {
2166       // Apply all tuple elements to the builder in order.
2167       bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
2168       (void)Dummy;
2169     }
2170 
2171   public:
2172     BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
2173         : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
2174       assert(DiagID != 0 && "no diagnostic for type diagnoser");
2175     }
2176 
2177     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2178       const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
2179       emit(DB, std::index_sequence_for<Ts...>());
2180       DB << T;
2181     }
2182   };
2183 
2184   /// Do a check to make sure \p Name looks like a legal argument for the
2185   /// swift_name attribute applied to decl \p D.  Raise a diagnostic if the name
2186   /// is invalid for the given declaration.
2187   ///
2188   /// \p AL is used to provide caret diagnostics in case of a malformed name.
2189   ///
2190   /// \returns true if the name is a valid swift name for \p D, false otherwise.
2191   bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc,
2192                          const ParsedAttr &AL, bool IsAsync);
2193 
2194   /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
2195   /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
2196   /// For example, a diagnostic with no other parameters would generally have
2197   /// the form "...%select{incomplete|sizeless}0 type %1...".
2198   template <typename... Ts>
2199   class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> {
2200   public:
2201     SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args)
2202         : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
2203 
2204     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2205       const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
2206       this->emit(DB, std::index_sequence_for<Ts...>());
2207       DB << T->isSizelessType() << T;
2208     }
2209   };
2210 
2211   enum class CompleteTypeKind {
2212     /// Apply the normal rules for complete types.  In particular,
2213     /// treat all sizeless types as incomplete.
2214     Normal,
2215 
2216     /// Relax the normal rules for complete types so that they include
2217     /// sizeless built-in types.
2218     AcceptSizeless,
2219 
2220     // FIXME: Eventually we should flip the default to Normal and opt in
2221     // to AcceptSizeless rather than opt out of it.
2222     Default = AcceptSizeless
2223   };
2224 
2225   enum class AcceptableKind { Visible, Reachable };
2226 
2227 private:
2228   /// Methods for marking which expressions involve dereferencing a pointer
2229   /// marked with the 'noderef' attribute. Expressions are checked bottom up as
2230   /// they are parsed, meaning that a noderef pointer may not be accessed. For
2231   /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
2232   /// `*p`, but need to check that `address of` is called on it. This requires
2233   /// keeping a container of all pending expressions and checking if the address
2234   /// of them are eventually taken.
2235   void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
2236   void CheckAddressOfNoDeref(const Expr *E);
2237   void CheckMemberAccessOfNoDeref(const MemberExpr *E);
2238 
2239   bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
2240                                CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
2241 
2242   struct ModuleScope {
2243     SourceLocation BeginLoc;
2244     clang::Module *Module = nullptr;
2245     bool ModuleInterface = false;
2246     bool IsPartition = false;
2247     bool ImplicitGlobalModuleFragment = false;
2248     VisibleModuleSet OuterVisibleModules;
2249   };
2250   /// The modules we're currently parsing.
2251   llvm::SmallVector<ModuleScope, 16> ModuleScopes;
2252   /// The global module fragment of the current translation unit.
2253   clang::Module *GlobalModuleFragment = nullptr;
2254 
2255   /// The modules we imported directly.
2256   llvm::SmallPtrSet<clang::Module *, 8> DirectModuleImports;
2257 
2258   /// Namespace definitions that we will export when they finish.
2259   llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
2260 
2261   /// Helper function to judge if we are in module purview.
2262   /// Return false if we are not in a module.
2263   bool isCurrentModulePurview() const {
2264     return getCurrentModule() ? getCurrentModule()->isModulePurview() : false;
2265   }
2266 
2267   /// Enter the scope of the global module.
2268   Module *PushGlobalModuleFragment(SourceLocation BeginLoc, bool IsImplicit);
2269   /// Leave the scope of the global module.
2270   void PopGlobalModuleFragment();
2271 
2272   VisibleModuleSet VisibleModules;
2273 
2274   /// Cache for module units which is usable for current module.
2275   llvm::DenseSet<const Module *> UsableModuleUnitsCache;
2276 
2277   bool isUsableModule(const Module *M);
2278 
2279   bool isAcceptableSlow(const NamedDecl *D, AcceptableKind Kind);
2280 
2281   // Determine whether the module M belongs to the  current TU.
2282   bool isModuleUnitOfCurrentTU(const Module *M) const;
2283 
2284 public:
2285   /// Get the module unit whose scope we are currently within.
2286   Module *getCurrentModule() const {
2287     return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
2288   }
2289 
2290   /// Is the module scope we are an interface?
2291   bool currentModuleIsInterface() const {
2292     return ModuleScopes.empty() ? false : ModuleScopes.back().ModuleInterface;
2293   }
2294 
2295   /// Get the module owning an entity.
2296   Module *getOwningModule(const Decl *Entity) {
2297     return Entity->getOwningModule();
2298   }
2299 
2300   bool isModuleDirectlyImported(const Module *M) {
2301     return DirectModuleImports.contains(M);
2302   }
2303 
2304   /// Make a merged definition of an existing hidden definition \p ND
2305   /// visible at the specified location.
2306   void makeMergedDefinitionVisible(NamedDecl *ND);
2307 
2308   bool isModuleVisible(const Module *M, bool ModulePrivate = false);
2309 
2310   // When loading a non-modular PCH files, this is used to restore module
2311   // visibility.
2312   void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) {
2313     VisibleModules.setVisible(Mod, ImportLoc);
2314   }
2315 
2316   /// Determine whether a declaration is visible to name lookup.
2317   bool isVisible(const NamedDecl *D) {
2318     return D->isUnconditionallyVisible() ||
2319            isAcceptableSlow(D, AcceptableKind::Visible);
2320   }
2321 
2322   /// Determine whether a declaration is reachable.
2323   bool isReachable(const NamedDecl *D) {
2324     // All visible declarations are reachable.
2325     return D->isUnconditionallyVisible() ||
2326            isAcceptableSlow(D, AcceptableKind::Reachable);
2327   }
2328 
2329   /// Determine whether a declaration is acceptable (visible/reachable).
2330   bool isAcceptable(const NamedDecl *D, AcceptableKind Kind) {
2331     return Kind == AcceptableKind::Visible ? isVisible(D) : isReachable(D);
2332   }
2333 
2334   /// Determine whether any declaration of an entity is visible.
2335   bool
2336   hasVisibleDeclaration(const NamedDecl *D,
2337                         llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
2338     return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
2339   }
2340 
2341   bool hasVisibleDeclarationSlow(const NamedDecl *D,
2342                                  llvm::SmallVectorImpl<Module *> *Modules);
2343   /// Determine whether any declaration of an entity is reachable.
2344   bool
2345   hasReachableDeclaration(const NamedDecl *D,
2346                           llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
2347     return isReachable(D) || hasReachableDeclarationSlow(D, Modules);
2348   }
2349   bool hasReachableDeclarationSlow(
2350       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2351 
2352   bool hasVisibleMergedDefinition(NamedDecl *Def);
2353   bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
2354 
2355   /// Determine if \p D and \p Suggested have a structurally compatible
2356   /// layout as described in C11 6.2.7/1.
2357   bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
2358 
2359   /// Determine if \p D has a visible definition. If not, suggest a declaration
2360   /// that should be made visible to expose the definition.
2361   bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
2362                             bool OnlyNeedComplete = false);
2363   bool hasVisibleDefinition(const NamedDecl *D) {
2364     NamedDecl *Hidden;
2365     return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
2366   }
2367 
2368   /// Determine if \p D has a reachable definition. If not, suggest a
2369   /// declaration that should be made reachable to expose the definition.
2370   bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested,
2371                               bool OnlyNeedComplete = false);
2372   bool hasReachableDefinition(NamedDecl *D) {
2373     NamedDecl *Hidden;
2374     return hasReachableDefinition(D, &Hidden);
2375   }
2376 
2377   bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested,
2378                                AcceptableKind Kind,
2379                                bool OnlyNeedComplete = false);
2380   bool hasAcceptableDefinition(NamedDecl *D, AcceptableKind Kind) {
2381     NamedDecl *Hidden;
2382     return hasAcceptableDefinition(D, &Hidden, Kind);
2383   }
2384 
2385   /// Determine if the template parameter \p D has a visible default argument.
2386   bool
2387   hasVisibleDefaultArgument(const NamedDecl *D,
2388                             llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2389   /// Determine if the template parameter \p D has a reachable default argument.
2390   bool hasReachableDefaultArgument(
2391       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2392   /// Determine if the template parameter \p D has a reachable default argument.
2393   bool hasAcceptableDefaultArgument(const NamedDecl *D,
2394                                     llvm::SmallVectorImpl<Module *> *Modules,
2395                                     Sema::AcceptableKind Kind);
2396 
2397   /// Determine if there is a visible declaration of \p D that is an explicit
2398   /// specialization declaration for a specialization of a template. (For a
2399   /// member specialization, use hasVisibleMemberSpecialization.)
2400   bool hasVisibleExplicitSpecialization(
2401       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2402   /// Determine if there is a reachable declaration of \p D that is an explicit
2403   /// specialization declaration for a specialization of a template. (For a
2404   /// member specialization, use hasReachableMemberSpecialization.)
2405   bool hasReachableExplicitSpecialization(
2406       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2407 
2408   /// Determine if there is a visible declaration of \p D that is a member
2409   /// specialization declaration (as opposed to an instantiated declaration).
2410   bool hasVisibleMemberSpecialization(
2411       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2412   /// Determine if there is a reachable declaration of \p D that is a member
2413   /// specialization declaration (as opposed to an instantiated declaration).
2414   bool hasReachableMemberSpecialization(
2415       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2416 
2417   /// Determine if \p A and \p B are equivalent internal linkage declarations
2418   /// from different modules, and thus an ambiguity error can be downgraded to
2419   /// an extension warning.
2420   bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
2421                                               const NamedDecl *B);
2422   void diagnoseEquivalentInternalLinkageDeclarations(
2423       SourceLocation Loc, const NamedDecl *D,
2424       ArrayRef<const NamedDecl *> Equiv);
2425 
2426   bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
2427 
2428   bool isCompleteType(SourceLocation Loc, QualType T,
2429                       CompleteTypeKind Kind = CompleteTypeKind::Default) {
2430     return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr);
2431   }
2432   bool RequireCompleteType(SourceLocation Loc, QualType T,
2433                            CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
2434   bool RequireCompleteType(SourceLocation Loc, QualType T,
2435                            CompleteTypeKind Kind, unsigned DiagID);
2436 
2437   bool RequireCompleteType(SourceLocation Loc, QualType T,
2438                            TypeDiagnoser &Diagnoser) {
2439     return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser);
2440   }
2441   bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
2442     return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID);
2443   }
2444 
2445   template <typename... Ts>
2446   bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
2447                            const Ts &...Args) {
2448     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2449     return RequireCompleteType(Loc, T, Diagnoser);
2450   }
2451 
2452   template <typename... Ts>
2453   bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID,
2454                                 const Ts &... Args) {
2455     SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2456     return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
2457   }
2458 
2459   /// Get the type of expression E, triggering instantiation to complete the
2460   /// type if necessary -- that is, if the expression refers to a templated
2461   /// static data member of incomplete array type.
2462   ///
2463   /// May still return an incomplete type if instantiation was not possible or
2464   /// if the type is incomplete for a different reason. Use
2465   /// RequireCompleteExprType instead if a diagnostic is expected for an
2466   /// incomplete expression type.
2467   QualType getCompletedType(Expr *E);
2468 
2469   void completeExprArrayBound(Expr *E);
2470   bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
2471                                TypeDiagnoser &Diagnoser);
2472   bool RequireCompleteExprType(Expr *E, unsigned DiagID);
2473 
2474   template <typename... Ts>
2475   bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
2476     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2477     return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
2478   }
2479 
2480   template <typename... Ts>
2481   bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
2482                                     const Ts &... Args) {
2483     SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2484     return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser);
2485   }
2486 
2487   bool RequireLiteralType(SourceLocation Loc, QualType T,
2488                           TypeDiagnoser &Diagnoser);
2489   bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
2490 
2491   template <typename... Ts>
2492   bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
2493                           const Ts &...Args) {
2494     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2495     return RequireLiteralType(Loc, T, Diagnoser);
2496   }
2497 
2498   QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
2499                              const CXXScopeSpec &SS, QualType T,
2500                              TagDecl *OwnedTagDecl = nullptr);
2501 
2502   // Returns the underlying type of a decltype with the given expression.
2503   QualType getDecltypeForExpr(Expr *E);
2504 
2505   QualType BuildTypeofExprType(Expr *E);
2506   /// If AsUnevaluated is false, E is treated as though it were an evaluated
2507   /// context, such as when building a type for decltype(auto).
2508   QualType BuildDecltypeType(Expr *E, bool AsUnevaluated = true);
2509   QualType BuildUnaryTransformType(QualType BaseType,
2510                                    UnaryTransformType::UTTKind UKind,
2511                                    SourceLocation Loc);
2512 
2513   //===--------------------------------------------------------------------===//
2514   // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
2515   //
2516 
2517   struct SkipBodyInfo {
2518     SkipBodyInfo()
2519         : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
2520           New(nullptr) {}
2521     bool ShouldSkip;
2522     bool CheckSameAsPrevious;
2523     NamedDecl *Previous;
2524     NamedDecl *New;
2525   };
2526 
2527   DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
2528 
2529   void DiagnoseUseOfUnimplementedSelectors();
2530 
2531   bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
2532 
2533   ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
2534                          Scope *S, CXXScopeSpec *SS = nullptr,
2535                          bool isClassName = false, bool HasTrailingDot = false,
2536                          ParsedType ObjectType = nullptr,
2537                          bool IsCtorOrDtorName = false,
2538                          bool WantNontrivialTypeSourceInfo = false,
2539                          bool IsClassTemplateDeductionContext = true,
2540                          IdentifierInfo **CorrectedII = nullptr);
2541   TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
2542   bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
2543   void DiagnoseUnknownTypeName(IdentifierInfo *&II,
2544                                SourceLocation IILoc,
2545                                Scope *S,
2546                                CXXScopeSpec *SS,
2547                                ParsedType &SuggestedType,
2548                                bool IsTemplateName = false);
2549 
2550   /// Attempt to behave like MSVC in situations where lookup of an unqualified
2551   /// type name has failed in a dependent context. In these situations, we
2552   /// automatically form a DependentTypeName that will retry lookup in a related
2553   /// scope during instantiation.
2554   ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
2555                                       SourceLocation NameLoc,
2556                                       bool IsTemplateTypeArg);
2557 
2558   /// Describes the result of the name lookup and resolution performed
2559   /// by \c ClassifyName().
2560   enum NameClassificationKind {
2561     /// This name is not a type or template in this context, but might be
2562     /// something else.
2563     NC_Unknown,
2564     /// Classification failed; an error has been produced.
2565     NC_Error,
2566     /// The name has been typo-corrected to a keyword.
2567     NC_Keyword,
2568     /// The name was classified as a type.
2569     NC_Type,
2570     /// The name was classified as a specific non-type, non-template
2571     /// declaration. ActOnNameClassifiedAsNonType should be called to
2572     /// convert the declaration to an expression.
2573     NC_NonType,
2574     /// The name was classified as an ADL-only function name.
2575     /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
2576     /// result to an expression.
2577     NC_UndeclaredNonType,
2578     /// The name denotes a member of a dependent type that could not be
2579     /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
2580     /// convert the result to an expression.
2581     NC_DependentNonType,
2582     /// The name was classified as an overload set, and an expression
2583     /// representing that overload set has been formed.
2584     /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
2585     /// expression referencing the overload set.
2586     NC_OverloadSet,
2587     /// The name was classified as a template whose specializations are types.
2588     NC_TypeTemplate,
2589     /// The name was classified as a variable template name.
2590     NC_VarTemplate,
2591     /// The name was classified as a function template name.
2592     NC_FunctionTemplate,
2593     /// The name was classified as an ADL-only function template name.
2594     NC_UndeclaredTemplate,
2595     /// The name was classified as a concept name.
2596     NC_Concept,
2597   };
2598 
2599   class NameClassification {
2600     NameClassificationKind Kind;
2601     union {
2602       ExprResult Expr;
2603       NamedDecl *NonTypeDecl;
2604       TemplateName Template;
2605       ParsedType Type;
2606     };
2607 
2608     explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
2609 
2610   public:
2611     NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
2612 
2613     NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
2614 
2615     static NameClassification Error() {
2616       return NameClassification(NC_Error);
2617     }
2618 
2619     static NameClassification Unknown() {
2620       return NameClassification(NC_Unknown);
2621     }
2622 
2623     static NameClassification OverloadSet(ExprResult E) {
2624       NameClassification Result(NC_OverloadSet);
2625       Result.Expr = E;
2626       return Result;
2627     }
2628 
2629     static NameClassification NonType(NamedDecl *D) {
2630       NameClassification Result(NC_NonType);
2631       Result.NonTypeDecl = D;
2632       return Result;
2633     }
2634 
2635     static NameClassification UndeclaredNonType() {
2636       return NameClassification(NC_UndeclaredNonType);
2637     }
2638 
2639     static NameClassification DependentNonType() {
2640       return NameClassification(NC_DependentNonType);
2641     }
2642 
2643     static NameClassification TypeTemplate(TemplateName Name) {
2644       NameClassification Result(NC_TypeTemplate);
2645       Result.Template = Name;
2646       return Result;
2647     }
2648 
2649     static NameClassification VarTemplate(TemplateName Name) {
2650       NameClassification Result(NC_VarTemplate);
2651       Result.Template = Name;
2652       return Result;
2653     }
2654 
2655     static NameClassification FunctionTemplate(TemplateName Name) {
2656       NameClassification Result(NC_FunctionTemplate);
2657       Result.Template = Name;
2658       return Result;
2659     }
2660 
2661     static NameClassification Concept(TemplateName Name) {
2662       NameClassification Result(NC_Concept);
2663       Result.Template = Name;
2664       return Result;
2665     }
2666 
2667     static NameClassification UndeclaredTemplate(TemplateName Name) {
2668       NameClassification Result(NC_UndeclaredTemplate);
2669       Result.Template = Name;
2670       return Result;
2671     }
2672 
2673     NameClassificationKind getKind() const { return Kind; }
2674 
2675     ExprResult getExpression() const {
2676       assert(Kind == NC_OverloadSet);
2677       return Expr;
2678     }
2679 
2680     ParsedType getType() const {
2681       assert(Kind == NC_Type);
2682       return Type;
2683     }
2684 
2685     NamedDecl *getNonTypeDecl() const {
2686       assert(Kind == NC_NonType);
2687       return NonTypeDecl;
2688     }
2689 
2690     TemplateName getTemplateName() const {
2691       assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
2692              Kind == NC_VarTemplate || Kind == NC_Concept ||
2693              Kind == NC_UndeclaredTemplate);
2694       return Template;
2695     }
2696 
2697     TemplateNameKind getTemplateNameKind() const {
2698       switch (Kind) {
2699       case NC_TypeTemplate:
2700         return TNK_Type_template;
2701       case NC_FunctionTemplate:
2702         return TNK_Function_template;
2703       case NC_VarTemplate:
2704         return TNK_Var_template;
2705       case NC_Concept:
2706         return TNK_Concept_template;
2707       case NC_UndeclaredTemplate:
2708         return TNK_Undeclared_template;
2709       default:
2710         llvm_unreachable("unsupported name classification.");
2711       }
2712     }
2713   };
2714 
2715   /// Perform name lookup on the given name, classifying it based on
2716   /// the results of name lookup and the following token.
2717   ///
2718   /// This routine is used by the parser to resolve identifiers and help direct
2719   /// parsing. When the identifier cannot be found, this routine will attempt
2720   /// to correct the typo and classify based on the resulting name.
2721   ///
2722   /// \param S The scope in which we're performing name lookup.
2723   ///
2724   /// \param SS The nested-name-specifier that precedes the name.
2725   ///
2726   /// \param Name The identifier. If typo correction finds an alternative name,
2727   /// this pointer parameter will be updated accordingly.
2728   ///
2729   /// \param NameLoc The location of the identifier.
2730   ///
2731   /// \param NextToken The token following the identifier. Used to help
2732   /// disambiguate the name.
2733   ///
2734   /// \param CCC The correction callback, if typo correction is desired.
2735   NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
2736                                   IdentifierInfo *&Name, SourceLocation NameLoc,
2737                                   const Token &NextToken,
2738                                   CorrectionCandidateCallback *CCC = nullptr);
2739 
2740   /// Act on the result of classifying a name as an undeclared (ADL-only)
2741   /// non-type declaration.
2742   ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
2743                                                     SourceLocation NameLoc);
2744   /// Act on the result of classifying a name as an undeclared member of a
2745   /// dependent base class.
2746   ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
2747                                                    IdentifierInfo *Name,
2748                                                    SourceLocation NameLoc,
2749                                                    bool IsAddressOfOperand);
2750   /// Act on the result of classifying a name as a specific non-type
2751   /// declaration.
2752   ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
2753                                           NamedDecl *Found,
2754                                           SourceLocation NameLoc,
2755                                           const Token &NextToken);
2756   /// Act on the result of classifying a name as an overload set.
2757   ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet);
2758 
2759   /// Describes the detailed kind of a template name. Used in diagnostics.
2760   enum class TemplateNameKindForDiagnostics {
2761     ClassTemplate,
2762     FunctionTemplate,
2763     VarTemplate,
2764     AliasTemplate,
2765     TemplateTemplateParam,
2766     Concept,
2767     DependentTemplate
2768   };
2769   TemplateNameKindForDiagnostics
2770   getTemplateNameKindForDiagnostics(TemplateName Name);
2771 
2772   /// Determine whether it's plausible that E was intended to be a
2773   /// template-name.
2774   bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
2775     if (!getLangOpts().CPlusPlus || E.isInvalid())
2776       return false;
2777     Dependent = false;
2778     if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
2779       return !DRE->hasExplicitTemplateArgs();
2780     if (auto *ME = dyn_cast<MemberExpr>(E.get()))
2781       return !ME->hasExplicitTemplateArgs();
2782     Dependent = true;
2783     if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2784       return !DSDRE->hasExplicitTemplateArgs();
2785     if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2786       return !DSME->hasExplicitTemplateArgs();
2787     // Any additional cases recognized here should also be handled by
2788     // diagnoseExprIntendedAsTemplateName.
2789     return false;
2790   }
2791   void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
2792                                           SourceLocation Less,
2793                                           SourceLocation Greater);
2794 
2795   void warnOnReservedIdentifier(const NamedDecl *D);
2796 
2797   Decl *ActOnDeclarator(Scope *S, Declarator &D);
2798 
2799   NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
2800                               MultiTemplateParamsArg TemplateParameterLists);
2801   bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
2802                                        QualType &T, SourceLocation Loc,
2803                                        unsigned FailedFoldDiagID);
2804   void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
2805   bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
2806   bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
2807                                     DeclarationName Name, SourceLocation Loc,
2808                                     bool IsTemplateId);
2809   void
2810   diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2811                             SourceLocation FallbackLoc,
2812                             SourceLocation ConstQualLoc = SourceLocation(),
2813                             SourceLocation VolatileQualLoc = SourceLocation(),
2814                             SourceLocation RestrictQualLoc = SourceLocation(),
2815                             SourceLocation AtomicQualLoc = SourceLocation(),
2816                             SourceLocation UnalignedQualLoc = SourceLocation());
2817 
2818   static bool adjustContextForLocalExternDecl(DeclContext *&DC);
2819   void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2820   NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
2821                                     const LookupResult &R);
2822   NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
2823   NamedDecl *getShadowedDeclaration(const BindingDecl *D,
2824                                     const LookupResult &R);
2825   void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2826                    const LookupResult &R);
2827   void CheckShadow(Scope *S, VarDecl *D);
2828 
2829   /// Warn if 'E', which is an expression that is about to be modified, refers
2830   /// to a shadowing declaration.
2831   void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
2832 
2833   void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
2834 
2835 private:
2836   /// Map of current shadowing declarations to shadowed declarations. Warn if
2837   /// it looks like the user is trying to modify the shadowing declaration.
2838   llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2839 
2840 public:
2841   void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2842   void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2843   void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2844                                     TypedefNameDecl *NewTD);
2845   void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
2846   NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2847                                     TypeSourceInfo *TInfo,
2848                                     LookupResult &Previous);
2849   NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
2850                                   LookupResult &Previous, bool &Redeclaration);
2851   NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
2852                                      TypeSourceInfo *TInfo,
2853                                      LookupResult &Previous,
2854                                      MultiTemplateParamsArg TemplateParamLists,
2855                                      bool &AddToScope,
2856                                      ArrayRef<BindingDecl *> Bindings = None);
2857   NamedDecl *
2858   ActOnDecompositionDeclarator(Scope *S, Declarator &D,
2859                                MultiTemplateParamsArg TemplateParamLists);
2860   // Returns true if the variable declaration is a redeclaration
2861   bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
2862   void CheckVariableDeclarationType(VarDecl *NewVD);
2863   bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
2864                                      Expr *Init);
2865   void CheckCompleteVariableDeclaration(VarDecl *VD);
2866   void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
2867   void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
2868 
2869   NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2870                                      TypeSourceInfo *TInfo,
2871                                      LookupResult &Previous,
2872                                      MultiTemplateParamsArg TemplateParamLists,
2873                                      bool &AddToScope);
2874   bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
2875 
2876   enum class CheckConstexprKind {
2877     /// Diagnose issues that are non-constant or that are extensions.
2878     Diagnose,
2879     /// Identify whether this function satisfies the formal rules for constexpr
2880     /// functions in the current lanugage mode (with no extensions).
2881     CheckValid
2882   };
2883 
2884   bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
2885                                         CheckConstexprKind Kind);
2886 
2887   void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
2888   void FindHiddenVirtualMethods(CXXMethodDecl *MD,
2889                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2890   void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
2891                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2892   // Returns true if the function declaration is a redeclaration
2893   bool CheckFunctionDeclaration(Scope *S,
2894                                 FunctionDecl *NewFD, LookupResult &Previous,
2895                                 bool IsMemberSpecialization, bool DeclIsDefn);
2896   bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
2897   bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
2898                                       QualType NewT, QualType OldT);
2899   void CheckMain(FunctionDecl *FD, const DeclSpec &D);
2900   void CheckMSVCRTEntryPoint(FunctionDecl *FD);
2901   Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
2902                                                    bool IsDefinition);
2903   void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
2904   Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
2905   ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
2906                                           SourceLocation Loc,
2907                                           QualType T);
2908   ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
2909                               SourceLocation NameLoc, IdentifierInfo *Name,
2910                               QualType T, TypeSourceInfo *TSInfo,
2911                               StorageClass SC);
2912   void ActOnParamDefaultArgument(Decl *param,
2913                                  SourceLocation EqualLoc,
2914                                  Expr *defarg);
2915   void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc,
2916                                          SourceLocation ArgLoc);
2917   void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
2918   ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2919                                          SourceLocation EqualLoc);
2920   void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2921                                SourceLocation EqualLoc);
2922 
2923   // Contexts where using non-trivial C union types can be disallowed. This is
2924   // passed to err_non_trivial_c_union_in_invalid_context.
2925   enum NonTrivialCUnionContext {
2926     // Function parameter.
2927     NTCUC_FunctionParam,
2928     // Function return.
2929     NTCUC_FunctionReturn,
2930     // Default-initialized object.
2931     NTCUC_DefaultInitializedObject,
2932     // Variable with automatic storage duration.
2933     NTCUC_AutoVar,
2934     // Initializer expression that might copy from another object.
2935     NTCUC_CopyInit,
2936     // Assignment.
2937     NTCUC_Assignment,
2938     // Compound literal.
2939     NTCUC_CompoundLiteral,
2940     // Block capture.
2941     NTCUC_BlockCapture,
2942     // lvalue-to-rvalue conversion of volatile type.
2943     NTCUC_LValueToRValueVolatile,
2944   };
2945 
2946   /// Emit diagnostics if the initializer or any of its explicit or
2947   /// implicitly-generated subexpressions require copying or
2948   /// default-initializing a type that is or contains a C union type that is
2949   /// non-trivial to copy or default-initialize.
2950   void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
2951 
2952   // These flags are passed to checkNonTrivialCUnion.
2953   enum NonTrivialCUnionKind {
2954     NTCUK_Init = 0x1,
2955     NTCUK_Destruct = 0x2,
2956     NTCUK_Copy = 0x4,
2957   };
2958 
2959   /// Emit diagnostics if a non-trivial C union type or a struct that contains
2960   /// a non-trivial C union is used in an invalid context.
2961   void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
2962                              NonTrivialCUnionContext UseContext,
2963                              unsigned NonTrivialKind);
2964 
2965   void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
2966   void ActOnUninitializedDecl(Decl *dcl);
2967   void ActOnInitializerError(Decl *Dcl);
2968 
2969   void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
2970   void ActOnCXXForRangeDecl(Decl *D);
2971   StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
2972                                         IdentifierInfo *Ident,
2973                                         ParsedAttributes &Attrs);
2974   void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
2975   void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
2976   void CheckStaticLocalForDllExport(VarDecl *VD);
2977   void FinalizeDeclaration(Decl *D);
2978   DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
2979                                          ArrayRef<Decl *> Group);
2980   DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
2981 
2982   /// Should be called on all declarations that might have attached
2983   /// documentation comments.
2984   void ActOnDocumentableDecl(Decl *D);
2985   void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
2986 
2987   enum class FnBodyKind {
2988     /// C++ [dcl.fct.def.general]p1
2989     /// function-body:
2990     ///   ctor-initializer[opt] compound-statement
2991     ///   function-try-block
2992     Other,
2993     ///   = default ;
2994     Default,
2995     ///   = delete ;
2996     Delete
2997   };
2998 
2999   void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
3000                                        SourceLocation LocAfterDecls);
3001   void CheckForFunctionRedefinition(
3002       FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
3003       SkipBodyInfo *SkipBody = nullptr);
3004   Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
3005                                 MultiTemplateParamsArg TemplateParamLists,
3006                                 SkipBodyInfo *SkipBody = nullptr,
3007                                 FnBodyKind BodyKind = FnBodyKind::Other);
3008   Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
3009                                 SkipBodyInfo *SkipBody = nullptr,
3010                                 FnBodyKind BodyKind = FnBodyKind::Other);
3011   void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind);
3012   void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D);
3013   ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr);
3014   ExprResult ActOnRequiresClause(ExprResult ConstraintExpr);
3015   void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
3016   bool isObjCMethodDecl(Decl *D) {
3017     return D && isa<ObjCMethodDecl>(D);
3018   }
3019 
3020   /// Determine whether we can delay parsing the body of a function or
3021   /// function template until it is used, assuming we don't care about emitting
3022   /// code for that function.
3023   ///
3024   /// This will be \c false if we may need the body of the function in the
3025   /// middle of parsing an expression (where it's impractical to switch to
3026   /// parsing a different function), for instance, if it's constexpr in C++11
3027   /// or has an 'auto' return type in C++14. These cases are essentially bugs.
3028   bool canDelayFunctionBody(const Declarator &D);
3029 
3030   /// Determine whether we can skip parsing the body of a function
3031   /// definition, assuming we don't care about analyzing its body or emitting
3032   /// code for that function.
3033   ///
3034   /// This will be \c false only if we may need the body of the function in
3035   /// order to parse the rest of the program (for instance, if it is
3036   /// \c constexpr in C++11 or has an 'auto' return type in C++14).
3037   bool canSkipFunctionBody(Decl *D);
3038 
3039   void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
3040   Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
3041   Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
3042   Decl *ActOnSkippedFunctionBody(Decl *Decl);
3043   void ActOnFinishInlineFunctionDef(FunctionDecl *D);
3044 
3045   /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
3046   /// attribute for which parsing is delayed.
3047   void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
3048 
3049   /// Diagnose any unused parameters in the given sequence of
3050   /// ParmVarDecl pointers.
3051   void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
3052 
3053   /// Diagnose whether the size of parameters or return value of a
3054   /// function or obj-c method definition is pass-by-value and larger than a
3055   /// specified threshold.
3056   void
3057   DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
3058                                          QualType ReturnTy, NamedDecl *D);
3059 
3060   void DiagnoseInvalidJumps(Stmt *Body);
3061   Decl *ActOnFileScopeAsmDecl(Expr *expr,
3062                               SourceLocation AsmLoc,
3063                               SourceLocation RParenLoc);
3064 
3065   /// Handle a C++11 empty-declaration and attribute-declaration.
3066   Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
3067                               SourceLocation SemiLoc);
3068 
3069   enum class ModuleDeclKind {
3070     Interface,               ///< 'export module X;'
3071     Implementation,          ///< 'module X;'
3072     PartitionInterface,      ///< 'export module X:Y;'
3073     PartitionImplementation, ///< 'module X:Y;'
3074   };
3075 
3076   /// An enumeration to represent the transition of states in parsing module
3077   /// fragments and imports.  If we are not parsing a C++20 TU, or we find
3078   /// an error in state transition, the state is set to NotACXX20Module.
3079   enum class ModuleImportState {
3080     FirstDecl,       ///< Parsing the first decl in a TU.
3081     GlobalFragment,  ///< after 'module;' but before 'module X;'
3082     ImportAllowed,   ///< after 'module X;' but before any non-import decl.
3083     ImportFinished,  ///< after any non-import decl.
3084     PrivateFragment, ///< after 'module :private;'.
3085     NotACXX20Module  ///< Not a C++20 TU, or an invalid state was found.
3086   };
3087 
3088 private:
3089   /// The parser has begun a translation unit to be compiled as a C++20
3090   /// Header Unit, helper for ActOnStartOfTranslationUnit() only.
3091   void HandleStartOfHeaderUnit();
3092 
3093 public:
3094   /// The parser has processed a module-declaration that begins the definition
3095   /// of a module interface or implementation.
3096   DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
3097                                  SourceLocation ModuleLoc, ModuleDeclKind MDK,
3098                                  ModuleIdPath Path, ModuleIdPath Partition,
3099                                  ModuleImportState &ImportState);
3100 
3101   /// The parser has processed a global-module-fragment declaration that begins
3102   /// the definition of the global module fragment of the current module unit.
3103   /// \param ModuleLoc The location of the 'module' keyword.
3104   DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
3105 
3106   /// The parser has processed a private-module-fragment declaration that begins
3107   /// the definition of the private module fragment of the current module unit.
3108   /// \param ModuleLoc The location of the 'module' keyword.
3109   /// \param PrivateLoc The location of the 'private' keyword.
3110   DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
3111                                                 SourceLocation PrivateLoc);
3112 
3113   /// The parser has processed a module import declaration.
3114   ///
3115   /// \param StartLoc The location of the first token in the declaration. This
3116   ///        could be the location of an '@', 'export', or 'import'.
3117   /// \param ExportLoc The location of the 'export' keyword, if any.
3118   /// \param ImportLoc The location of the 'import' keyword.
3119   /// \param Path The module toplevel name as an access path.
3120   /// \param IsPartition If the name is for a partition.
3121   DeclResult ActOnModuleImport(SourceLocation StartLoc,
3122                                SourceLocation ExportLoc,
3123                                SourceLocation ImportLoc, ModuleIdPath Path,
3124                                bool IsPartition = false);
3125   DeclResult ActOnModuleImport(SourceLocation StartLoc,
3126                                SourceLocation ExportLoc,
3127                                SourceLocation ImportLoc, Module *M,
3128                                ModuleIdPath Path = {});
3129 
3130   /// The parser has processed a module import translated from a
3131   /// #include or similar preprocessing directive.
3132   void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
3133   void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
3134 
3135   /// The parsed has entered a submodule.
3136   void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
3137   /// The parser has left a submodule.
3138   void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
3139 
3140   /// Create an implicit import of the given module at the given
3141   /// source location, for error recovery, if possible.
3142   ///
3143   /// This routine is typically used when an entity found by name lookup
3144   /// is actually hidden within a module that we know about but the user
3145   /// has forgotten to import.
3146   void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
3147                                                   Module *Mod);
3148 
3149   /// Kinds of missing import. Note, the values of these enumerators correspond
3150   /// to %select values in diagnostics.
3151   enum class MissingImportKind {
3152     Declaration,
3153     Definition,
3154     DefaultArgument,
3155     ExplicitSpecialization,
3156     PartialSpecialization
3157   };
3158 
3159   /// Diagnose that the specified declaration needs to be visible but
3160   /// isn't, and suggest a module import that would resolve the problem.
3161   void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
3162                              MissingImportKind MIK, bool Recover = true);
3163   void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
3164                              SourceLocation DeclLoc, ArrayRef<Module *> Modules,
3165                              MissingImportKind MIK, bool Recover);
3166 
3167   Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
3168                              SourceLocation LBraceLoc);
3169   Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
3170                               SourceLocation RBraceLoc);
3171 
3172   /// We've found a use of a templated declaration that would trigger an
3173   /// implicit instantiation. Check that any relevant explicit specializations
3174   /// and partial specializations are visible/reachable, and diagnose if not.
3175   void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
3176   void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec);
3177 
3178   /// Retrieve a suitable printing policy for diagnostics.
3179   PrintingPolicy getPrintingPolicy() const {
3180     return getPrintingPolicy(Context, PP);
3181   }
3182 
3183   /// Retrieve a suitable printing policy for diagnostics.
3184   static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
3185                                           const Preprocessor &PP);
3186 
3187   /// Scope actions.
3188   void ActOnPopScope(SourceLocation Loc, Scope *S);
3189   void ActOnTranslationUnitScope(Scope *S);
3190 
3191   Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3192                                    const ParsedAttributesView &DeclAttrs,
3193                                    RecordDecl *&AnonRecord);
3194   Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3195                                    const ParsedAttributesView &DeclAttrs,
3196                                    MultiTemplateParamsArg TemplateParams,
3197                                    bool IsExplicitInstantiation,
3198                                    RecordDecl *&AnonRecord);
3199 
3200   Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
3201                                     AccessSpecifier AS,
3202                                     RecordDecl *Record,
3203                                     const PrintingPolicy &Policy);
3204 
3205   Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3206                                        RecordDecl *Record);
3207 
3208   /// Common ways to introduce type names without a tag for use in diagnostics.
3209   /// Keep in sync with err_tag_reference_non_tag.
3210   enum NonTagKind {
3211     NTK_NonStruct,
3212     NTK_NonClass,
3213     NTK_NonUnion,
3214     NTK_NonEnum,
3215     NTK_Typedef,
3216     NTK_TypeAlias,
3217     NTK_Template,
3218     NTK_TypeAliasTemplate,
3219     NTK_TemplateTemplateArgument,
3220   };
3221 
3222   /// Given a non-tag type declaration, returns an enum useful for indicating
3223   /// what kind of non-tag type this is.
3224   NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
3225 
3226   bool isAcceptableTagRedeclaration(const TagDecl *Previous,
3227                                     TagTypeKind NewTag, bool isDefinition,
3228                                     SourceLocation NewTagLoc,
3229                                     const IdentifierInfo *Name);
3230 
3231   enum TagUseKind {
3232     TUK_Reference,   // Reference to a tag:  'struct foo *X;'
3233     TUK_Declaration, // Fwd decl of a tag:   'struct foo;'
3234     TUK_Definition,  // Definition of a tag: 'struct foo { int X; } Y;'
3235     TUK_Friend       // Friend declaration:  'friend struct foo;'
3236   };
3237 
3238   Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
3239                  SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
3240                  SourceLocation NameLoc, const ParsedAttributesView &Attr,
3241                  AccessSpecifier AS, SourceLocation ModulePrivateLoc,
3242                  MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
3243                  bool &IsDependent, SourceLocation ScopedEnumKWLoc,
3244                  bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
3245                  bool IsTypeSpecifier, bool IsTemplateParamOrArg,
3246                  SkipBodyInfo *SkipBody = nullptr);
3247 
3248   Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
3249                                 unsigned TagSpec, SourceLocation TagLoc,
3250                                 CXXScopeSpec &SS, IdentifierInfo *Name,
3251                                 SourceLocation NameLoc,
3252                                 const ParsedAttributesView &Attr,
3253                                 MultiTemplateParamsArg TempParamLists);
3254 
3255   TypeResult ActOnDependentTag(Scope *S,
3256                                unsigned TagSpec,
3257                                TagUseKind TUK,
3258                                const CXXScopeSpec &SS,
3259                                IdentifierInfo *Name,
3260                                SourceLocation TagLoc,
3261                                SourceLocation NameLoc);
3262 
3263   void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
3264                  IdentifierInfo *ClassName,
3265                  SmallVectorImpl<Decl *> &Decls);
3266   Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
3267                    Declarator &D, Expr *BitfieldWidth);
3268 
3269   FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
3270                          Declarator &D, Expr *BitfieldWidth,
3271                          InClassInitStyle InitStyle,
3272                          AccessSpecifier AS);
3273   MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
3274                                    SourceLocation DeclStart, Declarator &D,
3275                                    Expr *BitfieldWidth,
3276                                    InClassInitStyle InitStyle,
3277                                    AccessSpecifier AS,
3278                                    const ParsedAttr &MSPropertyAttr);
3279 
3280   FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
3281                             TypeSourceInfo *TInfo,
3282                             RecordDecl *Record, SourceLocation Loc,
3283                             bool Mutable, Expr *BitfieldWidth,
3284                             InClassInitStyle InitStyle,
3285                             SourceLocation TSSL,
3286                             AccessSpecifier AS, NamedDecl *PrevDecl,
3287                             Declarator *D = nullptr);
3288 
3289   bool CheckNontrivialField(FieldDecl *FD);
3290   void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
3291 
3292   enum TrivialABIHandling {
3293     /// The triviality of a method unaffected by "trivial_abi".
3294     TAH_IgnoreTrivialABI,
3295 
3296     /// The triviality of a method affected by "trivial_abi".
3297     TAH_ConsiderTrivialABI
3298   };
3299 
3300   bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
3301                               TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
3302                               bool Diagnose = false);
3303 
3304   /// For a defaulted function, the kind of defaulted function that it is.
3305   class DefaultedFunctionKind {
3306     CXXSpecialMember SpecialMember : 8;
3307     DefaultedComparisonKind Comparison : 8;
3308 
3309   public:
3310     DefaultedFunctionKind()
3311         : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) {
3312     }
3313     DefaultedFunctionKind(CXXSpecialMember CSM)
3314         : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {}
3315     DefaultedFunctionKind(DefaultedComparisonKind Comp)
3316         : SpecialMember(CXXInvalid), Comparison(Comp) {}
3317 
3318     bool isSpecialMember() const { return SpecialMember != CXXInvalid; }
3319     bool isComparison() const {
3320       return Comparison != DefaultedComparisonKind::None;
3321     }
3322 
3323     explicit operator bool() const {
3324       return isSpecialMember() || isComparison();
3325     }
3326 
3327     CXXSpecialMember asSpecialMember() const { return SpecialMember; }
3328     DefaultedComparisonKind asComparison() const { return Comparison; }
3329 
3330     /// Get the index of this function kind for use in diagnostics.
3331     unsigned getDiagnosticIndex() const {
3332       static_assert(CXXInvalid > CXXDestructor,
3333                     "invalid should have highest index");
3334       static_assert((unsigned)DefaultedComparisonKind::None == 0,
3335                     "none should be equal to zero");
3336       return SpecialMember + (unsigned)Comparison;
3337     }
3338   };
3339 
3340   DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
3341 
3342   CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) {
3343     return getDefaultedFunctionKind(MD).asSpecialMember();
3344   }
3345   DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) {
3346     return getDefaultedFunctionKind(FD).asComparison();
3347   }
3348 
3349   void ActOnLastBitfield(SourceLocation DeclStart,
3350                          SmallVectorImpl<Decl *> &AllIvarDecls);
3351   Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
3352                   Declarator &D, Expr *BitfieldWidth,
3353                   tok::ObjCKeywordKind visibility);
3354 
3355   // This is used for both record definitions and ObjC interface declarations.
3356   void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
3357                    ArrayRef<Decl *> Fields, SourceLocation LBrac,
3358                    SourceLocation RBrac, const ParsedAttributesView &AttrList);
3359 
3360   /// ActOnTagStartDefinition - Invoked when we have entered the
3361   /// scope of a tag's definition (e.g., for an enumeration, class,
3362   /// struct, or union).
3363   void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
3364 
3365   /// Perform ODR-like check for C/ObjC when merging tag types from modules.
3366   /// Differently from C++, actually parse the body and reject / error out
3367   /// in case of a structural mismatch.
3368   bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody);
3369 
3370   typedef void *SkippedDefinitionContext;
3371 
3372   /// Invoked when we enter a tag definition that we're skipping.
3373   SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
3374 
3375   void ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl);
3376 
3377   /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
3378   /// C++ record definition's base-specifiers clause and are starting its
3379   /// member declarations.
3380   void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
3381                                        SourceLocation FinalLoc,
3382                                        bool IsFinalSpelledSealed,
3383                                        bool IsAbstract,
3384                                        SourceLocation LBraceLoc);
3385 
3386   /// ActOnTagFinishDefinition - Invoked once we have finished parsing
3387   /// the definition of a tag (enumeration, class, struct, or union).
3388   void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
3389                                 SourceRange BraceRange);
3390 
3391   void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
3392 
3393   void ActOnObjCContainerFinishDefinition();
3394 
3395   /// Invoked when we must temporarily exit the objective-c container
3396   /// scope for parsing/looking-up C constructs.
3397   ///
3398   /// Must be followed by a call to \see ActOnObjCReenterContainerContext
3399   void ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx);
3400   void ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx);
3401 
3402   /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
3403   /// error parsing the definition of a tag.
3404   void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
3405 
3406   EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
3407                                       EnumConstantDecl *LastEnumConst,
3408                                       SourceLocation IdLoc,
3409                                       IdentifierInfo *Id,
3410                                       Expr *val);
3411   bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
3412   bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
3413                               QualType EnumUnderlyingTy, bool IsFixed,
3414                               const EnumDecl *Prev);
3415 
3416   /// Determine whether the body of an anonymous enumeration should be skipped.
3417   /// \param II The name of the first enumerator.
3418   SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
3419                                       SourceLocation IILoc);
3420 
3421   Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
3422                           SourceLocation IdLoc, IdentifierInfo *Id,
3423                           const ParsedAttributesView &Attrs,
3424                           SourceLocation EqualLoc, Expr *Val);
3425   void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
3426                      Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
3427                      const ParsedAttributesView &Attr);
3428 
3429   /// Set the current declaration context until it gets popped.
3430   void PushDeclContext(Scope *S, DeclContext *DC);
3431   void PopDeclContext();
3432 
3433   /// EnterDeclaratorContext - Used when we must lookup names in the context
3434   /// of a declarator's nested name specifier.
3435   void EnterDeclaratorContext(Scope *S, DeclContext *DC);
3436   void ExitDeclaratorContext(Scope *S);
3437 
3438   /// Enter a template parameter scope, after it's been associated with a particular
3439   /// DeclContext. Causes lookup within the scope to chain through enclosing contexts
3440   /// in the correct order.
3441   void EnterTemplatedContext(Scope *S, DeclContext *DC);
3442 
3443   /// Push the parameters of D, which must be a function, into scope.
3444   void ActOnReenterFunctionContext(Scope* S, Decl* D);
3445   void ActOnExitFunctionContext();
3446 
3447   /// If \p AllowLambda is true, treat lambda as function.
3448   DeclContext *getFunctionLevelDeclContext(bool AllowLambda = false);
3449 
3450   /// Returns a pointer to the innermost enclosing function, or nullptr if the
3451   /// current context is not inside a function. If \p AllowLambda is true,
3452   /// this can return the call operator of an enclosing lambda, otherwise
3453   /// lambdas are skipped when looking for an enclosing function.
3454   FunctionDecl *getCurFunctionDecl(bool AllowLambda = false);
3455 
3456   /// getCurMethodDecl - If inside of a method body, this returns a pointer to
3457   /// the method decl for the method being parsed.  If we're currently
3458   /// in a 'block', this returns the containing context.
3459   ObjCMethodDecl *getCurMethodDecl();
3460 
3461   /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
3462   /// or C function we're in, otherwise return null.  If we're currently
3463   /// in a 'block', this returns the containing context.
3464   NamedDecl *getCurFunctionOrMethodDecl();
3465 
3466   /// Add this decl to the scope shadowed decl chains.
3467   void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
3468 
3469   /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
3470   /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
3471   /// true if 'D' belongs to the given declaration context.
3472   ///
3473   /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
3474   ///        enclosing namespace set of the context, rather than contained
3475   ///        directly within it.
3476   bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
3477                      bool AllowInlineNamespace = false);
3478 
3479   /// Finds the scope corresponding to the given decl context, if it
3480   /// happens to be an enclosing scope.  Otherwise return NULL.
3481   static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
3482 
3483   /// Subroutines of ActOnDeclarator().
3484   TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
3485                                 TypeSourceInfo *TInfo);
3486   bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
3487 
3488   /// Describes the kind of merge to perform for availability
3489   /// attributes (including "deprecated", "unavailable", and "availability").
3490   enum AvailabilityMergeKind {
3491     /// Don't merge availability attributes at all.
3492     AMK_None,
3493     /// Merge availability attributes for a redeclaration, which requires
3494     /// an exact match.
3495     AMK_Redeclaration,
3496     /// Merge availability attributes for an override, which requires
3497     /// an exact match or a weakening of constraints.
3498     AMK_Override,
3499     /// Merge availability attributes for an implementation of
3500     /// a protocol requirement.
3501     AMK_ProtocolImplementation,
3502     /// Merge availability attributes for an implementation of
3503     /// an optional protocol requirement.
3504     AMK_OptionalProtocolImplementation
3505   };
3506 
3507   /// Describes the kind of priority given to an availability attribute.
3508   ///
3509   /// The sum of priorities deteremines the final priority of the attribute.
3510   /// The final priority determines how the attribute will be merged.
3511   /// An attribute with a lower priority will always remove higher priority
3512   /// attributes for the specified platform when it is being applied. An
3513   /// attribute with a higher priority will not be applied if the declaration
3514   /// already has an availability attribute with a lower priority for the
3515   /// specified platform. The final prirority values are not expected to match
3516   /// the values in this enumeration, but instead should be treated as a plain
3517   /// integer value. This enumeration just names the priority weights that are
3518   /// used to calculate that final vaue.
3519   enum AvailabilityPriority : int {
3520     /// The availability attribute was specified explicitly next to the
3521     /// declaration.
3522     AP_Explicit = 0,
3523 
3524     /// The availability attribute was applied using '#pragma clang attribute'.
3525     AP_PragmaClangAttribute = 1,
3526 
3527     /// The availability attribute for a specific platform was inferred from
3528     /// an availability attribute for another platform.
3529     AP_InferredFromOtherPlatform = 2
3530   };
3531 
3532   /// Attribute merging methods. Return true if a new attribute was added.
3533   AvailabilityAttr *
3534   mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
3535                         IdentifierInfo *Platform, bool Implicit,
3536                         VersionTuple Introduced, VersionTuple Deprecated,
3537                         VersionTuple Obsoleted, bool IsUnavailable,
3538                         StringRef Message, bool IsStrict, StringRef Replacement,
3539                         AvailabilityMergeKind AMK, int Priority);
3540   TypeVisibilityAttr *
3541   mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3542                           TypeVisibilityAttr::VisibilityType Vis);
3543   VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3544                                       VisibilityAttr::VisibilityType Vis);
3545   UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
3546                           StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
3547   DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
3548   DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
3549   MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
3550                                             const AttributeCommonInfo &CI,
3551                                             bool BestCase,
3552                                             MSInheritanceModel Model);
3553   ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
3554                             StringRef NewUserDiagnostic);
3555   FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
3556                               IdentifierInfo *Format, int FormatIdx,
3557                               int FirstArg);
3558   SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
3559                                 StringRef Name);
3560   CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
3561                                 StringRef Name);
3562   AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
3563                                           const AttributeCommonInfo &CI,
3564                                           const IdentifierInfo *Ident);
3565   MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
3566   SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
3567                                     StringRef Name);
3568   OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
3569                                           const AttributeCommonInfo &CI);
3570   InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
3571   InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
3572                                                 const InternalLinkageAttr &AL);
3573   WebAssemblyImportNameAttr *mergeImportNameAttr(
3574       Decl *D, const WebAssemblyImportNameAttr &AL);
3575   WebAssemblyImportModuleAttr *mergeImportModuleAttr(
3576       Decl *D, const WebAssemblyImportModuleAttr &AL);
3577   EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
3578   EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
3579                                               const EnforceTCBLeafAttr &AL);
3580   BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL);
3581   HLSLNumThreadsAttr *mergeHLSLNumThreadsAttr(Decl *D,
3582                                               const AttributeCommonInfo &AL,
3583                                               int X, int Y, int Z);
3584   HLSLShaderAttr *mergeHLSLShaderAttr(Decl *D, const AttributeCommonInfo &AL,
3585                                       HLSLShaderAttr::ShaderType ShaderType);
3586 
3587   void mergeDeclAttributes(NamedDecl *New, Decl *Old,
3588                            AvailabilityMergeKind AMK = AMK_Redeclaration);
3589   void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
3590                             LookupResult &OldDecls);
3591   bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
3592                          bool MergeTypeWithOld, bool NewDeclIsDefn);
3593   bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3594                                     Scope *S, bool MergeTypeWithOld);
3595   void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
3596   void MergeVarDecl(VarDecl *New, LookupResult &Previous);
3597   void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
3598   void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
3599   bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
3600   void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
3601   bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
3602 
3603   // AssignmentAction - This is used by all the assignment diagnostic functions
3604   // to represent what is actually causing the operation
3605   enum AssignmentAction {
3606     AA_Assigning,
3607     AA_Passing,
3608     AA_Returning,
3609     AA_Converting,
3610     AA_Initializing,
3611     AA_Sending,
3612     AA_Casting,
3613     AA_Passing_CFAudited
3614   };
3615 
3616   /// C++ Overloading.
3617   enum OverloadKind {
3618     /// This is a legitimate overload: the existing declarations are
3619     /// functions or function templates with different signatures.
3620     Ovl_Overload,
3621 
3622     /// This is not an overload because the signature exactly matches
3623     /// an existing declaration.
3624     Ovl_Match,
3625 
3626     /// This is not an overload because the lookup results contain a
3627     /// non-function.
3628     Ovl_NonFunction
3629   };
3630   OverloadKind CheckOverload(Scope *S,
3631                              FunctionDecl *New,
3632                              const LookupResult &OldDecls,
3633                              NamedDecl *&OldDecl,
3634                              bool IsForUsingDecl);
3635   bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
3636                   bool ConsiderCudaAttrs = true,
3637                   bool ConsiderRequiresClauses = true);
3638 
3639   enum class AllowedExplicit {
3640     /// Allow no explicit functions to be used.
3641     None,
3642     /// Allow explicit conversion functions but not explicit constructors.
3643     Conversions,
3644     /// Allow both explicit conversion functions and explicit constructors.
3645     All
3646   };
3647 
3648   ImplicitConversionSequence
3649   TryImplicitConversion(Expr *From, QualType ToType,
3650                         bool SuppressUserConversions,
3651                         AllowedExplicit AllowExplicit,
3652                         bool InOverloadResolution,
3653                         bool CStyle,
3654                         bool AllowObjCWritebackConversion);
3655 
3656   bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
3657   bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
3658   bool IsComplexPromotion(QualType FromType, QualType ToType);
3659   bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
3660                            bool InOverloadResolution,
3661                            QualType& ConvertedType, bool &IncompatibleObjC);
3662   bool isObjCPointerConversion(QualType FromType, QualType ToType,
3663                                QualType& ConvertedType, bool &IncompatibleObjC);
3664   bool isObjCWritebackConversion(QualType FromType, QualType ToType,
3665                                  QualType &ConvertedType);
3666   bool IsBlockPointerConversion(QualType FromType, QualType ToType,
3667                                 QualType& ConvertedType);
3668   bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3669                                   const FunctionProtoType *NewType,
3670                                   unsigned *ArgPos = nullptr,
3671                                   bool Reversed = false);
3672   void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
3673                                   QualType FromType, QualType ToType);
3674 
3675   void maybeExtendBlockObject(ExprResult &E);
3676   CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
3677   bool CheckPointerConversion(Expr *From, QualType ToType,
3678                               CastKind &Kind,
3679                               CXXCastPath& BasePath,
3680                               bool IgnoreBaseAccess,
3681                               bool Diagnose = true);
3682   bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
3683                                  bool InOverloadResolution,
3684                                  QualType &ConvertedType);
3685   bool CheckMemberPointerConversion(Expr *From, QualType ToType,
3686                                     CastKind &Kind,
3687                                     CXXCastPath &BasePath,
3688                                     bool IgnoreBaseAccess);
3689   bool IsQualificationConversion(QualType FromType, QualType ToType,
3690                                  bool CStyle, bool &ObjCLifetimeConversion);
3691   bool IsFunctionConversion(QualType FromType, QualType ToType,
3692                             QualType &ResultTy);
3693   bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
3694   bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg);
3695 
3696   bool CanPerformAggregateInitializationForOverloadResolution(
3697       const InitializedEntity &Entity, InitListExpr *From);
3698 
3699   bool IsStringInit(Expr *Init, const ArrayType *AT);
3700 
3701   bool CanPerformCopyInitialization(const InitializedEntity &Entity,
3702                                     ExprResult Init);
3703   ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
3704                                        SourceLocation EqualLoc,
3705                                        ExprResult Init,
3706                                        bool TopLevelOfInitList = false,
3707                                        bool AllowExplicit = false);
3708   ExprResult PerformObjectArgumentInitialization(Expr *From,
3709                                                  NestedNameSpecifier *Qualifier,
3710                                                  NamedDecl *FoundDecl,
3711                                                  CXXMethodDecl *Method);
3712 
3713   /// Check that the lifetime of the initializer (and its subobjects) is
3714   /// sufficient for initializing the entity, and perform lifetime extension
3715   /// (when permitted) if not.
3716   void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
3717 
3718   ExprResult PerformContextuallyConvertToBool(Expr *From);
3719   ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
3720 
3721   /// Contexts in which a converted constant expression is required.
3722   enum CCEKind {
3723     CCEK_CaseValue,    ///< Expression in a case label.
3724     CCEK_Enumerator,   ///< Enumerator value with fixed underlying type.
3725     CCEK_TemplateArg,  ///< Value of a non-type template parameter.
3726     CCEK_ArrayBound,   ///< Array bound in array declarator or new-expression.
3727     CCEK_ExplicitBool, ///< Condition in an explicit(bool) specifier.
3728     CCEK_Noexcept      ///< Condition in a noexcept(bool) specifier.
3729   };
3730   ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
3731                                               llvm::APSInt &Value, CCEKind CCE);
3732   ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
3733                                               APValue &Value, CCEKind CCE,
3734                                               NamedDecl *Dest = nullptr);
3735 
3736   /// Abstract base class used to perform a contextual implicit
3737   /// conversion from an expression to any type passing a filter.
3738   class ContextualImplicitConverter {
3739   public:
3740     bool Suppress;
3741     bool SuppressConversion;
3742 
3743     ContextualImplicitConverter(bool Suppress = false,
3744                                 bool SuppressConversion = false)
3745         : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
3746 
3747     /// Determine whether the specified type is a valid destination type
3748     /// for this conversion.
3749     virtual bool match(QualType T) = 0;
3750 
3751     /// Emits a diagnostic complaining that the expression does not have
3752     /// integral or enumeration type.
3753     virtual SemaDiagnosticBuilder
3754     diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
3755 
3756     /// Emits a diagnostic when the expression has incomplete class type.
3757     virtual SemaDiagnosticBuilder
3758     diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
3759 
3760     /// Emits a diagnostic when the only matching conversion function
3761     /// is explicit.
3762     virtual SemaDiagnosticBuilder diagnoseExplicitConv(
3763         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3764 
3765     /// Emits a note for the explicit conversion function.
3766     virtual SemaDiagnosticBuilder
3767     noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3768 
3769     /// Emits a diagnostic when there are multiple possible conversion
3770     /// functions.
3771     virtual SemaDiagnosticBuilder
3772     diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
3773 
3774     /// Emits a note for one of the candidate conversions.
3775     virtual SemaDiagnosticBuilder
3776     noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3777 
3778     /// Emits a diagnostic when we picked a conversion function
3779     /// (for cases when we are not allowed to pick a conversion function).
3780     virtual SemaDiagnosticBuilder diagnoseConversion(
3781         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3782 
3783     virtual ~ContextualImplicitConverter() {}
3784   };
3785 
3786   class ICEConvertDiagnoser : public ContextualImplicitConverter {
3787     bool AllowScopedEnumerations;
3788 
3789   public:
3790     ICEConvertDiagnoser(bool AllowScopedEnumerations,
3791                         bool Suppress, bool SuppressConversion)
3792         : ContextualImplicitConverter(Suppress, SuppressConversion),
3793           AllowScopedEnumerations(AllowScopedEnumerations) {}
3794 
3795     /// Match an integral or (possibly scoped) enumeration type.
3796     bool match(QualType T) override;
3797 
3798     SemaDiagnosticBuilder
3799     diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
3800       return diagnoseNotInt(S, Loc, T);
3801     }
3802 
3803     /// Emits a diagnostic complaining that the expression does not have
3804     /// integral or enumeration type.
3805     virtual SemaDiagnosticBuilder
3806     diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
3807   };
3808 
3809   /// Perform a contextual implicit conversion.
3810   ExprResult PerformContextualImplicitConversion(
3811       SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
3812 
3813 
3814   enum ObjCSubscriptKind {
3815     OS_Array,
3816     OS_Dictionary,
3817     OS_Error
3818   };
3819   ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
3820 
3821   // Note that LK_String is intentionally after the other literals, as
3822   // this is used for diagnostics logic.
3823   enum ObjCLiteralKind {
3824     LK_Array,
3825     LK_Dictionary,
3826     LK_Numeric,
3827     LK_Boxed,
3828     LK_String,
3829     LK_Block,
3830     LK_None
3831   };
3832   ObjCLiteralKind CheckLiteralKind(Expr *FromE);
3833 
3834   ExprResult PerformObjectMemberConversion(Expr *From,
3835                                            NestedNameSpecifier *Qualifier,
3836                                            NamedDecl *FoundDecl,
3837                                            NamedDecl *Member);
3838 
3839   // Members have to be NamespaceDecl* or TranslationUnitDecl*.
3840   // TODO: make this is a typesafe union.
3841   typedef llvm::SmallSetVector<DeclContext   *, 16> AssociatedNamespaceSet;
3842   typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
3843 
3844   using ADLCallKind = CallExpr::ADLCallKind;
3845 
3846   void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl,
3847                             ArrayRef<Expr *> Args,
3848                             OverloadCandidateSet &CandidateSet,
3849                             bool SuppressUserConversions = false,
3850                             bool PartialOverloading = false,
3851                             bool AllowExplicit = true,
3852                             bool AllowExplicitConversion = false,
3853                             ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3854                             ConversionSequenceList EarlyConversions = None,
3855                             OverloadCandidateParamOrder PO = {});
3856   void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
3857                       ArrayRef<Expr *> Args,
3858                       OverloadCandidateSet &CandidateSet,
3859                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3860                       bool SuppressUserConversions = false,
3861                       bool PartialOverloading = false,
3862                       bool FirstArgumentIsBase = false);
3863   void AddMethodCandidate(DeclAccessPair FoundDecl,
3864                           QualType ObjectType,
3865                           Expr::Classification ObjectClassification,
3866                           ArrayRef<Expr *> Args,
3867                           OverloadCandidateSet& CandidateSet,
3868                           bool SuppressUserConversion = false,
3869                           OverloadCandidateParamOrder PO = {});
3870   void AddMethodCandidate(CXXMethodDecl *Method,
3871                           DeclAccessPair FoundDecl,
3872                           CXXRecordDecl *ActingContext, QualType ObjectType,
3873                           Expr::Classification ObjectClassification,
3874                           ArrayRef<Expr *> Args,
3875                           OverloadCandidateSet& CandidateSet,
3876                           bool SuppressUserConversions = false,
3877                           bool PartialOverloading = false,
3878                           ConversionSequenceList EarlyConversions = None,
3879                           OverloadCandidateParamOrder PO = {});
3880   void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
3881                                   DeclAccessPair FoundDecl,
3882                                   CXXRecordDecl *ActingContext,
3883                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
3884                                   QualType ObjectType,
3885                                   Expr::Classification ObjectClassification,
3886                                   ArrayRef<Expr *> Args,
3887                                   OverloadCandidateSet& CandidateSet,
3888                                   bool SuppressUserConversions = false,
3889                                   bool PartialOverloading = false,
3890                                   OverloadCandidateParamOrder PO = {});
3891   void AddTemplateOverloadCandidate(
3892       FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3893       TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
3894       OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
3895       bool PartialOverloading = false, bool AllowExplicit = true,
3896       ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3897       OverloadCandidateParamOrder PO = {});
3898   bool CheckNonDependentConversions(
3899       FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
3900       ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
3901       ConversionSequenceList &Conversions, bool SuppressUserConversions,
3902       CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
3903       Expr::Classification ObjectClassification = {},
3904       OverloadCandidateParamOrder PO = {});
3905   void AddConversionCandidate(
3906       CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
3907       CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3908       OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3909       bool AllowExplicit, bool AllowResultConversion = true);
3910   void AddTemplateConversionCandidate(
3911       FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3912       CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3913       OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3914       bool AllowExplicit, bool AllowResultConversion = true);
3915   void AddSurrogateCandidate(CXXConversionDecl *Conversion,
3916                              DeclAccessPair FoundDecl,
3917                              CXXRecordDecl *ActingContext,
3918                              const FunctionProtoType *Proto,
3919                              Expr *Object, ArrayRef<Expr *> Args,
3920                              OverloadCandidateSet& CandidateSet);
3921   void AddNonMemberOperatorCandidates(
3922       const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
3923       OverloadCandidateSet &CandidateSet,
3924       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
3925   void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3926                                    SourceLocation OpLoc, ArrayRef<Expr *> Args,
3927                                    OverloadCandidateSet &CandidateSet,
3928                                    OverloadCandidateParamOrder PO = {});
3929   void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
3930                            OverloadCandidateSet& CandidateSet,
3931                            bool IsAssignmentOperator = false,
3932                            unsigned NumContextualBoolArguments = 0);
3933   void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
3934                                     SourceLocation OpLoc, ArrayRef<Expr *> Args,
3935                                     OverloadCandidateSet& CandidateSet);
3936   void AddArgumentDependentLookupCandidates(DeclarationName Name,
3937                                             SourceLocation Loc,
3938                                             ArrayRef<Expr *> Args,
3939                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
3940                                             OverloadCandidateSet& CandidateSet,
3941                                             bool PartialOverloading = false);
3942 
3943   // Emit as a 'note' the specific overload candidate
3944   void NoteOverloadCandidate(
3945       NamedDecl *Found, FunctionDecl *Fn,
3946       OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(),
3947       QualType DestType = QualType(), bool TakingAddress = false);
3948 
3949   // Emit as a series of 'note's all template and non-templates identified by
3950   // the expression Expr
3951   void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
3952                                  bool TakingAddress = false);
3953 
3954   /// Check the enable_if expressions on the given function. Returns the first
3955   /// failing attribute, or NULL if they were all successful.
3956   EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc,
3957                               ArrayRef<Expr *> Args,
3958                               bool MissingImplicitThis = false);
3959 
3960   /// Find the failed Boolean condition within a given Boolean
3961   /// constant expression, and describe it with a string.
3962   std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
3963 
3964   /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3965   /// non-ArgDependent DiagnoseIfAttrs.
3966   ///
3967   /// Argument-dependent diagnose_if attributes should be checked each time a
3968   /// function is used as a direct callee of a function call.
3969   ///
3970   /// Returns true if any errors were emitted.
3971   bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
3972                                            const Expr *ThisArg,
3973                                            ArrayRef<const Expr *> Args,
3974                                            SourceLocation Loc);
3975 
3976   /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3977   /// ArgDependent DiagnoseIfAttrs.
3978   ///
3979   /// Argument-independent diagnose_if attributes should be checked on every use
3980   /// of a function.
3981   ///
3982   /// Returns true if any errors were emitted.
3983   bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
3984                                              SourceLocation Loc);
3985 
3986   /// Returns whether the given function's address can be taken or not,
3987   /// optionally emitting a diagnostic if the address can't be taken.
3988   ///
3989   /// Returns false if taking the address of the function is illegal.
3990   bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
3991                                          bool Complain = false,
3992                                          SourceLocation Loc = SourceLocation());
3993 
3994   // [PossiblyAFunctionType]  -->   [Return]
3995   // NonFunctionType --> NonFunctionType
3996   // R (A) --> R(A)
3997   // R (*)(A) --> R (A)
3998   // R (&)(A) --> R (A)
3999   // R (S::*)(A) --> R (A)
4000   QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
4001 
4002   FunctionDecl *
4003   ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
4004                                      QualType TargetType,
4005                                      bool Complain,
4006                                      DeclAccessPair &Found,
4007                                      bool *pHadMultipleCandidates = nullptr);
4008 
4009   FunctionDecl *
4010   resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
4011 
4012   bool resolveAndFixAddressOfSingleOverloadCandidate(
4013       ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
4014 
4015   FunctionDecl *
4016   ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
4017                                               bool Complain = false,
4018                                               DeclAccessPair *Found = nullptr);
4019 
4020   bool ResolveAndFixSingleFunctionTemplateSpecialization(
4021                       ExprResult &SrcExpr,
4022                       bool DoFunctionPointerConverion = false,
4023                       bool Complain = false,
4024                       SourceRange OpRangeForComplaining = SourceRange(),
4025                       QualType DestTypeForComplaining = QualType(),
4026                       unsigned DiagIDForComplaining = 0);
4027 
4028 
4029   Expr *FixOverloadedFunctionReference(Expr *E,
4030                                        DeclAccessPair FoundDecl,
4031                                        FunctionDecl *Fn);
4032   ExprResult FixOverloadedFunctionReference(ExprResult,
4033                                             DeclAccessPair FoundDecl,
4034                                             FunctionDecl *Fn);
4035 
4036   void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
4037                                    ArrayRef<Expr *> Args,
4038                                    OverloadCandidateSet &CandidateSet,
4039                                    bool PartialOverloading = false);
4040   void AddOverloadedCallCandidates(
4041       LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
4042       ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet);
4043 
4044   // An enum used to represent the different possible results of building a
4045   // range-based for loop.
4046   enum ForRangeStatus {
4047     FRS_Success,
4048     FRS_NoViableFunction,
4049     FRS_DiagnosticIssued
4050   };
4051 
4052   ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
4053                                            SourceLocation RangeLoc,
4054                                            const DeclarationNameInfo &NameInfo,
4055                                            LookupResult &MemberLookup,
4056                                            OverloadCandidateSet *CandidateSet,
4057                                            Expr *Range, ExprResult *CallExpr);
4058 
4059   ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
4060                                      UnresolvedLookupExpr *ULE,
4061                                      SourceLocation LParenLoc,
4062                                      MultiExprArg Args,
4063                                      SourceLocation RParenLoc,
4064                                      Expr *ExecConfig,
4065                                      bool AllowTypoCorrection=true,
4066                                      bool CalleesAddressIsTaken=false);
4067 
4068   bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
4069                               MultiExprArg Args, SourceLocation RParenLoc,
4070                               OverloadCandidateSet *CandidateSet,
4071                               ExprResult *Result);
4072 
4073   ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
4074                                         NestedNameSpecifierLoc NNSLoc,
4075                                         DeclarationNameInfo DNI,
4076                                         const UnresolvedSetImpl &Fns,
4077                                         bool PerformADL = true);
4078 
4079   ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
4080                                      UnaryOperatorKind Opc,
4081                                      const UnresolvedSetImpl &Fns,
4082                                      Expr *input, bool RequiresADL = true);
4083 
4084   void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
4085                              OverloadedOperatorKind Op,
4086                              const UnresolvedSetImpl &Fns,
4087                              ArrayRef<Expr *> Args, bool RequiresADL = true);
4088   ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
4089                                    BinaryOperatorKind Opc,
4090                                    const UnresolvedSetImpl &Fns,
4091                                    Expr *LHS, Expr *RHS,
4092                                    bool RequiresADL = true,
4093                                    bool AllowRewrittenCandidates = true,
4094                                    FunctionDecl *DefaultedFn = nullptr);
4095   ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc,
4096                                                 const UnresolvedSetImpl &Fns,
4097                                                 Expr *LHS, Expr *RHS,
4098                                                 FunctionDecl *DefaultedFn);
4099 
4100   ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
4101                                                 SourceLocation RLoc, Expr *Base,
4102                                                 MultiExprArg Args);
4103 
4104   ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
4105                                        SourceLocation LParenLoc,
4106                                        MultiExprArg Args,
4107                                        SourceLocation RParenLoc,
4108                                        Expr *ExecConfig = nullptr,
4109                                        bool IsExecConfig = false,
4110                                        bool AllowRecovery = false);
4111   ExprResult
4112   BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
4113                                MultiExprArg Args,
4114                                SourceLocation RParenLoc);
4115 
4116   ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
4117                                       SourceLocation OpLoc,
4118                                       bool *NoArrowOperatorFound = nullptr);
4119 
4120   /// CheckCallReturnType - Checks that a call expression's return type is
4121   /// complete. Returns true on failure. The location passed in is the location
4122   /// that best represents the call.
4123   bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
4124                            CallExpr *CE, FunctionDecl *FD);
4125 
4126   /// Helpers for dealing with blocks and functions.
4127   bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
4128                                 bool CheckParameterNames);
4129   void CheckCXXDefaultArguments(FunctionDecl *FD);
4130   void CheckExtraCXXDefaultArguments(Declarator &D);
4131   Scope *getNonFieldDeclScope(Scope *S);
4132 
4133   /// \name Name lookup
4134   ///
4135   /// These routines provide name lookup that is used during semantic
4136   /// analysis to resolve the various kinds of names (identifiers,
4137   /// overloaded operator names, constructor names, etc.) into zero or
4138   /// more declarations within a particular scope. The major entry
4139   /// points are LookupName, which performs unqualified name lookup,
4140   /// and LookupQualifiedName, which performs qualified name lookup.
4141   ///
4142   /// All name lookup is performed based on some specific criteria,
4143   /// which specify what names will be visible to name lookup and how
4144   /// far name lookup should work. These criteria are important both
4145   /// for capturing language semantics (certain lookups will ignore
4146   /// certain names, for example) and for performance, since name
4147   /// lookup is often a bottleneck in the compilation of C++. Name
4148   /// lookup criteria is specified via the LookupCriteria enumeration.
4149   ///
4150   /// The results of name lookup can vary based on the kind of name
4151   /// lookup performed, the current language, and the translation
4152   /// unit. In C, for example, name lookup will either return nothing
4153   /// (no entity found) or a single declaration. In C++, name lookup
4154   /// can additionally refer to a set of overloaded functions or
4155   /// result in an ambiguity. All of the possible results of name
4156   /// lookup are captured by the LookupResult class, which provides
4157   /// the ability to distinguish among them.
4158   //@{
4159 
4160   /// Describes the kind of name lookup to perform.
4161   enum LookupNameKind {
4162     /// Ordinary name lookup, which finds ordinary names (functions,
4163     /// variables, typedefs, etc.) in C and most kinds of names
4164     /// (functions, variables, members, types, etc.) in C++.
4165     LookupOrdinaryName = 0,
4166     /// Tag name lookup, which finds the names of enums, classes,
4167     /// structs, and unions.
4168     LookupTagName,
4169     /// Label name lookup.
4170     LookupLabel,
4171     /// Member name lookup, which finds the names of
4172     /// class/struct/union members.
4173     LookupMemberName,
4174     /// Look up of an operator name (e.g., operator+) for use with
4175     /// operator overloading. This lookup is similar to ordinary name
4176     /// lookup, but will ignore any declarations that are class members.
4177     LookupOperatorName,
4178     /// Look up a name following ~ in a destructor name. This is an ordinary
4179     /// lookup, but prefers tags to typedefs.
4180     LookupDestructorName,
4181     /// Look up of a name that precedes the '::' scope resolution
4182     /// operator in C++. This lookup completely ignores operator, object,
4183     /// function, and enumerator names (C++ [basic.lookup.qual]p1).
4184     LookupNestedNameSpecifierName,
4185     /// Look up a namespace name within a C++ using directive or
4186     /// namespace alias definition, ignoring non-namespace names (C++
4187     /// [basic.lookup.udir]p1).
4188     LookupNamespaceName,
4189     /// Look up all declarations in a scope with the given name,
4190     /// including resolved using declarations.  This is appropriate
4191     /// for checking redeclarations for a using declaration.
4192     LookupUsingDeclName,
4193     /// Look up an ordinary name that is going to be redeclared as a
4194     /// name with linkage. This lookup ignores any declarations that
4195     /// are outside of the current scope unless they have linkage. See
4196     /// C99 6.2.2p4-5 and C++ [basic.link]p6.
4197     LookupRedeclarationWithLinkage,
4198     /// Look up a friend of a local class. This lookup does not look
4199     /// outside the innermost non-class scope. See C++11 [class.friend]p11.
4200     LookupLocalFriendName,
4201     /// Look up the name of an Objective-C protocol.
4202     LookupObjCProtocolName,
4203     /// Look up implicit 'self' parameter of an objective-c method.
4204     LookupObjCImplicitSelfParam,
4205     /// Look up the name of an OpenMP user-defined reduction operation.
4206     LookupOMPReductionName,
4207     /// Look up the name of an OpenMP user-defined mapper.
4208     LookupOMPMapperName,
4209     /// Look up any declaration with any name.
4210     LookupAnyName
4211   };
4212 
4213   /// Specifies whether (or how) name lookup is being performed for a
4214   /// redeclaration (vs. a reference).
4215   enum RedeclarationKind {
4216     /// The lookup is a reference to this name that is not for the
4217     /// purpose of redeclaring the name.
4218     NotForRedeclaration = 0,
4219     /// The lookup results will be used for redeclaration of a name,
4220     /// if an entity by that name already exists and is visible.
4221     ForVisibleRedeclaration,
4222     /// The lookup results will be used for redeclaration of a name
4223     /// with external linkage; non-visible lookup results with external linkage
4224     /// may also be found.
4225     ForExternalRedeclaration
4226   };
4227 
4228   RedeclarationKind forRedeclarationInCurContext() {
4229     // A declaration with an owning module for linkage can never link against
4230     // anything that is not visible. We don't need to check linkage here; if
4231     // the context has internal linkage, redeclaration lookup won't find things
4232     // from other TUs, and we can't safely compute linkage yet in general.
4233     if (cast<Decl>(CurContext)
4234             ->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
4235       return ForVisibleRedeclaration;
4236     return ForExternalRedeclaration;
4237   }
4238 
4239   /// The possible outcomes of name lookup for a literal operator.
4240   enum LiteralOperatorLookupResult {
4241     /// The lookup resulted in an error.
4242     LOLR_Error,
4243     /// The lookup found no match but no diagnostic was issued.
4244     LOLR_ErrorNoDiagnostic,
4245     /// The lookup found a single 'cooked' literal operator, which
4246     /// expects a normal literal to be built and passed to it.
4247     LOLR_Cooked,
4248     /// The lookup found a single 'raw' literal operator, which expects
4249     /// a string literal containing the spelling of the literal token.
4250     LOLR_Raw,
4251     /// The lookup found an overload set of literal operator templates,
4252     /// which expect the characters of the spelling of the literal token to be
4253     /// passed as a non-type template argument pack.
4254     LOLR_Template,
4255     /// The lookup found an overload set of literal operator templates,
4256     /// which expect the character type and characters of the spelling of the
4257     /// string literal token to be passed as template arguments.
4258     LOLR_StringTemplatePack,
4259   };
4260 
4261   SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
4262                                                   CXXSpecialMember SM,
4263                                                   bool ConstArg,
4264                                                   bool VolatileArg,
4265                                                   bool RValueThis,
4266                                                   bool ConstThis,
4267                                                   bool VolatileThis);
4268 
4269   typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
4270   typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
4271       TypoRecoveryCallback;
4272 
4273 private:
4274   bool CppLookupName(LookupResult &R, Scope *S);
4275 
4276   struct TypoExprState {
4277     std::unique_ptr<TypoCorrectionConsumer> Consumer;
4278     TypoDiagnosticGenerator DiagHandler;
4279     TypoRecoveryCallback RecoveryHandler;
4280     TypoExprState();
4281     TypoExprState(TypoExprState &&other) noexcept;
4282     TypoExprState &operator=(TypoExprState &&other) noexcept;
4283   };
4284 
4285   /// The set of unhandled TypoExprs and their associated state.
4286   llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
4287 
4288   /// Creates a new TypoExpr AST node.
4289   TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
4290                               TypoDiagnosticGenerator TDG,
4291                               TypoRecoveryCallback TRC, SourceLocation TypoLoc);
4292 
4293   // The set of known/encountered (unique, canonicalized) NamespaceDecls.
4294   //
4295   // The boolean value will be true to indicate that the namespace was loaded
4296   // from an AST/PCH file, or false otherwise.
4297   llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
4298 
4299   /// Whether we have already loaded known namespaces from an extenal
4300   /// source.
4301   bool LoadedExternalKnownNamespaces;
4302 
4303   /// Helper for CorrectTypo and CorrectTypoDelayed used to create and
4304   /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
4305   /// should be skipped entirely.
4306   std::unique_ptr<TypoCorrectionConsumer>
4307   makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
4308                              Sema::LookupNameKind LookupKind, Scope *S,
4309                              CXXScopeSpec *SS,
4310                              CorrectionCandidateCallback &CCC,
4311                              DeclContext *MemberContext, bool EnteringContext,
4312                              const ObjCObjectPointerType *OPT,
4313                              bool ErrorRecovery);
4314 
4315 public:
4316   const TypoExprState &getTypoExprState(TypoExpr *TE) const;
4317 
4318   /// Clears the state of the given TypoExpr.
4319   void clearDelayedTypo(TypoExpr *TE);
4320 
4321   /// Look up a name, looking for a single declaration.  Return
4322   /// null if the results were absent, ambiguous, or overloaded.
4323   ///
4324   /// It is preferable to use the elaborated form and explicitly handle
4325   /// ambiguity and overloaded.
4326   NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
4327                               SourceLocation Loc,
4328                               LookupNameKind NameKind,
4329                               RedeclarationKind Redecl
4330                                 = NotForRedeclaration);
4331   bool LookupBuiltin(LookupResult &R);
4332   void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID);
4333   bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false,
4334                   bool ForceNoCPlusPlus = false);
4335   bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
4336                            bool InUnqualifiedLookup = false);
4337   bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
4338                            CXXScopeSpec &SS);
4339   bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
4340                         bool AllowBuiltinCreation = false,
4341                         bool EnteringContext = false);
4342   ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
4343                                    RedeclarationKind Redecl
4344                                      = NotForRedeclaration);
4345   bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
4346 
4347   void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
4348                                     UnresolvedSetImpl &Functions);
4349 
4350   LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
4351                                  SourceLocation GnuLabelLoc = SourceLocation());
4352 
4353   DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
4354   CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
4355   CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
4356                                                unsigned Quals);
4357   CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
4358                                          bool RValueThis, unsigned ThisQuals);
4359   CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
4360                                               unsigned Quals);
4361   CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
4362                                         bool RValueThis, unsigned ThisQuals);
4363   CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
4364 
4365   bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id,
4366                               bool IsUDSuffix);
4367   LiteralOperatorLookupResult
4368   LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys,
4369                         bool AllowRaw, bool AllowTemplate,
4370                         bool AllowStringTemplate, bool DiagnoseMissing,
4371                         StringLiteral *StringLit = nullptr);
4372   bool isKnownName(StringRef name);
4373 
4374   /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
4375   enum class FunctionEmissionStatus {
4376     Emitted,
4377     CUDADiscarded,     // Discarded due to CUDA/HIP hostness
4378     OMPDiscarded,      // Discarded due to OpenMP hostness
4379     TemplateDiscarded, // Discarded due to uninstantiated templates
4380     Unknown,
4381   };
4382   FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl,
4383                                            bool Final = false);
4384 
4385   // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
4386   bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee);
4387 
4388   void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
4389                                ArrayRef<Expr *> Args, ADLResult &Functions);
4390 
4391   void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
4392                           VisibleDeclConsumer &Consumer,
4393                           bool IncludeGlobalScope = true,
4394                           bool LoadExternal = true);
4395   void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
4396                           VisibleDeclConsumer &Consumer,
4397                           bool IncludeGlobalScope = true,
4398                           bool IncludeDependentBases = false,
4399                           bool LoadExternal = true);
4400 
4401   enum CorrectTypoKind {
4402     CTK_NonError,     // CorrectTypo used in a non error recovery situation.
4403     CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
4404   };
4405 
4406   TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
4407                              Sema::LookupNameKind LookupKind,
4408                              Scope *S, CXXScopeSpec *SS,
4409                              CorrectionCandidateCallback &CCC,
4410                              CorrectTypoKind Mode,
4411                              DeclContext *MemberContext = nullptr,
4412                              bool EnteringContext = false,
4413                              const ObjCObjectPointerType *OPT = nullptr,
4414                              bool RecordFailure = true);
4415 
4416   TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
4417                                Sema::LookupNameKind LookupKind, Scope *S,
4418                                CXXScopeSpec *SS,
4419                                CorrectionCandidateCallback &CCC,
4420                                TypoDiagnosticGenerator TDG,
4421                                TypoRecoveryCallback TRC, CorrectTypoKind Mode,
4422                                DeclContext *MemberContext = nullptr,
4423                                bool EnteringContext = false,
4424                                const ObjCObjectPointerType *OPT = nullptr);
4425 
4426   /// Process any TypoExprs in the given Expr and its children,
4427   /// generating diagnostics as appropriate and returning a new Expr if there
4428   /// were typos that were all successfully corrected and ExprError if one or
4429   /// more typos could not be corrected.
4430   ///
4431   /// \param E The Expr to check for TypoExprs.
4432   ///
4433   /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
4434   /// initializer.
4435   ///
4436   /// \param RecoverUncorrectedTypos If true, when typo correction fails, it
4437   /// will rebuild the given Expr with all TypoExprs degraded to RecoveryExprs.
4438   ///
4439   /// \param Filter A function applied to a newly rebuilt Expr to determine if
4440   /// it is an acceptable/usable result from a single combination of typo
4441   /// corrections. As long as the filter returns ExprError, different
4442   /// combinations of corrections will be tried until all are exhausted.
4443   ExprResult CorrectDelayedTyposInExpr(
4444       Expr *E, VarDecl *InitDecl = nullptr,
4445       bool RecoverUncorrectedTypos = false,
4446       llvm::function_ref<ExprResult(Expr *)> Filter =
4447           [](Expr *E) -> ExprResult { return E; });
4448 
4449   ExprResult CorrectDelayedTyposInExpr(
4450       ExprResult ER, VarDecl *InitDecl = nullptr,
4451       bool RecoverUncorrectedTypos = false,
4452       llvm::function_ref<ExprResult(Expr *)> Filter =
4453           [](Expr *E) -> ExprResult { return E; }) {
4454     return ER.isInvalid()
4455                ? ER
4456                : CorrectDelayedTyposInExpr(ER.get(), InitDecl,
4457                                            RecoverUncorrectedTypos, Filter);
4458   }
4459 
4460   void diagnoseTypo(const TypoCorrection &Correction,
4461                     const PartialDiagnostic &TypoDiag,
4462                     bool ErrorRecovery = true);
4463 
4464   void diagnoseTypo(const TypoCorrection &Correction,
4465                     const PartialDiagnostic &TypoDiag,
4466                     const PartialDiagnostic &PrevNote,
4467                     bool ErrorRecovery = true);
4468 
4469   void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
4470 
4471   void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
4472                                           ArrayRef<Expr *> Args,
4473                                    AssociatedNamespaceSet &AssociatedNamespaces,
4474                                    AssociatedClassSet &AssociatedClasses);
4475 
4476   void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
4477                             bool ConsiderLinkage, bool AllowInlineNamespace);
4478 
4479   bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
4480   bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old);
4481   bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old);
4482   bool IsRedefinitionInModule(const NamedDecl *New,
4483                                  const NamedDecl *Old) const;
4484 
4485   void DiagnoseAmbiguousLookup(LookupResult &Result);
4486   //@}
4487 
4488   /// Attempts to produce a RecoveryExpr after some AST node cannot be created.
4489   ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
4490                                 ArrayRef<Expr *> SubExprs,
4491                                 QualType T = QualType());
4492 
4493   ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
4494                                           SourceLocation IdLoc,
4495                                           bool TypoCorrection = false);
4496   FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID,
4497                               SourceLocation Loc);
4498   NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
4499                                  Scope *S, bool ForRedeclaration,
4500                                  SourceLocation Loc);
4501   NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
4502                                       Scope *S);
4503   void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
4504       FunctionDecl *FD);
4505   void AddKnownFunctionAttributes(FunctionDecl *FD);
4506 
4507   // More parsing and symbol table subroutines.
4508 
4509   void ProcessPragmaWeak(Scope *S, Decl *D);
4510   // Decl attributes - this routine is the top level dispatcher.
4511   void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
4512   // Helper for delayed processing of attributes.
4513   void ProcessDeclAttributeDelayed(Decl *D,
4514                                    const ParsedAttributesView &AttrList);
4515 
4516   // Options for ProcessDeclAttributeList().
4517   struct ProcessDeclAttributeOptions {
4518     ProcessDeclAttributeOptions()
4519         : IncludeCXX11Attributes(true), IgnoreTypeAttributes(false) {}
4520 
4521     ProcessDeclAttributeOptions WithIncludeCXX11Attributes(bool Val) {
4522       ProcessDeclAttributeOptions Result = *this;
4523       Result.IncludeCXX11Attributes = Val;
4524       return Result;
4525     }
4526 
4527     ProcessDeclAttributeOptions WithIgnoreTypeAttributes(bool Val) {
4528       ProcessDeclAttributeOptions Result = *this;
4529       Result.IgnoreTypeAttributes = Val;
4530       return Result;
4531     }
4532 
4533     // Should C++11 attributes be processed?
4534     bool IncludeCXX11Attributes;
4535 
4536     // Should any type attributes encountered be ignored?
4537     // If this option is false, a diagnostic will be emitted for any type
4538     // attributes of a kind that does not "slide" from the declaration to
4539     // the decl-specifier-seq.
4540     bool IgnoreTypeAttributes;
4541   };
4542 
4543   void ProcessDeclAttributeList(Scope *S, Decl *D,
4544                                 const ParsedAttributesView &AttrList,
4545                                 const ProcessDeclAttributeOptions &Options =
4546                                     ProcessDeclAttributeOptions());
4547   bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
4548                                    const ParsedAttributesView &AttrList);
4549 
4550   void checkUnusedDeclAttributes(Declarator &D);
4551 
4552   /// Handles semantic checking for features that are common to all attributes,
4553   /// such as checking whether a parameter was properly specified, or the
4554   /// correct number of arguments were passed, etc. Returns true if the
4555   /// attribute has been diagnosed.
4556   bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A,
4557                                     bool SkipArgCountCheck = false);
4558   bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A,
4559                                     bool SkipArgCountCheck = false);
4560 
4561   /// Determine if type T is a valid subject for a nonnull and similar
4562   /// attributes. By default, we look through references (the behavior used by
4563   /// nonnull), but if the second parameter is true, then we treat a reference
4564   /// type as valid.
4565   bool isValidPointerAttrType(QualType T, bool RefOkay = false);
4566 
4567   bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
4568   bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC,
4569                             const FunctionDecl *FD = nullptr);
4570   bool CheckAttrTarget(const ParsedAttr &CurrAttr);
4571   bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
4572   bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI,
4573                                       const Expr *E, StringRef &Str,
4574                                       SourceLocation *ArgLocation = nullptr);
4575   bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
4576                                       StringRef &Str,
4577                                       SourceLocation *ArgLocation = nullptr);
4578   llvm::Error isValidSectionSpecifier(StringRef Str);
4579   bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
4580   bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
4581   bool checkTargetClonesAttrString(SourceLocation LiteralLoc, StringRef Str,
4582                                    const StringLiteral *Literal,
4583                                    bool &HasDefault, bool &HasCommas,
4584                                    SmallVectorImpl<StringRef> &Strings);
4585   bool checkMSInheritanceAttrOnDefinition(
4586       CXXRecordDecl *RD, SourceRange Range, bool BestCase,
4587       MSInheritanceModel SemanticSpelling);
4588 
4589   void CheckAlignasUnderalignment(Decl *D);
4590 
4591   /// Adjust the calling convention of a method to be the ABI default if it
4592   /// wasn't specified explicitly.  This handles method types formed from
4593   /// function type typedefs and typename template arguments.
4594   void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
4595                               SourceLocation Loc);
4596 
4597   // Check if there is an explicit attribute, but only look through parens.
4598   // The intent is to look for an attribute on the current declarator, but not
4599   // one that came from a typedef.
4600   bool hasExplicitCallingConv(QualType T);
4601 
4602   /// Get the outermost AttributedType node that sets a calling convention.
4603   /// Valid types should not have multiple attributes with different CCs.
4604   const AttributedType *getCallingConvAttributedType(QualType T) const;
4605 
4606   /// Process the attributes before creating an attributed statement. Returns
4607   /// the semantic attributes that have been processed.
4608   void ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributes &InAttrs,
4609                              SmallVectorImpl<const Attr *> &OutAttrs);
4610 
4611   void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
4612                                    ObjCMethodDecl *MethodDecl,
4613                                    bool IsProtocolMethodDecl);
4614 
4615   void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
4616                                    ObjCMethodDecl *Overridden,
4617                                    bool IsProtocolMethodDecl);
4618 
4619   /// WarnExactTypedMethods - This routine issues a warning if method
4620   /// implementation declaration matches exactly that of its declaration.
4621   void WarnExactTypedMethods(ObjCMethodDecl *Method,
4622                              ObjCMethodDecl *MethodDecl,
4623                              bool IsProtocolMethodDecl);
4624 
4625   typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
4626 
4627   /// CheckImplementationIvars - This routine checks if the instance variables
4628   /// listed in the implelementation match those listed in the interface.
4629   void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
4630                                 ObjCIvarDecl **Fields, unsigned nIvars,
4631                                 SourceLocation Loc);
4632 
4633   /// ImplMethodsVsClassMethods - This is main routine to warn if any method
4634   /// remains unimplemented in the class or category \@implementation.
4635   void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
4636                                  ObjCContainerDecl* IDecl,
4637                                  bool IncompleteImpl = false);
4638 
4639   /// DiagnoseUnimplementedProperties - This routine warns on those properties
4640   /// which must be implemented by this implementation.
4641   void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
4642                                        ObjCContainerDecl *CDecl,
4643                                        bool SynthesizeProperties);
4644 
4645   /// Diagnose any null-resettable synthesized setters.
4646   void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
4647 
4648   /// DefaultSynthesizeProperties - This routine default synthesizes all
4649   /// properties which must be synthesized in the class's \@implementation.
4650   void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
4651                                    ObjCInterfaceDecl *IDecl,
4652                                    SourceLocation AtEnd);
4653   void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd);
4654 
4655   /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
4656   /// an ivar synthesized for 'Method' and 'Method' is a property accessor
4657   /// declared in class 'IFace'.
4658   bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
4659                                       ObjCMethodDecl *Method, ObjCIvarDecl *IV);
4660 
4661   /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
4662   /// backs the property is not used in the property's accessor.
4663   void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
4664                                            const ObjCImplementationDecl *ImplD);
4665 
4666   /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
4667   /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
4668   /// It also returns ivar's property on success.
4669   ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
4670                                                const ObjCPropertyDecl *&PDecl) const;
4671 
4672   /// Called by ActOnProperty to handle \@property declarations in
4673   /// class extensions.
4674   ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
4675                       SourceLocation AtLoc,
4676                       SourceLocation LParenLoc,
4677                       FieldDeclarator &FD,
4678                       Selector GetterSel,
4679                       SourceLocation GetterNameLoc,
4680                       Selector SetterSel,
4681                       SourceLocation SetterNameLoc,
4682                       const bool isReadWrite,
4683                       unsigned &Attributes,
4684                       const unsigned AttributesAsWritten,
4685                       QualType T,
4686                       TypeSourceInfo *TSI,
4687                       tok::ObjCKeywordKind MethodImplKind);
4688 
4689   /// Called by ActOnProperty and HandlePropertyInClassExtension to
4690   /// handle creating the ObjcPropertyDecl for a category or \@interface.
4691   ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
4692                                        ObjCContainerDecl *CDecl,
4693                                        SourceLocation AtLoc,
4694                                        SourceLocation LParenLoc,
4695                                        FieldDeclarator &FD,
4696                                        Selector GetterSel,
4697                                        SourceLocation GetterNameLoc,
4698                                        Selector SetterSel,
4699                                        SourceLocation SetterNameLoc,
4700                                        const bool isReadWrite,
4701                                        const unsigned Attributes,
4702                                        const unsigned AttributesAsWritten,
4703                                        QualType T,
4704                                        TypeSourceInfo *TSI,
4705                                        tok::ObjCKeywordKind MethodImplKind,
4706                                        DeclContext *lexicalDC = nullptr);
4707 
4708   /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
4709   /// warning) when atomic property has one but not the other user-declared
4710   /// setter or getter.
4711   void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
4712                                        ObjCInterfaceDecl* IDecl);
4713 
4714   void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
4715 
4716   void DiagnoseMissingDesignatedInitOverrides(
4717                                           const ObjCImplementationDecl *ImplD,
4718                                           const ObjCInterfaceDecl *IFD);
4719 
4720   void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
4721 
4722   enum MethodMatchStrategy {
4723     MMS_loose,
4724     MMS_strict
4725   };
4726 
4727   /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
4728   /// true, or false, accordingly.
4729   bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
4730                                   const ObjCMethodDecl *PrevMethod,
4731                                   MethodMatchStrategy strategy = MMS_strict);
4732 
4733   /// MatchAllMethodDeclarations - Check methods declaraed in interface or
4734   /// or protocol against those declared in their implementations.
4735   void MatchAllMethodDeclarations(const SelectorSet &InsMap,
4736                                   const SelectorSet &ClsMap,
4737                                   SelectorSet &InsMapSeen,
4738                                   SelectorSet &ClsMapSeen,
4739                                   ObjCImplDecl* IMPDecl,
4740                                   ObjCContainerDecl* IDecl,
4741                                   bool &IncompleteImpl,
4742                                   bool ImmediateClass,
4743                                   bool WarnCategoryMethodImpl=false);
4744 
4745   /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
4746   /// category matches with those implemented in its primary class and
4747   /// warns each time an exact match is found.
4748   void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
4749 
4750   /// Add the given method to the list of globally-known methods.
4751   void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
4752 
4753   /// Returns default addr space for method qualifiers.
4754   LangAS getDefaultCXXMethodAddrSpace() const;
4755 
4756 private:
4757   /// AddMethodToGlobalPool - Add an instance or factory method to the global
4758   /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
4759   void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
4760 
4761   /// LookupMethodInGlobalPool - Returns the instance or factory method and
4762   /// optionally warns if there are multiple signatures.
4763   ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
4764                                            bool receiverIdOrClass,
4765                                            bool instance);
4766 
4767 public:
4768   /// - Returns instance or factory methods in global method pool for
4769   /// given selector. It checks the desired kind first, if none is found, and
4770   /// parameter checkTheOther is set, it then checks the other kind. If no such
4771   /// method or only one method is found, function returns false; otherwise, it
4772   /// returns true.
4773   bool
4774   CollectMultipleMethodsInGlobalPool(Selector Sel,
4775                                      SmallVectorImpl<ObjCMethodDecl*>& Methods,
4776                                      bool InstanceFirst, bool CheckTheOther,
4777                                      const ObjCObjectType *TypeBound = nullptr);
4778 
4779   bool
4780   AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
4781                                  SourceRange R, bool receiverIdOrClass,
4782                                  SmallVectorImpl<ObjCMethodDecl*>& Methods);
4783 
4784   void
4785   DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
4786                                      Selector Sel, SourceRange R,
4787                                      bool receiverIdOrClass);
4788 
4789 private:
4790   /// - Returns a selector which best matches given argument list or
4791   /// nullptr if none could be found
4792   ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
4793                                    bool IsInstance,
4794                                    SmallVectorImpl<ObjCMethodDecl*>& Methods);
4795 
4796 
4797   /// Record the typo correction failure and return an empty correction.
4798   TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
4799                                   bool RecordFailure = true) {
4800     if (RecordFailure)
4801       TypoCorrectionFailures[Typo].insert(TypoLoc);
4802     return TypoCorrection();
4803   }
4804 
4805 public:
4806   /// AddInstanceMethodToGlobalPool - All instance methods in a translation
4807   /// unit are added to a global pool. This allows us to efficiently associate
4808   /// a selector with a method declaraation for purposes of typechecking
4809   /// messages sent to "id" (where the class of the object is unknown).
4810   void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
4811     AddMethodToGlobalPool(Method, impl, /*instance*/true);
4812   }
4813 
4814   /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
4815   void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
4816     AddMethodToGlobalPool(Method, impl, /*instance*/false);
4817   }
4818 
4819   /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
4820   /// pool.
4821   void AddAnyMethodToGlobalPool(Decl *D);
4822 
4823   /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
4824   /// there are multiple signatures.
4825   ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
4826                                                    bool receiverIdOrClass=false) {
4827     return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
4828                                     /*instance*/true);
4829   }
4830 
4831   /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
4832   /// there are multiple signatures.
4833   ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
4834                                                   bool receiverIdOrClass=false) {
4835     return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
4836                                     /*instance*/false);
4837   }
4838 
4839   const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
4840                               QualType ObjectType=QualType());
4841   /// LookupImplementedMethodInGlobalPool - Returns the method which has an
4842   /// implementation.
4843   ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
4844 
4845   /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
4846   /// initialization.
4847   void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
4848                                   SmallVectorImpl<ObjCIvarDecl*> &Ivars);
4849 
4850   //===--------------------------------------------------------------------===//
4851   // Statement Parsing Callbacks: SemaStmt.cpp.
4852 public:
4853   class FullExprArg {
4854   public:
4855     FullExprArg() : E(nullptr) { }
4856     FullExprArg(Sema &actions) : E(nullptr) { }
4857 
4858     ExprResult release() {
4859       return E;
4860     }
4861 
4862     Expr *get() const { return E; }
4863 
4864     Expr *operator->() {
4865       return E;
4866     }
4867 
4868   private:
4869     // FIXME: No need to make the entire Sema class a friend when it's just
4870     // Sema::MakeFullExpr that needs access to the constructor below.
4871     friend class Sema;
4872 
4873     explicit FullExprArg(Expr *expr) : E(expr) {}
4874 
4875     Expr *E;
4876   };
4877 
4878   FullExprArg MakeFullExpr(Expr *Arg) {
4879     return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
4880   }
4881   FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
4882     return FullExprArg(
4883         ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get());
4884   }
4885   FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
4886     ExprResult FE =
4887         ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
4888                             /*DiscardedValue*/ true);
4889     return FullExprArg(FE.get());
4890   }
4891 
4892   StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
4893   StmtResult ActOnExprStmtError();
4894 
4895   StmtResult ActOnNullStmt(SourceLocation SemiLoc,
4896                            bool HasLeadingEmptyMacro = false);
4897 
4898   void ActOnStartOfCompoundStmt(bool IsStmtExpr);
4899   void ActOnAfterCompoundStatementLeadingPragmas();
4900   void ActOnFinishOfCompoundStmt();
4901   StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
4902                                ArrayRef<Stmt *> Elts, bool isStmtExpr);
4903 
4904   /// A RAII object to enter scope of a compound statement.
4905   class CompoundScopeRAII {
4906   public:
4907     CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
4908       S.ActOnStartOfCompoundStmt(IsStmtExpr);
4909     }
4910 
4911     ~CompoundScopeRAII() {
4912       S.ActOnFinishOfCompoundStmt();
4913     }
4914 
4915   private:
4916     Sema &S;
4917   };
4918 
4919   /// An RAII helper that pops function a function scope on exit.
4920   struct FunctionScopeRAII {
4921     Sema &S;
4922     bool Active;
4923     FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
4924     ~FunctionScopeRAII() {
4925       if (Active)
4926         S.PopFunctionScopeInfo();
4927     }
4928     void disable() { Active = false; }
4929   };
4930 
4931   StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
4932                                    SourceLocation StartLoc,
4933                                    SourceLocation EndLoc);
4934   void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
4935   StmtResult ActOnForEachLValueExpr(Expr *E);
4936   ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
4937   StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
4938                            SourceLocation DotDotDotLoc, ExprResult RHS,
4939                            SourceLocation ColonLoc);
4940   void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
4941 
4942   StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
4943                                       SourceLocation ColonLoc,
4944                                       Stmt *SubStmt, Scope *CurScope);
4945   StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
4946                             SourceLocation ColonLoc, Stmt *SubStmt);
4947 
4948   StmtResult BuildAttributedStmt(SourceLocation AttrsLoc,
4949                                  ArrayRef<const Attr *> Attrs, Stmt *SubStmt);
4950   StmtResult ActOnAttributedStmt(const ParsedAttributes &AttrList,
4951                                  Stmt *SubStmt);
4952 
4953   class ConditionResult;
4954 
4955   StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind,
4956                          SourceLocation LParenLoc, Stmt *InitStmt,
4957                          ConditionResult Cond, SourceLocation RParenLoc,
4958                          Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
4959   StmtResult BuildIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind,
4960                          SourceLocation LParenLoc, Stmt *InitStmt,
4961                          ConditionResult Cond, SourceLocation RParenLoc,
4962                          Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
4963   StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
4964                                     SourceLocation LParenLoc, Stmt *InitStmt,
4965                                     ConditionResult Cond,
4966                                     SourceLocation RParenLoc);
4967   StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
4968                                            Stmt *Switch, Stmt *Body);
4969   StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
4970                             ConditionResult Cond, SourceLocation RParenLoc,
4971                             Stmt *Body);
4972   StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
4973                          SourceLocation WhileLoc, SourceLocation CondLParen,
4974                          Expr *Cond, SourceLocation CondRParen);
4975 
4976   StmtResult ActOnForStmt(SourceLocation ForLoc,
4977                           SourceLocation LParenLoc,
4978                           Stmt *First,
4979                           ConditionResult Second,
4980                           FullExprArg Third,
4981                           SourceLocation RParenLoc,
4982                           Stmt *Body);
4983   ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
4984                                            Expr *collection);
4985   StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
4986                                         Stmt *First, Expr *collection,
4987                                         SourceLocation RParenLoc);
4988   StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
4989 
4990   enum BuildForRangeKind {
4991     /// Initial building of a for-range statement.
4992     BFRK_Build,
4993     /// Instantiation or recovery rebuild of a for-range statement. Don't
4994     /// attempt any typo-correction.
4995     BFRK_Rebuild,
4996     /// Determining whether a for-range statement could be built. Avoid any
4997     /// unnecessary or irreversible actions.
4998     BFRK_Check
4999   };
5000 
5001   StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
5002                                   SourceLocation CoawaitLoc,
5003                                   Stmt *InitStmt,
5004                                   Stmt *LoopVar,
5005                                   SourceLocation ColonLoc, Expr *Collection,
5006                                   SourceLocation RParenLoc,
5007                                   BuildForRangeKind Kind);
5008   StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
5009                                   SourceLocation CoawaitLoc,
5010                                   Stmt *InitStmt,
5011                                   SourceLocation ColonLoc,
5012                                   Stmt *RangeDecl, Stmt *Begin, Stmt *End,
5013                                   Expr *Cond, Expr *Inc,
5014                                   Stmt *LoopVarDecl,
5015                                   SourceLocation RParenLoc,
5016                                   BuildForRangeKind Kind);
5017   StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
5018 
5019   StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
5020                            SourceLocation LabelLoc,
5021                            LabelDecl *TheDecl);
5022   StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
5023                                    SourceLocation StarLoc,
5024                                    Expr *DestExp);
5025   StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
5026   StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
5027 
5028   void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
5029                                 CapturedRegionKind Kind, unsigned NumParams);
5030   typedef std::pair<StringRef, QualType> CapturedParamNameType;
5031   void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
5032                                 CapturedRegionKind Kind,
5033                                 ArrayRef<CapturedParamNameType> Params,
5034                                 unsigned OpenMPCaptureLevel = 0);
5035   StmtResult ActOnCapturedRegionEnd(Stmt *S);
5036   void ActOnCapturedRegionError();
5037   RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
5038                                            SourceLocation Loc,
5039                                            unsigned NumParams);
5040 
5041   struct NamedReturnInfo {
5042     const VarDecl *Candidate;
5043 
5044     enum Status : uint8_t { None, MoveEligible, MoveEligibleAndCopyElidable };
5045     Status S;
5046 
5047     bool isMoveEligible() const { return S != None; };
5048     bool isCopyElidable() const { return S == MoveEligibleAndCopyElidable; }
5049   };
5050   enum class SimplerImplicitMoveMode { ForceOff, Normal, ForceOn };
5051   NamedReturnInfo getNamedReturnInfo(
5052       Expr *&E, SimplerImplicitMoveMode Mode = SimplerImplicitMoveMode::Normal);
5053   NamedReturnInfo getNamedReturnInfo(const VarDecl *VD);
5054   const VarDecl *getCopyElisionCandidate(NamedReturnInfo &Info,
5055                                          QualType ReturnType);
5056 
5057   ExprResult
5058   PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
5059                                   const NamedReturnInfo &NRInfo, Expr *Value,
5060                                   bool SupressSimplerImplicitMoves = false);
5061 
5062   StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
5063                              Scope *CurScope);
5064   StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
5065                              bool AllowRecovery = false);
5066   StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
5067                                      NamedReturnInfo &NRInfo,
5068                                      bool SupressSimplerImplicitMoves);
5069 
5070   StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
5071                              bool IsVolatile, unsigned NumOutputs,
5072                              unsigned NumInputs, IdentifierInfo **Names,
5073                              MultiExprArg Constraints, MultiExprArg Exprs,
5074                              Expr *AsmString, MultiExprArg Clobbers,
5075                              unsigned NumLabels,
5076                              SourceLocation RParenLoc);
5077 
5078   void FillInlineAsmIdentifierInfo(Expr *Res,
5079                                    llvm::InlineAsmIdentifierInfo &Info);
5080   ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
5081                                        SourceLocation TemplateKWLoc,
5082                                        UnqualifiedId &Id,
5083                                        bool IsUnevaluatedContext);
5084   bool LookupInlineAsmField(StringRef Base, StringRef Member,
5085                             unsigned &Offset, SourceLocation AsmLoc);
5086   ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
5087                                          SourceLocation AsmLoc);
5088   StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
5089                             ArrayRef<Token> AsmToks,
5090                             StringRef AsmString,
5091                             unsigned NumOutputs, unsigned NumInputs,
5092                             ArrayRef<StringRef> Constraints,
5093                             ArrayRef<StringRef> Clobbers,
5094                             ArrayRef<Expr*> Exprs,
5095                             SourceLocation EndLoc);
5096   LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
5097                                    SourceLocation Location,
5098                                    bool AlwaysCreate);
5099 
5100   VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
5101                                   SourceLocation StartLoc,
5102                                   SourceLocation IdLoc, IdentifierInfo *Id,
5103                                   bool Invalid = false);
5104 
5105   Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
5106 
5107   StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
5108                                   Decl *Parm, Stmt *Body);
5109 
5110   StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
5111 
5112   StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
5113                                 MultiStmtArg Catch, Stmt *Finally);
5114 
5115   StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
5116   StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
5117                                   Scope *CurScope);
5118   ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
5119                                             Expr *operand);
5120   StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
5121                                          Expr *SynchExpr,
5122                                          Stmt *SynchBody);
5123 
5124   StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
5125 
5126   VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
5127                                      SourceLocation StartLoc,
5128                                      SourceLocation IdLoc,
5129                                      IdentifierInfo *Id);
5130 
5131   Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
5132 
5133   StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
5134                                 Decl *ExDecl, Stmt *HandlerBlock);
5135   StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
5136                               ArrayRef<Stmt *> Handlers);
5137 
5138   StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
5139                               SourceLocation TryLoc, Stmt *TryBlock,
5140                               Stmt *Handler);
5141   StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
5142                                  Expr *FilterExpr,
5143                                  Stmt *Block);
5144   void ActOnStartSEHFinallyBlock();
5145   void ActOnAbortSEHFinallyBlock();
5146   StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
5147   StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
5148 
5149   void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
5150 
5151   bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
5152 
5153   /// If it's a file scoped decl that must warn if not used, keep track
5154   /// of it.
5155   void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
5156 
5157   /// DiagnoseUnusedExprResult - If the statement passed in is an expression
5158   /// whose result is unused, warn.
5159   void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID);
5160   void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
5161   void DiagnoseUnusedDecl(const NamedDecl *ND);
5162 
5163   /// If VD is set but not otherwise used, diagnose, for a parameter or a
5164   /// variable.
5165   void DiagnoseUnusedButSetDecl(const VarDecl *VD);
5166 
5167   /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
5168   /// statement as a \p Body, and it is located on the same line.
5169   ///
5170   /// This helps prevent bugs due to typos, such as:
5171   ///     if (condition);
5172   ///       do_stuff();
5173   void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
5174                              const Stmt *Body,
5175                              unsigned DiagID);
5176 
5177   /// Warn if a for/while loop statement \p S, which is followed by
5178   /// \p PossibleBody, has a suspicious null statement as a body.
5179   void DiagnoseEmptyLoopBody(const Stmt *S,
5180                              const Stmt *PossibleBody);
5181 
5182   /// Warn if a value is moved to itself.
5183   void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
5184                         SourceLocation OpLoc);
5185 
5186   /// Returns a field in a CXXRecordDecl that has the same name as the decl \p
5187   /// SelfAssigned when inside a CXXMethodDecl.
5188   const FieldDecl *
5189   getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned);
5190 
5191   /// Warn if we're implicitly casting from a _Nullable pointer type to a
5192   /// _Nonnull one.
5193   void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
5194                                            SourceLocation Loc);
5195 
5196   /// Warn when implicitly casting 0 to nullptr.
5197   void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
5198 
5199   ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
5200     return DelayedDiagnostics.push(pool);
5201   }
5202   void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
5203 
5204   typedef ProcessingContextState ParsingClassState;
5205   ParsingClassState PushParsingClass() {
5206     ParsingClassDepth++;
5207     return DelayedDiagnostics.pushUndelayed();
5208   }
5209   void PopParsingClass(ParsingClassState state) {
5210     ParsingClassDepth--;
5211     DelayedDiagnostics.popUndelayed(state);
5212   }
5213 
5214   void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
5215 
5216   void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
5217                                   const ObjCInterfaceDecl *UnknownObjCClass,
5218                                   bool ObjCPropertyAccess,
5219                                   bool AvoidPartialAvailabilityChecks = false,
5220                                   ObjCInterfaceDecl *ClassReceiver = nullptr);
5221 
5222   bool makeUnavailableInSystemHeader(SourceLocation loc,
5223                                      UnavailableAttr::ImplicitReason reason);
5224 
5225   /// Issue any -Wunguarded-availability warnings in \c FD
5226   void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
5227 
5228   void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
5229 
5230   //===--------------------------------------------------------------------===//
5231   // Expression Parsing Callbacks: SemaExpr.cpp.
5232 
5233   bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
5234   bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
5235                          const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
5236                          bool ObjCPropertyAccess = false,
5237                          bool AvoidPartialAvailabilityChecks = false,
5238                          ObjCInterfaceDecl *ClassReciever = nullptr);
5239   void NoteDeletedFunction(FunctionDecl *FD);
5240   void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
5241   bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
5242                                         ObjCMethodDecl *Getter,
5243                                         SourceLocation Loc);
5244   void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
5245                              ArrayRef<Expr *> Args);
5246 
5247   void PushExpressionEvaluationContext(
5248       ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
5249       ExpressionEvaluationContextRecord::ExpressionKind Type =
5250           ExpressionEvaluationContextRecord::EK_Other);
5251   enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
5252   void PushExpressionEvaluationContext(
5253       ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
5254       ExpressionEvaluationContextRecord::ExpressionKind Type =
5255           ExpressionEvaluationContextRecord::EK_Other);
5256   void PopExpressionEvaluationContext();
5257 
5258   void DiscardCleanupsInEvaluationContext();
5259 
5260   ExprResult TransformToPotentiallyEvaluated(Expr *E);
5261   TypeSourceInfo *TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo);
5262   ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
5263 
5264   ExprResult CheckUnevaluatedOperand(Expr *E);
5265   void CheckUnusedVolatileAssignment(Expr *E);
5266 
5267   ExprResult ActOnConstantExpression(ExprResult Res);
5268 
5269   // Functions for marking a declaration referenced.  These functions also
5270   // contain the relevant logic for marking if a reference to a function or
5271   // variable is an odr-use (in the C++11 sense).  There are separate variants
5272   // for expressions referring to a decl; these exist because odr-use marking
5273   // needs to be delayed for some constant variables when we build one of the
5274   // named expressions.
5275   //
5276   // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
5277   // should usually be true. This only needs to be set to false if the lack of
5278   // odr-use cannot be determined from the current context (for instance,
5279   // because the name denotes a virtual function and was written without an
5280   // explicit nested-name-specifier).
5281   void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
5282   void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
5283                               bool MightBeOdrUse = true);
5284   void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
5285   void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
5286   void MarkMemberReferenced(MemberExpr *E);
5287   void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E);
5288   void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc,
5289                                          unsigned CapturingScopeIndex);
5290 
5291   ExprResult CheckLValueToRValueConversionOperand(Expr *E);
5292   void CleanupVarDeclMarking();
5293 
5294   enum TryCaptureKind {
5295     TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
5296   };
5297 
5298   /// Try to capture the given variable.
5299   ///
5300   /// \param Var The variable to capture.
5301   ///
5302   /// \param Loc The location at which the capture occurs.
5303   ///
5304   /// \param Kind The kind of capture, which may be implicit (for either a
5305   /// block or a lambda), or explicit by-value or by-reference (for a lambda).
5306   ///
5307   /// \param EllipsisLoc The location of the ellipsis, if one is provided in
5308   /// an explicit lambda capture.
5309   ///
5310   /// \param BuildAndDiagnose Whether we are actually supposed to add the
5311   /// captures or diagnose errors. If false, this routine merely check whether
5312   /// the capture can occur without performing the capture itself or complaining
5313   /// if the variable cannot be captured.
5314   ///
5315   /// \param CaptureType Will be set to the type of the field used to capture
5316   /// this variable in the innermost block or lambda. Only valid when the
5317   /// variable can be captured.
5318   ///
5319   /// \param DeclRefType Will be set to the type of a reference to the capture
5320   /// from within the current scope. Only valid when the variable can be
5321   /// captured.
5322   ///
5323   /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
5324   /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
5325   /// This is useful when enclosing lambdas must speculatively capture
5326   /// variables that may or may not be used in certain specializations of
5327   /// a nested generic lambda.
5328   ///
5329   /// \returns true if an error occurred (i.e., the variable cannot be
5330   /// captured) and false if the capture succeeded.
5331   bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
5332                           SourceLocation EllipsisLoc, bool BuildAndDiagnose,
5333                           QualType &CaptureType,
5334                           QualType &DeclRefType,
5335                           const unsigned *const FunctionScopeIndexToStopAt);
5336 
5337   /// Try to capture the given variable.
5338   bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
5339                           TryCaptureKind Kind = TryCapture_Implicit,
5340                           SourceLocation EllipsisLoc = SourceLocation());
5341 
5342   /// Checks if the variable must be captured.
5343   bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
5344 
5345   /// Given a variable, determine the type that a reference to that
5346   /// variable will have in the given scope.
5347   QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
5348 
5349   /// Mark all of the declarations referenced within a particular AST node as
5350   /// referenced. Used when template instantiation instantiates a non-dependent
5351   /// type -- entities referenced by the type are now referenced.
5352   void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
5353   void MarkDeclarationsReferencedInExpr(Expr *E,
5354                                         bool SkipLocalVariables = false,
5355                                         ArrayRef<const Expr *> StopAt = None);
5356 
5357   /// Try to recover by turning the given expression into a
5358   /// call.  Returns true if recovery was attempted or an error was
5359   /// emitted; this may also leave the ExprResult invalid.
5360   bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
5361                             bool ForceComplain = false,
5362                             bool (*IsPlausibleResult)(QualType) = nullptr);
5363 
5364   /// Figure out if an expression could be turned into a call.
5365   bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
5366                      UnresolvedSetImpl &NonTemplateOverloads);
5367 
5368   /// Try to convert an expression \p E to type \p Ty. Returns the result of the
5369   /// conversion.
5370   ExprResult tryConvertExprToType(Expr *E, QualType Ty);
5371 
5372   /// Conditionally issue a diagnostic based on the statements's reachability
5373   /// analysis.
5374   ///
5375   /// \param Stmts If Stmts is non-empty, delay reporting the diagnostic until
5376   /// the function body is parsed, and then do a basic reachability analysis to
5377   /// determine if the statement is reachable. If it is unreachable, the
5378   /// diagnostic will not be emitted.
5379   bool DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
5380                        const PartialDiagnostic &PD);
5381 
5382   /// Conditionally issue a diagnostic based on the current
5383   /// evaluation context.
5384   ///
5385   /// \param Statement If Statement is non-null, delay reporting the
5386   /// diagnostic until the function body is parsed, and then do a basic
5387   /// reachability analysis to determine if the statement is reachable.
5388   /// If it is unreachable, the diagnostic will not be emitted.
5389   bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
5390                            const PartialDiagnostic &PD);
5391   /// Similar, but diagnostic is only produced if all the specified statements
5392   /// are reachable.
5393   bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
5394                            const PartialDiagnostic &PD);
5395 
5396   // Primary Expressions.
5397   SourceRange getExprRange(Expr *E) const;
5398 
5399   ExprResult ActOnIdExpression(
5400       Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5401       UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
5402       CorrectionCandidateCallback *CCC = nullptr,
5403       bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
5404 
5405   void DecomposeUnqualifiedId(const UnqualifiedId &Id,
5406                               TemplateArgumentListInfo &Buffer,
5407                               DeclarationNameInfo &NameInfo,
5408                               const TemplateArgumentListInfo *&TemplateArgs);
5409 
5410   bool DiagnoseDependentMemberLookup(LookupResult &R);
5411 
5412   bool
5413   DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
5414                       CorrectionCandidateCallback &CCC,
5415                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
5416                       ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
5417 
5418   DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
5419                                     IdentifierInfo *II);
5420   ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV);
5421 
5422   ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
5423                                 IdentifierInfo *II,
5424                                 bool AllowBuiltinCreation=false);
5425 
5426   ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
5427                                         SourceLocation TemplateKWLoc,
5428                                         const DeclarationNameInfo &NameInfo,
5429                                         bool isAddressOfOperand,
5430                                 const TemplateArgumentListInfo *TemplateArgs);
5431 
5432   /// If \p D cannot be odr-used in the current expression evaluation context,
5433   /// return a reason explaining why. Otherwise, return NOUR_None.
5434   NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D);
5435 
5436   DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
5437                                 SourceLocation Loc,
5438                                 const CXXScopeSpec *SS = nullptr);
5439   DeclRefExpr *
5440   BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
5441                    const DeclarationNameInfo &NameInfo,
5442                    const CXXScopeSpec *SS = nullptr,
5443                    NamedDecl *FoundD = nullptr,
5444                    SourceLocation TemplateKWLoc = SourceLocation(),
5445                    const TemplateArgumentListInfo *TemplateArgs = nullptr);
5446   DeclRefExpr *
5447   BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
5448                    const DeclarationNameInfo &NameInfo,
5449                    NestedNameSpecifierLoc NNS,
5450                    NamedDecl *FoundD = nullptr,
5451                    SourceLocation TemplateKWLoc = SourceLocation(),
5452                    const TemplateArgumentListInfo *TemplateArgs = nullptr);
5453 
5454   ExprResult
5455   BuildAnonymousStructUnionMemberReference(
5456       const CXXScopeSpec &SS,
5457       SourceLocation nameLoc,
5458       IndirectFieldDecl *indirectField,
5459       DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
5460       Expr *baseObjectExpr = nullptr,
5461       SourceLocation opLoc = SourceLocation());
5462 
5463   ExprResult BuildPossibleImplicitMemberExpr(
5464       const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R,
5465       const TemplateArgumentListInfo *TemplateArgs, const Scope *S,
5466       UnresolvedLookupExpr *AsULE = nullptr);
5467   ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
5468                                      SourceLocation TemplateKWLoc,
5469                                      LookupResult &R,
5470                                 const TemplateArgumentListInfo *TemplateArgs,
5471                                      bool IsDefiniteInstance,
5472                                      const Scope *S);
5473   bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
5474                                   const LookupResult &R,
5475                                   bool HasTrailingLParen);
5476 
5477   ExprResult
5478   BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
5479                                     const DeclarationNameInfo &NameInfo,
5480                                     bool IsAddressOfOperand, const Scope *S,
5481                                     TypeSourceInfo **RecoveryTSI = nullptr);
5482 
5483   ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
5484                                        SourceLocation TemplateKWLoc,
5485                                 const DeclarationNameInfo &NameInfo,
5486                                 const TemplateArgumentListInfo *TemplateArgs);
5487 
5488   ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
5489                                       LookupResult &R,
5490                                       bool NeedsADL,
5491                                       bool AcceptInvalidDecl = false);
5492   ExprResult BuildDeclarationNameExpr(
5493       const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
5494       NamedDecl *FoundD = nullptr,
5495       const TemplateArgumentListInfo *TemplateArgs = nullptr,
5496       bool AcceptInvalidDecl = false);
5497 
5498   ExprResult BuildLiteralOperatorCall(LookupResult &R,
5499                       DeclarationNameInfo &SuffixInfo,
5500                       ArrayRef<Expr *> Args,
5501                       SourceLocation LitEndLoc,
5502                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
5503 
5504   ExprResult BuildPredefinedExpr(SourceLocation Loc,
5505                                  PredefinedExpr::IdentKind IK);
5506   ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
5507   ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
5508 
5509   ExprResult BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
5510                                            SourceLocation LParen,
5511                                            SourceLocation RParen,
5512                                            TypeSourceInfo *TSI);
5513   ExprResult ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
5514                                            SourceLocation LParen,
5515                                            SourceLocation RParen,
5516                                            ParsedType ParsedTy);
5517 
5518   bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
5519 
5520   ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
5521   ExprResult ActOnCharacterConstant(const Token &Tok,
5522                                     Scope *UDLScope = nullptr);
5523   ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
5524   ExprResult ActOnParenListExpr(SourceLocation L,
5525                                 SourceLocation R,
5526                                 MultiExprArg Val);
5527 
5528   /// ActOnStringLiteral - The specified tokens were lexed as pasted string
5529   /// fragments (e.g. "foo" "bar" L"baz").
5530   ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
5531                                 Scope *UDLScope = nullptr);
5532 
5533   ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
5534                                        SourceLocation DefaultLoc,
5535                                        SourceLocation RParenLoc,
5536                                        Expr *ControllingExpr,
5537                                        ArrayRef<ParsedType> ArgTypes,
5538                                        ArrayRef<Expr *> ArgExprs);
5539   ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
5540                                         SourceLocation DefaultLoc,
5541                                         SourceLocation RParenLoc,
5542                                         Expr *ControllingExpr,
5543                                         ArrayRef<TypeSourceInfo *> Types,
5544                                         ArrayRef<Expr *> Exprs);
5545 
5546   // Binary/Unary Operators.  'Tok' is the token for the operator.
5547   ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
5548                                   Expr *InputExpr);
5549   ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
5550                           UnaryOperatorKind Opc, Expr *Input);
5551   ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5552                           tok::TokenKind Op, Expr *Input);
5553 
5554   bool isQualifiedMemberAccess(Expr *E);
5555   QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
5556 
5557   ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
5558                                             SourceLocation OpLoc,
5559                                             UnaryExprOrTypeTrait ExprKind,
5560                                             SourceRange R);
5561   ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
5562                                             UnaryExprOrTypeTrait ExprKind);
5563   ExprResult
5564     ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
5565                                   UnaryExprOrTypeTrait ExprKind,
5566                                   bool IsType, void *TyOrEx,
5567                                   SourceRange ArgRange);
5568 
5569   ExprResult CheckPlaceholderExpr(Expr *E);
5570   bool CheckVecStepExpr(Expr *E);
5571 
5572   bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
5573   bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
5574                                         SourceRange ExprRange,
5575                                         UnaryExprOrTypeTrait ExprKind);
5576   ExprResult ActOnSizeofParameterPackExpr(Scope *S,
5577                                           SourceLocation OpLoc,
5578                                           IdentifierInfo &Name,
5579                                           SourceLocation NameLoc,
5580                                           SourceLocation RParenLoc);
5581   ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
5582                                  tok::TokenKind Kind, Expr *Input);
5583 
5584   ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
5585                                      MultiExprArg ArgExprs,
5586                                      SourceLocation RLoc);
5587   ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5588                                              Expr *Idx, SourceLocation RLoc);
5589 
5590   ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
5591                                               Expr *ColumnIdx,
5592                                               SourceLocation RBLoc);
5593 
5594   ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
5595                                       Expr *LowerBound,
5596                                       SourceLocation ColonLocFirst,
5597                                       SourceLocation ColonLocSecond,
5598                                       Expr *Length, Expr *Stride,
5599                                       SourceLocation RBLoc);
5600   ExprResult ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5601                                       SourceLocation RParenLoc,
5602                                       ArrayRef<Expr *> Dims,
5603                                       ArrayRef<SourceRange> Brackets);
5604 
5605   /// Data structure for iterator expression.
5606   struct OMPIteratorData {
5607     IdentifierInfo *DeclIdent = nullptr;
5608     SourceLocation DeclIdentLoc;
5609     ParsedType Type;
5610     OMPIteratorExpr::IteratorRange Range;
5611     SourceLocation AssignLoc;
5612     SourceLocation ColonLoc;
5613     SourceLocation SecColonLoc;
5614   };
5615 
5616   ExprResult ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5617                                   SourceLocation LLoc, SourceLocation RLoc,
5618                                   ArrayRef<OMPIteratorData> Data);
5619 
5620   // This struct is for use by ActOnMemberAccess to allow
5621   // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
5622   // changing the access operator from a '.' to a '->' (to see if that is the
5623   // change needed to fix an error about an unknown member, e.g. when the class
5624   // defines a custom operator->).
5625   struct ActOnMemberAccessExtraArgs {
5626     Scope *S;
5627     UnqualifiedId &Id;
5628     Decl *ObjCImpDecl;
5629   };
5630 
5631   ExprResult BuildMemberReferenceExpr(
5632       Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
5633       CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5634       NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
5635       const TemplateArgumentListInfo *TemplateArgs,
5636       const Scope *S,
5637       ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
5638 
5639   ExprResult
5640   BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
5641                            bool IsArrow, const CXXScopeSpec &SS,
5642                            SourceLocation TemplateKWLoc,
5643                            NamedDecl *FirstQualifierInScope, LookupResult &R,
5644                            const TemplateArgumentListInfo *TemplateArgs,
5645                            const Scope *S,
5646                            bool SuppressQualifierCheck = false,
5647                            ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
5648 
5649   ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
5650                                      SourceLocation OpLoc,
5651                                      const CXXScopeSpec &SS, FieldDecl *Field,
5652                                      DeclAccessPair FoundDecl,
5653                                      const DeclarationNameInfo &MemberNameInfo);
5654 
5655   ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
5656 
5657   bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
5658                                      const CXXScopeSpec &SS,
5659                                      const LookupResult &R);
5660 
5661   ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
5662                                       bool IsArrow, SourceLocation OpLoc,
5663                                       const CXXScopeSpec &SS,
5664                                       SourceLocation TemplateKWLoc,
5665                                       NamedDecl *FirstQualifierInScope,
5666                                const DeclarationNameInfo &NameInfo,
5667                                const TemplateArgumentListInfo *TemplateArgs);
5668 
5669   ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
5670                                    SourceLocation OpLoc,
5671                                    tok::TokenKind OpKind,
5672                                    CXXScopeSpec &SS,
5673                                    SourceLocation TemplateKWLoc,
5674                                    UnqualifiedId &Member,
5675                                    Decl *ObjCImpDecl);
5676 
5677   MemberExpr *
5678   BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
5679                   const CXXScopeSpec *SS, SourceLocation TemplateKWLoc,
5680                   ValueDecl *Member, DeclAccessPair FoundDecl,
5681                   bool HadMultipleCandidates,
5682                   const DeclarationNameInfo &MemberNameInfo, QualType Ty,
5683                   ExprValueKind VK, ExprObjectKind OK,
5684                   const TemplateArgumentListInfo *TemplateArgs = nullptr);
5685   MemberExpr *
5686   BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
5687                   NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
5688                   ValueDecl *Member, DeclAccessPair FoundDecl,
5689                   bool HadMultipleCandidates,
5690                   const DeclarationNameInfo &MemberNameInfo, QualType Ty,
5691                   ExprValueKind VK, ExprObjectKind OK,
5692                   const TemplateArgumentListInfo *TemplateArgs = nullptr);
5693 
5694   void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
5695   bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5696                                FunctionDecl *FDecl,
5697                                const FunctionProtoType *Proto,
5698                                ArrayRef<Expr *> Args,
5699                                SourceLocation RParenLoc,
5700                                bool ExecConfig = false);
5701   void CheckStaticArrayArgument(SourceLocation CallLoc,
5702                                 ParmVarDecl *Param,
5703                                 const Expr *ArgExpr);
5704 
5705   /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5706   /// This provides the location of the left/right parens and a list of comma
5707   /// locations.
5708   ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
5709                            MultiExprArg ArgExprs, SourceLocation RParenLoc,
5710                            Expr *ExecConfig = nullptr);
5711   ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
5712                            MultiExprArg ArgExprs, SourceLocation RParenLoc,
5713                            Expr *ExecConfig = nullptr,
5714                            bool IsExecConfig = false,
5715                            bool AllowRecovery = false);
5716   Expr *BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
5717                              MultiExprArg CallArgs);
5718   enum class AtomicArgumentOrder { API, AST };
5719   ExprResult
5720   BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5721                   SourceLocation RParenLoc, MultiExprArg Args,
5722                   AtomicExpr::AtomicOp Op,
5723                   AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API);
5724   ExprResult
5725   BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
5726                         ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
5727                         Expr *Config = nullptr, bool IsExecConfig = false,
5728                         ADLCallKind UsesADL = ADLCallKind::NotADL);
5729 
5730   ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
5731                                      MultiExprArg ExecConfig,
5732                                      SourceLocation GGGLoc);
5733 
5734   ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5735                            Declarator &D, ParsedType &Ty,
5736                            SourceLocation RParenLoc, Expr *CastExpr);
5737   ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
5738                                  TypeSourceInfo *Ty,
5739                                  SourceLocation RParenLoc,
5740                                  Expr *Op);
5741   CastKind PrepareScalarCast(ExprResult &src, QualType destType);
5742 
5743   /// Build an altivec or OpenCL literal.
5744   ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
5745                                 SourceLocation RParenLoc, Expr *E,
5746                                 TypeSourceInfo *TInfo);
5747 
5748   ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
5749 
5750   ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
5751                                   ParsedType Ty,
5752                                   SourceLocation RParenLoc,
5753                                   Expr *InitExpr);
5754 
5755   ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
5756                                       TypeSourceInfo *TInfo,
5757                                       SourceLocation RParenLoc,
5758                                       Expr *LiteralExpr);
5759 
5760   ExprResult ActOnInitList(SourceLocation LBraceLoc,
5761                            MultiExprArg InitArgList,
5762                            SourceLocation RBraceLoc);
5763 
5764   ExprResult BuildInitList(SourceLocation LBraceLoc,
5765                            MultiExprArg InitArgList,
5766                            SourceLocation RBraceLoc);
5767 
5768   ExprResult ActOnDesignatedInitializer(Designation &Desig,
5769                                         SourceLocation EqualOrColonLoc,
5770                                         bool GNUSyntax,
5771                                         ExprResult Init);
5772 
5773 private:
5774   static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
5775 
5776 public:
5777   ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
5778                         tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
5779   ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
5780                         BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
5781   ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
5782                                 Expr *LHSExpr, Expr *RHSExpr);
5783   void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
5784                    UnresolvedSetImpl &Functions);
5785 
5786   void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
5787 
5788   /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
5789   /// in the case of a the GNU conditional expr extension.
5790   ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
5791                                 SourceLocation ColonLoc,
5792                                 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
5793 
5794   /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
5795   ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
5796                             LabelDecl *TheDecl);
5797 
5798   void ActOnStartStmtExpr();
5799   ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
5800                            SourceLocation RPLoc);
5801   ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
5802                            SourceLocation RPLoc, unsigned TemplateDepth);
5803   // Handle the final expression in a statement expression.
5804   ExprResult ActOnStmtExprResult(ExprResult E);
5805   void ActOnStmtExprError();
5806 
5807   // __builtin_offsetof(type, identifier(.identifier|[expr])*)
5808   struct OffsetOfComponent {
5809     SourceLocation LocStart, LocEnd;
5810     bool isBrackets;  // true if [expr], false if .ident
5811     union {
5812       IdentifierInfo *IdentInfo;
5813       Expr *E;
5814     } U;
5815   };
5816 
5817   /// __builtin_offsetof(type, a.b[123][456].c)
5818   ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
5819                                   TypeSourceInfo *TInfo,
5820                                   ArrayRef<OffsetOfComponent> Components,
5821                                   SourceLocation RParenLoc);
5822   ExprResult ActOnBuiltinOffsetOf(Scope *S,
5823                                   SourceLocation BuiltinLoc,
5824                                   SourceLocation TypeLoc,
5825                                   ParsedType ParsedArgTy,
5826                                   ArrayRef<OffsetOfComponent> Components,
5827                                   SourceLocation RParenLoc);
5828 
5829   // __builtin_choose_expr(constExpr, expr1, expr2)
5830   ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
5831                              Expr *CondExpr, Expr *LHSExpr,
5832                              Expr *RHSExpr, SourceLocation RPLoc);
5833 
5834   // __builtin_va_arg(expr, type)
5835   ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
5836                         SourceLocation RPLoc);
5837   ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
5838                             TypeSourceInfo *TInfo, SourceLocation RPLoc);
5839 
5840   // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(),
5841   // __builtin_COLUMN(), __builtin_source_location()
5842   ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
5843                                 SourceLocation BuiltinLoc,
5844                                 SourceLocation RPLoc);
5845 
5846   // Build a potentially resolved SourceLocExpr.
5847   ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
5848                                 QualType ResultTy, SourceLocation BuiltinLoc,
5849                                 SourceLocation RPLoc,
5850                                 DeclContext *ParentContext);
5851 
5852   // __null
5853   ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
5854 
5855   bool CheckCaseExpression(Expr *E);
5856 
5857   /// Describes the result of an "if-exists" condition check.
5858   enum IfExistsResult {
5859     /// The symbol exists.
5860     IER_Exists,
5861 
5862     /// The symbol does not exist.
5863     IER_DoesNotExist,
5864 
5865     /// The name is a dependent name, so the results will differ
5866     /// from one instantiation to the next.
5867     IER_Dependent,
5868 
5869     /// An error occurred.
5870     IER_Error
5871   };
5872 
5873   IfExistsResult
5874   CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
5875                                const DeclarationNameInfo &TargetNameInfo);
5876 
5877   IfExistsResult
5878   CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
5879                                bool IsIfExists, CXXScopeSpec &SS,
5880                                UnqualifiedId &Name);
5881 
5882   StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
5883                                         bool IsIfExists,
5884                                         NestedNameSpecifierLoc QualifierLoc,
5885                                         DeclarationNameInfo NameInfo,
5886                                         Stmt *Nested);
5887   StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
5888                                         bool IsIfExists,
5889                                         CXXScopeSpec &SS, UnqualifiedId &Name,
5890                                         Stmt *Nested);
5891 
5892   //===------------------------- "Block" Extension ------------------------===//
5893 
5894   /// ActOnBlockStart - This callback is invoked when a block literal is
5895   /// started.
5896   void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
5897 
5898   /// ActOnBlockArguments - This callback allows processing of block arguments.
5899   /// If there are no arguments, this is still invoked.
5900   void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
5901                            Scope *CurScope);
5902 
5903   /// ActOnBlockError - If there is an error parsing a block, this callback
5904   /// is invoked to pop the information about the block from the action impl.
5905   void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
5906 
5907   /// ActOnBlockStmtExpr - This is called when the body of a block statement
5908   /// literal was successfully completed.  ^(int x){...}
5909   ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
5910                                 Scope *CurScope);
5911 
5912   //===---------------------------- Clang Extensions ----------------------===//
5913 
5914   /// __builtin_convertvector(...)
5915   ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5916                                     SourceLocation BuiltinLoc,
5917                                     SourceLocation RParenLoc);
5918 
5919   //===---------------------------- OpenCL Features -----------------------===//
5920 
5921   /// __builtin_astype(...)
5922   ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5923                              SourceLocation BuiltinLoc,
5924                              SourceLocation RParenLoc);
5925   ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy,
5926                              SourceLocation BuiltinLoc,
5927                              SourceLocation RParenLoc);
5928 
5929   //===---------------------------- C++ Features --------------------------===//
5930 
5931   // Act on C++ namespaces
5932   Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
5933                                SourceLocation NamespaceLoc,
5934                                SourceLocation IdentLoc, IdentifierInfo *Ident,
5935                                SourceLocation LBrace,
5936                                const ParsedAttributesView &AttrList,
5937                                UsingDirectiveDecl *&UsingDecl);
5938   void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
5939 
5940   NamespaceDecl *getStdNamespace() const;
5941   NamespaceDecl *getOrCreateStdNamespace();
5942 
5943   NamespaceDecl *lookupStdExperimentalNamespace();
5944   NamespaceDecl *getCachedCoroNamespace() { return CoroTraitsNamespaceCache; }
5945 
5946   CXXRecordDecl *getStdBadAlloc() const;
5947   EnumDecl *getStdAlignValT() const;
5948 
5949 private:
5950   // A cache representing if we've fully checked the various comparison category
5951   // types stored in ASTContext. The bit-index corresponds to the integer value
5952   // of a ComparisonCategoryType enumerator.
5953   llvm::SmallBitVector FullyCheckedComparisonCategories;
5954 
5955   ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
5956                                          CXXScopeSpec &SS,
5957                                          ParsedType TemplateTypeTy,
5958                                          IdentifierInfo *MemberOrBase);
5959 
5960 public:
5961   enum class ComparisonCategoryUsage {
5962     /// The '<=>' operator was used in an expression and a builtin operator
5963     /// was selected.
5964     OperatorInExpression,
5965     /// A defaulted 'operator<=>' needed the comparison category. This
5966     /// typically only applies to 'std::strong_ordering', due to the implicit
5967     /// fallback return value.
5968     DefaultedOperator,
5969   };
5970 
5971   /// Lookup the specified comparison category types in the standard
5972   ///   library, an check the VarDecls possibly returned by the operator<=>
5973   ///   builtins for that type.
5974   ///
5975   /// \return The type of the comparison category type corresponding to the
5976   ///   specified Kind, or a null type if an error occurs
5977   QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
5978                                        SourceLocation Loc,
5979                                        ComparisonCategoryUsage Usage);
5980 
5981   /// Tests whether Ty is an instance of std::initializer_list and, if
5982   /// it is and Element is not NULL, assigns the element type to Element.
5983   bool isStdInitializerList(QualType Ty, QualType *Element);
5984 
5985   /// Looks for the std::initializer_list template and instantiates it
5986   /// with Element, or emits an error if it's not found.
5987   ///
5988   /// \returns The instantiated template, or null on error.
5989   QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
5990 
5991   /// Determine whether Ctor is an initializer-list constructor, as
5992   /// defined in [dcl.init.list]p2.
5993   bool isInitListConstructor(const FunctionDecl *Ctor);
5994 
5995   Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
5996                             SourceLocation NamespcLoc, CXXScopeSpec &SS,
5997                             SourceLocation IdentLoc,
5998                             IdentifierInfo *NamespcName,
5999                             const ParsedAttributesView &AttrList);
6000 
6001   void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
6002 
6003   Decl *ActOnNamespaceAliasDef(Scope *CurScope,
6004                                SourceLocation NamespaceLoc,
6005                                SourceLocation AliasLoc,
6006                                IdentifierInfo *Alias,
6007                                CXXScopeSpec &SS,
6008                                SourceLocation IdentLoc,
6009                                IdentifierInfo *Ident);
6010 
6011   void FilterUsingLookup(Scope *S, LookupResult &lookup);
6012   void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
6013   bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target,
6014                             const LookupResult &PreviousDecls,
6015                             UsingShadowDecl *&PrevShadow);
6016   UsingShadowDecl *BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
6017                                         NamedDecl *Target,
6018                                         UsingShadowDecl *PrevDecl);
6019 
6020   bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6021                                    bool HasTypenameKeyword,
6022                                    const CXXScopeSpec &SS,
6023                                    SourceLocation NameLoc,
6024                                    const LookupResult &Previous);
6025   bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
6026                                const CXXScopeSpec &SS,
6027                                const DeclarationNameInfo &NameInfo,
6028                                SourceLocation NameLoc,
6029                                const LookupResult *R = nullptr,
6030                                const UsingDecl *UD = nullptr);
6031 
6032   NamedDecl *BuildUsingDeclaration(
6033       Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
6034       bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
6035       DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
6036       const ParsedAttributesView &AttrList, bool IsInstantiation,
6037       bool IsUsingIfExists);
6038   NamedDecl *BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
6039                                        SourceLocation UsingLoc,
6040                                        SourceLocation EnumLoc,
6041                                        SourceLocation NameLoc, EnumDecl *ED);
6042   NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
6043                                 ArrayRef<NamedDecl *> Expansions);
6044 
6045   bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
6046 
6047   /// Given a derived-class using shadow declaration for a constructor and the
6048   /// correspnding base class constructor, find or create the implicit
6049   /// synthesized derived class constructor to use for this initialization.
6050   CXXConstructorDecl *
6051   findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
6052                             ConstructorUsingShadowDecl *DerivedShadow);
6053 
6054   Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
6055                               SourceLocation UsingLoc,
6056                               SourceLocation TypenameLoc, CXXScopeSpec &SS,
6057                               UnqualifiedId &Name, SourceLocation EllipsisLoc,
6058                               const ParsedAttributesView &AttrList);
6059   Decl *ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS,
6060                                   SourceLocation UsingLoc,
6061                                   SourceLocation EnumLoc, const DeclSpec &);
6062   Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
6063                               MultiTemplateParamsArg TemplateParams,
6064                               SourceLocation UsingLoc, UnqualifiedId &Name,
6065                               const ParsedAttributesView &AttrList,
6066                               TypeResult Type, Decl *DeclFromDeclSpec);
6067 
6068   /// BuildCXXConstructExpr - Creates a complete call to a constructor,
6069   /// including handling of its default argument expressions.
6070   ///
6071   /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
6072   ExprResult
6073   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
6074                         NamedDecl *FoundDecl,
6075                         CXXConstructorDecl *Constructor, MultiExprArg Exprs,
6076                         bool HadMultipleCandidates, bool IsListInitialization,
6077                         bool IsStdInitListInitialization,
6078                         bool RequiresZeroInit, unsigned ConstructKind,
6079                         SourceRange ParenRange);
6080 
6081   /// Build a CXXConstructExpr whose constructor has already been resolved if
6082   /// it denotes an inherited constructor.
6083   ExprResult
6084   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
6085                         CXXConstructorDecl *Constructor, bool Elidable,
6086                         MultiExprArg Exprs,
6087                         bool HadMultipleCandidates, bool IsListInitialization,
6088                         bool IsStdInitListInitialization,
6089                         bool RequiresZeroInit, unsigned ConstructKind,
6090                         SourceRange ParenRange);
6091 
6092   // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
6093   // the constructor can be elidable?
6094   ExprResult
6095   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
6096                         NamedDecl *FoundDecl,
6097                         CXXConstructorDecl *Constructor, bool Elidable,
6098                         MultiExprArg Exprs, bool HadMultipleCandidates,
6099                         bool IsListInitialization,
6100                         bool IsStdInitListInitialization, bool RequiresZeroInit,
6101                         unsigned ConstructKind, SourceRange ParenRange);
6102 
6103   ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
6104 
6105 
6106   /// Instantiate or parse a C++ default argument expression as necessary.
6107   /// Return true on error.
6108   bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
6109                               ParmVarDecl *Param);
6110 
6111   /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
6112   /// the default expr if needed.
6113   ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
6114                                     FunctionDecl *FD,
6115                                     ParmVarDecl *Param);
6116 
6117   /// FinalizeVarWithDestructor - Prepare for calling destructor on the
6118   /// constructed variable.
6119   void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
6120 
6121   /// Helper class that collects exception specifications for
6122   /// implicitly-declared special member functions.
6123   class ImplicitExceptionSpecification {
6124     // Pointer to allow copying
6125     Sema *Self;
6126     // We order exception specifications thus:
6127     // noexcept is the most restrictive, but is only used in C++11.
6128     // throw() comes next.
6129     // Then a throw(collected exceptions)
6130     // Finally no specification, which is expressed as noexcept(false).
6131     // throw(...) is used instead if any called function uses it.
6132     ExceptionSpecificationType ComputedEST;
6133     llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
6134     SmallVector<QualType, 4> Exceptions;
6135 
6136     void ClearExceptions() {
6137       ExceptionsSeen.clear();
6138       Exceptions.clear();
6139     }
6140 
6141   public:
6142     explicit ImplicitExceptionSpecification(Sema &Self)
6143       : Self(&Self), ComputedEST(EST_BasicNoexcept) {
6144       if (!Self.getLangOpts().CPlusPlus11)
6145         ComputedEST = EST_DynamicNone;
6146     }
6147 
6148     /// Get the computed exception specification type.
6149     ExceptionSpecificationType getExceptionSpecType() const {
6150       assert(!isComputedNoexcept(ComputedEST) &&
6151              "noexcept(expr) should not be a possible result");
6152       return ComputedEST;
6153     }
6154 
6155     /// The number of exceptions in the exception specification.
6156     unsigned size() const { return Exceptions.size(); }
6157 
6158     /// The set of exceptions in the exception specification.
6159     const QualType *data() const { return Exceptions.data(); }
6160 
6161     /// Integrate another called method into the collected data.
6162     void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
6163 
6164     /// Integrate an invoked expression into the collected data.
6165     void CalledExpr(Expr *E) { CalledStmt(E); }
6166 
6167     /// Integrate an invoked statement into the collected data.
6168     void CalledStmt(Stmt *S);
6169 
6170     /// Overwrite an EPI's exception specification with this
6171     /// computed exception specification.
6172     FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
6173       FunctionProtoType::ExceptionSpecInfo ESI;
6174       ESI.Type = getExceptionSpecType();
6175       if (ESI.Type == EST_Dynamic) {
6176         ESI.Exceptions = Exceptions;
6177       } else if (ESI.Type == EST_None) {
6178         /// C++11 [except.spec]p14:
6179         ///   The exception-specification is noexcept(false) if the set of
6180         ///   potential exceptions of the special member function contains "any"
6181         ESI.Type = EST_NoexceptFalse;
6182         ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
6183                                                      tok::kw_false).get();
6184       }
6185       return ESI;
6186     }
6187   };
6188 
6189   /// Evaluate the implicit exception specification for a defaulted
6190   /// special member function.
6191   void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD);
6192 
6193   /// Check the given noexcept-specifier, convert its expression, and compute
6194   /// the appropriate ExceptionSpecificationType.
6195   ExprResult ActOnNoexceptSpec(Expr *NoexceptExpr,
6196                                ExceptionSpecificationType &EST);
6197 
6198   /// Check the given exception-specification and update the
6199   /// exception specification information with the results.
6200   void checkExceptionSpecification(bool IsTopLevel,
6201                                    ExceptionSpecificationType EST,
6202                                    ArrayRef<ParsedType> DynamicExceptions,
6203                                    ArrayRef<SourceRange> DynamicExceptionRanges,
6204                                    Expr *NoexceptExpr,
6205                                    SmallVectorImpl<QualType> &Exceptions,
6206                                    FunctionProtoType::ExceptionSpecInfo &ESI);
6207 
6208   /// Determine if we're in a case where we need to (incorrectly) eagerly
6209   /// parse an exception specification to work around a libstdc++ bug.
6210   bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
6211 
6212   /// Add an exception-specification to the given member function
6213   /// (or member function template). The exception-specification was parsed
6214   /// after the method itself was declared.
6215   void actOnDelayedExceptionSpecification(Decl *Method,
6216          ExceptionSpecificationType EST,
6217          SourceRange SpecificationRange,
6218          ArrayRef<ParsedType> DynamicExceptions,
6219          ArrayRef<SourceRange> DynamicExceptionRanges,
6220          Expr *NoexceptExpr);
6221 
6222   class InheritedConstructorInfo;
6223 
6224   /// Determine if a special member function should have a deleted
6225   /// definition when it is defaulted.
6226   bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
6227                                  InheritedConstructorInfo *ICI = nullptr,
6228                                  bool Diagnose = false);
6229 
6230   /// Produce notes explaining why a defaulted function was defined as deleted.
6231   void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD);
6232 
6233   /// Declare the implicit default constructor for the given class.
6234   ///
6235   /// \param ClassDecl The class declaration into which the implicit
6236   /// default constructor will be added.
6237   ///
6238   /// \returns The implicitly-declared default constructor.
6239   CXXConstructorDecl *DeclareImplicitDefaultConstructor(
6240                                                      CXXRecordDecl *ClassDecl);
6241 
6242   /// DefineImplicitDefaultConstructor - Checks for feasibility of
6243   /// defining this constructor as the default constructor.
6244   void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6245                                         CXXConstructorDecl *Constructor);
6246 
6247   /// Declare the implicit destructor for the given class.
6248   ///
6249   /// \param ClassDecl The class declaration into which the implicit
6250   /// destructor will be added.
6251   ///
6252   /// \returns The implicitly-declared destructor.
6253   CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
6254 
6255   /// DefineImplicitDestructor - Checks for feasibility of
6256   /// defining this destructor as the default destructor.
6257   void DefineImplicitDestructor(SourceLocation CurrentLocation,
6258                                 CXXDestructorDecl *Destructor);
6259 
6260   /// Build an exception spec for destructors that don't have one.
6261   ///
6262   /// C++11 says that user-defined destructors with no exception spec get one
6263   /// that looks as if the destructor was implicitly declared.
6264   void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor);
6265 
6266   /// Define the specified inheriting constructor.
6267   void DefineInheritingConstructor(SourceLocation UseLoc,
6268                                    CXXConstructorDecl *Constructor);
6269 
6270   /// Declare the implicit copy constructor for the given class.
6271   ///
6272   /// \param ClassDecl The class declaration into which the implicit
6273   /// copy constructor will be added.
6274   ///
6275   /// \returns The implicitly-declared copy constructor.
6276   CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
6277 
6278   /// DefineImplicitCopyConstructor - Checks for feasibility of
6279   /// defining this constructor as the copy constructor.
6280   void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
6281                                      CXXConstructorDecl *Constructor);
6282 
6283   /// Declare the implicit move constructor for the given class.
6284   ///
6285   /// \param ClassDecl The Class declaration into which the implicit
6286   /// move constructor will be added.
6287   ///
6288   /// \returns The implicitly-declared move constructor, or NULL if it wasn't
6289   /// declared.
6290   CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
6291 
6292   /// DefineImplicitMoveConstructor - Checks for feasibility of
6293   /// defining this constructor as the move constructor.
6294   void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
6295                                      CXXConstructorDecl *Constructor);
6296 
6297   /// Declare the implicit copy assignment operator for the given class.
6298   ///
6299   /// \param ClassDecl The class declaration into which the implicit
6300   /// copy assignment operator will be added.
6301   ///
6302   /// \returns The implicitly-declared copy assignment operator.
6303   CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
6304 
6305   /// Defines an implicitly-declared copy assignment operator.
6306   void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
6307                                     CXXMethodDecl *MethodDecl);
6308 
6309   /// Declare the implicit move assignment operator for the given class.
6310   ///
6311   /// \param ClassDecl The Class declaration into which the implicit
6312   /// move assignment operator will be added.
6313   ///
6314   /// \returns The implicitly-declared move assignment operator, or NULL if it
6315   /// wasn't declared.
6316   CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
6317 
6318   /// Defines an implicitly-declared move assignment operator.
6319   void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
6320                                     CXXMethodDecl *MethodDecl);
6321 
6322   /// Force the declaration of any implicitly-declared members of this
6323   /// class.
6324   void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
6325 
6326   /// Check a completed declaration of an implicit special member.
6327   void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
6328 
6329   /// Determine whether the given function is an implicitly-deleted
6330   /// special member function.
6331   bool isImplicitlyDeleted(FunctionDecl *FD);
6332 
6333   /// Check whether 'this' shows up in the type of a static member
6334   /// function after the (naturally empty) cv-qualifier-seq would be.
6335   ///
6336   /// \returns true if an error occurred.
6337   bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
6338 
6339   /// Whether this' shows up in the exception specification of a static
6340   /// member function.
6341   bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
6342 
6343   /// Check whether 'this' shows up in the attributes of the given
6344   /// static member function.
6345   ///
6346   /// \returns true if an error occurred.
6347   bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
6348 
6349   /// MaybeBindToTemporary - If the passed in expression has a record type with
6350   /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
6351   /// it simply returns the passed in expression.
6352   ExprResult MaybeBindToTemporary(Expr *E);
6353 
6354   /// Wrap the expression in a ConstantExpr if it is a potential immediate
6355   /// invocation.
6356   ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl);
6357 
6358   bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
6359                                QualType DeclInitType, MultiExprArg ArgsPtr,
6360                                SourceLocation Loc,
6361                                SmallVectorImpl<Expr *> &ConvertedArgs,
6362                                bool AllowExplicit = false,
6363                                bool IsListInitialization = false);
6364 
6365   ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
6366                                           SourceLocation NameLoc,
6367                                           IdentifierInfo &Name);
6368 
6369   ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc,
6370                                 Scope *S, CXXScopeSpec &SS,
6371                                 bool EnteringContext);
6372   ParsedType getDestructorName(SourceLocation TildeLoc,
6373                                IdentifierInfo &II, SourceLocation NameLoc,
6374                                Scope *S, CXXScopeSpec &SS,
6375                                ParsedType ObjectType,
6376                                bool EnteringContext);
6377 
6378   ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
6379                                           ParsedType ObjectType);
6380 
6381   // Checks that reinterpret casts don't have undefined behavior.
6382   void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
6383                                       bool IsDereference, SourceRange Range);
6384 
6385   // Checks that the vector type should be initialized from a scalar
6386   // by splatting the value rather than populating a single element.
6387   // This is the case for AltiVecVector types as well as with
6388   // AltiVecPixel and AltiVecBool when -faltivec-src-compat=xl is specified.
6389   bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy);
6390 
6391   // Checks if the -faltivec-src-compat=gcc option is specified.
6392   // If so, AltiVecVector, AltiVecBool and AltiVecPixel types are
6393   // treated the same way as they are when trying to initialize
6394   // these vectors on gcc (an error is emitted).
6395   bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy,
6396                                   QualType SrcTy);
6397 
6398   /// ActOnCXXNamedCast - Parse
6399   /// {dynamic,static,reinterpret,const,addrspace}_cast's.
6400   ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
6401                                tok::TokenKind Kind,
6402                                SourceLocation LAngleBracketLoc,
6403                                Declarator &D,
6404                                SourceLocation RAngleBracketLoc,
6405                                SourceLocation LParenLoc,
6406                                Expr *E,
6407                                SourceLocation RParenLoc);
6408 
6409   ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
6410                                tok::TokenKind Kind,
6411                                TypeSourceInfo *Ty,
6412                                Expr *E,
6413                                SourceRange AngleBrackets,
6414                                SourceRange Parens);
6415 
6416   ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl,
6417                                      ExprResult Operand,
6418                                      SourceLocation RParenLoc);
6419 
6420   ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI,
6421                                      Expr *Operand, SourceLocation RParenLoc);
6422 
6423   ExprResult BuildCXXTypeId(QualType TypeInfoType,
6424                             SourceLocation TypeidLoc,
6425                             TypeSourceInfo *Operand,
6426                             SourceLocation RParenLoc);
6427   ExprResult BuildCXXTypeId(QualType TypeInfoType,
6428                             SourceLocation TypeidLoc,
6429                             Expr *Operand,
6430                             SourceLocation RParenLoc);
6431 
6432   /// ActOnCXXTypeid - Parse typeid( something ).
6433   ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
6434                             SourceLocation LParenLoc, bool isType,
6435                             void *TyOrExpr,
6436                             SourceLocation RParenLoc);
6437 
6438   ExprResult BuildCXXUuidof(QualType TypeInfoType,
6439                             SourceLocation TypeidLoc,
6440                             TypeSourceInfo *Operand,
6441                             SourceLocation RParenLoc);
6442   ExprResult BuildCXXUuidof(QualType TypeInfoType,
6443                             SourceLocation TypeidLoc,
6444                             Expr *Operand,
6445                             SourceLocation RParenLoc);
6446 
6447   /// ActOnCXXUuidof - Parse __uuidof( something ).
6448   ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
6449                             SourceLocation LParenLoc, bool isType,
6450                             void *TyOrExpr,
6451                             SourceLocation RParenLoc);
6452 
6453   /// Handle a C++1z fold-expression: ( expr op ... op expr ).
6454   ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS,
6455                               tok::TokenKind Operator,
6456                               SourceLocation EllipsisLoc, Expr *RHS,
6457                               SourceLocation RParenLoc);
6458   ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee,
6459                               SourceLocation LParenLoc, Expr *LHS,
6460                               BinaryOperatorKind Operator,
6461                               SourceLocation EllipsisLoc, Expr *RHS,
6462                               SourceLocation RParenLoc,
6463                               Optional<unsigned> NumExpansions);
6464   ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
6465                                    BinaryOperatorKind Operator);
6466 
6467   //// ActOnCXXThis -  Parse 'this' pointer.
6468   ExprResult ActOnCXXThis(SourceLocation loc);
6469 
6470   /// Build a CXXThisExpr and mark it referenced in the current context.
6471   Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
6472   void MarkThisReferenced(CXXThisExpr *This);
6473 
6474   /// Try to retrieve the type of the 'this' pointer.
6475   ///
6476   /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
6477   QualType getCurrentThisType();
6478 
6479   /// When non-NULL, the C++ 'this' expression is allowed despite the
6480   /// current context not being a non-static member function. In such cases,
6481   /// this provides the type used for 'this'.
6482   QualType CXXThisTypeOverride;
6483 
6484   /// RAII object used to temporarily allow the C++ 'this' expression
6485   /// to be used, with the given qualifiers on the current class type.
6486   class CXXThisScopeRAII {
6487     Sema &S;
6488     QualType OldCXXThisTypeOverride;
6489     bool Enabled;
6490 
6491   public:
6492     /// Introduce a new scope where 'this' may be allowed (when enabled),
6493     /// using the given declaration (which is either a class template or a
6494     /// class) along with the given qualifiers.
6495     /// along with the qualifiers placed on '*this'.
6496     CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
6497                      bool Enabled = true);
6498 
6499     ~CXXThisScopeRAII();
6500   };
6501 
6502   /// Make sure the value of 'this' is actually available in the current
6503   /// context, if it is a potentially evaluated context.
6504   ///
6505   /// \param Loc The location at which the capture of 'this' occurs.
6506   ///
6507   /// \param Explicit Whether 'this' is explicitly captured in a lambda
6508   /// capture list.
6509   ///
6510   /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
6511   /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
6512   /// This is useful when enclosing lambdas must speculatively capture
6513   /// 'this' that may or may not be used in certain specializations of
6514   /// a nested generic lambda (depending on whether the name resolves to
6515   /// a non-static member function or a static function).
6516   /// \return returns 'true' if failed, 'false' if success.
6517   bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
6518       bool BuildAndDiagnose = true,
6519       const unsigned *const FunctionScopeIndexToStopAt = nullptr,
6520       bool ByCopy = false);
6521 
6522   /// Determine whether the given type is the type of *this that is used
6523   /// outside of the body of a member function for a type that is currently
6524   /// being defined.
6525   bool isThisOutsideMemberFunctionBody(QualType BaseType);
6526 
6527   /// ActOnCXXBoolLiteral - Parse {true,false} literals.
6528   ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
6529 
6530 
6531   /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
6532   ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
6533 
6534   ExprResult
6535   ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
6536                                  SourceLocation AtLoc, SourceLocation RParen);
6537 
6538   /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
6539   ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
6540 
6541   //// ActOnCXXThrow -  Parse throw expressions.
6542   ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
6543   ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
6544                            bool IsThrownVarInScope);
6545   bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
6546 
6547   /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
6548   /// Can be interpreted either as function-style casting ("int(x)")
6549   /// or class type construction ("ClassType(x,y,z)")
6550   /// or creation of a value-initialized type ("int()").
6551   ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
6552                                        SourceLocation LParenOrBraceLoc,
6553                                        MultiExprArg Exprs,
6554                                        SourceLocation RParenOrBraceLoc,
6555                                        bool ListInitialization);
6556 
6557   ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
6558                                        SourceLocation LParenLoc,
6559                                        MultiExprArg Exprs,
6560                                        SourceLocation RParenLoc,
6561                                        bool ListInitialization);
6562 
6563   /// ActOnCXXNew - Parsed a C++ 'new' expression.
6564   ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
6565                          SourceLocation PlacementLParen,
6566                          MultiExprArg PlacementArgs,
6567                          SourceLocation PlacementRParen,
6568                          SourceRange TypeIdParens, Declarator &D,
6569                          Expr *Initializer);
6570   ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
6571                          SourceLocation PlacementLParen,
6572                          MultiExprArg PlacementArgs,
6573                          SourceLocation PlacementRParen,
6574                          SourceRange TypeIdParens,
6575                          QualType AllocType,
6576                          TypeSourceInfo *AllocTypeInfo,
6577                          Optional<Expr *> ArraySize,
6578                          SourceRange DirectInitRange,
6579                          Expr *Initializer);
6580 
6581   /// Determine whether \p FD is an aligned allocation or deallocation
6582   /// function that is unavailable.
6583   bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const;
6584 
6585   /// Produce diagnostics if \p FD is an aligned allocation or deallocation
6586   /// function that is unavailable.
6587   void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
6588                                             SourceLocation Loc);
6589 
6590   bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
6591                           SourceRange R);
6592 
6593   /// The scope in which to find allocation functions.
6594   enum AllocationFunctionScope {
6595     /// Only look for allocation functions in the global scope.
6596     AFS_Global,
6597     /// Only look for allocation functions in the scope of the
6598     /// allocated class.
6599     AFS_Class,
6600     /// Look for allocation functions in both the global scope
6601     /// and in the scope of the allocated class.
6602     AFS_Both
6603   };
6604 
6605   /// Finds the overloads of operator new and delete that are appropriate
6606   /// for the allocation.
6607   bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
6608                                AllocationFunctionScope NewScope,
6609                                AllocationFunctionScope DeleteScope,
6610                                QualType AllocType, bool IsArray,
6611                                bool &PassAlignment, MultiExprArg PlaceArgs,
6612                                FunctionDecl *&OperatorNew,
6613                                FunctionDecl *&OperatorDelete,
6614                                bool Diagnose = true);
6615   void DeclareGlobalNewDelete();
6616   void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
6617                                        ArrayRef<QualType> Params);
6618 
6619   bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
6620                                 DeclarationName Name, FunctionDecl* &Operator,
6621                                 bool Diagnose = true);
6622   FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
6623                                               bool CanProvideSize,
6624                                               bool Overaligned,
6625                                               DeclarationName Name);
6626   FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
6627                                                       CXXRecordDecl *RD);
6628 
6629   /// ActOnCXXDelete - Parsed a C++ 'delete' expression
6630   ExprResult ActOnCXXDelete(SourceLocation StartLoc,
6631                             bool UseGlobal, bool ArrayForm,
6632                             Expr *Operand);
6633   void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
6634                             bool IsDelete, bool CallCanBeVirtual,
6635                             bool WarnOnNonAbstractTypes,
6636                             SourceLocation DtorLoc);
6637 
6638   ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
6639                                Expr *Operand, SourceLocation RParen);
6640   ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
6641                                   SourceLocation RParen);
6642 
6643   /// Parsed one of the type trait support pseudo-functions.
6644   ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
6645                             ArrayRef<ParsedType> Args,
6646                             SourceLocation RParenLoc);
6647   ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
6648                             ArrayRef<TypeSourceInfo *> Args,
6649                             SourceLocation RParenLoc);
6650 
6651   /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
6652   /// pseudo-functions.
6653   ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
6654                                  SourceLocation KWLoc,
6655                                  ParsedType LhsTy,
6656                                  Expr *DimExpr,
6657                                  SourceLocation RParen);
6658 
6659   ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
6660                                  SourceLocation KWLoc,
6661                                  TypeSourceInfo *TSInfo,
6662                                  Expr *DimExpr,
6663                                  SourceLocation RParen);
6664 
6665   /// ActOnExpressionTrait - Parsed one of the unary type trait support
6666   /// pseudo-functions.
6667   ExprResult ActOnExpressionTrait(ExpressionTrait OET,
6668                                   SourceLocation KWLoc,
6669                                   Expr *Queried,
6670                                   SourceLocation RParen);
6671 
6672   ExprResult BuildExpressionTrait(ExpressionTrait OET,
6673                                   SourceLocation KWLoc,
6674                                   Expr *Queried,
6675                                   SourceLocation RParen);
6676 
6677   ExprResult ActOnStartCXXMemberReference(Scope *S,
6678                                           Expr *Base,
6679                                           SourceLocation OpLoc,
6680                                           tok::TokenKind OpKind,
6681                                           ParsedType &ObjectType,
6682                                           bool &MayBePseudoDestructor);
6683 
6684   ExprResult BuildPseudoDestructorExpr(Expr *Base,
6685                                        SourceLocation OpLoc,
6686                                        tok::TokenKind OpKind,
6687                                        const CXXScopeSpec &SS,
6688                                        TypeSourceInfo *ScopeType,
6689                                        SourceLocation CCLoc,
6690                                        SourceLocation TildeLoc,
6691                                      PseudoDestructorTypeStorage DestroyedType);
6692 
6693   ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6694                                        SourceLocation OpLoc,
6695                                        tok::TokenKind OpKind,
6696                                        CXXScopeSpec &SS,
6697                                        UnqualifiedId &FirstTypeName,
6698                                        SourceLocation CCLoc,
6699                                        SourceLocation TildeLoc,
6700                                        UnqualifiedId &SecondTypeName);
6701 
6702   ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6703                                        SourceLocation OpLoc,
6704                                        tok::TokenKind OpKind,
6705                                        SourceLocation TildeLoc,
6706                                        const DeclSpec& DS);
6707 
6708   /// MaybeCreateExprWithCleanups - If the current full-expression
6709   /// requires any cleanups, surround it with a ExprWithCleanups node.
6710   /// Otherwise, just returns the passed-in expression.
6711   Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
6712   Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
6713   ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
6714 
6715   MaterializeTemporaryExpr *
6716   CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
6717                                  bool BoundToLvalueReference);
6718 
6719   ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
6720     return ActOnFinishFullExpr(
6721         Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
6722   }
6723   ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
6724                                  bool DiscardedValue, bool IsConstexpr = false);
6725   StmtResult ActOnFinishFullStmt(Stmt *Stmt);
6726 
6727   // Marks SS invalid if it represents an incomplete type.
6728   bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
6729   // Complete an enum decl, maybe without a scope spec.
6730   bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L,
6731                                CXXScopeSpec *SS = nullptr);
6732 
6733   DeclContext *computeDeclContext(QualType T);
6734   DeclContext *computeDeclContext(const CXXScopeSpec &SS,
6735                                   bool EnteringContext = false);
6736   bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
6737   CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
6738 
6739   /// The parser has parsed a global nested-name-specifier '::'.
6740   ///
6741   /// \param CCLoc The location of the '::'.
6742   ///
6743   /// \param SS The nested-name-specifier, which will be updated in-place
6744   /// to reflect the parsed nested-name-specifier.
6745   ///
6746   /// \returns true if an error occurred, false otherwise.
6747   bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
6748 
6749   /// The parser has parsed a '__super' nested-name-specifier.
6750   ///
6751   /// \param SuperLoc The location of the '__super' keyword.
6752   ///
6753   /// \param ColonColonLoc The location of the '::'.
6754   ///
6755   /// \param SS The nested-name-specifier, which will be updated in-place
6756   /// to reflect the parsed nested-name-specifier.
6757   ///
6758   /// \returns true if an error occurred, false otherwise.
6759   bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
6760                                 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
6761 
6762   bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
6763                                        bool *CanCorrect = nullptr);
6764   NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
6765 
6766   /// Keeps information about an identifier in a nested-name-spec.
6767   ///
6768   struct NestedNameSpecInfo {
6769     /// The type of the object, if we're parsing nested-name-specifier in
6770     /// a member access expression.
6771     ParsedType ObjectType;
6772 
6773     /// The identifier preceding the '::'.
6774     IdentifierInfo *Identifier;
6775 
6776     /// The location of the identifier.
6777     SourceLocation IdentifierLoc;
6778 
6779     /// The location of the '::'.
6780     SourceLocation CCLoc;
6781 
6782     /// Creates info object for the most typical case.
6783     NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
6784              SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
6785       : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
6786         CCLoc(ColonColonLoc) {
6787     }
6788 
6789     NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
6790                        SourceLocation ColonColonLoc, QualType ObjectType)
6791       : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
6792         IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
6793     }
6794   };
6795 
6796   bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
6797                                     NestedNameSpecInfo &IdInfo);
6798 
6799   bool BuildCXXNestedNameSpecifier(Scope *S,
6800                                    NestedNameSpecInfo &IdInfo,
6801                                    bool EnteringContext,
6802                                    CXXScopeSpec &SS,
6803                                    NamedDecl *ScopeLookupResult,
6804                                    bool ErrorRecoveryLookup,
6805                                    bool *IsCorrectedToColon = nullptr,
6806                                    bool OnlyNamespace = false);
6807 
6808   /// The parser has parsed a nested-name-specifier 'identifier::'.
6809   ///
6810   /// \param S The scope in which this nested-name-specifier occurs.
6811   ///
6812   /// \param IdInfo Parser information about an identifier in the
6813   /// nested-name-spec.
6814   ///
6815   /// \param EnteringContext Whether we're entering the context nominated by
6816   /// this nested-name-specifier.
6817   ///
6818   /// \param SS The nested-name-specifier, which is both an input
6819   /// parameter (the nested-name-specifier before this type) and an
6820   /// output parameter (containing the full nested-name-specifier,
6821   /// including this new type).
6822   ///
6823   /// \param ErrorRecoveryLookup If true, then this method is called to improve
6824   /// error recovery. In this case do not emit error message.
6825   ///
6826   /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
6827   /// are allowed.  The bool value pointed by this parameter is set to 'true'
6828   /// if the identifier is treated as if it was followed by ':', not '::'.
6829   ///
6830   /// \param OnlyNamespace If true, only considers namespaces in lookup.
6831   ///
6832   /// \returns true if an error occurred, false otherwise.
6833   bool ActOnCXXNestedNameSpecifier(Scope *S,
6834                                    NestedNameSpecInfo &IdInfo,
6835                                    bool EnteringContext,
6836                                    CXXScopeSpec &SS,
6837                                    bool *IsCorrectedToColon = nullptr,
6838                                    bool OnlyNamespace = false);
6839 
6840   ExprResult ActOnDecltypeExpression(Expr *E);
6841 
6842   bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
6843                                            const DeclSpec &DS,
6844                                            SourceLocation ColonColonLoc);
6845 
6846   bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
6847                                  NestedNameSpecInfo &IdInfo,
6848                                  bool EnteringContext);
6849 
6850   /// The parser has parsed a nested-name-specifier
6851   /// 'template[opt] template-name < template-args >::'.
6852   ///
6853   /// \param S The scope in which this nested-name-specifier occurs.
6854   ///
6855   /// \param SS The nested-name-specifier, which is both an input
6856   /// parameter (the nested-name-specifier before this type) and an
6857   /// output parameter (containing the full nested-name-specifier,
6858   /// including this new type).
6859   ///
6860   /// \param TemplateKWLoc the location of the 'template' keyword, if any.
6861   /// \param TemplateName the template name.
6862   /// \param TemplateNameLoc The location of the template name.
6863   /// \param LAngleLoc The location of the opening angle bracket  ('<').
6864   /// \param TemplateArgs The template arguments.
6865   /// \param RAngleLoc The location of the closing angle bracket  ('>').
6866   /// \param CCLoc The location of the '::'.
6867   ///
6868   /// \param EnteringContext Whether we're entering the context of the
6869   /// nested-name-specifier.
6870   ///
6871   ///
6872   /// \returns true if an error occurred, false otherwise.
6873   bool ActOnCXXNestedNameSpecifier(Scope *S,
6874                                    CXXScopeSpec &SS,
6875                                    SourceLocation TemplateKWLoc,
6876                                    TemplateTy TemplateName,
6877                                    SourceLocation TemplateNameLoc,
6878                                    SourceLocation LAngleLoc,
6879                                    ASTTemplateArgsPtr TemplateArgs,
6880                                    SourceLocation RAngleLoc,
6881                                    SourceLocation CCLoc,
6882                                    bool EnteringContext);
6883 
6884   /// Given a C++ nested-name-specifier, produce an annotation value
6885   /// that the parser can use later to reconstruct the given
6886   /// nested-name-specifier.
6887   ///
6888   /// \param SS A nested-name-specifier.
6889   ///
6890   /// \returns A pointer containing all of the information in the
6891   /// nested-name-specifier \p SS.
6892   void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
6893 
6894   /// Given an annotation pointer for a nested-name-specifier, restore
6895   /// the nested-name-specifier structure.
6896   ///
6897   /// \param Annotation The annotation pointer, produced by
6898   /// \c SaveNestedNameSpecifierAnnotation().
6899   ///
6900   /// \param AnnotationRange The source range corresponding to the annotation.
6901   ///
6902   /// \param SS The nested-name-specifier that will be updated with the contents
6903   /// of the annotation pointer.
6904   void RestoreNestedNameSpecifierAnnotation(void *Annotation,
6905                                             SourceRange AnnotationRange,
6906                                             CXXScopeSpec &SS);
6907 
6908   bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
6909 
6910   /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
6911   /// scope or nested-name-specifier) is parsed, part of a declarator-id.
6912   /// After this method is called, according to [C++ 3.4.3p3], names should be
6913   /// looked up in the declarator-id's scope, until the declarator is parsed and
6914   /// ActOnCXXExitDeclaratorScope is called.
6915   /// The 'SS' should be a non-empty valid CXXScopeSpec.
6916   bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
6917 
6918   /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
6919   /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
6920   /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
6921   /// Used to indicate that names should revert to being looked up in the
6922   /// defining scope.
6923   void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
6924 
6925   /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
6926   /// initializer for the declaration 'Dcl'.
6927   /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6928   /// static data member of class X, names should be looked up in the scope of
6929   /// class X.
6930   void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
6931 
6932   /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
6933   /// initializer for the declaration 'Dcl'.
6934   void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
6935 
6936   /// Create a new lambda closure type.
6937   CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
6938                                          TypeSourceInfo *Info,
6939                                          unsigned LambdaDependencyKind,
6940                                          LambdaCaptureDefault CaptureDefault);
6941 
6942   /// Start the definition of a lambda expression.
6943   CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
6944                                        SourceRange IntroducerRange,
6945                                        TypeSourceInfo *MethodType,
6946                                        SourceLocation EndLoc,
6947                                        ArrayRef<ParmVarDecl *> Params,
6948                                        ConstexprSpecKind ConstexprKind,
6949                                        Expr *TrailingRequiresClause);
6950 
6951   /// Number lambda for linkage purposes if necessary.
6952   void handleLambdaNumbering(
6953       CXXRecordDecl *Class, CXXMethodDecl *Method,
6954       Optional<std::tuple<bool, unsigned, unsigned, Decl *>> Mangling = None);
6955 
6956   /// Endow the lambda scope info with the relevant properties.
6957   void buildLambdaScope(sema::LambdaScopeInfo *LSI,
6958                         CXXMethodDecl *CallOperator,
6959                         SourceRange IntroducerRange,
6960                         LambdaCaptureDefault CaptureDefault,
6961                         SourceLocation CaptureDefaultLoc,
6962                         bool ExplicitParams,
6963                         bool ExplicitResultType,
6964                         bool Mutable);
6965 
6966   /// Perform initialization analysis of the init-capture and perform
6967   /// any implicit conversions such as an lvalue-to-rvalue conversion if
6968   /// not being used to initialize a reference.
6969   ParsedType actOnLambdaInitCaptureInitialization(
6970       SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
6971       IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
6972     return ParsedType::make(buildLambdaInitCaptureInitialization(
6973         Loc, ByRef, EllipsisLoc, None, Id,
6974         InitKind != LambdaCaptureInitKind::CopyInit, Init));
6975   }
6976   QualType buildLambdaInitCaptureInitialization(
6977       SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
6978       Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit,
6979       Expr *&Init);
6980 
6981   /// Create a dummy variable within the declcontext of the lambda's
6982   ///  call operator, for name lookup purposes for a lambda init capture.
6983   ///
6984   ///  CodeGen handles emission of lambda captures, ignoring these dummy
6985   ///  variables appropriately.
6986   VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
6987                                           QualType InitCaptureType,
6988                                           SourceLocation EllipsisLoc,
6989                                           IdentifierInfo *Id,
6990                                           unsigned InitStyle, Expr *Init);
6991 
6992   /// Add an init-capture to a lambda scope.
6993   void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var);
6994 
6995   /// Note that we have finished the explicit captures for the
6996   /// given lambda.
6997   void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
6998 
6999   /// \brief This is called after parsing the explicit template parameter list
7000   /// on a lambda (if it exists) in C++2a.
7001   void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc,
7002                                                 ArrayRef<NamedDecl *> TParams,
7003                                                 SourceLocation RAngleLoc,
7004                                                 ExprResult RequiresClause);
7005 
7006   /// Introduce the lambda parameters into scope.
7007   void addLambdaParameters(
7008       ArrayRef<LambdaIntroducer::LambdaCapture> Captures,
7009       CXXMethodDecl *CallOperator, Scope *CurScope);
7010 
7011   /// Deduce a block or lambda's return type based on the return
7012   /// statements present in the body.
7013   void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
7014 
7015   /// ActOnStartOfLambdaDefinition - This is called just before we start
7016   /// parsing the body of a lambda; it analyzes the explicit captures and
7017   /// arguments, and sets up various data-structures for the body of the
7018   /// lambda.
7019   void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
7020                                     Declarator &ParamInfo, Scope *CurScope);
7021 
7022   /// ActOnLambdaError - If there is an error parsing a lambda, this callback
7023   /// is invoked to pop the information about the lambda.
7024   void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
7025                         bool IsInstantiation = false);
7026 
7027   /// ActOnLambdaExpr - This is called when the body of a lambda expression
7028   /// was successfully completed.
7029   ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
7030                              Scope *CurScope);
7031 
7032   /// Does copying/destroying the captured variable have side effects?
7033   bool CaptureHasSideEffects(const sema::Capture &From);
7034 
7035   /// Diagnose if an explicit lambda capture is unused. Returns true if a
7036   /// diagnostic is emitted.
7037   bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
7038                                    const sema::Capture &From);
7039 
7040   /// Build a FieldDecl suitable to hold the given capture.
7041   FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture);
7042 
7043   /// Initialize the given capture with a suitable expression.
7044   ExprResult BuildCaptureInit(const sema::Capture &Capture,
7045                               SourceLocation ImplicitCaptureLoc,
7046                               bool IsOpenMPMapping = false);
7047 
7048   /// Complete a lambda-expression having processed and attached the
7049   /// lambda body.
7050   ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
7051                              sema::LambdaScopeInfo *LSI);
7052 
7053   /// Get the return type to use for a lambda's conversion function(s) to
7054   /// function pointer type, given the type of the call operator.
7055   QualType
7056   getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType,
7057                                         CallingConv CC);
7058 
7059   /// Define the "body" of the conversion from a lambda object to a
7060   /// function pointer.
7061   ///
7062   /// This routine doesn't actually define a sensible body; rather, it fills
7063   /// in the initialization expression needed to copy the lambda object into
7064   /// the block, and IR generation actually generates the real body of the
7065   /// block pointer conversion.
7066   void DefineImplicitLambdaToFunctionPointerConversion(
7067          SourceLocation CurrentLoc, CXXConversionDecl *Conv);
7068 
7069   /// Define the "body" of the conversion from a lambda object to a
7070   /// block pointer.
7071   ///
7072   /// This routine doesn't actually define a sensible body; rather, it fills
7073   /// in the initialization expression needed to copy the lambda object into
7074   /// the block, and IR generation actually generates the real body of the
7075   /// block pointer conversion.
7076   void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
7077                                                     CXXConversionDecl *Conv);
7078 
7079   ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
7080                                            SourceLocation ConvLocation,
7081                                            CXXConversionDecl *Conv,
7082                                            Expr *Src);
7083 
7084   /// Check whether the given expression is a valid constraint expression.
7085   /// A diagnostic is emitted if it is not, false is returned, and
7086   /// PossibleNonPrimary will be set to true if the failure might be due to a
7087   /// non-primary expression being used as an atomic constraint.
7088   bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(),
7089                                  bool *PossibleNonPrimary = nullptr,
7090                                  bool IsTrailingRequiresClause = false);
7091 
7092 private:
7093   /// Caches pairs of template-like decls whose associated constraints were
7094   /// checked for subsumption and whether or not the first's constraints did in
7095   /// fact subsume the second's.
7096   llvm::DenseMap<std::pair<NamedDecl *, NamedDecl *>, bool> SubsumptionCache;
7097   /// Caches the normalized associated constraints of declarations (concepts or
7098   /// constrained declarations). If an error occurred while normalizing the
7099   /// associated constraints of the template or concept, nullptr will be cached
7100   /// here.
7101   llvm::DenseMap<NamedDecl *, NormalizedConstraint *>
7102       NormalizationCache;
7103 
7104   llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &>
7105       SatisfactionCache;
7106 
7107   /// Introduce the instantiated function parameters into the local
7108   /// instantiation scope, and set the parameter names to those used
7109   /// in the template.
7110   bool addInstantiatedParametersToScope(
7111       FunctionDecl *Function, const FunctionDecl *PatternDecl,
7112       LocalInstantiationScope &Scope,
7113       const MultiLevelTemplateArgumentList &TemplateArgs);
7114 
7115 public:
7116   const NormalizedConstraint *
7117   getNormalizedAssociatedConstraints(
7118       NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints);
7119 
7120   /// \brief Check whether the given declaration's associated constraints are
7121   /// at least as constrained than another declaration's according to the
7122   /// partial ordering of constraints.
7123   ///
7124   /// \param Result If no error occurred, receives the result of true if D1 is
7125   /// at least constrained than D2, and false otherwise.
7126   ///
7127   /// \returns true if an error occurred, false otherwise.
7128   bool IsAtLeastAsConstrained(NamedDecl *D1, ArrayRef<const Expr *> AC1,
7129                               NamedDecl *D2, ArrayRef<const Expr *> AC2,
7130                               bool &Result);
7131 
7132   /// If D1 was not at least as constrained as D2, but would've been if a pair
7133   /// of atomic constraints involved had been declared in a concept and not
7134   /// repeated in two separate places in code.
7135   /// \returns true if such a diagnostic was emitted, false otherwise.
7136   bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1,
7137       ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2);
7138 
7139   /// \brief Check whether the given list of constraint expressions are
7140   /// satisfied (as if in a 'conjunction') given template arguments.
7141   /// \param Template the template-like entity that triggered the constraints
7142   /// check (either a concept or a constrained entity).
7143   /// \param ConstraintExprs a list of constraint expressions, treated as if
7144   /// they were 'AND'ed together.
7145   /// \param TemplateArgs the list of template arguments to substitute into the
7146   /// constraint expression.
7147   /// \param TemplateIDRange The source range of the template id that
7148   /// caused the constraints check.
7149   /// \param Satisfaction if true is returned, will contain details of the
7150   /// satisfaction, with enough information to diagnose an unsatisfied
7151   /// expression.
7152   /// \returns true if an error occurred and satisfaction could not be checked,
7153   /// false otherwise.
7154   bool CheckConstraintSatisfaction(
7155       const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs,
7156       ArrayRef<TemplateArgument> TemplateArgs,
7157       SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction);
7158 
7159   /// \brief Check whether the given non-dependent constraint expression is
7160   /// satisfied. Returns false and updates Satisfaction with the satisfaction
7161   /// verdict if successful, emits a diagnostic and returns true if an error
7162   /// occurred and satisfaction could not be determined.
7163   ///
7164   /// \returns true if an error occurred, false otherwise.
7165   bool CheckConstraintSatisfaction(const Expr *ConstraintExpr,
7166                                    ConstraintSatisfaction &Satisfaction);
7167 
7168   /// Check whether the given function decl's trailing requires clause is
7169   /// satisfied, if any. Returns false and updates Satisfaction with the
7170   /// satisfaction verdict if successful, emits a diagnostic and returns true if
7171   /// an error occurred and satisfaction could not be determined.
7172   ///
7173   /// \returns true if an error occurred, false otherwise.
7174   bool CheckFunctionConstraints(const FunctionDecl *FD,
7175                                 ConstraintSatisfaction &Satisfaction,
7176                                 SourceLocation UsageLoc = SourceLocation());
7177 
7178 
7179   /// \brief Ensure that the given template arguments satisfy the constraints
7180   /// associated with the given template, emitting a diagnostic if they do not.
7181   ///
7182   /// \param Template The template to which the template arguments are being
7183   /// provided.
7184   ///
7185   /// \param TemplateArgs The converted, canonicalized template arguments.
7186   ///
7187   /// \param TemplateIDRange The source range of the template id that
7188   /// caused the constraints check.
7189   ///
7190   /// \returns true if the constrains are not satisfied or could not be checked
7191   /// for satisfaction, false if the constraints are satisfied.
7192   bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template,
7193                                        ArrayRef<TemplateArgument> TemplateArgs,
7194                                              SourceRange TemplateIDRange);
7195 
7196   /// \brief Emit diagnostics explaining why a constraint expression was deemed
7197   /// unsatisfied.
7198   /// \param First whether this is the first time an unsatisfied constraint is
7199   /// diagnosed for this error.
7200   void
7201   DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction,
7202                                 bool First = true);
7203 
7204   /// \brief Emit diagnostics explaining why a constraint expression was deemed
7205   /// unsatisfied.
7206   void
7207   DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction &Satisfaction,
7208                                 bool First = true);
7209 
7210   // ParseObjCStringLiteral - Parse Objective-C string literals.
7211   ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
7212                                     ArrayRef<Expr *> Strings);
7213 
7214   ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
7215 
7216   /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
7217   /// numeric literal expression. Type of the expression will be "NSNumber *"
7218   /// or "id" if NSNumber is unavailable.
7219   ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
7220   ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
7221                                   bool Value);
7222   ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
7223 
7224   /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
7225   /// '@' prefixed parenthesized expression. The type of the expression will
7226   /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
7227   /// of ValueType, which is allowed to be a built-in numeric type, "char *",
7228   /// "const char *" or C structure with attribute 'objc_boxable'.
7229   ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
7230 
7231   ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
7232                                           Expr *IndexExpr,
7233                                           ObjCMethodDecl *getterMethod,
7234                                           ObjCMethodDecl *setterMethod);
7235 
7236   ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
7237                                MutableArrayRef<ObjCDictionaryElement> Elements);
7238 
7239   ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
7240                                   TypeSourceInfo *EncodedTypeInfo,
7241                                   SourceLocation RParenLoc);
7242   ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
7243                                     CXXConversionDecl *Method,
7244                                     bool HadMultipleCandidates);
7245 
7246   ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
7247                                        SourceLocation EncodeLoc,
7248                                        SourceLocation LParenLoc,
7249                                        ParsedType Ty,
7250                                        SourceLocation RParenLoc);
7251 
7252   /// ParseObjCSelectorExpression - Build selector expression for \@selector
7253   ExprResult ParseObjCSelectorExpression(Selector Sel,
7254                                          SourceLocation AtLoc,
7255                                          SourceLocation SelLoc,
7256                                          SourceLocation LParenLoc,
7257                                          SourceLocation RParenLoc,
7258                                          bool WarnMultipleSelectors);
7259 
7260   /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
7261   ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
7262                                          SourceLocation AtLoc,
7263                                          SourceLocation ProtoLoc,
7264                                          SourceLocation LParenLoc,
7265                                          SourceLocation ProtoIdLoc,
7266                                          SourceLocation RParenLoc);
7267 
7268   //===--------------------------------------------------------------------===//
7269   // C++ Declarations
7270   //
7271   Decl *ActOnStartLinkageSpecification(Scope *S,
7272                                        SourceLocation ExternLoc,
7273                                        Expr *LangStr,
7274                                        SourceLocation LBraceLoc);
7275   Decl *ActOnFinishLinkageSpecification(Scope *S,
7276                                         Decl *LinkageSpec,
7277                                         SourceLocation RBraceLoc);
7278 
7279 
7280   //===--------------------------------------------------------------------===//
7281   // C++ Classes
7282   //
7283   CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS);
7284   bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
7285                           const CXXScopeSpec *SS = nullptr);
7286   bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
7287 
7288   bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
7289                             SourceLocation ColonLoc,
7290                             const ParsedAttributesView &Attrs);
7291 
7292   NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
7293                                  Declarator &D,
7294                                  MultiTemplateParamsArg TemplateParameterLists,
7295                                  Expr *BitfieldWidth, const VirtSpecifiers &VS,
7296                                  InClassInitStyle InitStyle);
7297 
7298   void ActOnStartCXXInClassMemberInitializer();
7299   void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
7300                                               SourceLocation EqualLoc,
7301                                               Expr *Init);
7302 
7303   MemInitResult ActOnMemInitializer(Decl *ConstructorD,
7304                                     Scope *S,
7305                                     CXXScopeSpec &SS,
7306                                     IdentifierInfo *MemberOrBase,
7307                                     ParsedType TemplateTypeTy,
7308                                     const DeclSpec &DS,
7309                                     SourceLocation IdLoc,
7310                                     SourceLocation LParenLoc,
7311                                     ArrayRef<Expr *> Args,
7312                                     SourceLocation RParenLoc,
7313                                     SourceLocation EllipsisLoc);
7314 
7315   MemInitResult ActOnMemInitializer(Decl *ConstructorD,
7316                                     Scope *S,
7317                                     CXXScopeSpec &SS,
7318                                     IdentifierInfo *MemberOrBase,
7319                                     ParsedType TemplateTypeTy,
7320                                     const DeclSpec &DS,
7321                                     SourceLocation IdLoc,
7322                                     Expr *InitList,
7323                                     SourceLocation EllipsisLoc);
7324 
7325   MemInitResult BuildMemInitializer(Decl *ConstructorD,
7326                                     Scope *S,
7327                                     CXXScopeSpec &SS,
7328                                     IdentifierInfo *MemberOrBase,
7329                                     ParsedType TemplateTypeTy,
7330                                     const DeclSpec &DS,
7331                                     SourceLocation IdLoc,
7332                                     Expr *Init,
7333                                     SourceLocation EllipsisLoc);
7334 
7335   MemInitResult BuildMemberInitializer(ValueDecl *Member,
7336                                        Expr *Init,
7337                                        SourceLocation IdLoc);
7338 
7339   MemInitResult BuildBaseInitializer(QualType BaseType,
7340                                      TypeSourceInfo *BaseTInfo,
7341                                      Expr *Init,
7342                                      CXXRecordDecl *ClassDecl,
7343                                      SourceLocation EllipsisLoc);
7344 
7345   MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
7346                                            Expr *Init,
7347                                            CXXRecordDecl *ClassDecl);
7348 
7349   bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
7350                                 CXXCtorInitializer *Initializer);
7351 
7352   bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
7353                            ArrayRef<CXXCtorInitializer *> Initializers = None);
7354 
7355   void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
7356 
7357 
7358   /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
7359   /// mark all the non-trivial destructors of its members and bases as
7360   /// referenced.
7361   void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
7362                                               CXXRecordDecl *Record);
7363 
7364   /// Mark destructors of virtual bases of this class referenced. In the Itanium
7365   /// C++ ABI, this is done when emitting a destructor for any non-abstract
7366   /// class. In the Microsoft C++ ABI, this is done any time a class's
7367   /// destructor is referenced.
7368   void MarkVirtualBaseDestructorsReferenced(
7369       SourceLocation Location, CXXRecordDecl *ClassDecl,
7370       llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases = nullptr);
7371 
7372   /// Do semantic checks to allow the complete destructor variant to be emitted
7373   /// when the destructor is defined in another translation unit. In the Itanium
7374   /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they
7375   /// can be emitted in separate TUs. To emit the complete variant, run a subset
7376   /// of the checks performed when emitting a regular destructor.
7377   void CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
7378                                       CXXDestructorDecl *Dtor);
7379 
7380   /// The list of classes whose vtables have been used within
7381   /// this translation unit, and the source locations at which the
7382   /// first use occurred.
7383   typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
7384 
7385   /// The list of vtables that are required but have not yet been
7386   /// materialized.
7387   SmallVector<VTableUse, 16> VTableUses;
7388 
7389   /// The set of classes whose vtables have been used within
7390   /// this translation unit, and a bit that will be true if the vtable is
7391   /// required to be emitted (otherwise, it should be emitted only if needed
7392   /// by code generation).
7393   llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
7394 
7395   /// Load any externally-stored vtable uses.
7396   void LoadExternalVTableUses();
7397 
7398   /// Note that the vtable for the given class was used at the
7399   /// given location.
7400   void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
7401                       bool DefinitionRequired = false);
7402 
7403   /// Mark the exception specifications of all virtual member functions
7404   /// in the given class as needed.
7405   void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
7406                                              const CXXRecordDecl *RD);
7407 
7408   /// MarkVirtualMembersReferenced - Will mark all members of the given
7409   /// CXXRecordDecl referenced.
7410   void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD,
7411                                     bool ConstexprOnly = false);
7412 
7413   /// Define all of the vtables that have been used in this
7414   /// translation unit and reference any virtual members used by those
7415   /// vtables.
7416   ///
7417   /// \returns true if any work was done, false otherwise.
7418   bool DefineUsedVTables();
7419 
7420   void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
7421 
7422   void ActOnMemInitializers(Decl *ConstructorDecl,
7423                             SourceLocation ColonLoc,
7424                             ArrayRef<CXXCtorInitializer*> MemInits,
7425                             bool AnyErrors);
7426 
7427   /// Check class-level dllimport/dllexport attribute. The caller must
7428   /// ensure that referenceDLLExportedClassMethods is called some point later
7429   /// when all outer classes of Class are complete.
7430   void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
7431   void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class);
7432 
7433   void referenceDLLExportedClassMethods();
7434 
7435   void propagateDLLAttrToBaseClassTemplate(
7436       CXXRecordDecl *Class, Attr *ClassAttr,
7437       ClassTemplateSpecializationDecl *BaseTemplateSpec,
7438       SourceLocation BaseLoc);
7439 
7440   /// Add gsl::Pointer attribute to std::container::iterator
7441   /// \param ND The declaration that introduces the name
7442   /// std::container::iterator. \param UnderlyingRecord The record named by ND.
7443   void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
7444 
7445   /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
7446   void inferGslOwnerPointerAttribute(CXXRecordDecl *Record);
7447 
7448   /// Add [[gsl::Pointer]] attributes for std:: types.
7449   void inferGslPointerAttribute(TypedefNameDecl *TD);
7450 
7451   void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record);
7452 
7453   /// Check that the C++ class annoated with "trivial_abi" satisfies all the
7454   /// conditions that are needed for the attribute to have an effect.
7455   void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
7456 
7457   void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc,
7458                                          Decl *TagDecl, SourceLocation LBrac,
7459                                          SourceLocation RBrac,
7460                                          const ParsedAttributesView &AttrList);
7461   void ActOnFinishCXXMemberDecls();
7462   void ActOnFinishCXXNonNestedClass();
7463 
7464   void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
7465   unsigned ActOnReenterTemplateScope(Decl *Template,
7466                                      llvm::function_ref<Scope *()> EnterScope);
7467   void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
7468   void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
7469   void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
7470   void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
7471   void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
7472   void ActOnFinishDelayedMemberInitializers(Decl *Record);
7473   void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
7474                                 CachedTokens &Toks);
7475   void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
7476   bool IsInsideALocalClassWithinATemplateFunction();
7477 
7478   Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
7479                                      Expr *AssertExpr,
7480                                      Expr *AssertMessageExpr,
7481                                      SourceLocation RParenLoc);
7482   Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
7483                                      Expr *AssertExpr,
7484                                      StringLiteral *AssertMessageExpr,
7485                                      SourceLocation RParenLoc,
7486                                      bool Failed);
7487 
7488   FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
7489                                   SourceLocation FriendLoc,
7490                                   TypeSourceInfo *TSInfo);
7491   Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
7492                             MultiTemplateParamsArg TemplateParams);
7493   NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
7494                                      MultiTemplateParamsArg TemplateParams);
7495 
7496   QualType CheckConstructorDeclarator(Declarator &D, QualType R,
7497                                       StorageClass& SC);
7498   void CheckConstructor(CXXConstructorDecl *Constructor);
7499   QualType CheckDestructorDeclarator(Declarator &D, QualType R,
7500                                      StorageClass& SC);
7501   bool CheckDestructor(CXXDestructorDecl *Destructor);
7502   void CheckConversionDeclarator(Declarator &D, QualType &R,
7503                                  StorageClass& SC);
7504   Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
7505   void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
7506                                      StorageClass &SC);
7507   void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
7508 
7509   void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD);
7510 
7511   bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7512                                              CXXSpecialMember CSM);
7513   void CheckDelayedMemberExceptionSpecs();
7514 
7515   bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD,
7516                                           DefaultedComparisonKind DCK);
7517   void DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
7518                                          FunctionDecl *Spaceship);
7519   void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD,
7520                                  DefaultedComparisonKind DCK);
7521 
7522   //===--------------------------------------------------------------------===//
7523   // C++ Derived Classes
7524   //
7525 
7526   /// ActOnBaseSpecifier - Parsed a base specifier
7527   CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
7528                                        SourceRange SpecifierRange,
7529                                        bool Virtual, AccessSpecifier Access,
7530                                        TypeSourceInfo *TInfo,
7531                                        SourceLocation EllipsisLoc);
7532 
7533   BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
7534                                 const ParsedAttributesView &Attrs, bool Virtual,
7535                                 AccessSpecifier Access, ParsedType basetype,
7536                                 SourceLocation BaseLoc,
7537                                 SourceLocation EllipsisLoc);
7538 
7539   bool AttachBaseSpecifiers(CXXRecordDecl *Class,
7540                             MutableArrayRef<CXXBaseSpecifier *> Bases);
7541   void ActOnBaseSpecifiers(Decl *ClassDecl,
7542                            MutableArrayRef<CXXBaseSpecifier *> Bases);
7543 
7544   bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
7545   bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
7546                      CXXBasePaths &Paths);
7547 
7548   // FIXME: I don't like this name.
7549   void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
7550 
7551   bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
7552                                     SourceLocation Loc, SourceRange Range,
7553                                     CXXCastPath *BasePath = nullptr,
7554                                     bool IgnoreAccess = false);
7555   bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
7556                                     unsigned InaccessibleBaseID,
7557                                     unsigned AmbiguousBaseConvID,
7558                                     SourceLocation Loc, SourceRange Range,
7559                                     DeclarationName Name,
7560                                     CXXCastPath *BasePath,
7561                                     bool IgnoreAccess = false);
7562 
7563   std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
7564 
7565   bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
7566                                          const CXXMethodDecl *Old);
7567 
7568   /// CheckOverridingFunctionReturnType - Checks whether the return types are
7569   /// covariant, according to C++ [class.virtual]p5.
7570   bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
7571                                          const CXXMethodDecl *Old);
7572 
7573   /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
7574   /// spec is a subset of base spec.
7575   bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
7576                                             const CXXMethodDecl *Old);
7577 
7578   bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
7579 
7580   /// CheckOverrideControl - Check C++11 override control semantics.
7581   void CheckOverrideControl(NamedDecl *D);
7582 
7583   /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
7584   /// not used in the declaration of an overriding method.
7585   void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent);
7586 
7587   /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
7588   /// overrides a virtual member function marked 'final', according to
7589   /// C++11 [class.virtual]p4.
7590   bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
7591                                               const CXXMethodDecl *Old);
7592 
7593 
7594   //===--------------------------------------------------------------------===//
7595   // C++ Access Control
7596   //
7597 
7598   enum AccessResult {
7599     AR_accessible,
7600     AR_inaccessible,
7601     AR_dependent,
7602     AR_delayed
7603   };
7604 
7605   bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
7606                                 NamedDecl *PrevMemberDecl,
7607                                 AccessSpecifier LexicalAS);
7608 
7609   AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
7610                                            DeclAccessPair FoundDecl);
7611   AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
7612                                            DeclAccessPair FoundDecl);
7613   AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
7614                                      SourceRange PlacementRange,
7615                                      CXXRecordDecl *NamingClass,
7616                                      DeclAccessPair FoundDecl,
7617                                      bool Diagnose = true);
7618   AccessResult CheckConstructorAccess(SourceLocation Loc,
7619                                       CXXConstructorDecl *D,
7620                                       DeclAccessPair FoundDecl,
7621                                       const InitializedEntity &Entity,
7622                                       bool IsCopyBindingRefToTemp = false);
7623   AccessResult CheckConstructorAccess(SourceLocation Loc,
7624                                       CXXConstructorDecl *D,
7625                                       DeclAccessPair FoundDecl,
7626                                       const InitializedEntity &Entity,
7627                                       const PartialDiagnostic &PDiag);
7628   AccessResult CheckDestructorAccess(SourceLocation Loc,
7629                                      CXXDestructorDecl *Dtor,
7630                                      const PartialDiagnostic &PDiag,
7631                                      QualType objectType = QualType());
7632   AccessResult CheckFriendAccess(NamedDecl *D);
7633   AccessResult CheckMemberAccess(SourceLocation UseLoc,
7634                                  CXXRecordDecl *NamingClass,
7635                                  DeclAccessPair Found);
7636   AccessResult
7637   CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
7638                                      CXXRecordDecl *DecomposedClass,
7639                                      DeclAccessPair Field);
7640   AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
7641                                          const SourceRange &,
7642                                          DeclAccessPair FoundDecl);
7643   AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
7644                                          Expr *ObjectExpr,
7645                                          Expr *ArgExpr,
7646                                          DeclAccessPair FoundDecl);
7647   AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
7648                                          ArrayRef<Expr *> ArgExprs,
7649                                          DeclAccessPair FoundDecl);
7650   AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
7651                                           DeclAccessPair FoundDecl);
7652   AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
7653                                     QualType Base, QualType Derived,
7654                                     const CXXBasePath &Path,
7655                                     unsigned DiagID,
7656                                     bool ForceCheck = false,
7657                                     bool ForceUnprivileged = false);
7658   void CheckLookupAccess(const LookupResult &R);
7659   bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
7660                           QualType BaseType);
7661   bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
7662                                      DeclAccessPair Found, QualType ObjectType,
7663                                      SourceLocation Loc,
7664                                      const PartialDiagnostic &Diag);
7665   bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
7666                                      DeclAccessPair Found,
7667                                      QualType ObjectType) {
7668     return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType,
7669                                          SourceLocation(), PDiag());
7670   }
7671 
7672   void HandleDependentAccessCheck(const DependentDiagnostic &DD,
7673                          const MultiLevelTemplateArgumentList &TemplateArgs);
7674   void PerformDependentDiagnostics(const DeclContext *Pattern,
7675                         const MultiLevelTemplateArgumentList &TemplateArgs);
7676 
7677   void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
7678 
7679   /// When true, access checking violations are treated as SFINAE
7680   /// failures rather than hard errors.
7681   bool AccessCheckingSFINAE;
7682 
7683   enum AbstractDiagSelID {
7684     AbstractNone = -1,
7685     AbstractReturnType,
7686     AbstractParamType,
7687     AbstractVariableType,
7688     AbstractFieldType,
7689     AbstractIvarType,
7690     AbstractSynthesizedIvarType,
7691     AbstractArrayType
7692   };
7693 
7694   bool isAbstractType(SourceLocation Loc, QualType T);
7695   bool RequireNonAbstractType(SourceLocation Loc, QualType T,
7696                               TypeDiagnoser &Diagnoser);
7697   template <typename... Ts>
7698   bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
7699                               const Ts &...Args) {
7700     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
7701     return RequireNonAbstractType(Loc, T, Diagnoser);
7702   }
7703 
7704   void DiagnoseAbstractType(const CXXRecordDecl *RD);
7705 
7706   //===--------------------------------------------------------------------===//
7707   // C++ Overloaded Operators [C++ 13.5]
7708   //
7709 
7710   bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
7711 
7712   bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
7713 
7714   //===--------------------------------------------------------------------===//
7715   // C++ Templates [C++ 14]
7716   //
7717   void FilterAcceptableTemplateNames(LookupResult &R,
7718                                      bool AllowFunctionTemplates = true,
7719                                      bool AllowDependent = true);
7720   bool hasAnyAcceptableTemplateNames(LookupResult &R,
7721                                      bool AllowFunctionTemplates = true,
7722                                      bool AllowDependent = true,
7723                                      bool AllowNonTemplateFunctions = false);
7724   /// Try to interpret the lookup result D as a template-name.
7725   ///
7726   /// \param D A declaration found by name lookup.
7727   /// \param AllowFunctionTemplates Whether function templates should be
7728   ///        considered valid results.
7729   /// \param AllowDependent Whether unresolved using declarations (that might
7730   ///        name templates) should be considered valid results.
7731   static NamedDecl *getAsTemplateNameDecl(NamedDecl *D,
7732                                           bool AllowFunctionTemplates = true,
7733                                           bool AllowDependent = true);
7734 
7735   enum TemplateNameIsRequiredTag { TemplateNameIsRequired };
7736   /// Whether and why a template name is required in this lookup.
7737   class RequiredTemplateKind {
7738   public:
7739     /// Template name is required if TemplateKWLoc is valid.
7740     RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation())
7741         : TemplateKW(TemplateKWLoc) {}
7742     /// Template name is unconditionally required.
7743     RequiredTemplateKind(TemplateNameIsRequiredTag) {}
7744 
7745     SourceLocation getTemplateKeywordLoc() const {
7746       return TemplateKW.value_or(SourceLocation());
7747     }
7748     bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
7749     bool isRequired() const { return TemplateKW != SourceLocation(); }
7750     explicit operator bool() const { return isRequired(); }
7751 
7752   private:
7753     llvm::Optional<SourceLocation> TemplateKW;
7754   };
7755 
7756   enum class AssumedTemplateKind {
7757     /// This is not assumed to be a template name.
7758     None,
7759     /// This is assumed to be a template name because lookup found nothing.
7760     FoundNothing,
7761     /// This is assumed to be a template name because lookup found one or more
7762     /// functions (but no function templates).
7763     FoundFunctions,
7764   };
7765   bool LookupTemplateName(
7766       LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType,
7767       bool EnteringContext, bool &MemberOfUnknownSpecialization,
7768       RequiredTemplateKind RequiredTemplate = SourceLocation(),
7769       AssumedTemplateKind *ATK = nullptr, bool AllowTypoCorrection = true);
7770 
7771   TemplateNameKind isTemplateName(Scope *S,
7772                                   CXXScopeSpec &SS,
7773                                   bool hasTemplateKeyword,
7774                                   const UnqualifiedId &Name,
7775                                   ParsedType ObjectType,
7776                                   bool EnteringContext,
7777                                   TemplateTy &Template,
7778                                   bool &MemberOfUnknownSpecialization,
7779                                   bool Disambiguation = false);
7780 
7781   /// Try to resolve an undeclared template name as a type template.
7782   ///
7783   /// Sets II to the identifier corresponding to the template name, and updates
7784   /// Name to a corresponding (typo-corrected) type template name and TNK to
7785   /// the corresponding kind, if possible.
7786   void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name,
7787                                        TemplateNameKind &TNK,
7788                                        SourceLocation NameLoc,
7789                                        IdentifierInfo *&II);
7790 
7791   bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
7792                                         SourceLocation NameLoc,
7793                                         bool Diagnose = true);
7794 
7795   /// Determine whether a particular identifier might be the name in a C++1z
7796   /// deduction-guide declaration.
7797   bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
7798                             SourceLocation NameLoc,
7799                             ParsedTemplateTy *Template = nullptr);
7800 
7801   bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
7802                                    SourceLocation IILoc,
7803                                    Scope *S,
7804                                    const CXXScopeSpec *SS,
7805                                    TemplateTy &SuggestedTemplate,
7806                                    TemplateNameKind &SuggestedKind);
7807 
7808   bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
7809                                       NamedDecl *Instantiation,
7810                                       bool InstantiatedFromMember,
7811                                       const NamedDecl *Pattern,
7812                                       const NamedDecl *PatternDef,
7813                                       TemplateSpecializationKind TSK,
7814                                       bool Complain = true);
7815 
7816   void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
7817   TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
7818 
7819   NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
7820                                 SourceLocation EllipsisLoc,
7821                                 SourceLocation KeyLoc,
7822                                 IdentifierInfo *ParamName,
7823                                 SourceLocation ParamNameLoc,
7824                                 unsigned Depth, unsigned Position,
7825                                 SourceLocation EqualLoc,
7826                                 ParsedType DefaultArg, bool HasTypeConstraint);
7827 
7828   bool ActOnTypeConstraint(const CXXScopeSpec &SS,
7829                            TemplateIdAnnotation *TypeConstraint,
7830                            TemplateTypeParmDecl *ConstrainedParameter,
7831                            SourceLocation EllipsisLoc);
7832   bool BuildTypeConstraint(const CXXScopeSpec &SS,
7833                            TemplateIdAnnotation *TypeConstraint,
7834                            TemplateTypeParmDecl *ConstrainedParameter,
7835                            SourceLocation EllipsisLoc,
7836                            bool AllowUnexpandedPack);
7837 
7838   bool AttachTypeConstraint(NestedNameSpecifierLoc NS,
7839                             DeclarationNameInfo NameInfo,
7840                             ConceptDecl *NamedConcept,
7841                             const TemplateArgumentListInfo *TemplateArgs,
7842                             TemplateTypeParmDecl *ConstrainedParameter,
7843                             SourceLocation EllipsisLoc);
7844 
7845   bool AttachTypeConstraint(AutoTypeLoc TL,
7846                             NonTypeTemplateParmDecl *ConstrainedParameter,
7847                             SourceLocation EllipsisLoc);
7848 
7849   bool RequireStructuralType(QualType T, SourceLocation Loc);
7850 
7851   QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
7852                                              SourceLocation Loc);
7853   QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
7854 
7855   NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
7856                                       unsigned Depth,
7857                                       unsigned Position,
7858                                       SourceLocation EqualLoc,
7859                                       Expr *DefaultArg);
7860   NamedDecl *ActOnTemplateTemplateParameter(Scope *S,
7861                                        SourceLocation TmpLoc,
7862                                        TemplateParameterList *Params,
7863                                        SourceLocation EllipsisLoc,
7864                                        IdentifierInfo *ParamName,
7865                                        SourceLocation ParamNameLoc,
7866                                        unsigned Depth,
7867                                        unsigned Position,
7868                                        SourceLocation EqualLoc,
7869                                        ParsedTemplateArgument DefaultArg);
7870 
7871   TemplateParameterList *
7872   ActOnTemplateParameterList(unsigned Depth,
7873                              SourceLocation ExportLoc,
7874                              SourceLocation TemplateLoc,
7875                              SourceLocation LAngleLoc,
7876                              ArrayRef<NamedDecl *> Params,
7877                              SourceLocation RAngleLoc,
7878                              Expr *RequiresClause);
7879 
7880   /// The context in which we are checking a template parameter list.
7881   enum TemplateParamListContext {
7882     TPC_ClassTemplate,
7883     TPC_VarTemplate,
7884     TPC_FunctionTemplate,
7885     TPC_ClassTemplateMember,
7886     TPC_FriendClassTemplate,
7887     TPC_FriendFunctionTemplate,
7888     TPC_FriendFunctionTemplateDefinition,
7889     TPC_TypeAliasTemplate
7890   };
7891 
7892   bool CheckTemplateParameterList(TemplateParameterList *NewParams,
7893                                   TemplateParameterList *OldParams,
7894                                   TemplateParamListContext TPC,
7895                                   SkipBodyInfo *SkipBody = nullptr);
7896   TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
7897       SourceLocation DeclStartLoc, SourceLocation DeclLoc,
7898       const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
7899       ArrayRef<TemplateParameterList *> ParamLists,
7900       bool IsFriend, bool &IsMemberSpecialization, bool &Invalid,
7901       bool SuppressDiagnostic = false);
7902 
7903   DeclResult CheckClassTemplate(
7904       Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7905       CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
7906       const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
7907       AccessSpecifier AS, SourceLocation ModulePrivateLoc,
7908       SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
7909       TemplateParameterList **OuterTemplateParamLists,
7910       SkipBodyInfo *SkipBody = nullptr);
7911 
7912   TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
7913                                                     QualType NTTPType,
7914                                                     SourceLocation Loc);
7915 
7916   /// Get a template argument mapping the given template parameter to itself,
7917   /// e.g. for X in \c template<int X>, this would return an expression template
7918   /// argument referencing X.
7919   TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param,
7920                                                      SourceLocation Location);
7921 
7922   void translateTemplateArguments(const ASTTemplateArgsPtr &In,
7923                                   TemplateArgumentListInfo &Out);
7924 
7925   ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
7926 
7927   void NoteAllFoundTemplates(TemplateName Name);
7928 
7929   QualType CheckTemplateIdType(TemplateName Template,
7930                                SourceLocation TemplateLoc,
7931                               TemplateArgumentListInfo &TemplateArgs);
7932 
7933   TypeResult
7934   ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
7935                       TemplateTy Template, IdentifierInfo *TemplateII,
7936                       SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
7937                       ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
7938                       bool IsCtorOrDtorName = false, bool IsClassName = false);
7939 
7940   /// Parsed an elaborated-type-specifier that refers to a template-id,
7941   /// such as \c class T::template apply<U>.
7942   TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
7943                                     TypeSpecifierType TagSpec,
7944                                     SourceLocation TagLoc,
7945                                     CXXScopeSpec &SS,
7946                                     SourceLocation TemplateKWLoc,
7947                                     TemplateTy TemplateD,
7948                                     SourceLocation TemplateLoc,
7949                                     SourceLocation LAngleLoc,
7950                                     ASTTemplateArgsPtr TemplateArgsIn,
7951                                     SourceLocation RAngleLoc);
7952 
7953   DeclResult ActOnVarTemplateSpecialization(
7954       Scope *S, Declarator &D, TypeSourceInfo *DI,
7955       SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
7956       StorageClass SC, bool IsPartialSpecialization);
7957 
7958   /// Get the specialization of the given variable template corresponding to
7959   /// the specified argument list, or a null-but-valid result if the arguments
7960   /// are dependent.
7961   DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
7962                                 SourceLocation TemplateLoc,
7963                                 SourceLocation TemplateNameLoc,
7964                                 const TemplateArgumentListInfo &TemplateArgs);
7965 
7966   /// Form a reference to the specialization of the given variable template
7967   /// corresponding to the specified argument list, or a null-but-valid result
7968   /// if the arguments are dependent.
7969   ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
7970                                 const DeclarationNameInfo &NameInfo,
7971                                 VarTemplateDecl *Template,
7972                                 SourceLocation TemplateLoc,
7973                                 const TemplateArgumentListInfo *TemplateArgs);
7974 
7975   ExprResult
7976   CheckConceptTemplateId(const CXXScopeSpec &SS,
7977                          SourceLocation TemplateKWLoc,
7978                          const DeclarationNameInfo &ConceptNameInfo,
7979                          NamedDecl *FoundDecl, ConceptDecl *NamedConcept,
7980                          const TemplateArgumentListInfo *TemplateArgs);
7981 
7982   void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc);
7983 
7984   ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
7985                                  SourceLocation TemplateKWLoc,
7986                                  LookupResult &R,
7987                                  bool RequiresADL,
7988                                const TemplateArgumentListInfo *TemplateArgs);
7989 
7990   ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
7991                                           SourceLocation TemplateKWLoc,
7992                                const DeclarationNameInfo &NameInfo,
7993                                const TemplateArgumentListInfo *TemplateArgs);
7994 
7995   TemplateNameKind ActOnTemplateName(
7996       Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
7997       const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
7998       TemplateTy &Template, bool AllowInjectedClassName = false);
7999 
8000   DeclResult ActOnClassTemplateSpecialization(
8001       Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8002       SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8003       TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
8004       MultiTemplateParamsArg TemplateParameterLists,
8005       SkipBodyInfo *SkipBody = nullptr);
8006 
8007   bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
8008                                               TemplateDecl *PrimaryTemplate,
8009                                               unsigned NumExplicitArgs,
8010                                               ArrayRef<TemplateArgument> Args);
8011   void CheckTemplatePartialSpecialization(
8012       ClassTemplatePartialSpecializationDecl *Partial);
8013   void CheckTemplatePartialSpecialization(
8014       VarTemplatePartialSpecializationDecl *Partial);
8015 
8016   Decl *ActOnTemplateDeclarator(Scope *S,
8017                                 MultiTemplateParamsArg TemplateParameterLists,
8018                                 Declarator &D);
8019 
8020   bool
8021   CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
8022                                          TemplateSpecializationKind NewTSK,
8023                                          NamedDecl *PrevDecl,
8024                                          TemplateSpecializationKind PrevTSK,
8025                                          SourceLocation PrevPtOfInstantiation,
8026                                          bool &SuppressNew);
8027 
8028   bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
8029                     const TemplateArgumentListInfo &ExplicitTemplateArgs,
8030                                                     LookupResult &Previous);
8031 
8032   bool CheckFunctionTemplateSpecialization(
8033       FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
8034       LookupResult &Previous, bool QualifiedFriend = false);
8035   bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
8036   void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
8037 
8038   DeclResult ActOnExplicitInstantiation(
8039       Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
8040       unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
8041       TemplateTy Template, SourceLocation TemplateNameLoc,
8042       SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
8043       SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
8044 
8045   DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
8046                                         SourceLocation TemplateLoc,
8047                                         unsigned TagSpec, SourceLocation KWLoc,
8048                                         CXXScopeSpec &SS, IdentifierInfo *Name,
8049                                         SourceLocation NameLoc,
8050                                         const ParsedAttributesView &Attr);
8051 
8052   DeclResult ActOnExplicitInstantiation(Scope *S,
8053                                         SourceLocation ExternLoc,
8054                                         SourceLocation TemplateLoc,
8055                                         Declarator &D);
8056 
8057   TemplateArgumentLoc
8058   SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
8059                                           SourceLocation TemplateLoc,
8060                                           SourceLocation RAngleLoc,
8061                                           Decl *Param,
8062                                           SmallVectorImpl<TemplateArgument>
8063                                             &Converted,
8064                                           bool &HasDefaultArg);
8065 
8066   /// Specifies the context in which a particular template
8067   /// argument is being checked.
8068   enum CheckTemplateArgumentKind {
8069     /// The template argument was specified in the code or was
8070     /// instantiated with some deduced template arguments.
8071     CTAK_Specified,
8072 
8073     /// The template argument was deduced via template argument
8074     /// deduction.
8075     CTAK_Deduced,
8076 
8077     /// The template argument was deduced from an array bound
8078     /// via template argument deduction.
8079     CTAK_DeducedFromArrayBound
8080   };
8081 
8082   bool CheckTemplateArgument(NamedDecl *Param,
8083                              TemplateArgumentLoc &Arg,
8084                              NamedDecl *Template,
8085                              SourceLocation TemplateLoc,
8086                              SourceLocation RAngleLoc,
8087                              unsigned ArgumentPackIndex,
8088                            SmallVectorImpl<TemplateArgument> &Converted,
8089                              CheckTemplateArgumentKind CTAK = CTAK_Specified);
8090 
8091   /// Check that the given template arguments can be be provided to
8092   /// the given template, converting the arguments along the way.
8093   ///
8094   /// \param Template The template to which the template arguments are being
8095   /// provided.
8096   ///
8097   /// \param TemplateLoc The location of the template name in the source.
8098   ///
8099   /// \param TemplateArgs The list of template arguments. If the template is
8100   /// a template template parameter, this function may extend the set of
8101   /// template arguments to also include substituted, defaulted template
8102   /// arguments.
8103   ///
8104   /// \param PartialTemplateArgs True if the list of template arguments is
8105   /// intentionally partial, e.g., because we're checking just the initial
8106   /// set of template arguments.
8107   ///
8108   /// \param Converted Will receive the converted, canonicalized template
8109   /// arguments.
8110   ///
8111   /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
8112   /// contain the converted forms of the template arguments as written.
8113   /// Otherwise, \p TemplateArgs will not be modified.
8114   ///
8115   /// \param ConstraintsNotSatisfied If provided, and an error occurred, will
8116   /// receive true if the cause for the error is the associated constraints of
8117   /// the template not being satisfied by the template arguments.
8118   ///
8119   /// \returns true if an error occurred, false otherwise.
8120   bool CheckTemplateArgumentList(TemplateDecl *Template,
8121                                  SourceLocation TemplateLoc,
8122                                  TemplateArgumentListInfo &TemplateArgs,
8123                                  bool PartialTemplateArgs,
8124                                  SmallVectorImpl<TemplateArgument> &Converted,
8125                                  bool UpdateArgsWithConversions = true,
8126                                  bool *ConstraintsNotSatisfied = nullptr);
8127 
8128   bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
8129                                  TemplateArgumentLoc &Arg,
8130                            SmallVectorImpl<TemplateArgument> &Converted);
8131 
8132   bool CheckTemplateArgument(TypeSourceInfo *Arg);
8133   ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
8134                                    QualType InstantiatedParamType, Expr *Arg,
8135                                    TemplateArgument &Converted,
8136                                CheckTemplateArgumentKind CTAK = CTAK_Specified);
8137   bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
8138                                      TemplateParameterList *Params,
8139                                      TemplateArgumentLoc &Arg);
8140 
8141   ExprResult
8142   BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
8143                                           QualType ParamType,
8144                                           SourceLocation Loc);
8145   ExprResult
8146   BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
8147                                               SourceLocation Loc);
8148 
8149   /// Enumeration describing how template parameter lists are compared
8150   /// for equality.
8151   enum TemplateParameterListEqualKind {
8152     /// We are matching the template parameter lists of two templates
8153     /// that might be redeclarations.
8154     ///
8155     /// \code
8156     /// template<typename T> struct X;
8157     /// template<typename T> struct X;
8158     /// \endcode
8159     TPL_TemplateMatch,
8160 
8161     /// We are matching the template parameter lists of two template
8162     /// template parameters as part of matching the template parameter lists
8163     /// of two templates that might be redeclarations.
8164     ///
8165     /// \code
8166     /// template<template<int I> class TT> struct X;
8167     /// template<template<int Value> class Other> struct X;
8168     /// \endcode
8169     TPL_TemplateTemplateParmMatch,
8170 
8171     /// We are matching the template parameter lists of a template
8172     /// template argument against the template parameter lists of a template
8173     /// template parameter.
8174     ///
8175     /// \code
8176     /// template<template<int Value> class Metafun> struct X;
8177     /// template<int Value> struct integer_c;
8178     /// X<integer_c> xic;
8179     /// \endcode
8180     TPL_TemplateTemplateArgumentMatch
8181   };
8182 
8183   bool TemplateParameterListsAreEqual(TemplateParameterList *New,
8184                                       TemplateParameterList *Old,
8185                                       bool Complain,
8186                                       TemplateParameterListEqualKind Kind,
8187                                       SourceLocation TemplateArgLoc
8188                                         = SourceLocation());
8189 
8190   bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
8191 
8192   /// Called when the parser has parsed a C++ typename
8193   /// specifier, e.g., "typename T::type".
8194   ///
8195   /// \param S The scope in which this typename type occurs.
8196   /// \param TypenameLoc the location of the 'typename' keyword
8197   /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
8198   /// \param II the identifier we're retrieving (e.g., 'type' in the example).
8199   /// \param IdLoc the location of the identifier.
8200   TypeResult
8201   ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
8202                     const CXXScopeSpec &SS, const IdentifierInfo &II,
8203                     SourceLocation IdLoc);
8204 
8205   /// Called when the parser has parsed a C++ typename
8206   /// specifier that ends in a template-id, e.g.,
8207   /// "typename MetaFun::template apply<T1, T2>".
8208   ///
8209   /// \param S The scope in which this typename type occurs.
8210   /// \param TypenameLoc the location of the 'typename' keyword
8211   /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
8212   /// \param TemplateLoc the location of the 'template' keyword, if any.
8213   /// \param TemplateName The template name.
8214   /// \param TemplateII The identifier used to name the template.
8215   /// \param TemplateIILoc The location of the template name.
8216   /// \param LAngleLoc The location of the opening angle bracket  ('<').
8217   /// \param TemplateArgs The template arguments.
8218   /// \param RAngleLoc The location of the closing angle bracket  ('>').
8219   TypeResult
8220   ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
8221                     const CXXScopeSpec &SS,
8222                     SourceLocation TemplateLoc,
8223                     TemplateTy TemplateName,
8224                     IdentifierInfo *TemplateII,
8225                     SourceLocation TemplateIILoc,
8226                     SourceLocation LAngleLoc,
8227                     ASTTemplateArgsPtr TemplateArgs,
8228                     SourceLocation RAngleLoc);
8229 
8230   QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
8231                              SourceLocation KeywordLoc,
8232                              NestedNameSpecifierLoc QualifierLoc,
8233                              const IdentifierInfo &II,
8234                              SourceLocation IILoc,
8235                              TypeSourceInfo **TSI,
8236                              bool DeducedTSTContext);
8237 
8238   QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
8239                              SourceLocation KeywordLoc,
8240                              NestedNameSpecifierLoc QualifierLoc,
8241                              const IdentifierInfo &II,
8242                              SourceLocation IILoc,
8243                              bool DeducedTSTContext = true);
8244 
8245 
8246   TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8247                                                     SourceLocation Loc,
8248                                                     DeclarationName Name);
8249   bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
8250 
8251   ExprResult RebuildExprInCurrentInstantiation(Expr *E);
8252   bool RebuildTemplateParamsInCurrentInstantiation(
8253                                                 TemplateParameterList *Params);
8254 
8255   std::string
8256   getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8257                                   const TemplateArgumentList &Args);
8258 
8259   std::string
8260   getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8261                                   const TemplateArgument *Args,
8262                                   unsigned NumArgs);
8263 
8264   //===--------------------------------------------------------------------===//
8265   // C++ Concepts
8266   //===--------------------------------------------------------------------===//
8267   Decl *ActOnConceptDefinition(
8268       Scope *S, MultiTemplateParamsArg TemplateParameterLists,
8269       IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr);
8270 
8271   void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous,
8272                                 bool &AddToScope);
8273 
8274   RequiresExprBodyDecl *
8275   ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
8276                          ArrayRef<ParmVarDecl *> LocalParameters,
8277                          Scope *BodyScope);
8278   void ActOnFinishRequiresExpr();
8279   concepts::Requirement *ActOnSimpleRequirement(Expr *E);
8280   concepts::Requirement *ActOnTypeRequirement(
8281       SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc,
8282       IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId);
8283   concepts::Requirement *ActOnCompoundRequirement(Expr *E,
8284                                                   SourceLocation NoexceptLoc);
8285   concepts::Requirement *
8286   ActOnCompoundRequirement(
8287       Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
8288       TemplateIdAnnotation *TypeConstraint, unsigned Depth);
8289   concepts::Requirement *ActOnNestedRequirement(Expr *Constraint);
8290   concepts::ExprRequirement *
8291   BuildExprRequirement(
8292       Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc,
8293       concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
8294   concepts::ExprRequirement *
8295   BuildExprRequirement(
8296       concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag,
8297       bool IsSatisfied, SourceLocation NoexceptLoc,
8298       concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
8299   concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type);
8300   concepts::TypeRequirement *
8301   BuildTypeRequirement(
8302       concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
8303   concepts::NestedRequirement *BuildNestedRequirement(Expr *E);
8304   concepts::NestedRequirement *
8305   BuildNestedRequirement(
8306       concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
8307   ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc,
8308                                RequiresExprBodyDecl *Body,
8309                                ArrayRef<ParmVarDecl *> LocalParameters,
8310                                ArrayRef<concepts::Requirement *> Requirements,
8311                                SourceLocation ClosingBraceLoc);
8312 
8313   //===--------------------------------------------------------------------===//
8314   // C++ Variadic Templates (C++0x [temp.variadic])
8315   //===--------------------------------------------------------------------===//
8316 
8317   /// Determine whether an unexpanded parameter pack might be permitted in this
8318   /// location. Useful for error recovery.
8319   bool isUnexpandedParameterPackPermitted();
8320 
8321   /// The context in which an unexpanded parameter pack is
8322   /// being diagnosed.
8323   ///
8324   /// Note that the values of this enumeration line up with the first
8325   /// argument to the \c err_unexpanded_parameter_pack diagnostic.
8326   enum UnexpandedParameterPackContext {
8327     /// An arbitrary expression.
8328     UPPC_Expression = 0,
8329 
8330     /// The base type of a class type.
8331     UPPC_BaseType,
8332 
8333     /// The type of an arbitrary declaration.
8334     UPPC_DeclarationType,
8335 
8336     /// The type of a data member.
8337     UPPC_DataMemberType,
8338 
8339     /// The size of a bit-field.
8340     UPPC_BitFieldWidth,
8341 
8342     /// The expression in a static assertion.
8343     UPPC_StaticAssertExpression,
8344 
8345     /// The fixed underlying type of an enumeration.
8346     UPPC_FixedUnderlyingType,
8347 
8348     /// The enumerator value.
8349     UPPC_EnumeratorValue,
8350 
8351     /// A using declaration.
8352     UPPC_UsingDeclaration,
8353 
8354     /// A friend declaration.
8355     UPPC_FriendDeclaration,
8356 
8357     /// A declaration qualifier.
8358     UPPC_DeclarationQualifier,
8359 
8360     /// An initializer.
8361     UPPC_Initializer,
8362 
8363     /// A default argument.
8364     UPPC_DefaultArgument,
8365 
8366     /// The type of a non-type template parameter.
8367     UPPC_NonTypeTemplateParameterType,
8368 
8369     /// The type of an exception.
8370     UPPC_ExceptionType,
8371 
8372     /// Partial specialization.
8373     UPPC_PartialSpecialization,
8374 
8375     /// Microsoft __if_exists.
8376     UPPC_IfExists,
8377 
8378     /// Microsoft __if_not_exists.
8379     UPPC_IfNotExists,
8380 
8381     /// Lambda expression.
8382     UPPC_Lambda,
8383 
8384     /// Block expression.
8385     UPPC_Block,
8386 
8387     /// A type constraint.
8388     UPPC_TypeConstraint,
8389 
8390     // A requirement in a requires-expression.
8391     UPPC_Requirement,
8392 
8393     // A requires-clause.
8394     UPPC_RequiresClause,
8395   };
8396 
8397   /// Diagnose unexpanded parameter packs.
8398   ///
8399   /// \param Loc The location at which we should emit the diagnostic.
8400   ///
8401   /// \param UPPC The context in which we are diagnosing unexpanded
8402   /// parameter packs.
8403   ///
8404   /// \param Unexpanded the set of unexpanded parameter packs.
8405   ///
8406   /// \returns true if an error occurred, false otherwise.
8407   bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
8408                                         UnexpandedParameterPackContext UPPC,
8409                                   ArrayRef<UnexpandedParameterPack> Unexpanded);
8410 
8411   /// If the given type contains an unexpanded parameter pack,
8412   /// diagnose the error.
8413   ///
8414   /// \param Loc The source location where a diagnostc should be emitted.
8415   ///
8416   /// \param T The type that is being checked for unexpanded parameter
8417   /// packs.
8418   ///
8419   /// \returns true if an error occurred, false otherwise.
8420   bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
8421                                        UnexpandedParameterPackContext UPPC);
8422 
8423   /// If the given expression contains an unexpanded parameter
8424   /// pack, diagnose the error.
8425   ///
8426   /// \param E The expression that is being checked for unexpanded
8427   /// parameter packs.
8428   ///
8429   /// \returns true if an error occurred, false otherwise.
8430   bool DiagnoseUnexpandedParameterPack(Expr *E,
8431                        UnexpandedParameterPackContext UPPC = UPPC_Expression);
8432 
8433   /// If the given requirees-expression contains an unexpanded reference to one
8434   /// of its own parameter packs, diagnose the error.
8435   ///
8436   /// \param RE The requiress-expression that is being checked for unexpanded
8437   /// parameter packs.
8438   ///
8439   /// \returns true if an error occurred, false otherwise.
8440   bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE);
8441 
8442   /// If the given nested-name-specifier contains an unexpanded
8443   /// parameter pack, diagnose the error.
8444   ///
8445   /// \param SS The nested-name-specifier that is being checked for
8446   /// unexpanded parameter packs.
8447   ///
8448   /// \returns true if an error occurred, false otherwise.
8449   bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
8450                                        UnexpandedParameterPackContext UPPC);
8451 
8452   /// If the given name contains an unexpanded parameter pack,
8453   /// diagnose the error.
8454   ///
8455   /// \param NameInfo The name (with source location information) that
8456   /// is being checked for unexpanded parameter packs.
8457   ///
8458   /// \returns true if an error occurred, false otherwise.
8459   bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
8460                                        UnexpandedParameterPackContext UPPC);
8461 
8462   /// If the given template name contains an unexpanded parameter pack,
8463   /// diagnose the error.
8464   ///
8465   /// \param Loc The location of the template name.
8466   ///
8467   /// \param Template The template name that is being checked for unexpanded
8468   /// parameter packs.
8469   ///
8470   /// \returns true if an error occurred, false otherwise.
8471   bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
8472                                        TemplateName Template,
8473                                        UnexpandedParameterPackContext UPPC);
8474 
8475   /// If the given template argument contains an unexpanded parameter
8476   /// pack, diagnose the error.
8477   ///
8478   /// \param Arg The template argument that is being checked for unexpanded
8479   /// parameter packs.
8480   ///
8481   /// \returns true if an error occurred, false otherwise.
8482   bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
8483                                        UnexpandedParameterPackContext UPPC);
8484 
8485   /// Collect the set of unexpanded parameter packs within the given
8486   /// template argument.
8487   ///
8488   /// \param Arg The template argument that will be traversed to find
8489   /// unexpanded parameter packs.
8490   void collectUnexpandedParameterPacks(TemplateArgument Arg,
8491                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8492 
8493   /// Collect the set of unexpanded parameter packs within the given
8494   /// template argument.
8495   ///
8496   /// \param Arg The template argument that will be traversed to find
8497   /// unexpanded parameter packs.
8498   void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
8499                     SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8500 
8501   /// Collect the set of unexpanded parameter packs within the given
8502   /// type.
8503   ///
8504   /// \param T The type that will be traversed to find
8505   /// unexpanded parameter packs.
8506   void collectUnexpandedParameterPacks(QualType T,
8507                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8508 
8509   /// Collect the set of unexpanded parameter packs within the given
8510   /// type.
8511   ///
8512   /// \param TL The type that will be traversed to find
8513   /// unexpanded parameter packs.
8514   void collectUnexpandedParameterPacks(TypeLoc TL,
8515                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8516 
8517   /// Collect the set of unexpanded parameter packs within the given
8518   /// nested-name-specifier.
8519   ///
8520   /// \param NNS The nested-name-specifier that will be traversed to find
8521   /// unexpanded parameter packs.
8522   void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
8523                          SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8524 
8525   /// Collect the set of unexpanded parameter packs within the given
8526   /// name.
8527   ///
8528   /// \param NameInfo The name that will be traversed to find
8529   /// unexpanded parameter packs.
8530   void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
8531                          SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8532 
8533   /// Invoked when parsing a template argument followed by an
8534   /// ellipsis, which creates a pack expansion.
8535   ///
8536   /// \param Arg The template argument preceding the ellipsis, which
8537   /// may already be invalid.
8538   ///
8539   /// \param EllipsisLoc The location of the ellipsis.
8540   ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
8541                                             SourceLocation EllipsisLoc);
8542 
8543   /// Invoked when parsing a type followed by an ellipsis, which
8544   /// creates a pack expansion.
8545   ///
8546   /// \param Type The type preceding the ellipsis, which will become
8547   /// the pattern of the pack expansion.
8548   ///
8549   /// \param EllipsisLoc The location of the ellipsis.
8550   TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
8551 
8552   /// Construct a pack expansion type from the pattern of the pack
8553   /// expansion.
8554   TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
8555                                      SourceLocation EllipsisLoc,
8556                                      Optional<unsigned> NumExpansions);
8557 
8558   /// Construct a pack expansion type from the pattern of the pack
8559   /// expansion.
8560   QualType CheckPackExpansion(QualType Pattern,
8561                               SourceRange PatternRange,
8562                               SourceLocation EllipsisLoc,
8563                               Optional<unsigned> NumExpansions);
8564 
8565   /// Invoked when parsing an expression followed by an ellipsis, which
8566   /// creates a pack expansion.
8567   ///
8568   /// \param Pattern The expression preceding the ellipsis, which will become
8569   /// the pattern of the pack expansion.
8570   ///
8571   /// \param EllipsisLoc The location of the ellipsis.
8572   ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
8573 
8574   /// Invoked when parsing an expression followed by an ellipsis, which
8575   /// creates a pack expansion.
8576   ///
8577   /// \param Pattern The expression preceding the ellipsis, which will become
8578   /// the pattern of the pack expansion.
8579   ///
8580   /// \param EllipsisLoc The location of the ellipsis.
8581   ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
8582                                 Optional<unsigned> NumExpansions);
8583 
8584   /// Determine whether we could expand a pack expansion with the
8585   /// given set of parameter packs into separate arguments by repeatedly
8586   /// transforming the pattern.
8587   ///
8588   /// \param EllipsisLoc The location of the ellipsis that identifies the
8589   /// pack expansion.
8590   ///
8591   /// \param PatternRange The source range that covers the entire pattern of
8592   /// the pack expansion.
8593   ///
8594   /// \param Unexpanded The set of unexpanded parameter packs within the
8595   /// pattern.
8596   ///
8597   /// \param ShouldExpand Will be set to \c true if the transformer should
8598   /// expand the corresponding pack expansions into separate arguments. When
8599   /// set, \c NumExpansions must also be set.
8600   ///
8601   /// \param RetainExpansion Whether the caller should add an unexpanded
8602   /// pack expansion after all of the expanded arguments. This is used
8603   /// when extending explicitly-specified template argument packs per
8604   /// C++0x [temp.arg.explicit]p9.
8605   ///
8606   /// \param NumExpansions The number of separate arguments that will be in
8607   /// the expanded form of the corresponding pack expansion. This is both an
8608   /// input and an output parameter, which can be set by the caller if the
8609   /// number of expansions is known a priori (e.g., due to a prior substitution)
8610   /// and will be set by the callee when the number of expansions is known.
8611   /// The callee must set this value when \c ShouldExpand is \c true; it may
8612   /// set this value in other cases.
8613   ///
8614   /// \returns true if an error occurred (e.g., because the parameter packs
8615   /// are to be instantiated with arguments of different lengths), false
8616   /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
8617   /// must be set.
8618   bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
8619                                        SourceRange PatternRange,
8620                              ArrayRef<UnexpandedParameterPack> Unexpanded,
8621                              const MultiLevelTemplateArgumentList &TemplateArgs,
8622                                        bool &ShouldExpand,
8623                                        bool &RetainExpansion,
8624                                        Optional<unsigned> &NumExpansions);
8625 
8626   /// Determine the number of arguments in the given pack expansion
8627   /// type.
8628   ///
8629   /// This routine assumes that the number of arguments in the expansion is
8630   /// consistent across all of the unexpanded parameter packs in its pattern.
8631   ///
8632   /// Returns an empty Optional if the type can't be expanded.
8633   Optional<unsigned> getNumArgumentsInExpansion(QualType T,
8634       const MultiLevelTemplateArgumentList &TemplateArgs);
8635 
8636   /// Determine whether the given declarator contains any unexpanded
8637   /// parameter packs.
8638   ///
8639   /// This routine is used by the parser to disambiguate function declarators
8640   /// with an ellipsis prior to the ')', e.g.,
8641   ///
8642   /// \code
8643   ///   void f(T...);
8644   /// \endcode
8645   ///
8646   /// To determine whether we have an (unnamed) function parameter pack or
8647   /// a variadic function.
8648   ///
8649   /// \returns true if the declarator contains any unexpanded parameter packs,
8650   /// false otherwise.
8651   bool containsUnexpandedParameterPacks(Declarator &D);
8652 
8653   /// Returns the pattern of the pack expansion for a template argument.
8654   ///
8655   /// \param OrigLoc The template argument to expand.
8656   ///
8657   /// \param Ellipsis Will be set to the location of the ellipsis.
8658   ///
8659   /// \param NumExpansions Will be set to the number of expansions that will
8660   /// be generated from this pack expansion, if known a priori.
8661   TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
8662       TemplateArgumentLoc OrigLoc,
8663       SourceLocation &Ellipsis,
8664       Optional<unsigned> &NumExpansions) const;
8665 
8666   /// Given a template argument that contains an unexpanded parameter pack, but
8667   /// which has already been substituted, attempt to determine the number of
8668   /// elements that will be produced once this argument is fully-expanded.
8669   ///
8670   /// This is intended for use when transforming 'sizeof...(Arg)' in order to
8671   /// avoid actually expanding the pack where possible.
8672   Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
8673 
8674   //===--------------------------------------------------------------------===//
8675   // C++ Template Argument Deduction (C++ [temp.deduct])
8676   //===--------------------------------------------------------------------===//
8677 
8678   /// Adjust the type \p ArgFunctionType to match the calling convention,
8679   /// noreturn, and optionally the exception specification of \p FunctionType.
8680   /// Deduction often wants to ignore these properties when matching function
8681   /// types.
8682   QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
8683                                bool AdjustExceptionSpec = false);
8684 
8685   /// Describes the result of template argument deduction.
8686   ///
8687   /// The TemplateDeductionResult enumeration describes the result of
8688   /// template argument deduction, as returned from
8689   /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
8690   /// structure provides additional information about the results of
8691   /// template argument deduction, e.g., the deduced template argument
8692   /// list (if successful) or the specific template parameters or
8693   /// deduced arguments that were involved in the failure.
8694   enum TemplateDeductionResult {
8695     /// Template argument deduction was successful.
8696     TDK_Success = 0,
8697     /// The declaration was invalid; do nothing.
8698     TDK_Invalid,
8699     /// Template argument deduction exceeded the maximum template
8700     /// instantiation depth (which has already been diagnosed).
8701     TDK_InstantiationDepth,
8702     /// Template argument deduction did not deduce a value
8703     /// for every template parameter.
8704     TDK_Incomplete,
8705     /// Template argument deduction did not deduce a value for every
8706     /// expansion of an expanded template parameter pack.
8707     TDK_IncompletePack,
8708     /// Template argument deduction produced inconsistent
8709     /// deduced values for the given template parameter.
8710     TDK_Inconsistent,
8711     /// Template argument deduction failed due to inconsistent
8712     /// cv-qualifiers on a template parameter type that would
8713     /// otherwise be deduced, e.g., we tried to deduce T in "const T"
8714     /// but were given a non-const "X".
8715     TDK_Underqualified,
8716     /// Substitution of the deduced template argument values
8717     /// resulted in an error.
8718     TDK_SubstitutionFailure,
8719     /// After substituting deduced template arguments, a dependent
8720     /// parameter type did not match the corresponding argument.
8721     TDK_DeducedMismatch,
8722     /// After substituting deduced template arguments, an element of
8723     /// a dependent parameter type did not match the corresponding element
8724     /// of the corresponding argument (when deducing from an initializer list).
8725     TDK_DeducedMismatchNested,
8726     /// A non-depnedent component of the parameter did not match the
8727     /// corresponding component of the argument.
8728     TDK_NonDeducedMismatch,
8729     /// When performing template argument deduction for a function
8730     /// template, there were too many call arguments.
8731     TDK_TooManyArguments,
8732     /// When performing template argument deduction for a function
8733     /// template, there were too few call arguments.
8734     TDK_TooFewArguments,
8735     /// The explicitly-specified template arguments were not valid
8736     /// template arguments for the given template.
8737     TDK_InvalidExplicitArguments,
8738     /// Checking non-dependent argument conversions failed.
8739     TDK_NonDependentConversionFailure,
8740     /// The deduced arguments did not satisfy the constraints associated
8741     /// with the template.
8742     TDK_ConstraintsNotSatisfied,
8743     /// Deduction failed; that's all we know.
8744     TDK_MiscellaneousDeductionFailure,
8745     /// CUDA Target attributes do not match.
8746     TDK_CUDATargetMismatch
8747   };
8748 
8749   TemplateDeductionResult
8750   DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
8751                           const TemplateArgumentList &TemplateArgs,
8752                           sema::TemplateDeductionInfo &Info);
8753 
8754   TemplateDeductionResult
8755   DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
8756                           const TemplateArgumentList &TemplateArgs,
8757                           sema::TemplateDeductionInfo &Info);
8758 
8759   TemplateDeductionResult SubstituteExplicitTemplateArguments(
8760       FunctionTemplateDecl *FunctionTemplate,
8761       TemplateArgumentListInfo &ExplicitTemplateArgs,
8762       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
8763       SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
8764       sema::TemplateDeductionInfo &Info);
8765 
8766   /// brief A function argument from which we performed template argument
8767   // deduction for a call.
8768   struct OriginalCallArg {
8769     OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
8770                     unsigned ArgIdx, QualType OriginalArgType)
8771         : OriginalParamType(OriginalParamType),
8772           DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
8773           OriginalArgType(OriginalArgType) {}
8774 
8775     QualType OriginalParamType;
8776     bool DecomposedParam;
8777     unsigned ArgIdx;
8778     QualType OriginalArgType;
8779   };
8780 
8781   TemplateDeductionResult FinishTemplateArgumentDeduction(
8782       FunctionTemplateDecl *FunctionTemplate,
8783       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
8784       unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
8785       sema::TemplateDeductionInfo &Info,
8786       SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
8787       bool PartialOverloading = false,
8788       llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
8789 
8790   TemplateDeductionResult DeduceTemplateArguments(
8791       FunctionTemplateDecl *FunctionTemplate,
8792       TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8793       FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
8794       bool PartialOverloading,
8795       llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
8796 
8797   TemplateDeductionResult
8798   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
8799                           TemplateArgumentListInfo *ExplicitTemplateArgs,
8800                           QualType ArgFunctionType,
8801                           FunctionDecl *&Specialization,
8802                           sema::TemplateDeductionInfo &Info,
8803                           bool IsAddressOfFunction = false);
8804 
8805   TemplateDeductionResult
8806   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
8807                           QualType ToType,
8808                           CXXConversionDecl *&Specialization,
8809                           sema::TemplateDeductionInfo &Info);
8810 
8811   TemplateDeductionResult
8812   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
8813                           TemplateArgumentListInfo *ExplicitTemplateArgs,
8814                           FunctionDecl *&Specialization,
8815                           sema::TemplateDeductionInfo &Info,
8816                           bool IsAddressOfFunction = false);
8817 
8818   /// Substitute Replacement for \p auto in \p TypeWithAuto
8819   QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
8820   /// Substitute Replacement for auto in TypeWithAuto
8821   TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
8822                                           QualType Replacement);
8823 
8824   // Substitute auto in TypeWithAuto for a Dependent auto type
8825   QualType SubstAutoTypeDependent(QualType TypeWithAuto);
8826 
8827   // Substitute auto in TypeWithAuto for a Dependent auto type
8828   TypeSourceInfo *
8829   SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto);
8830 
8831   /// Completely replace the \c auto in \p TypeWithAuto by
8832   /// \p Replacement. This does not retain any \c auto type sugar.
8833   QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
8834   TypeSourceInfo *ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
8835                                             QualType Replacement);
8836 
8837   /// Result type of DeduceAutoType.
8838   enum DeduceAutoResult {
8839     DAR_Succeeded,
8840     DAR_Failed,
8841     DAR_FailedAlreadyDiagnosed
8842   };
8843 
8844   DeduceAutoResult
8845   DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
8846                  Optional<unsigned> DependentDeductionDepth = None,
8847                  bool IgnoreConstraints = false);
8848   DeduceAutoResult
8849   DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
8850                  Optional<unsigned> DependentDeductionDepth = None,
8851                  bool IgnoreConstraints = false);
8852   void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
8853   bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
8854                         bool Diagnose = true);
8855 
8856   /// Declare implicit deduction guides for a class template if we've
8857   /// not already done so.
8858   void DeclareImplicitDeductionGuides(TemplateDecl *Template,
8859                                       SourceLocation Loc);
8860 
8861   QualType DeduceTemplateSpecializationFromInitializer(
8862       TypeSourceInfo *TInfo, const InitializedEntity &Entity,
8863       const InitializationKind &Kind, MultiExprArg Init);
8864 
8865   QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
8866                                         QualType Type, TypeSourceInfo *TSI,
8867                                         SourceRange Range, bool DirectInit,
8868                                         Expr *Init);
8869 
8870   TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
8871 
8872   bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
8873                                         SourceLocation ReturnLoc,
8874                                         Expr *&RetExpr, const AutoType *AT);
8875 
8876   FunctionTemplateDecl *getMoreSpecializedTemplate(
8877       FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc,
8878       TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
8879       unsigned NumCallArguments2, bool Reversed = false,
8880       bool AllowOrderingByConstraints = true);
8881   UnresolvedSetIterator
8882   getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
8883                      TemplateSpecCandidateSet &FailedCandidates,
8884                      SourceLocation Loc,
8885                      const PartialDiagnostic &NoneDiag,
8886                      const PartialDiagnostic &AmbigDiag,
8887                      const PartialDiagnostic &CandidateDiag,
8888                      bool Complain = true, QualType TargetType = QualType());
8889 
8890   ClassTemplatePartialSpecializationDecl *
8891   getMoreSpecializedPartialSpecialization(
8892                                   ClassTemplatePartialSpecializationDecl *PS1,
8893                                   ClassTemplatePartialSpecializationDecl *PS2,
8894                                   SourceLocation Loc);
8895 
8896   bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
8897                                     sema::TemplateDeductionInfo &Info);
8898 
8899   VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
8900       VarTemplatePartialSpecializationDecl *PS1,
8901       VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
8902 
8903   bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
8904                                     sema::TemplateDeductionInfo &Info);
8905 
8906   bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
8907       TemplateParameterList *PParam, TemplateDecl *AArg, SourceLocation Loc);
8908 
8909   void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
8910                                   unsigned Depth, llvm::SmallBitVector &Used);
8911 
8912   void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
8913                                   bool OnlyDeduced,
8914                                   unsigned Depth,
8915                                   llvm::SmallBitVector &Used);
8916   void MarkDeducedTemplateParameters(
8917                                   const FunctionTemplateDecl *FunctionTemplate,
8918                                   llvm::SmallBitVector &Deduced) {
8919     return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
8920   }
8921   static void MarkDeducedTemplateParameters(ASTContext &Ctx,
8922                                   const FunctionTemplateDecl *FunctionTemplate,
8923                                   llvm::SmallBitVector &Deduced);
8924 
8925   //===--------------------------------------------------------------------===//
8926   // C++ Template Instantiation
8927   //
8928 
8929   MultiLevelTemplateArgumentList getTemplateInstantiationArgs(
8930       const NamedDecl *D, const TemplateArgumentList *Innermost = nullptr,
8931       bool RelativeToPrimary = false, const FunctionDecl *Pattern = nullptr);
8932 
8933   /// A context in which code is being synthesized (where a source location
8934   /// alone is not sufficient to identify the context). This covers template
8935   /// instantiation and various forms of implicitly-generated functions.
8936   struct CodeSynthesisContext {
8937     /// The kind of template instantiation we are performing
8938     enum SynthesisKind {
8939       /// We are instantiating a template declaration. The entity is
8940       /// the declaration we're instantiating (e.g., a CXXRecordDecl).
8941       TemplateInstantiation,
8942 
8943       /// We are instantiating a default argument for a template
8944       /// parameter. The Entity is the template parameter whose argument is
8945       /// being instantiated, the Template is the template, and the
8946       /// TemplateArgs/NumTemplateArguments provide the template arguments as
8947       /// specified.
8948       DefaultTemplateArgumentInstantiation,
8949 
8950       /// We are instantiating a default argument for a function.
8951       /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
8952       /// provides the template arguments as specified.
8953       DefaultFunctionArgumentInstantiation,
8954 
8955       /// We are substituting explicit template arguments provided for
8956       /// a function template. The entity is a FunctionTemplateDecl.
8957       ExplicitTemplateArgumentSubstitution,
8958 
8959       /// We are substituting template argument determined as part of
8960       /// template argument deduction for either a class template
8961       /// partial specialization or a function template. The
8962       /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
8963       /// a TemplateDecl.
8964       DeducedTemplateArgumentSubstitution,
8965 
8966       /// We are substituting prior template arguments into a new
8967       /// template parameter. The template parameter itself is either a
8968       /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
8969       PriorTemplateArgumentSubstitution,
8970 
8971       /// We are checking the validity of a default template argument that
8972       /// has been used when naming a template-id.
8973       DefaultTemplateArgumentChecking,
8974 
8975       /// We are computing the exception specification for a defaulted special
8976       /// member function.
8977       ExceptionSpecEvaluation,
8978 
8979       /// We are instantiating the exception specification for a function
8980       /// template which was deferred until it was needed.
8981       ExceptionSpecInstantiation,
8982 
8983       /// We are instantiating a requirement of a requires expression.
8984       RequirementInstantiation,
8985 
8986       /// We are checking the satisfaction of a nested requirement of a requires
8987       /// expression.
8988       NestedRequirementConstraintsCheck,
8989 
8990       /// We are declaring an implicit special member function.
8991       DeclaringSpecialMember,
8992 
8993       /// We are declaring an implicit 'operator==' for a defaulted
8994       /// 'operator<=>'.
8995       DeclaringImplicitEqualityComparison,
8996 
8997       /// We are defining a synthesized function (such as a defaulted special
8998       /// member).
8999       DefiningSynthesizedFunction,
9000 
9001       // We are checking the constraints associated with a constrained entity or
9002       // the constraint expression of a concept. This includes the checks that
9003       // atomic constraints have the type 'bool' and that they can be constant
9004       // evaluated.
9005       ConstraintsCheck,
9006 
9007       // We are substituting template arguments into a constraint expression.
9008       ConstraintSubstitution,
9009 
9010       // We are normalizing a constraint expression.
9011       ConstraintNormalization,
9012 
9013       // We are substituting into the parameter mapping of an atomic constraint
9014       // during normalization.
9015       ParameterMappingSubstitution,
9016 
9017       /// We are rewriting a comparison operator in terms of an operator<=>.
9018       RewritingOperatorAsSpaceship,
9019 
9020       /// We are initializing a structured binding.
9021       InitializingStructuredBinding,
9022 
9023       /// We are marking a class as __dllexport.
9024       MarkingClassDllexported,
9025 
9026       /// We are building an implied call from __builtin_dump_struct. The
9027       /// arguments are in CallArgs.
9028       BuildingBuiltinDumpStructCall,
9029 
9030       /// Added for Template instantiation observation.
9031       /// Memoization means we are _not_ instantiating a template because
9032       /// it is already instantiated (but we entered a context where we
9033       /// would have had to if it was not already instantiated).
9034       Memoization
9035     } Kind;
9036 
9037     /// Was the enclosing context a non-instantiation SFINAE context?
9038     bool SavedInNonInstantiationSFINAEContext;
9039 
9040     /// The point of instantiation or synthesis within the source code.
9041     SourceLocation PointOfInstantiation;
9042 
9043     /// The entity that is being synthesized.
9044     Decl *Entity;
9045 
9046     /// The template (or partial specialization) in which we are
9047     /// performing the instantiation, for substitutions of prior template
9048     /// arguments.
9049     NamedDecl *Template;
9050 
9051     union {
9052       /// The list of template arguments we are substituting, if they
9053       /// are not part of the entity.
9054       const TemplateArgument *TemplateArgs;
9055 
9056       /// The list of argument expressions in a synthesized call.
9057       const Expr *const *CallArgs;
9058     };
9059 
9060     // FIXME: Wrap this union around more members, or perhaps store the
9061     // kind-specific members in the RAII object owning the context.
9062     union {
9063       /// The number of template arguments in TemplateArgs.
9064       unsigned NumTemplateArgs;
9065 
9066       /// The number of expressions in CallArgs.
9067       unsigned NumCallArgs;
9068 
9069       /// The special member being declared or defined.
9070       CXXSpecialMember SpecialMember;
9071     };
9072 
9073     ArrayRef<TemplateArgument> template_arguments() const {
9074       assert(Kind != DeclaringSpecialMember);
9075       return {TemplateArgs, NumTemplateArgs};
9076     }
9077 
9078     /// The template deduction info object associated with the
9079     /// substitution or checking of explicit or deduced template arguments.
9080     sema::TemplateDeductionInfo *DeductionInfo;
9081 
9082     /// The source range that covers the construct that cause
9083     /// the instantiation, e.g., the template-id that causes a class
9084     /// template instantiation.
9085     SourceRange InstantiationRange;
9086 
9087     CodeSynthesisContext()
9088         : Kind(TemplateInstantiation),
9089           SavedInNonInstantiationSFINAEContext(false), Entity(nullptr),
9090           Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0),
9091           DeductionInfo(nullptr) {}
9092 
9093     /// Determines whether this template is an actual instantiation
9094     /// that should be counted toward the maximum instantiation depth.
9095     bool isInstantiationRecord() const;
9096   };
9097 
9098   /// List of active code synthesis contexts.
9099   ///
9100   /// This vector is treated as a stack. As synthesis of one entity requires
9101   /// synthesis of another, additional contexts are pushed onto the stack.
9102   SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
9103 
9104   /// Specializations whose definitions are currently being instantiated.
9105   llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
9106 
9107   /// Non-dependent types used in templates that have already been instantiated
9108   /// by some template instantiation.
9109   llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
9110 
9111   /// Extra modules inspected when performing a lookup during a template
9112   /// instantiation. Computed lazily.
9113   SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
9114 
9115   /// Cache of additional modules that should be used for name lookup
9116   /// within the current template instantiation. Computed lazily; use
9117   /// getLookupModules() to get a complete set.
9118   llvm::DenseSet<Module*> LookupModulesCache;
9119 
9120   /// Get the set of additional modules that should be checked during
9121   /// name lookup. A module and its imports become visible when instanting a
9122   /// template defined within it.
9123   llvm::DenseSet<Module*> &getLookupModules();
9124 
9125   /// Map from the most recent declaration of a namespace to the most
9126   /// recent visible declaration of that namespace.
9127   llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
9128 
9129   /// Whether we are in a SFINAE context that is not associated with
9130   /// template instantiation.
9131   ///
9132   /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
9133   /// of a template instantiation or template argument deduction.
9134   bool InNonInstantiationSFINAEContext;
9135 
9136   /// The number of \p CodeSynthesisContexts that are not template
9137   /// instantiations and, therefore, should not be counted as part of the
9138   /// instantiation depth.
9139   ///
9140   /// When the instantiation depth reaches the user-configurable limit
9141   /// \p LangOptions::InstantiationDepth we will abort instantiation.
9142   // FIXME: Should we have a similar limit for other forms of synthesis?
9143   unsigned NonInstantiationEntries;
9144 
9145   /// The depth of the context stack at the point when the most recent
9146   /// error or warning was produced.
9147   ///
9148   /// This value is used to suppress printing of redundant context stacks
9149   /// when there are multiple errors or warnings in the same instantiation.
9150   // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
9151   unsigned LastEmittedCodeSynthesisContextDepth = 0;
9152 
9153   /// The template instantiation callbacks to trace or track
9154   /// instantiations (objects can be chained).
9155   ///
9156   /// This callbacks is used to print, trace or track template
9157   /// instantiations as they are being constructed.
9158   std::vector<std::unique_ptr<TemplateInstantiationCallback>>
9159       TemplateInstCallbacks;
9160 
9161   /// The current index into pack expansion arguments that will be
9162   /// used for substitution of parameter packs.
9163   ///
9164   /// The pack expansion index will be -1 to indicate that parameter packs
9165   /// should be instantiated as themselves. Otherwise, the index specifies
9166   /// which argument within the parameter pack will be used for substitution.
9167   int ArgumentPackSubstitutionIndex;
9168 
9169   /// RAII object used to change the argument pack substitution index
9170   /// within a \c Sema object.
9171   ///
9172   /// See \c ArgumentPackSubstitutionIndex for more information.
9173   class ArgumentPackSubstitutionIndexRAII {
9174     Sema &Self;
9175     int OldSubstitutionIndex;
9176 
9177   public:
9178     ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
9179       : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
9180       Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
9181     }
9182 
9183     ~ArgumentPackSubstitutionIndexRAII() {
9184       Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
9185     }
9186   };
9187 
9188   friend class ArgumentPackSubstitutionRAII;
9189 
9190   /// For each declaration that involved template argument deduction, the
9191   /// set of diagnostics that were suppressed during that template argument
9192   /// deduction.
9193   ///
9194   /// FIXME: Serialize this structure to the AST file.
9195   typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
9196     SuppressedDiagnosticsMap;
9197   SuppressedDiagnosticsMap SuppressedDiagnostics;
9198 
9199   /// A stack object to be created when performing template
9200   /// instantiation.
9201   ///
9202   /// Construction of an object of type \c InstantiatingTemplate
9203   /// pushes the current instantiation onto the stack of active
9204   /// instantiations. If the size of this stack exceeds the maximum
9205   /// number of recursive template instantiations, construction
9206   /// produces an error and evaluates true.
9207   ///
9208   /// Destruction of this object will pop the named instantiation off
9209   /// the stack.
9210   struct InstantiatingTemplate {
9211     /// Note that we are instantiating a class template,
9212     /// function template, variable template, alias template,
9213     /// or a member thereof.
9214     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9215                           Decl *Entity,
9216                           SourceRange InstantiationRange = SourceRange());
9217 
9218     struct ExceptionSpecification {};
9219     /// Note that we are instantiating an exception specification
9220     /// of a function template.
9221     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9222                           FunctionDecl *Entity, ExceptionSpecification,
9223                           SourceRange InstantiationRange = SourceRange());
9224 
9225     /// Note that we are instantiating a default argument in a
9226     /// template-id.
9227     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9228                           TemplateParameter Param, TemplateDecl *Template,
9229                           ArrayRef<TemplateArgument> TemplateArgs,
9230                           SourceRange InstantiationRange = SourceRange());
9231 
9232     /// Note that we are substituting either explicitly-specified or
9233     /// deduced template arguments during function template argument deduction.
9234     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9235                           FunctionTemplateDecl *FunctionTemplate,
9236                           ArrayRef<TemplateArgument> TemplateArgs,
9237                           CodeSynthesisContext::SynthesisKind Kind,
9238                           sema::TemplateDeductionInfo &DeductionInfo,
9239                           SourceRange InstantiationRange = SourceRange());
9240 
9241     /// Note that we are instantiating as part of template
9242     /// argument deduction for a class template declaration.
9243     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9244                           TemplateDecl *Template,
9245                           ArrayRef<TemplateArgument> TemplateArgs,
9246                           sema::TemplateDeductionInfo &DeductionInfo,
9247                           SourceRange InstantiationRange = SourceRange());
9248 
9249     /// Note that we are instantiating as part of template
9250     /// argument deduction for a class template partial
9251     /// specialization.
9252     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9253                           ClassTemplatePartialSpecializationDecl *PartialSpec,
9254                           ArrayRef<TemplateArgument> TemplateArgs,
9255                           sema::TemplateDeductionInfo &DeductionInfo,
9256                           SourceRange InstantiationRange = SourceRange());
9257 
9258     /// Note that we are instantiating as part of template
9259     /// argument deduction for a variable template partial
9260     /// specialization.
9261     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9262                           VarTemplatePartialSpecializationDecl *PartialSpec,
9263                           ArrayRef<TemplateArgument> TemplateArgs,
9264                           sema::TemplateDeductionInfo &DeductionInfo,
9265                           SourceRange InstantiationRange = SourceRange());
9266 
9267     /// Note that we are instantiating a default argument for a function
9268     /// parameter.
9269     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9270                           ParmVarDecl *Param,
9271                           ArrayRef<TemplateArgument> TemplateArgs,
9272                           SourceRange InstantiationRange = SourceRange());
9273 
9274     /// Note that we are substituting prior template arguments into a
9275     /// non-type parameter.
9276     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9277                           NamedDecl *Template,
9278                           NonTypeTemplateParmDecl *Param,
9279                           ArrayRef<TemplateArgument> TemplateArgs,
9280                           SourceRange InstantiationRange);
9281 
9282     /// Note that we are substituting prior template arguments into a
9283     /// template template parameter.
9284     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9285                           NamedDecl *Template,
9286                           TemplateTemplateParmDecl *Param,
9287                           ArrayRef<TemplateArgument> TemplateArgs,
9288                           SourceRange InstantiationRange);
9289 
9290     /// Note that we are checking the default template argument
9291     /// against the template parameter for a given template-id.
9292     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9293                           TemplateDecl *Template,
9294                           NamedDecl *Param,
9295                           ArrayRef<TemplateArgument> TemplateArgs,
9296                           SourceRange InstantiationRange);
9297 
9298     struct ConstraintsCheck {};
9299     /// \brief Note that we are checking the constraints associated with some
9300     /// constrained entity (a concept declaration or a template with associated
9301     /// constraints).
9302     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9303                           ConstraintsCheck, NamedDecl *Template,
9304                           ArrayRef<TemplateArgument> TemplateArgs,
9305                           SourceRange InstantiationRange);
9306 
9307     struct ConstraintSubstitution {};
9308     /// \brief Note that we are checking a constraint expression associated
9309     /// with a template declaration or as part of the satisfaction check of a
9310     /// concept.
9311     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9312                           ConstraintSubstitution, NamedDecl *Template,
9313                           sema::TemplateDeductionInfo &DeductionInfo,
9314                           SourceRange InstantiationRange);
9315 
9316     struct ConstraintNormalization {};
9317     /// \brief Note that we are normalizing a constraint expression.
9318     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9319                           ConstraintNormalization, NamedDecl *Template,
9320                           SourceRange InstantiationRange);
9321 
9322     struct ParameterMappingSubstitution {};
9323     /// \brief Note that we are subtituting into the parameter mapping of an
9324     /// atomic constraint during constraint normalization.
9325     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9326                           ParameterMappingSubstitution, NamedDecl *Template,
9327                           SourceRange InstantiationRange);
9328 
9329     /// \brief Note that we are substituting template arguments into a part of
9330     /// a requirement of a requires expression.
9331     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9332                           concepts::Requirement *Req,
9333                           sema::TemplateDeductionInfo &DeductionInfo,
9334                           SourceRange InstantiationRange = SourceRange());
9335 
9336     /// \brief Note that we are checking the satisfaction of the constraint
9337     /// expression inside of a nested requirement.
9338     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9339                           concepts::NestedRequirement *Req, ConstraintsCheck,
9340                           SourceRange InstantiationRange = SourceRange());
9341 
9342     /// Note that we have finished instantiating this template.
9343     void Clear();
9344 
9345     ~InstantiatingTemplate() { Clear(); }
9346 
9347     /// Determines whether we have exceeded the maximum
9348     /// recursive template instantiations.
9349     bool isInvalid() const { return Invalid; }
9350 
9351     /// Determine whether we are already instantiating this
9352     /// specialization in some surrounding active instantiation.
9353     bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
9354 
9355   private:
9356     Sema &SemaRef;
9357     bool Invalid;
9358     bool AlreadyInstantiating;
9359     bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
9360                                  SourceRange InstantiationRange);
9361 
9362     InstantiatingTemplate(
9363         Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
9364         SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
9365         Decl *Entity, NamedDecl *Template = nullptr,
9366         ArrayRef<TemplateArgument> TemplateArgs = None,
9367         sema::TemplateDeductionInfo *DeductionInfo = nullptr);
9368 
9369     InstantiatingTemplate(const InstantiatingTemplate&) = delete;
9370 
9371     InstantiatingTemplate&
9372     operator=(const InstantiatingTemplate&) = delete;
9373   };
9374 
9375   void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
9376   void popCodeSynthesisContext();
9377 
9378   /// Determine whether we are currently performing template instantiation.
9379   bool inTemplateInstantiation() const {
9380     return CodeSynthesisContexts.size() > NonInstantiationEntries;
9381   }
9382 
9383   void PrintContextStack() {
9384     if (!CodeSynthesisContexts.empty() &&
9385         CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
9386       PrintInstantiationStack();
9387       LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
9388     }
9389     if (PragmaAttributeCurrentTargetDecl)
9390       PrintPragmaAttributeInstantiationPoint();
9391   }
9392   void PrintInstantiationStack();
9393 
9394   void PrintPragmaAttributeInstantiationPoint();
9395 
9396   /// Determines whether we are currently in a context where
9397   /// template argument substitution failures are not considered
9398   /// errors.
9399   ///
9400   /// \returns An empty \c Optional if we're not in a SFINAE context.
9401   /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
9402   /// template-deduction context object, which can be used to capture
9403   /// diagnostics that will be suppressed.
9404   Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
9405 
9406   /// Determines whether we are currently in a context that
9407   /// is not evaluated as per C++ [expr] p5.
9408   bool isUnevaluatedContext() const {
9409     assert(!ExprEvalContexts.empty() &&
9410            "Must be in an expression evaluation context");
9411     return ExprEvalContexts.back().isUnevaluated();
9412   }
9413 
9414   bool isImmediateFunctionContext() const {
9415     assert(!ExprEvalContexts.empty() &&
9416            "Must be in an expression evaluation context");
9417     return ExprEvalContexts.back().isImmediateFunctionContext();
9418   }
9419 
9420   /// RAII class used to determine whether SFINAE has
9421   /// trapped any errors that occur during template argument
9422   /// deduction.
9423   class SFINAETrap {
9424     Sema &SemaRef;
9425     unsigned PrevSFINAEErrors;
9426     bool PrevInNonInstantiationSFINAEContext;
9427     bool PrevAccessCheckingSFINAE;
9428     bool PrevLastDiagnosticIgnored;
9429 
9430   public:
9431     explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
9432       : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
9433         PrevInNonInstantiationSFINAEContext(
9434                                       SemaRef.InNonInstantiationSFINAEContext),
9435         PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE),
9436         PrevLastDiagnosticIgnored(
9437             SemaRef.getDiagnostics().isLastDiagnosticIgnored())
9438     {
9439       if (!SemaRef.isSFINAEContext())
9440         SemaRef.InNonInstantiationSFINAEContext = true;
9441       SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
9442     }
9443 
9444     ~SFINAETrap() {
9445       SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
9446       SemaRef.InNonInstantiationSFINAEContext
9447         = PrevInNonInstantiationSFINAEContext;
9448       SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
9449       SemaRef.getDiagnostics().setLastDiagnosticIgnored(
9450           PrevLastDiagnosticIgnored);
9451     }
9452 
9453     /// Determine whether any SFINAE errors have been trapped.
9454     bool hasErrorOccurred() const {
9455       return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
9456     }
9457   };
9458 
9459   /// RAII class used to indicate that we are performing provisional
9460   /// semantic analysis to determine the validity of a construct, so
9461   /// typo-correction and diagnostics in the immediate context (not within
9462   /// implicitly-instantiated templates) should be suppressed.
9463   class TentativeAnalysisScope {
9464     Sema &SemaRef;
9465     // FIXME: Using a SFINAETrap for this is a hack.
9466     SFINAETrap Trap;
9467     bool PrevDisableTypoCorrection;
9468   public:
9469     explicit TentativeAnalysisScope(Sema &SemaRef)
9470         : SemaRef(SemaRef), Trap(SemaRef, true),
9471           PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
9472       SemaRef.DisableTypoCorrection = true;
9473     }
9474     ~TentativeAnalysisScope() {
9475       SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
9476     }
9477   };
9478 
9479   /// The current instantiation scope used to store local
9480   /// variables.
9481   LocalInstantiationScope *CurrentInstantiationScope;
9482 
9483   /// Tracks whether we are in a context where typo correction is
9484   /// disabled.
9485   bool DisableTypoCorrection;
9486 
9487   /// The number of typos corrected by CorrectTypo.
9488   unsigned TyposCorrected;
9489 
9490   typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
9491   typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
9492 
9493   /// A cache containing identifiers for which typo correction failed and
9494   /// their locations, so that repeated attempts to correct an identifier in a
9495   /// given location are ignored if typo correction already failed for it.
9496   IdentifierSourceLocations TypoCorrectionFailures;
9497 
9498   /// Worker object for performing CFG-based warnings.
9499   sema::AnalysisBasedWarnings AnalysisWarnings;
9500   threadSafety::BeforeSet *ThreadSafetyDeclCache;
9501 
9502   /// An entity for which implicit template instantiation is required.
9503   ///
9504   /// The source location associated with the declaration is the first place in
9505   /// the source code where the declaration was "used". It is not necessarily
9506   /// the point of instantiation (which will be either before or after the
9507   /// namespace-scope declaration that triggered this implicit instantiation),
9508   /// However, it is the location that diagnostics should generally refer to,
9509   /// because users will need to know what code triggered the instantiation.
9510   typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
9511 
9512   /// The queue of implicit template instantiations that are required
9513   /// but have not yet been performed.
9514   std::deque<PendingImplicitInstantiation> PendingInstantiations;
9515 
9516   /// Queue of implicit template instantiations that cannot be performed
9517   /// eagerly.
9518   SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations;
9519 
9520   class GlobalEagerInstantiationScope {
9521   public:
9522     GlobalEagerInstantiationScope(Sema &S, bool Enabled)
9523         : S(S), Enabled(Enabled) {
9524       if (!Enabled) return;
9525 
9526       SavedPendingInstantiations.swap(S.PendingInstantiations);
9527       SavedVTableUses.swap(S.VTableUses);
9528     }
9529 
9530     void perform() {
9531       if (Enabled) {
9532         S.DefineUsedVTables();
9533         S.PerformPendingInstantiations();
9534       }
9535     }
9536 
9537     ~GlobalEagerInstantiationScope() {
9538       if (!Enabled) return;
9539 
9540       // Restore the set of pending vtables.
9541       assert(S.VTableUses.empty() &&
9542              "VTableUses should be empty before it is discarded.");
9543       S.VTableUses.swap(SavedVTableUses);
9544 
9545       // Restore the set of pending implicit instantiations.
9546       if (S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) {
9547         assert(S.PendingInstantiations.empty() &&
9548                "PendingInstantiations should be empty before it is discarded.");
9549         S.PendingInstantiations.swap(SavedPendingInstantiations);
9550       } else {
9551         // Template instantiations in the PCH may be delayed until the TU.
9552         S.PendingInstantiations.swap(SavedPendingInstantiations);
9553         S.PendingInstantiations.insert(S.PendingInstantiations.end(),
9554                                        SavedPendingInstantiations.begin(),
9555                                        SavedPendingInstantiations.end());
9556       }
9557     }
9558 
9559   private:
9560     Sema &S;
9561     SmallVector<VTableUse, 16> SavedVTableUses;
9562     std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
9563     bool Enabled;
9564   };
9565 
9566   /// The queue of implicit template instantiations that are required
9567   /// and must be performed within the current local scope.
9568   ///
9569   /// This queue is only used for member functions of local classes in
9570   /// templates, which must be instantiated in the same scope as their
9571   /// enclosing function, so that they can reference function-local
9572   /// types, static variables, enumerators, etc.
9573   std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
9574 
9575   class LocalEagerInstantiationScope {
9576   public:
9577     LocalEagerInstantiationScope(Sema &S) : S(S) {
9578       SavedPendingLocalImplicitInstantiations.swap(
9579           S.PendingLocalImplicitInstantiations);
9580     }
9581 
9582     void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); }
9583 
9584     ~LocalEagerInstantiationScope() {
9585       assert(S.PendingLocalImplicitInstantiations.empty() &&
9586              "there shouldn't be any pending local implicit instantiations");
9587       SavedPendingLocalImplicitInstantiations.swap(
9588           S.PendingLocalImplicitInstantiations);
9589     }
9590 
9591   private:
9592     Sema &S;
9593     std::deque<PendingImplicitInstantiation>
9594         SavedPendingLocalImplicitInstantiations;
9595   };
9596 
9597   /// A helper class for building up ExtParameterInfos.
9598   class ExtParameterInfoBuilder {
9599     SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
9600     bool HasInteresting = false;
9601 
9602   public:
9603     /// Set the ExtParameterInfo for the parameter at the given index,
9604     ///
9605     void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
9606       assert(Infos.size() <= index);
9607       Infos.resize(index);
9608       Infos.push_back(info);
9609 
9610       if (!HasInteresting)
9611         HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
9612     }
9613 
9614     /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
9615     /// ExtParameterInfo array we've built up.
9616     const FunctionProtoType::ExtParameterInfo *
9617     getPointerOrNull(unsigned numParams) {
9618       if (!HasInteresting) return nullptr;
9619       Infos.resize(numParams);
9620       return Infos.data();
9621     }
9622   };
9623 
9624   void PerformPendingInstantiations(bool LocalOnly = false);
9625 
9626   TypeSourceInfo *SubstType(TypeSourceInfo *T,
9627                             const MultiLevelTemplateArgumentList &TemplateArgs,
9628                             SourceLocation Loc, DeclarationName Entity,
9629                             bool AllowDeducedTST = false);
9630 
9631   QualType SubstType(QualType T,
9632                      const MultiLevelTemplateArgumentList &TemplateArgs,
9633                      SourceLocation Loc, DeclarationName Entity);
9634 
9635   TypeSourceInfo *SubstType(TypeLoc TL,
9636                             const MultiLevelTemplateArgumentList &TemplateArgs,
9637                             SourceLocation Loc, DeclarationName Entity);
9638 
9639   TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
9640                             const MultiLevelTemplateArgumentList &TemplateArgs,
9641                                         SourceLocation Loc,
9642                                         DeclarationName Entity,
9643                                         CXXRecordDecl *ThisContext,
9644                                         Qualifiers ThisTypeQuals);
9645   void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
9646                           const MultiLevelTemplateArgumentList &Args);
9647   bool SubstExceptionSpec(SourceLocation Loc,
9648                           FunctionProtoType::ExceptionSpecInfo &ESI,
9649                           SmallVectorImpl<QualType> &ExceptionStorage,
9650                           const MultiLevelTemplateArgumentList &Args);
9651   ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
9652                             const MultiLevelTemplateArgumentList &TemplateArgs,
9653                                 int indexAdjustment,
9654                                 Optional<unsigned> NumExpansions,
9655                                 bool ExpectParameterPack);
9656   bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
9657                       const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
9658                       const MultiLevelTemplateArgumentList &TemplateArgs,
9659                       SmallVectorImpl<QualType> &ParamTypes,
9660                       SmallVectorImpl<ParmVarDecl *> *OutParams,
9661                       ExtParameterInfoBuilder &ParamInfos);
9662   ExprResult SubstExpr(Expr *E,
9663                        const MultiLevelTemplateArgumentList &TemplateArgs);
9664 
9665   /// Substitute the given template arguments into a list of
9666   /// expressions, expanding pack expansions if required.
9667   ///
9668   /// \param Exprs The list of expressions to substitute into.
9669   ///
9670   /// \param IsCall Whether this is some form of call, in which case
9671   /// default arguments will be dropped.
9672   ///
9673   /// \param TemplateArgs The set of template arguments to substitute.
9674   ///
9675   /// \param Outputs Will receive all of the substituted arguments.
9676   ///
9677   /// \returns true if an error occurred, false otherwise.
9678   bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
9679                   const MultiLevelTemplateArgumentList &TemplateArgs,
9680                   SmallVectorImpl<Expr *> &Outputs);
9681 
9682   StmtResult SubstStmt(Stmt *S,
9683                        const MultiLevelTemplateArgumentList &TemplateArgs);
9684 
9685   TemplateParameterList *
9686   SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
9687                       const MultiLevelTemplateArgumentList &TemplateArgs);
9688 
9689   bool
9690   SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
9691                          const MultiLevelTemplateArgumentList &TemplateArgs,
9692                          TemplateArgumentListInfo &Outputs);
9693 
9694 
9695   Decl *SubstDecl(Decl *D, DeclContext *Owner,
9696                   const MultiLevelTemplateArgumentList &TemplateArgs);
9697 
9698   /// Substitute the name and return type of a defaulted 'operator<=>' to form
9699   /// an implicit 'operator=='.
9700   FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
9701                                            FunctionDecl *Spaceship);
9702 
9703   ExprResult SubstInitializer(Expr *E,
9704                        const MultiLevelTemplateArgumentList &TemplateArgs,
9705                        bool CXXDirectInit);
9706 
9707   bool
9708   SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
9709                       CXXRecordDecl *Pattern,
9710                       const MultiLevelTemplateArgumentList &TemplateArgs);
9711 
9712   bool
9713   InstantiateClass(SourceLocation PointOfInstantiation,
9714                    CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
9715                    const MultiLevelTemplateArgumentList &TemplateArgs,
9716                    TemplateSpecializationKind TSK,
9717                    bool Complain = true);
9718 
9719   bool InstantiateEnum(SourceLocation PointOfInstantiation,
9720                        EnumDecl *Instantiation, EnumDecl *Pattern,
9721                        const MultiLevelTemplateArgumentList &TemplateArgs,
9722                        TemplateSpecializationKind TSK);
9723 
9724   bool InstantiateInClassInitializer(
9725       SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
9726       FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
9727 
9728   struct LateInstantiatedAttribute {
9729     const Attr *TmplAttr;
9730     LocalInstantiationScope *Scope;
9731     Decl *NewDecl;
9732 
9733     LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
9734                               Decl *D)
9735       : TmplAttr(A), Scope(S), NewDecl(D)
9736     { }
9737   };
9738   typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
9739 
9740   void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
9741                         const Decl *Pattern, Decl *Inst,
9742                         LateInstantiatedAttrVec *LateAttrs = nullptr,
9743                         LocalInstantiationScope *OuterMostScope = nullptr);
9744 
9745   void
9746   InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
9747                           const Decl *Pattern, Decl *Inst,
9748                           LateInstantiatedAttrVec *LateAttrs = nullptr,
9749                           LocalInstantiationScope *OuterMostScope = nullptr);
9750 
9751   void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor);
9752 
9753   bool usesPartialOrExplicitSpecialization(
9754       SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
9755 
9756   bool
9757   InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
9758                            ClassTemplateSpecializationDecl *ClassTemplateSpec,
9759                            TemplateSpecializationKind TSK,
9760                            bool Complain = true);
9761 
9762   void InstantiateClassMembers(SourceLocation PointOfInstantiation,
9763                                CXXRecordDecl *Instantiation,
9764                             const MultiLevelTemplateArgumentList &TemplateArgs,
9765                                TemplateSpecializationKind TSK);
9766 
9767   void InstantiateClassTemplateSpecializationMembers(
9768                                           SourceLocation PointOfInstantiation,
9769                            ClassTemplateSpecializationDecl *ClassTemplateSpec,
9770                                                 TemplateSpecializationKind TSK);
9771 
9772   NestedNameSpecifierLoc
9773   SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
9774                            const MultiLevelTemplateArgumentList &TemplateArgs);
9775 
9776   DeclarationNameInfo
9777   SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
9778                            const MultiLevelTemplateArgumentList &TemplateArgs);
9779   TemplateName
9780   SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
9781                     SourceLocation Loc,
9782                     const MultiLevelTemplateArgumentList &TemplateArgs);
9783 
9784   bool SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
9785                            const MultiLevelTemplateArgumentList &TemplateArgs);
9786 
9787   bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
9788                                   ParmVarDecl *Param);
9789   void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
9790                                 FunctionDecl *Function);
9791   bool CheckInstantiatedFunctionTemplateConstraints(
9792       SourceLocation PointOfInstantiation, FunctionDecl *Decl,
9793       ArrayRef<TemplateArgument> TemplateArgs,
9794       ConstraintSatisfaction &Satisfaction);
9795   FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
9796                                                const TemplateArgumentList *Args,
9797                                                SourceLocation Loc);
9798   void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
9799                                      FunctionDecl *Function,
9800                                      bool Recursive = false,
9801                                      bool DefinitionRequired = false,
9802                                      bool AtEndOfTU = false);
9803   VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
9804       VarTemplateDecl *VarTemplate, VarDecl *FromVar,
9805       const TemplateArgumentList &TemplateArgList,
9806       const TemplateArgumentListInfo &TemplateArgsInfo,
9807       SmallVectorImpl<TemplateArgument> &Converted,
9808       SourceLocation PointOfInstantiation,
9809       LateInstantiatedAttrVec *LateAttrs = nullptr,
9810       LocalInstantiationScope *StartingScope = nullptr);
9811   VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
9812       VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
9813       const MultiLevelTemplateArgumentList &TemplateArgs);
9814   void
9815   BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
9816                              const MultiLevelTemplateArgumentList &TemplateArgs,
9817                              LateInstantiatedAttrVec *LateAttrs,
9818                              DeclContext *Owner,
9819                              LocalInstantiationScope *StartingScope,
9820                              bool InstantiatingVarTemplate = false,
9821                              VarTemplateSpecializationDecl *PrevVTSD = nullptr);
9822 
9823   void InstantiateVariableInitializer(
9824       VarDecl *Var, VarDecl *OldVar,
9825       const MultiLevelTemplateArgumentList &TemplateArgs);
9826   void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
9827                                      VarDecl *Var, bool Recursive = false,
9828                                      bool DefinitionRequired = false,
9829                                      bool AtEndOfTU = false);
9830 
9831   void InstantiateMemInitializers(CXXConstructorDecl *New,
9832                                   const CXXConstructorDecl *Tmpl,
9833                             const MultiLevelTemplateArgumentList &TemplateArgs);
9834 
9835   NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
9836                           const MultiLevelTemplateArgumentList &TemplateArgs,
9837                           bool FindingInstantiatedContext = false);
9838   DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
9839                           const MultiLevelTemplateArgumentList &TemplateArgs);
9840 
9841   // Objective-C declarations.
9842   enum ObjCContainerKind {
9843     OCK_None = -1,
9844     OCK_Interface = 0,
9845     OCK_Protocol,
9846     OCK_Category,
9847     OCK_ClassExtension,
9848     OCK_Implementation,
9849     OCK_CategoryImplementation
9850   };
9851   ObjCContainerKind getObjCContainerKind() const;
9852 
9853   DeclResult actOnObjCTypeParam(Scope *S,
9854                                 ObjCTypeParamVariance variance,
9855                                 SourceLocation varianceLoc,
9856                                 unsigned index,
9857                                 IdentifierInfo *paramName,
9858                                 SourceLocation paramLoc,
9859                                 SourceLocation colonLoc,
9860                                 ParsedType typeBound);
9861 
9862   ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
9863                                             ArrayRef<Decl *> typeParams,
9864                                             SourceLocation rAngleLoc);
9865   void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
9866 
9867   ObjCInterfaceDecl *ActOnStartClassInterface(
9868       Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
9869       SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
9870       IdentifierInfo *SuperName, SourceLocation SuperLoc,
9871       ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange,
9872       Decl *const *ProtoRefs, unsigned NumProtoRefs,
9873       const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
9874       const ParsedAttributesView &AttrList);
9875 
9876   void ActOnSuperClassOfClassInterface(Scope *S,
9877                                        SourceLocation AtInterfaceLoc,
9878                                        ObjCInterfaceDecl *IDecl,
9879                                        IdentifierInfo *ClassName,
9880                                        SourceLocation ClassLoc,
9881                                        IdentifierInfo *SuperName,
9882                                        SourceLocation SuperLoc,
9883                                        ArrayRef<ParsedType> SuperTypeArgs,
9884                                        SourceRange SuperTypeArgsRange);
9885 
9886   void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
9887                                SmallVectorImpl<SourceLocation> &ProtocolLocs,
9888                                IdentifierInfo *SuperName,
9889                                SourceLocation SuperLoc);
9890 
9891   Decl *ActOnCompatibilityAlias(
9892                     SourceLocation AtCompatibilityAliasLoc,
9893                     IdentifierInfo *AliasName,  SourceLocation AliasLocation,
9894                     IdentifierInfo *ClassName, SourceLocation ClassLocation);
9895 
9896   bool CheckForwardProtocolDeclarationForCircularDependency(
9897     IdentifierInfo *PName,
9898     SourceLocation &PLoc, SourceLocation PrevLoc,
9899     const ObjCList<ObjCProtocolDecl> &PList);
9900 
9901   ObjCProtocolDecl *ActOnStartProtocolInterface(
9902       SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
9903       SourceLocation ProtocolLoc, Decl *const *ProtoRefNames,
9904       unsigned NumProtoRefs, const SourceLocation *ProtoLocs,
9905       SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList);
9906 
9907   ObjCCategoryDecl *ActOnStartCategoryInterface(
9908       SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
9909       SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
9910       IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
9911       Decl *const *ProtoRefs, unsigned NumProtoRefs,
9912       const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
9913       const ParsedAttributesView &AttrList);
9914 
9915   ObjCImplementationDecl *ActOnStartClassImplementation(
9916       SourceLocation AtClassImplLoc, IdentifierInfo *ClassName,
9917       SourceLocation ClassLoc, IdentifierInfo *SuperClassname,
9918       SourceLocation SuperClassLoc, const ParsedAttributesView &AttrList);
9919 
9920   ObjCCategoryImplDecl *ActOnStartCategoryImplementation(
9921       SourceLocation AtCatImplLoc, IdentifierInfo *ClassName,
9922       SourceLocation ClassLoc, IdentifierInfo *CatName, SourceLocation CatLoc,
9923       const ParsedAttributesView &AttrList);
9924 
9925   DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
9926                                                ArrayRef<Decl *> Decls);
9927 
9928   DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
9929                    IdentifierInfo **IdentList,
9930                    SourceLocation *IdentLocs,
9931                    ArrayRef<ObjCTypeParamList *> TypeParamLists,
9932                    unsigned NumElts);
9933 
9934   DeclGroupPtrTy
9935   ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
9936                                   ArrayRef<IdentifierLocPair> IdentList,
9937                                   const ParsedAttributesView &attrList);
9938 
9939   void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
9940                                ArrayRef<IdentifierLocPair> ProtocolId,
9941                                SmallVectorImpl<Decl *> &Protocols);
9942 
9943   void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
9944                                     SourceLocation ProtocolLoc,
9945                                     IdentifierInfo *TypeArgId,
9946                                     SourceLocation TypeArgLoc,
9947                                     bool SelectProtocolFirst = false);
9948 
9949   /// Given a list of identifiers (and their locations), resolve the
9950   /// names to either Objective-C protocol qualifiers or type
9951   /// arguments, as appropriate.
9952   void actOnObjCTypeArgsOrProtocolQualifiers(
9953          Scope *S,
9954          ParsedType baseType,
9955          SourceLocation lAngleLoc,
9956          ArrayRef<IdentifierInfo *> identifiers,
9957          ArrayRef<SourceLocation> identifierLocs,
9958          SourceLocation rAngleLoc,
9959          SourceLocation &typeArgsLAngleLoc,
9960          SmallVectorImpl<ParsedType> &typeArgs,
9961          SourceLocation &typeArgsRAngleLoc,
9962          SourceLocation &protocolLAngleLoc,
9963          SmallVectorImpl<Decl *> &protocols,
9964          SourceLocation &protocolRAngleLoc,
9965          bool warnOnIncompleteProtocols);
9966 
9967   /// Build a an Objective-C protocol-qualified 'id' type where no
9968   /// base type was specified.
9969   TypeResult actOnObjCProtocolQualifierType(
9970                SourceLocation lAngleLoc,
9971                ArrayRef<Decl *> protocols,
9972                ArrayRef<SourceLocation> protocolLocs,
9973                SourceLocation rAngleLoc);
9974 
9975   /// Build a specialized and/or protocol-qualified Objective-C type.
9976   TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
9977                Scope *S,
9978                SourceLocation Loc,
9979                ParsedType BaseType,
9980                SourceLocation TypeArgsLAngleLoc,
9981                ArrayRef<ParsedType> TypeArgs,
9982                SourceLocation TypeArgsRAngleLoc,
9983                SourceLocation ProtocolLAngleLoc,
9984                ArrayRef<Decl *> Protocols,
9985                ArrayRef<SourceLocation> ProtocolLocs,
9986                SourceLocation ProtocolRAngleLoc);
9987 
9988   /// Build an Objective-C type parameter type.
9989   QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
9990                                   SourceLocation ProtocolLAngleLoc,
9991                                   ArrayRef<ObjCProtocolDecl *> Protocols,
9992                                   ArrayRef<SourceLocation> ProtocolLocs,
9993                                   SourceLocation ProtocolRAngleLoc,
9994                                   bool FailOnError = false);
9995 
9996   /// Build an Objective-C object pointer type.
9997   QualType BuildObjCObjectType(QualType BaseType,
9998                                SourceLocation Loc,
9999                                SourceLocation TypeArgsLAngleLoc,
10000                                ArrayRef<TypeSourceInfo *> TypeArgs,
10001                                SourceLocation TypeArgsRAngleLoc,
10002                                SourceLocation ProtocolLAngleLoc,
10003                                ArrayRef<ObjCProtocolDecl *> Protocols,
10004                                ArrayRef<SourceLocation> ProtocolLocs,
10005                                SourceLocation ProtocolRAngleLoc,
10006                                bool FailOnError = false);
10007 
10008   /// Ensure attributes are consistent with type.
10009   /// \param [in, out] Attributes The attributes to check; they will
10010   /// be modified to be consistent with \p PropertyTy.
10011   void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
10012                                    SourceLocation Loc,
10013                                    unsigned &Attributes,
10014                                    bool propertyInPrimaryClass);
10015 
10016   /// Process the specified property declaration and create decls for the
10017   /// setters and getters as needed.
10018   /// \param property The property declaration being processed
10019   void ProcessPropertyDecl(ObjCPropertyDecl *property);
10020 
10021 
10022   void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
10023                                 ObjCPropertyDecl *SuperProperty,
10024                                 const IdentifierInfo *Name,
10025                                 bool OverridingProtocolProperty);
10026 
10027   void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
10028                                         ObjCInterfaceDecl *ID);
10029 
10030   Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
10031                    ArrayRef<Decl *> allMethods = None,
10032                    ArrayRef<DeclGroupPtrTy> allTUVars = None);
10033 
10034   Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
10035                       SourceLocation LParenLoc,
10036                       FieldDeclarator &FD, ObjCDeclSpec &ODS,
10037                       Selector GetterSel, Selector SetterSel,
10038                       tok::ObjCKeywordKind MethodImplKind,
10039                       DeclContext *lexicalDC = nullptr);
10040 
10041   Decl *ActOnPropertyImplDecl(Scope *S,
10042                               SourceLocation AtLoc,
10043                               SourceLocation PropertyLoc,
10044                               bool ImplKind,
10045                               IdentifierInfo *PropertyId,
10046                               IdentifierInfo *PropertyIvar,
10047                               SourceLocation PropertyIvarLoc,
10048                               ObjCPropertyQueryKind QueryKind);
10049 
10050   enum ObjCSpecialMethodKind {
10051     OSMK_None,
10052     OSMK_Alloc,
10053     OSMK_New,
10054     OSMK_Copy,
10055     OSMK_RetainingInit,
10056     OSMK_NonRetainingInit
10057   };
10058 
10059   struct ObjCArgInfo {
10060     IdentifierInfo *Name;
10061     SourceLocation NameLoc;
10062     // The Type is null if no type was specified, and the DeclSpec is invalid
10063     // in this case.
10064     ParsedType Type;
10065     ObjCDeclSpec DeclSpec;
10066 
10067     /// ArgAttrs - Attribute list for this argument.
10068     ParsedAttributesView ArgAttrs;
10069   };
10070 
10071   Decl *ActOnMethodDeclaration(
10072       Scope *S,
10073       SourceLocation BeginLoc, // location of the + or -.
10074       SourceLocation EndLoc,   // location of the ; or {.
10075       tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
10076       ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
10077       // optional arguments. The number of types/arguments is obtained
10078       // from the Sel.getNumArgs().
10079       ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
10080       unsigned CNumArgs, // c-style args
10081       const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind,
10082       bool isVariadic, bool MethodDefinition);
10083 
10084   ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
10085                                               const ObjCObjectPointerType *OPT,
10086                                               bool IsInstance);
10087   ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
10088                                            bool IsInstance);
10089 
10090   bool CheckARCMethodDecl(ObjCMethodDecl *method);
10091   bool inferObjCARCLifetime(ValueDecl *decl);
10092 
10093   void deduceOpenCLAddressSpace(ValueDecl *decl);
10094 
10095   ExprResult
10096   HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
10097                             Expr *BaseExpr,
10098                             SourceLocation OpLoc,
10099                             DeclarationName MemberName,
10100                             SourceLocation MemberLoc,
10101                             SourceLocation SuperLoc, QualType SuperType,
10102                             bool Super);
10103 
10104   ExprResult
10105   ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
10106                             IdentifierInfo &propertyName,
10107                             SourceLocation receiverNameLoc,
10108                             SourceLocation propertyNameLoc);
10109 
10110   ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
10111 
10112   /// Describes the kind of message expression indicated by a message
10113   /// send that starts with an identifier.
10114   enum ObjCMessageKind {
10115     /// The message is sent to 'super'.
10116     ObjCSuperMessage,
10117     /// The message is an instance message.
10118     ObjCInstanceMessage,
10119     /// The message is a class message, and the identifier is a type
10120     /// name.
10121     ObjCClassMessage
10122   };
10123 
10124   ObjCMessageKind getObjCMessageKind(Scope *S,
10125                                      IdentifierInfo *Name,
10126                                      SourceLocation NameLoc,
10127                                      bool IsSuper,
10128                                      bool HasTrailingDot,
10129                                      ParsedType &ReceiverType);
10130 
10131   ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
10132                                Selector Sel,
10133                                SourceLocation LBracLoc,
10134                                ArrayRef<SourceLocation> SelectorLocs,
10135                                SourceLocation RBracLoc,
10136                                MultiExprArg Args);
10137 
10138   ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
10139                                QualType ReceiverType,
10140                                SourceLocation SuperLoc,
10141                                Selector Sel,
10142                                ObjCMethodDecl *Method,
10143                                SourceLocation LBracLoc,
10144                                ArrayRef<SourceLocation> SelectorLocs,
10145                                SourceLocation RBracLoc,
10146                                MultiExprArg Args,
10147                                bool isImplicit = false);
10148 
10149   ExprResult BuildClassMessageImplicit(QualType ReceiverType,
10150                                        bool isSuperReceiver,
10151                                        SourceLocation Loc,
10152                                        Selector Sel,
10153                                        ObjCMethodDecl *Method,
10154                                        MultiExprArg Args);
10155 
10156   ExprResult ActOnClassMessage(Scope *S,
10157                                ParsedType Receiver,
10158                                Selector Sel,
10159                                SourceLocation LBracLoc,
10160                                ArrayRef<SourceLocation> SelectorLocs,
10161                                SourceLocation RBracLoc,
10162                                MultiExprArg Args);
10163 
10164   ExprResult BuildInstanceMessage(Expr *Receiver,
10165                                   QualType ReceiverType,
10166                                   SourceLocation SuperLoc,
10167                                   Selector Sel,
10168                                   ObjCMethodDecl *Method,
10169                                   SourceLocation LBracLoc,
10170                                   ArrayRef<SourceLocation> SelectorLocs,
10171                                   SourceLocation RBracLoc,
10172                                   MultiExprArg Args,
10173                                   bool isImplicit = false);
10174 
10175   ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
10176                                           QualType ReceiverType,
10177                                           SourceLocation Loc,
10178                                           Selector Sel,
10179                                           ObjCMethodDecl *Method,
10180                                           MultiExprArg Args);
10181 
10182   ExprResult ActOnInstanceMessage(Scope *S,
10183                                   Expr *Receiver,
10184                                   Selector Sel,
10185                                   SourceLocation LBracLoc,
10186                                   ArrayRef<SourceLocation> SelectorLocs,
10187                                   SourceLocation RBracLoc,
10188                                   MultiExprArg Args);
10189 
10190   ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
10191                                   ObjCBridgeCastKind Kind,
10192                                   SourceLocation BridgeKeywordLoc,
10193                                   TypeSourceInfo *TSInfo,
10194                                   Expr *SubExpr);
10195 
10196   ExprResult ActOnObjCBridgedCast(Scope *S,
10197                                   SourceLocation LParenLoc,
10198                                   ObjCBridgeCastKind Kind,
10199                                   SourceLocation BridgeKeywordLoc,
10200                                   ParsedType Type,
10201                                   SourceLocation RParenLoc,
10202                                   Expr *SubExpr);
10203 
10204   void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
10205 
10206   void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
10207 
10208   bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
10209                                      CastKind &Kind);
10210 
10211   bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
10212                                         QualType DestType, QualType SrcType,
10213                                         ObjCInterfaceDecl *&RelatedClass,
10214                                         ObjCMethodDecl *&ClassMethod,
10215                                         ObjCMethodDecl *&InstanceMethod,
10216                                         TypedefNameDecl *&TDNDecl,
10217                                         bool CfToNs, bool Diagnose = true);
10218 
10219   bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
10220                                          QualType DestType, QualType SrcType,
10221                                          Expr *&SrcExpr, bool Diagnose = true);
10222 
10223   bool CheckConversionToObjCLiteral(QualType DstType, Expr *&SrcExpr,
10224                                     bool Diagnose = true);
10225 
10226   bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
10227 
10228   /// Check whether the given new method is a valid override of the
10229   /// given overridden method, and set any properties that should be inherited.
10230   void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
10231                                const ObjCMethodDecl *Overridden);
10232 
10233   /// Describes the compatibility of a result type with its method.
10234   enum ResultTypeCompatibilityKind {
10235     RTC_Compatible,
10236     RTC_Incompatible,
10237     RTC_Unknown
10238   };
10239 
10240   void CheckObjCMethodDirectOverrides(ObjCMethodDecl *method,
10241                                       ObjCMethodDecl *overridden);
10242 
10243   void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
10244                                 ObjCInterfaceDecl *CurrentClass,
10245                                 ResultTypeCompatibilityKind RTC);
10246 
10247   enum PragmaOptionsAlignKind {
10248     POAK_Native,  // #pragma options align=native
10249     POAK_Natural, // #pragma options align=natural
10250     POAK_Packed,  // #pragma options align=packed
10251     POAK_Power,   // #pragma options align=power
10252     POAK_Mac68k,  // #pragma options align=mac68k
10253     POAK_Reset    // #pragma options align=reset
10254   };
10255 
10256   /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
10257   void ActOnPragmaClangSection(SourceLocation PragmaLoc,
10258                                PragmaClangSectionAction Action,
10259                                PragmaClangSectionKind SecKind, StringRef SecName);
10260 
10261   /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
10262   void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
10263                                SourceLocation PragmaLoc);
10264 
10265   /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
10266   void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
10267                        StringRef SlotLabel, Expr *Alignment);
10268 
10269   enum class PragmaAlignPackDiagnoseKind {
10270     NonDefaultStateAtInclude,
10271     ChangedStateAtExit
10272   };
10273 
10274   void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind,
10275                                          SourceLocation IncludeLoc);
10276   void DiagnoseUnterminatedPragmaAlignPack();
10277 
10278   /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
10279   void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
10280 
10281   /// ActOnPragmaMSComment - Called on well formed
10282   /// \#pragma comment(kind, "arg").
10283   void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
10284                             StringRef Arg);
10285 
10286   /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
10287   /// pointers_to_members(representation method[, general purpose
10288   /// representation]).
10289   void ActOnPragmaMSPointersToMembers(
10290       LangOptions::PragmaMSPointersToMembersKind Kind,
10291       SourceLocation PragmaLoc);
10292 
10293   /// Called on well formed \#pragma vtordisp().
10294   void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
10295                              SourceLocation PragmaLoc,
10296                              MSVtorDispMode Value);
10297 
10298   enum PragmaSectionKind {
10299     PSK_DataSeg,
10300     PSK_BSSSeg,
10301     PSK_ConstSeg,
10302     PSK_CodeSeg,
10303   };
10304 
10305   bool UnifySection(StringRef SectionName, int SectionFlags,
10306                     NamedDecl *TheDecl);
10307   bool UnifySection(StringRef SectionName,
10308                     int SectionFlags,
10309                     SourceLocation PragmaSectionLocation);
10310 
10311   /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
10312   void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
10313                         PragmaMsStackAction Action,
10314                         llvm::StringRef StackSlotLabel,
10315                         StringLiteral *SegmentName,
10316                         llvm::StringRef PragmaName);
10317 
10318   /// Called on well formed \#pragma section().
10319   void ActOnPragmaMSSection(SourceLocation PragmaLocation,
10320                             int SectionFlags, StringLiteral *SegmentName);
10321 
10322   /// Called on well-formed \#pragma init_seg().
10323   void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
10324                             StringLiteral *SegmentName);
10325 
10326   /// Called on well-formed \#pragma alloc_text().
10327   void ActOnPragmaMSAllocText(
10328       SourceLocation PragmaLocation, StringRef Section,
10329       const SmallVector<std::tuple<IdentifierInfo *, SourceLocation>>
10330           &Functions);
10331 
10332   /// Called on #pragma clang __debug dump II
10333   void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
10334 
10335   /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
10336   void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
10337                                  StringRef Value);
10338 
10339   /// Are precise floating point semantics currently enabled?
10340   bool isPreciseFPEnabled() {
10341     return !CurFPFeatures.getAllowFPReassociate() &&
10342            !CurFPFeatures.getNoSignedZero() &&
10343            !CurFPFeatures.getAllowReciprocal() &&
10344            !CurFPFeatures.getAllowApproxFunc();
10345   }
10346 
10347   void ActOnPragmaFPEvalMethod(SourceLocation Loc,
10348                                LangOptions::FPEvalMethodKind Value);
10349 
10350   /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control
10351   void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action,
10352                                PragmaFloatControlKind Value);
10353 
10354   /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
10355   void ActOnPragmaUnused(const Token &Identifier,
10356                          Scope *curScope,
10357                          SourceLocation PragmaLoc);
10358 
10359   /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
10360   void ActOnPragmaVisibility(const IdentifierInfo* VisType,
10361                              SourceLocation PragmaLoc);
10362 
10363   NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, const IdentifierInfo *II,
10364                                  SourceLocation Loc);
10365   void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W);
10366 
10367   /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
10368   void ActOnPragmaWeakID(IdentifierInfo* WeakName,
10369                          SourceLocation PragmaLoc,
10370                          SourceLocation WeakNameLoc);
10371 
10372   /// ActOnPragmaRedefineExtname - Called on well formed
10373   /// \#pragma redefine_extname oldname newname.
10374   void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
10375                                   IdentifierInfo* AliasName,
10376                                   SourceLocation PragmaLoc,
10377                                   SourceLocation WeakNameLoc,
10378                                   SourceLocation AliasNameLoc);
10379 
10380   /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
10381   void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
10382                             IdentifierInfo* AliasName,
10383                             SourceLocation PragmaLoc,
10384                             SourceLocation WeakNameLoc,
10385                             SourceLocation AliasNameLoc);
10386 
10387   /// ActOnPragmaFPContract - Called on well formed
10388   /// \#pragma {STDC,OPENCL} FP_CONTRACT and
10389   /// \#pragma clang fp contract
10390   void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC);
10391 
10392   /// Called on well formed
10393   /// \#pragma clang fp reassociate
10394   void ActOnPragmaFPReassociate(SourceLocation Loc, bool IsEnabled);
10395 
10396   /// ActOnPragmaFenvAccess - Called on well formed
10397   /// \#pragma STDC FENV_ACCESS
10398   void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled);
10399 
10400   /// Called on well formed '\#pragma clang fp' that has option 'exceptions'.
10401   void ActOnPragmaFPExceptions(SourceLocation Loc,
10402                                LangOptions::FPExceptionModeKind);
10403 
10404   /// Called to set constant rounding mode for floating point operations.
10405   void ActOnPragmaFEnvRound(SourceLocation Loc, llvm::RoundingMode);
10406 
10407   /// Called to set exception behavior for floating point operations.
10408   void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind);
10409 
10410   /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
10411   /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
10412   void AddAlignmentAttributesForRecord(RecordDecl *RD);
10413 
10414   /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
10415   void AddMsStructLayoutForRecord(RecordDecl *RD);
10416 
10417   /// PushNamespaceVisibilityAttr - Note that we've entered a
10418   /// namespace with a visibility attribute.
10419   void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
10420                                    SourceLocation Loc);
10421 
10422   /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
10423   /// add an appropriate visibility attribute.
10424   void AddPushedVisibilityAttribute(Decl *RD);
10425 
10426   /// PopPragmaVisibility - Pop the top element of the visibility stack; used
10427   /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
10428   void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
10429 
10430   /// FreeVisContext - Deallocate and null out VisContext.
10431   void FreeVisContext();
10432 
10433   /// AddCFAuditedAttribute - Check whether we're currently within
10434   /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
10435   /// the appropriate attribute.
10436   void AddCFAuditedAttribute(Decl *D);
10437 
10438   void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute,
10439                                      SourceLocation PragmaLoc,
10440                                      attr::ParsedSubjectMatchRuleSet Rules);
10441   void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
10442                                      const IdentifierInfo *Namespace);
10443 
10444   /// Called on well-formed '\#pragma clang attribute pop'.
10445   void ActOnPragmaAttributePop(SourceLocation PragmaLoc,
10446                                const IdentifierInfo *Namespace);
10447 
10448   /// Adds the attributes that have been specified using the
10449   /// '\#pragma clang attribute push' directives to the given declaration.
10450   void AddPragmaAttributes(Scope *S, Decl *D);
10451 
10452   void DiagnoseUnterminatedPragmaAttribute();
10453 
10454   /// Called on well formed \#pragma clang optimize.
10455   void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
10456 
10457   /// #pragma optimize("[optimization-list]", on | off).
10458   void ActOnPragmaMSOptimize(SourceLocation Loc, bool IsOn);
10459 
10460   /// Call on well formed \#pragma function.
10461   void
10462   ActOnPragmaMSFunction(SourceLocation Loc,
10463                         const llvm::SmallVectorImpl<StringRef> &NoBuiltins);
10464 
10465   /// Get the location for the currently active "\#pragma clang optimize
10466   /// off". If this location is invalid, then the state of the pragma is "on".
10467   SourceLocation getOptimizeOffPragmaLocation() const {
10468     return OptimizeOffPragmaLocation;
10469   }
10470 
10471   /// Only called on function definitions; if there is a pragma in scope
10472   /// with the effect of a range-based optnone, consider marking the function
10473   /// with attribute optnone.
10474   void AddRangeBasedOptnone(FunctionDecl *FD);
10475 
10476   /// Only called on function definitions; if there is a `#pragma alloc_text`
10477   /// that decides which code section the function should be in, add
10478   /// attribute section to the function.
10479   void AddSectionMSAllocText(FunctionDecl *FD);
10480 
10481   /// Adds the 'optnone' attribute to the function declaration if there
10482   /// are no conflicts; Loc represents the location causing the 'optnone'
10483   /// attribute to be added (usually because of a pragma).
10484   void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
10485 
10486   /// Only called on function definitions; if there is a MSVC #pragma optimize
10487   /// in scope, consider changing the function's attributes based on the
10488   /// optimization list passed to the pragma.
10489   void ModifyFnAttributesMSPragmaOptimize(FunctionDecl *FD);
10490 
10491   /// Only called on function definitions; if there is a pragma in scope
10492   /// with the effect of a range-based no_builtin, consider marking the function
10493   /// with attribute no_builtin.
10494   void AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD);
10495 
10496   /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
10497   void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
10498                       bool IsPackExpansion);
10499   void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T,
10500                       bool IsPackExpansion);
10501 
10502   /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
10503   /// declaration.
10504   void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
10505                             Expr *OE);
10506 
10507   /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
10508   /// declaration.
10509   void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
10510                          Expr *ParamExpr);
10511 
10512   /// AddAlignValueAttr - Adds an align_value attribute to a particular
10513   /// declaration.
10514   void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
10515 
10516   /// AddAnnotationAttr - Adds an annotation Annot with Args arguments to D.
10517   void AddAnnotationAttr(Decl *D, const AttributeCommonInfo &CI,
10518                          StringRef Annot, MutableArrayRef<Expr *> Args);
10519 
10520   /// ConstantFoldAttrArgs - Folds attribute arguments into ConstantExprs
10521   /// (unless they are value dependent or type dependent). Returns false
10522   /// and emits a diagnostic if one or more of the arguments could not be
10523   /// folded into a constant.
10524   bool ConstantFoldAttrArgs(const AttributeCommonInfo &CI,
10525                             MutableArrayRef<Expr *> Args);
10526 
10527   /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
10528   /// declaration.
10529   void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
10530                            Expr *MaxThreads, Expr *MinBlocks);
10531 
10532   /// AddModeAttr - Adds a mode attribute to a particular declaration.
10533   void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name,
10534                    bool InInstantiation = false);
10535 
10536   void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI,
10537                            ParameterABI ABI);
10538 
10539   enum class RetainOwnershipKind {NS, CF, OS};
10540   void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI,
10541                         RetainOwnershipKind K, bool IsTemplateInstantiation);
10542 
10543   /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size
10544   /// attribute to a particular declaration.
10545   void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI,
10546                                       Expr *Min, Expr *Max);
10547 
10548   /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a
10549   /// particular declaration.
10550   void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI,
10551                                Expr *Min, Expr *Max);
10552 
10553   bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type);
10554 
10555   //===--------------------------------------------------------------------===//
10556   // C++ Coroutines TS
10557   //
10558   bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
10559                                StringRef Keyword);
10560   ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
10561   ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
10562   StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
10563 
10564   ExprResult BuildOperatorCoawaitLookupExpr(Scope *S, SourceLocation Loc);
10565   ExprResult BuildOperatorCoawaitCall(SourceLocation Loc, Expr *E,
10566                                       UnresolvedLookupExpr *Lookup);
10567   ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
10568                                       Expr *Awaiter, bool IsImplicit = false);
10569   ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
10570                                         UnresolvedLookupExpr *Lookup);
10571   ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
10572   StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
10573                                bool IsImplicit = false);
10574   StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
10575   bool buildCoroutineParameterMoves(SourceLocation Loc);
10576   VarDecl *buildCoroutinePromise(SourceLocation Loc);
10577   void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
10578   /// Lookup 'coroutine_traits' in std namespace and std::experimental
10579   /// namespace. The namespace found is recorded in Namespace.
10580   ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
10581                                            SourceLocation FuncLoc,
10582                                            NamespaceDecl *&Namespace);
10583   /// Check that the expression co_await promise.final_suspend() shall not be
10584   /// potentially-throwing.
10585   bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend);
10586 
10587   //===--------------------------------------------------------------------===//
10588   // OpenMP directives and clauses.
10589   //
10590 private:
10591   void *VarDataSharingAttributesStack;
10592 
10593   struct DeclareTargetContextInfo {
10594     struct MapInfo {
10595       OMPDeclareTargetDeclAttr::MapTypeTy MT;
10596       SourceLocation Loc;
10597     };
10598     /// Explicitly listed variables and functions in a 'to' or 'link' clause.
10599     llvm::DenseMap<NamedDecl *, MapInfo> ExplicitlyMapped;
10600 
10601     /// The 'device_type' as parsed from the clause.
10602     OMPDeclareTargetDeclAttr::DevTypeTy DT = OMPDeclareTargetDeclAttr::DT_Any;
10603 
10604     /// The directive kind, `begin declare target` or `declare target`.
10605     OpenMPDirectiveKind Kind;
10606 
10607     /// The directive with indirect clause.
10608     Optional<Expr *> Indirect;
10609 
10610     /// The directive location.
10611     SourceLocation Loc;
10612 
10613     DeclareTargetContextInfo(OpenMPDirectiveKind Kind, SourceLocation Loc)
10614         : Kind(Kind), Loc(Loc) {}
10615   };
10616 
10617   /// Number of nested '#pragma omp declare target' directives.
10618   SmallVector<DeclareTargetContextInfo, 4> DeclareTargetNesting;
10619 
10620   /// Initialization of data-sharing attributes stack.
10621   void InitDataSharingAttributesStack();
10622   void DestroyDataSharingAttributesStack();
10623   ExprResult
10624   VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
10625                                         bool StrictlyPositive = true,
10626                                         bool SuppressExprDiags = false);
10627   /// Returns OpenMP nesting level for current directive.
10628   unsigned getOpenMPNestingLevel() const;
10629 
10630   /// Adjusts the function scopes index for the target-based regions.
10631   void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
10632                                     unsigned Level) const;
10633 
10634   /// Returns the number of scopes associated with the construct on the given
10635   /// OpenMP level.
10636   int getNumberOfConstructScopes(unsigned Level) const;
10637 
10638   /// Push new OpenMP function region for non-capturing function.
10639   void pushOpenMPFunctionRegion();
10640 
10641   /// Pop OpenMP function region for non-capturing function.
10642   void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI);
10643 
10644   /// Analyzes and checks a loop nest for use by a loop transformation.
10645   ///
10646   /// \param Kind          The loop transformation directive kind.
10647   /// \param NumLoops      How many nested loops the directive is expecting.
10648   /// \param AStmt         Associated statement of the transformation directive.
10649   /// \param LoopHelpers   [out] The loop analysis result.
10650   /// \param Body          [out] The body code nested in \p NumLoops loop.
10651   /// \param OriginalInits [out] Collection of statements and declarations that
10652   ///                      must have been executed/declared before entering the
10653   ///                      loop.
10654   ///
10655   /// \return Whether there was any error.
10656   bool checkTransformableLoopNest(
10657       OpenMPDirectiveKind Kind, Stmt *AStmt, int NumLoops,
10658       SmallVectorImpl<OMPLoopBasedDirective::HelperExprs> &LoopHelpers,
10659       Stmt *&Body,
10660       SmallVectorImpl<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>>
10661           &OriginalInits);
10662 
10663   /// Helper to keep information about the current `omp begin/end declare
10664   /// variant` nesting.
10665   struct OMPDeclareVariantScope {
10666     /// The associated OpenMP context selector.
10667     OMPTraitInfo *TI;
10668 
10669     /// The associated OpenMP context selector mangling.
10670     std::string NameSuffix;
10671 
10672     OMPDeclareVariantScope(OMPTraitInfo &TI);
10673   };
10674 
10675   /// Return the OMPTraitInfo for the surrounding scope, if any.
10676   OMPTraitInfo *getOMPTraitInfoForSurroundingScope() {
10677     return OMPDeclareVariantScopes.empty() ? nullptr
10678                                            : OMPDeclareVariantScopes.back().TI;
10679   }
10680 
10681   /// The current `omp begin/end declare variant` scopes.
10682   SmallVector<OMPDeclareVariantScope, 4> OMPDeclareVariantScopes;
10683 
10684   /// The current `omp begin/end assumes` scopes.
10685   SmallVector<AssumptionAttr *, 4> OMPAssumeScoped;
10686 
10687   /// All `omp assumes` we encountered so far.
10688   SmallVector<AssumptionAttr *, 4> OMPAssumeGlobal;
10689 
10690 public:
10691   /// The declarator \p D defines a function in the scope \p S which is nested
10692   /// in an `omp begin/end declare variant` scope. In this method we create a
10693   /// declaration for \p D and rename \p D according to the OpenMP context
10694   /// selector of the surrounding scope. Return all base functions in \p Bases.
10695   void ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
10696       Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists,
10697       SmallVectorImpl<FunctionDecl *> &Bases);
10698 
10699   /// Register \p D as specialization of all base functions in \p Bases in the
10700   /// current `omp begin/end declare variant` scope.
10701   void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
10702       Decl *D, SmallVectorImpl<FunctionDecl *> &Bases);
10703 
10704   /// Act on \p D, a function definition inside of an `omp [begin/end] assumes`.
10705   void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D);
10706 
10707   /// Can we exit an OpenMP declare variant scope at the moment.
10708   bool isInOpenMPDeclareVariantScope() const {
10709     return !OMPDeclareVariantScopes.empty();
10710   }
10711 
10712   /// Given the potential call expression \p Call, determine if there is a
10713   /// specialization via the OpenMP declare variant mechanism available. If
10714   /// there is, return the specialized call expression, otherwise return the
10715   /// original \p Call.
10716   ExprResult ActOnOpenMPCall(ExprResult Call, Scope *Scope,
10717                              SourceLocation LParenLoc, MultiExprArg ArgExprs,
10718                              SourceLocation RParenLoc, Expr *ExecConfig);
10719 
10720   /// Handle a `omp begin declare variant`.
10721   void ActOnOpenMPBeginDeclareVariant(SourceLocation Loc, OMPTraitInfo &TI);
10722 
10723   /// Handle a `omp end declare variant`.
10724   void ActOnOpenMPEndDeclareVariant();
10725 
10726   /// Checks if the variant/multiversion functions are compatible.
10727   bool areMultiversionVariantFunctionsCompatible(
10728       const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10729       const PartialDiagnostic &NoProtoDiagID,
10730       const PartialDiagnosticAt &NoteCausedDiagIDAt,
10731       const PartialDiagnosticAt &NoSupportDiagIDAt,
10732       const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10733       bool ConstexprSupported, bool CLinkageMayDiffer);
10734 
10735   /// Function tries to capture lambda's captured variables in the OpenMP region
10736   /// before the original lambda is captured.
10737   void tryCaptureOpenMPLambdas(ValueDecl *V);
10738 
10739   /// Return true if the provided declaration \a VD should be captured by
10740   /// reference.
10741   /// \param Level Relative level of nested OpenMP construct for that the check
10742   /// is performed.
10743   /// \param OpenMPCaptureLevel Capture level within an OpenMP construct.
10744   bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
10745                              unsigned OpenMPCaptureLevel) const;
10746 
10747   /// Check if the specified variable is used in one of the private
10748   /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
10749   /// constructs.
10750   VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false,
10751                                 unsigned StopAt = 0);
10752 
10753   /// The member expression(this->fd) needs to be rebuilt in the template
10754   /// instantiation to generate private copy for OpenMP when default
10755   /// clause is used. The function will return true if default
10756   /// cluse is used.
10757   bool isOpenMPRebuildMemberExpr(ValueDecl *D);
10758 
10759   ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
10760                                    ExprObjectKind OK, SourceLocation Loc);
10761 
10762   /// If the current region is a loop-based region, mark the start of the loop
10763   /// construct.
10764   void startOpenMPLoop();
10765 
10766   /// If the current region is a range loop-based region, mark the start of the
10767   /// loop construct.
10768   void startOpenMPCXXRangeFor();
10769 
10770   /// Check if the specified variable is used in 'private' clause.
10771   /// \param Level Relative level of nested OpenMP construct for that the check
10772   /// is performed.
10773   OpenMPClauseKind isOpenMPPrivateDecl(ValueDecl *D, unsigned Level,
10774                                        unsigned CapLevel) const;
10775 
10776   /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.)
10777   /// for \p FD based on DSA for the provided corresponding captured declaration
10778   /// \p D.
10779   void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level);
10780 
10781   /// Check if the specified variable is captured  by 'target' directive.
10782   /// \param Level Relative level of nested OpenMP construct for that the check
10783   /// is performed.
10784   bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level,
10785                                   unsigned CaptureLevel) const;
10786 
10787   /// Check if the specified global variable must be captured  by outer capture
10788   /// regions.
10789   /// \param Level Relative level of nested OpenMP construct for that
10790   /// the check is performed.
10791   bool isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level,
10792                                   unsigned CaptureLevel) const;
10793 
10794   ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
10795                                                     Expr *Op);
10796   /// Called on start of new data sharing attribute block.
10797   void StartOpenMPDSABlock(OpenMPDirectiveKind K,
10798                            const DeclarationNameInfo &DirName, Scope *CurScope,
10799                            SourceLocation Loc);
10800   /// Start analysis of clauses.
10801   void StartOpenMPClause(OpenMPClauseKind K);
10802   /// End analysis of clauses.
10803   void EndOpenMPClause();
10804   /// Called on end of data sharing attribute block.
10805   void EndOpenMPDSABlock(Stmt *CurDirective);
10806 
10807   /// Check if the current region is an OpenMP loop region and if it is,
10808   /// mark loop control variable, used in \p Init for loop initialization, as
10809   /// private by default.
10810   /// \param Init First part of the for loop.
10811   void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
10812 
10813   /// Called on well-formed '\#pragma omp metadirective' after parsing
10814   /// of the  associated statement.
10815   StmtResult ActOnOpenMPMetaDirective(ArrayRef<OMPClause *> Clauses,
10816                                       Stmt *AStmt, SourceLocation StartLoc,
10817                                       SourceLocation EndLoc);
10818 
10819   // OpenMP directives and clauses.
10820   /// Called on correct id-expression from the '#pragma omp
10821   /// threadprivate'.
10822   ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec,
10823                                      const DeclarationNameInfo &Id,
10824                                      OpenMPDirectiveKind Kind);
10825   /// Called on well-formed '#pragma omp threadprivate'.
10826   DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
10827                                      SourceLocation Loc,
10828                                      ArrayRef<Expr *> VarList);
10829   /// Builds a new OpenMPThreadPrivateDecl and checks its correctness.
10830   OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc,
10831                                                   ArrayRef<Expr *> VarList);
10832   /// Called on well-formed '#pragma omp allocate'.
10833   DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc,
10834                                               ArrayRef<Expr *> VarList,
10835                                               ArrayRef<OMPClause *> Clauses,
10836                                               DeclContext *Owner = nullptr);
10837 
10838   /// Called on well-formed '#pragma omp [begin] assume[s]'.
10839   void ActOnOpenMPAssumesDirective(SourceLocation Loc,
10840                                    OpenMPDirectiveKind DKind,
10841                                    ArrayRef<std::string> Assumptions,
10842                                    bool SkippedClauses);
10843 
10844   /// Check if there is an active global `omp begin assumes` directive.
10845   bool isInOpenMPAssumeScope() const { return !OMPAssumeScoped.empty(); }
10846 
10847   /// Check if there is an active global `omp assumes` directive.
10848   bool hasGlobalOpenMPAssumes() const { return !OMPAssumeGlobal.empty(); }
10849 
10850   /// Called on well-formed '#pragma omp end assumes'.
10851   void ActOnOpenMPEndAssumesDirective();
10852 
10853   /// Called on well-formed '#pragma omp requires'.
10854   DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc,
10855                                               ArrayRef<OMPClause *> ClauseList);
10856   /// Check restrictions on Requires directive
10857   OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc,
10858                                         ArrayRef<OMPClause *> Clauses);
10859   /// Check if the specified type is allowed to be used in 'omp declare
10860   /// reduction' construct.
10861   QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
10862                                            TypeResult ParsedType);
10863   /// Called on start of '#pragma omp declare reduction'.
10864   DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
10865       Scope *S, DeclContext *DC, DeclarationName Name,
10866       ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10867       AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
10868   /// Initialize declare reduction construct initializer.
10869   void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
10870   /// Finish current declare reduction construct initializer.
10871   void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
10872   /// Initialize declare reduction construct initializer.
10873   /// \return omp_priv variable.
10874   VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
10875   /// Finish current declare reduction construct initializer.
10876   void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
10877                                                  VarDecl *OmpPrivParm);
10878   /// Called at the end of '#pragma omp declare reduction'.
10879   DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
10880       Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
10881 
10882   /// Check variable declaration in 'omp declare mapper' construct.
10883   TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D);
10884   /// Check if the specified type is allowed to be used in 'omp declare
10885   /// mapper' construct.
10886   QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
10887                                         TypeResult ParsedType);
10888   /// Called on start of '#pragma omp declare mapper'.
10889   DeclGroupPtrTy ActOnOpenMPDeclareMapperDirective(
10890       Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
10891       SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
10892       Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses,
10893       Decl *PrevDeclInScope = nullptr);
10894   /// Build the mapper variable of '#pragma omp declare mapper'.
10895   ExprResult ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S,
10896                                                       QualType MapperType,
10897                                                       SourceLocation StartLoc,
10898                                                       DeclarationName VN);
10899   bool isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const;
10900   const ValueDecl *getOpenMPDeclareMapperVarName() const;
10901 
10902   /// Called on the start of target region i.e. '#pragma omp declare target'.
10903   bool ActOnStartOpenMPDeclareTargetContext(DeclareTargetContextInfo &DTCI);
10904 
10905   /// Called at the end of target region i.e. '#pragma omp end declare target'.
10906   const DeclareTargetContextInfo ActOnOpenMPEndDeclareTargetDirective();
10907 
10908   /// Called once a target context is completed, that can be when a
10909   /// '#pragma omp end declare target' was encountered or when a
10910   /// '#pragma omp declare target' without declaration-definition-seq was
10911   /// encountered.
10912   void ActOnFinishedOpenMPDeclareTargetContext(DeclareTargetContextInfo &DTCI);
10913 
10914   /// Report unterminated 'omp declare target' or 'omp begin declare target' at
10915   /// the end of a compilation unit.
10916   void DiagnoseUnterminatedOpenMPDeclareTarget();
10917 
10918   /// Searches for the provided declaration name for OpenMP declare target
10919   /// directive.
10920   NamedDecl *lookupOpenMPDeclareTargetName(Scope *CurScope,
10921                                            CXXScopeSpec &ScopeSpec,
10922                                            const DeclarationNameInfo &Id);
10923 
10924   /// Called on correct id-expression from the '#pragma omp declare target'.
10925   void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc,
10926                                     OMPDeclareTargetDeclAttr::MapTypeTy MT,
10927                                     DeclareTargetContextInfo &DTCI);
10928 
10929   /// Check declaration inside target region.
10930   void
10931   checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
10932                                    SourceLocation IdLoc = SourceLocation());
10933   /// Finishes analysis of the deferred functions calls that may be declared as
10934   /// host/nohost during device/host compilation.
10935   void finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller,
10936                                      const FunctionDecl *Callee,
10937                                      SourceLocation Loc);
10938 
10939   /// Return true if currently in OpenMP task with untied clause context.
10940   bool isInOpenMPTaskUntiedContext() const;
10941 
10942   /// Return true inside OpenMP declare target region.
10943   bool isInOpenMPDeclareTargetContext() const {
10944     return !DeclareTargetNesting.empty();
10945   }
10946   /// Return true inside OpenMP target region.
10947   bool isInOpenMPTargetExecutionDirective() const;
10948 
10949   /// Return the number of captured regions created for an OpenMP directive.
10950   static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
10951 
10952   /// Initialization of captured region for OpenMP region.
10953   void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
10954 
10955   /// Called for syntactical loops (ForStmt or CXXForRangeStmt) associated to
10956   /// an OpenMP loop directive.
10957   StmtResult ActOnOpenMPCanonicalLoop(Stmt *AStmt);
10958 
10959   /// Process a canonical OpenMP loop nest that can either be a canonical
10960   /// literal loop (ForStmt or CXXForRangeStmt), or the generated loop of an
10961   /// OpenMP loop transformation construct.
10962   StmtResult ActOnOpenMPLoopnest(Stmt *AStmt);
10963 
10964   /// End of OpenMP region.
10965   ///
10966   /// \param S Statement associated with the current OpenMP region.
10967   /// \param Clauses List of clauses for the current OpenMP region.
10968   ///
10969   /// \returns Statement for finished OpenMP region.
10970   StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
10971   StmtResult ActOnOpenMPExecutableDirective(
10972       OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
10973       OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
10974       Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
10975   /// Called on well-formed '\#pragma omp parallel' after parsing
10976   /// of the  associated statement.
10977   StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
10978                                           Stmt *AStmt,
10979                                           SourceLocation StartLoc,
10980                                           SourceLocation EndLoc);
10981   using VarsWithInheritedDSAType =
10982       llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>;
10983   /// Called on well-formed '\#pragma omp simd' after parsing
10984   /// of the associated statement.
10985   StmtResult
10986   ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10987                            SourceLocation StartLoc, SourceLocation EndLoc,
10988                            VarsWithInheritedDSAType &VarsWithImplicitDSA);
10989   /// Called on well-formed '#pragma omp tile' after parsing of its clauses and
10990   /// the associated statement.
10991   StmtResult ActOnOpenMPTileDirective(ArrayRef<OMPClause *> Clauses,
10992                                       Stmt *AStmt, SourceLocation StartLoc,
10993                                       SourceLocation EndLoc);
10994   /// Called on well-formed '#pragma omp unroll' after parsing of its clauses
10995   /// and the associated statement.
10996   StmtResult ActOnOpenMPUnrollDirective(ArrayRef<OMPClause *> Clauses,
10997                                         Stmt *AStmt, SourceLocation StartLoc,
10998                                         SourceLocation EndLoc);
10999   /// Called on well-formed '\#pragma omp for' after parsing
11000   /// of the associated statement.
11001   StmtResult
11002   ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
11003                           SourceLocation StartLoc, SourceLocation EndLoc,
11004                           VarsWithInheritedDSAType &VarsWithImplicitDSA);
11005   /// Called on well-formed '\#pragma omp for simd' after parsing
11006   /// of the associated statement.
11007   StmtResult
11008   ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
11009                               SourceLocation StartLoc, SourceLocation EndLoc,
11010                               VarsWithInheritedDSAType &VarsWithImplicitDSA);
11011   /// Called on well-formed '\#pragma omp sections' after parsing
11012   /// of the associated statement.
11013   StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
11014                                           Stmt *AStmt, SourceLocation StartLoc,
11015                                           SourceLocation EndLoc);
11016   /// Called on well-formed '\#pragma omp section' after parsing of the
11017   /// associated statement.
11018   StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
11019                                          SourceLocation EndLoc);
11020   /// Called on well-formed '\#pragma omp single' after parsing of the
11021   /// associated statement.
11022   StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
11023                                         Stmt *AStmt, SourceLocation StartLoc,
11024                                         SourceLocation EndLoc);
11025   /// Called on well-formed '\#pragma omp master' after parsing of the
11026   /// associated statement.
11027   StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
11028                                         SourceLocation EndLoc);
11029   /// Called on well-formed '\#pragma omp critical' after parsing of the
11030   /// associated statement.
11031   StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
11032                                           ArrayRef<OMPClause *> Clauses,
11033                                           Stmt *AStmt, SourceLocation StartLoc,
11034                                           SourceLocation EndLoc);
11035   /// Called on well-formed '\#pragma omp parallel for' after parsing
11036   /// of the  associated statement.
11037   StmtResult ActOnOpenMPParallelForDirective(
11038       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11039       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11040   /// Called on well-formed '\#pragma omp parallel for simd' after
11041   /// parsing of the  associated statement.
11042   StmtResult ActOnOpenMPParallelForSimdDirective(
11043       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11044       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11045   /// Called on well-formed '\#pragma omp parallel master' after
11046   /// parsing of the  associated statement.
11047   StmtResult ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
11048                                                 Stmt *AStmt,
11049                                                 SourceLocation StartLoc,
11050                                                 SourceLocation EndLoc);
11051   /// Called on well-formed '\#pragma omp parallel masked' after
11052   /// parsing of the associated statement.
11053   StmtResult ActOnOpenMPParallelMaskedDirective(ArrayRef<OMPClause *> Clauses,
11054                                                 Stmt *AStmt,
11055                                                 SourceLocation StartLoc,
11056                                                 SourceLocation EndLoc);
11057   /// Called on well-formed '\#pragma omp parallel sections' after
11058   /// parsing of the  associated statement.
11059   StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
11060                                                   Stmt *AStmt,
11061                                                   SourceLocation StartLoc,
11062                                                   SourceLocation EndLoc);
11063   /// Called on well-formed '\#pragma omp task' after parsing of the
11064   /// associated statement.
11065   StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
11066                                       Stmt *AStmt, SourceLocation StartLoc,
11067                                       SourceLocation EndLoc);
11068   /// Called on well-formed '\#pragma omp taskyield'.
11069   StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
11070                                            SourceLocation EndLoc);
11071   /// Called on well-formed '\#pragma omp barrier'.
11072   StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
11073                                          SourceLocation EndLoc);
11074   /// Called on well-formed '\#pragma omp taskwait'.
11075   StmtResult ActOnOpenMPTaskwaitDirective(ArrayRef<OMPClause *> Clauses,
11076                                           SourceLocation StartLoc,
11077                                           SourceLocation EndLoc);
11078   /// Called on well-formed '\#pragma omp taskgroup'.
11079   StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
11080                                            Stmt *AStmt, SourceLocation StartLoc,
11081                                            SourceLocation EndLoc);
11082   /// Called on well-formed '\#pragma omp flush'.
11083   StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
11084                                        SourceLocation StartLoc,
11085                                        SourceLocation EndLoc);
11086   /// Called on well-formed '\#pragma omp depobj'.
11087   StmtResult ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses,
11088                                         SourceLocation StartLoc,
11089                                         SourceLocation EndLoc);
11090   /// Called on well-formed '\#pragma omp scan'.
11091   StmtResult ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses,
11092                                       SourceLocation StartLoc,
11093                                       SourceLocation EndLoc);
11094   /// Called on well-formed '\#pragma omp ordered' after parsing of the
11095   /// associated statement.
11096   StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
11097                                          Stmt *AStmt, SourceLocation StartLoc,
11098                                          SourceLocation EndLoc);
11099   /// Called on well-formed '\#pragma omp atomic' after parsing of the
11100   /// associated statement.
11101   StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
11102                                         Stmt *AStmt, SourceLocation StartLoc,
11103                                         SourceLocation EndLoc);
11104   /// Called on well-formed '\#pragma omp target' after parsing of the
11105   /// associated statement.
11106   StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
11107                                         Stmt *AStmt, SourceLocation StartLoc,
11108                                         SourceLocation EndLoc);
11109   /// Called on well-formed '\#pragma omp target data' after parsing of
11110   /// the associated statement.
11111   StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
11112                                             Stmt *AStmt, SourceLocation StartLoc,
11113                                             SourceLocation EndLoc);
11114   /// Called on well-formed '\#pragma omp target enter data' after
11115   /// parsing of the associated statement.
11116   StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
11117                                                  SourceLocation StartLoc,
11118                                                  SourceLocation EndLoc,
11119                                                  Stmt *AStmt);
11120   /// Called on well-formed '\#pragma omp target exit data' after
11121   /// parsing of the associated statement.
11122   StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
11123                                                 SourceLocation StartLoc,
11124                                                 SourceLocation EndLoc,
11125                                                 Stmt *AStmt);
11126   /// Called on well-formed '\#pragma omp target parallel' after
11127   /// parsing of the associated statement.
11128   StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
11129                                                 Stmt *AStmt,
11130                                                 SourceLocation StartLoc,
11131                                                 SourceLocation EndLoc);
11132   /// Called on well-formed '\#pragma omp target parallel for' after
11133   /// parsing of the  associated statement.
11134   StmtResult ActOnOpenMPTargetParallelForDirective(
11135       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11136       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11137   /// Called on well-formed '\#pragma omp teams' after parsing of the
11138   /// associated statement.
11139   StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
11140                                        Stmt *AStmt, SourceLocation StartLoc,
11141                                        SourceLocation EndLoc);
11142   /// Called on well-formed '\#pragma omp teams loop' after parsing of the
11143   /// associated statement.
11144   StmtResult ActOnOpenMPTeamsGenericLoopDirective(
11145       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11146       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11147   /// Called on well-formed '\#pragma omp target teams loop' after parsing of
11148   /// the associated statement.
11149   StmtResult ActOnOpenMPTargetTeamsGenericLoopDirective(
11150       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11151       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11152   /// Called on well-formed '\#pragma omp parallel loop' after parsing of the
11153   /// associated statement.
11154   StmtResult ActOnOpenMPParallelGenericLoopDirective(
11155       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11156       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11157   /// Called on well-formed '\#pragma omp target parallel loop' after parsing
11158   /// of the associated statement.
11159   StmtResult ActOnOpenMPTargetParallelGenericLoopDirective(
11160       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11161       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11162   /// Called on well-formed '\#pragma omp cancellation point'.
11163   StmtResult
11164   ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
11165                                         SourceLocation EndLoc,
11166                                         OpenMPDirectiveKind CancelRegion);
11167   /// Called on well-formed '\#pragma omp cancel'.
11168   StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
11169                                         SourceLocation StartLoc,
11170                                         SourceLocation EndLoc,
11171                                         OpenMPDirectiveKind CancelRegion);
11172   /// Called on well-formed '\#pragma omp taskloop' after parsing of the
11173   /// associated statement.
11174   StmtResult
11175   ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
11176                                SourceLocation StartLoc, SourceLocation EndLoc,
11177                                VarsWithInheritedDSAType &VarsWithImplicitDSA);
11178   /// Called on well-formed '\#pragma omp taskloop simd' after parsing of
11179   /// the associated statement.
11180   StmtResult ActOnOpenMPTaskLoopSimdDirective(
11181       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11182       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11183   /// Called on well-formed '\#pragma omp master taskloop' after parsing of the
11184   /// associated statement.
11185   StmtResult ActOnOpenMPMasterTaskLoopDirective(
11186       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11187       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11188   /// Called on well-formed '\#pragma omp master taskloop simd' after parsing of
11189   /// the associated statement.
11190   StmtResult ActOnOpenMPMasterTaskLoopSimdDirective(
11191       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11192       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11193   /// Called on well-formed '\#pragma omp parallel master taskloop' after
11194   /// parsing of the associated statement.
11195   StmtResult ActOnOpenMPParallelMasterTaskLoopDirective(
11196       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11197       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11198   /// Called on well-formed '\#pragma omp parallel master taskloop simd' after
11199   /// parsing of the associated statement.
11200   StmtResult ActOnOpenMPParallelMasterTaskLoopSimdDirective(
11201       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11202       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11203   /// Called on well-formed '\#pragma omp masked taskloop' after parsing of the
11204   /// associated statement.
11205   StmtResult ActOnOpenMPMaskedTaskLoopDirective(
11206       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11207       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11208   /// Called on well-formed '\#pragma omp masked taskloop simd' after parsing of
11209   /// the associated statement.
11210   StmtResult ActOnOpenMPMaskedTaskLoopSimdDirective(
11211       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11212       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11213   /// Called on well-formed '\#pragma omp parallel masked taskloop' after
11214   /// parsing of the associated statement.
11215   StmtResult ActOnOpenMPParallelMaskedTaskLoopDirective(
11216       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11217       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11218   /// Called on well-formed '\#pragma omp parallel masked taskloop simd' after
11219   /// parsing of the associated statement.
11220   StmtResult ActOnOpenMPParallelMaskedTaskLoopSimdDirective(
11221       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11222       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11223   /// Called on well-formed '\#pragma omp distribute' after parsing
11224   /// of the associated statement.
11225   StmtResult
11226   ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
11227                                  SourceLocation StartLoc, SourceLocation EndLoc,
11228                                  VarsWithInheritedDSAType &VarsWithImplicitDSA);
11229   /// Called on well-formed '\#pragma omp target update'.
11230   StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
11231                                               SourceLocation StartLoc,
11232                                               SourceLocation EndLoc,
11233                                               Stmt *AStmt);
11234   /// Called on well-formed '\#pragma omp distribute parallel for' after
11235   /// parsing of the associated statement.
11236   StmtResult ActOnOpenMPDistributeParallelForDirective(
11237       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11238       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11239   /// Called on well-formed '\#pragma omp distribute parallel for simd'
11240   /// after parsing of the associated statement.
11241   StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
11242       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11243       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11244   /// Called on well-formed '\#pragma omp distribute simd' after
11245   /// parsing of the associated statement.
11246   StmtResult ActOnOpenMPDistributeSimdDirective(
11247       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11248       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11249   /// Called on well-formed '\#pragma omp target parallel for simd' after
11250   /// parsing of the associated statement.
11251   StmtResult ActOnOpenMPTargetParallelForSimdDirective(
11252       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11253       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11254   /// Called on well-formed '\#pragma omp target simd' after parsing of
11255   /// the associated statement.
11256   StmtResult
11257   ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
11258                                  SourceLocation StartLoc, SourceLocation EndLoc,
11259                                  VarsWithInheritedDSAType &VarsWithImplicitDSA);
11260   /// Called on well-formed '\#pragma omp teams distribute' after parsing of
11261   /// the associated statement.
11262   StmtResult ActOnOpenMPTeamsDistributeDirective(
11263       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11264       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11265   /// Called on well-formed '\#pragma omp teams distribute simd' after parsing
11266   /// of the associated statement.
11267   StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
11268       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11269       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11270   /// Called on well-formed '\#pragma omp teams distribute parallel for simd'
11271   /// after parsing of the associated statement.
11272   StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
11273       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11274       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11275   /// Called on well-formed '\#pragma omp teams distribute parallel for'
11276   /// after parsing of the associated statement.
11277   StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
11278       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11279       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11280   /// Called on well-formed '\#pragma omp target teams' after parsing of the
11281   /// associated statement.
11282   StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
11283                                              Stmt *AStmt,
11284                                              SourceLocation StartLoc,
11285                                              SourceLocation EndLoc);
11286   /// Called on well-formed '\#pragma omp target teams distribute' after parsing
11287   /// of the associated statement.
11288   StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
11289       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11290       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11291   /// Called on well-formed '\#pragma omp target teams distribute parallel for'
11292   /// after parsing of the associated statement.
11293   StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
11294       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11295       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11296   /// Called on well-formed '\#pragma omp target teams distribute parallel for
11297   /// simd' after parsing of the associated statement.
11298   StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
11299       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11300       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11301   /// Called on well-formed '\#pragma omp target teams distribute simd' after
11302   /// parsing of the associated statement.
11303   StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
11304       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11305       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11306   /// Called on well-formed '\#pragma omp interop'.
11307   StmtResult ActOnOpenMPInteropDirective(ArrayRef<OMPClause *> Clauses,
11308                                          SourceLocation StartLoc,
11309                                          SourceLocation EndLoc);
11310   /// Called on well-formed '\#pragma omp dispatch' after parsing of the
11311   // /associated statement.
11312   StmtResult ActOnOpenMPDispatchDirective(ArrayRef<OMPClause *> Clauses,
11313                                           Stmt *AStmt, SourceLocation StartLoc,
11314                                           SourceLocation EndLoc);
11315   /// Called on well-formed '\#pragma omp masked' after parsing of the
11316   // /associated statement.
11317   StmtResult ActOnOpenMPMaskedDirective(ArrayRef<OMPClause *> Clauses,
11318                                         Stmt *AStmt, SourceLocation StartLoc,
11319                                         SourceLocation EndLoc);
11320 
11321   /// Called on well-formed '\#pragma omp loop' after parsing of the
11322   /// associated statement.
11323   StmtResult ActOnOpenMPGenericLoopDirective(
11324       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11325       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11326 
11327   /// Checks correctness of linear modifiers.
11328   bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
11329                                  SourceLocation LinLoc);
11330   /// Checks that the specified declaration matches requirements for the linear
11331   /// decls.
11332   bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
11333                              OpenMPLinearClauseKind LinKind, QualType Type,
11334                              bool IsDeclareSimd = false);
11335 
11336   /// Called on well-formed '\#pragma omp declare simd' after parsing of
11337   /// the associated method/function.
11338   DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
11339       DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
11340       Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
11341       ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
11342       ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
11343 
11344   /// Checks '\#pragma omp declare variant' variant function and original
11345   /// functions after parsing of the associated method/function.
11346   /// \param DG Function declaration to which declare variant directive is
11347   /// applied to.
11348   /// \param VariantRef Expression that references the variant function, which
11349   /// must be used instead of the original one, specified in \p DG.
11350   /// \param TI The trait info object representing the match clause.
11351   /// \param NumAppendArgs The number of omp_interop_t arguments to account for
11352   /// in checking.
11353   /// \returns None, if the function/variant function are not compatible with
11354   /// the pragma, pair of original function/variant ref expression otherwise.
11355   Optional<std::pair<FunctionDecl *, Expr *>>
11356   checkOpenMPDeclareVariantFunction(DeclGroupPtrTy DG, Expr *VariantRef,
11357                                     OMPTraitInfo &TI, unsigned NumAppendArgs,
11358                                     SourceRange SR);
11359 
11360   /// Called on well-formed '\#pragma omp declare variant' after parsing of
11361   /// the associated method/function.
11362   /// \param FD Function declaration to which declare variant directive is
11363   /// applied to.
11364   /// \param VariantRef Expression that references the variant function, which
11365   /// must be used instead of the original one, specified in \p DG.
11366   /// \param TI The context traits associated with the function variant.
11367   /// \param AdjustArgsNothing The list of 'nothing' arguments.
11368   /// \param AdjustArgsNeedDevicePtr The list of 'need_device_ptr' arguments.
11369   /// \param AppendArgs The list of 'append_args' arguments.
11370   /// \param AdjustArgsLoc The Location of an 'adjust_args' clause.
11371   /// \param AppendArgsLoc The Location of an 'append_args' clause.
11372   /// \param SR The SourceRange of the 'declare variant' directive.
11373   void ActOnOpenMPDeclareVariantDirective(
11374       FunctionDecl *FD, Expr *VariantRef, OMPTraitInfo &TI,
11375       ArrayRef<Expr *> AdjustArgsNothing,
11376       ArrayRef<Expr *> AdjustArgsNeedDevicePtr,
11377       ArrayRef<OMPDeclareVariantAttr::InteropType> AppendArgs,
11378       SourceLocation AdjustArgsLoc, SourceLocation AppendArgsLoc,
11379       SourceRange SR);
11380 
11381   OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
11382                                          Expr *Expr,
11383                                          SourceLocation StartLoc,
11384                                          SourceLocation LParenLoc,
11385                                          SourceLocation EndLoc);
11386   /// Called on well-formed 'allocator' clause.
11387   OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator,
11388                                         SourceLocation StartLoc,
11389                                         SourceLocation LParenLoc,
11390                                         SourceLocation EndLoc);
11391   /// Called on well-formed 'if' clause.
11392   OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
11393                                  Expr *Condition, SourceLocation StartLoc,
11394                                  SourceLocation LParenLoc,
11395                                  SourceLocation NameModifierLoc,
11396                                  SourceLocation ColonLoc,
11397                                  SourceLocation EndLoc);
11398   /// Called on well-formed 'final' clause.
11399   OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
11400                                     SourceLocation LParenLoc,
11401                                     SourceLocation EndLoc);
11402   /// Called on well-formed 'num_threads' clause.
11403   OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
11404                                          SourceLocation StartLoc,
11405                                          SourceLocation LParenLoc,
11406                                          SourceLocation EndLoc);
11407   /// Called on well-formed 'align' clause.
11408   OMPClause *ActOnOpenMPAlignClause(Expr *Alignment, SourceLocation StartLoc,
11409                                     SourceLocation LParenLoc,
11410                                     SourceLocation EndLoc);
11411   /// Called on well-formed 'safelen' clause.
11412   OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
11413                                       SourceLocation StartLoc,
11414                                       SourceLocation LParenLoc,
11415                                       SourceLocation EndLoc);
11416   /// Called on well-formed 'simdlen' clause.
11417   OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
11418                                       SourceLocation LParenLoc,
11419                                       SourceLocation EndLoc);
11420   /// Called on well-form 'sizes' clause.
11421   OMPClause *ActOnOpenMPSizesClause(ArrayRef<Expr *> SizeExprs,
11422                                     SourceLocation StartLoc,
11423                                     SourceLocation LParenLoc,
11424                                     SourceLocation EndLoc);
11425   /// Called on well-form 'full' clauses.
11426   OMPClause *ActOnOpenMPFullClause(SourceLocation StartLoc,
11427                                    SourceLocation EndLoc);
11428   /// Called on well-form 'partial' clauses.
11429   OMPClause *ActOnOpenMPPartialClause(Expr *FactorExpr, SourceLocation StartLoc,
11430                                       SourceLocation LParenLoc,
11431                                       SourceLocation EndLoc);
11432   /// Called on well-formed 'collapse' clause.
11433   OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
11434                                        SourceLocation StartLoc,
11435                                        SourceLocation LParenLoc,
11436                                        SourceLocation EndLoc);
11437   /// Called on well-formed 'ordered' clause.
11438   OMPClause *
11439   ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
11440                            SourceLocation LParenLoc = SourceLocation(),
11441                            Expr *NumForLoops = nullptr);
11442   /// Called on well-formed 'grainsize' clause.
11443   OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
11444                                         SourceLocation LParenLoc,
11445                                         SourceLocation EndLoc);
11446   /// Called on well-formed 'num_tasks' clause.
11447   OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
11448                                        SourceLocation LParenLoc,
11449                                        SourceLocation EndLoc);
11450   /// Called on well-formed 'hint' clause.
11451   OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
11452                                    SourceLocation LParenLoc,
11453                                    SourceLocation EndLoc);
11454   /// Called on well-formed 'detach' clause.
11455   OMPClause *ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc,
11456                                      SourceLocation LParenLoc,
11457                                      SourceLocation EndLoc);
11458 
11459   OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
11460                                      unsigned Argument,
11461                                      SourceLocation ArgumentLoc,
11462                                      SourceLocation StartLoc,
11463                                      SourceLocation LParenLoc,
11464                                      SourceLocation EndLoc);
11465   /// Called on well-formed 'when' clause.
11466   OMPClause *ActOnOpenMPWhenClause(OMPTraitInfo &TI, SourceLocation StartLoc,
11467                                    SourceLocation LParenLoc,
11468                                    SourceLocation EndLoc);
11469   /// Called on well-formed 'default' clause.
11470   OMPClause *ActOnOpenMPDefaultClause(llvm::omp::DefaultKind Kind,
11471                                       SourceLocation KindLoc,
11472                                       SourceLocation StartLoc,
11473                                       SourceLocation LParenLoc,
11474                                       SourceLocation EndLoc);
11475   /// Called on well-formed 'proc_bind' clause.
11476   OMPClause *ActOnOpenMPProcBindClause(llvm::omp::ProcBindKind Kind,
11477                                        SourceLocation KindLoc,
11478                                        SourceLocation StartLoc,
11479                                        SourceLocation LParenLoc,
11480                                        SourceLocation EndLoc);
11481   /// Called on well-formed 'order' clause.
11482   OMPClause *ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind,
11483                                     SourceLocation KindLoc,
11484                                     SourceLocation StartLoc,
11485                                     SourceLocation LParenLoc,
11486                                     SourceLocation EndLoc);
11487   /// Called on well-formed 'update' clause.
11488   OMPClause *ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind,
11489                                      SourceLocation KindLoc,
11490                                      SourceLocation StartLoc,
11491                                      SourceLocation LParenLoc,
11492                                      SourceLocation EndLoc);
11493 
11494   OMPClause *ActOnOpenMPSingleExprWithArgClause(
11495       OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
11496       SourceLocation StartLoc, SourceLocation LParenLoc,
11497       ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
11498       SourceLocation EndLoc);
11499   /// Called on well-formed 'schedule' clause.
11500   OMPClause *ActOnOpenMPScheduleClause(
11501       OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
11502       OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
11503       SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
11504       SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
11505 
11506   OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
11507                                SourceLocation EndLoc);
11508   /// Called on well-formed 'nowait' clause.
11509   OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
11510                                      SourceLocation EndLoc);
11511   /// Called on well-formed 'untied' clause.
11512   OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
11513                                      SourceLocation EndLoc);
11514   /// Called on well-formed 'mergeable' clause.
11515   OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
11516                                         SourceLocation EndLoc);
11517   /// Called on well-formed 'read' clause.
11518   OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
11519                                    SourceLocation EndLoc);
11520   /// Called on well-formed 'write' clause.
11521   OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
11522                                     SourceLocation EndLoc);
11523   /// Called on well-formed 'update' clause.
11524   OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
11525                                      SourceLocation EndLoc);
11526   /// Called on well-formed 'capture' clause.
11527   OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
11528                                       SourceLocation EndLoc);
11529   /// Called on well-formed 'compare' clause.
11530   OMPClause *ActOnOpenMPCompareClause(SourceLocation StartLoc,
11531                                       SourceLocation EndLoc);
11532   /// Called on well-formed 'seq_cst' clause.
11533   OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
11534                                      SourceLocation EndLoc);
11535   /// Called on well-formed 'acq_rel' clause.
11536   OMPClause *ActOnOpenMPAcqRelClause(SourceLocation StartLoc,
11537                                      SourceLocation EndLoc);
11538   /// Called on well-formed 'acquire' clause.
11539   OMPClause *ActOnOpenMPAcquireClause(SourceLocation StartLoc,
11540                                       SourceLocation EndLoc);
11541   /// Called on well-formed 'release' clause.
11542   OMPClause *ActOnOpenMPReleaseClause(SourceLocation StartLoc,
11543                                       SourceLocation EndLoc);
11544   /// Called on well-formed 'relaxed' clause.
11545   OMPClause *ActOnOpenMPRelaxedClause(SourceLocation StartLoc,
11546                                       SourceLocation EndLoc);
11547 
11548   /// Called on well-formed 'init' clause.
11549   OMPClause *ActOnOpenMPInitClause(Expr *InteropVar, ArrayRef<Expr *> PrefExprs,
11550                                    bool IsTarget, bool IsTargetSync,
11551                                    SourceLocation StartLoc,
11552                                    SourceLocation LParenLoc,
11553                                    SourceLocation VarLoc,
11554                                    SourceLocation EndLoc);
11555 
11556   /// Called on well-formed 'use' clause.
11557   OMPClause *ActOnOpenMPUseClause(Expr *InteropVar, SourceLocation StartLoc,
11558                                   SourceLocation LParenLoc,
11559                                   SourceLocation VarLoc, SourceLocation EndLoc);
11560 
11561   /// Called on well-formed 'destroy' clause.
11562   OMPClause *ActOnOpenMPDestroyClause(Expr *InteropVar, SourceLocation StartLoc,
11563                                       SourceLocation LParenLoc,
11564                                       SourceLocation VarLoc,
11565                                       SourceLocation EndLoc);
11566   /// Called on well-formed 'novariants' clause.
11567   OMPClause *ActOnOpenMPNovariantsClause(Expr *Condition,
11568                                          SourceLocation StartLoc,
11569                                          SourceLocation LParenLoc,
11570                                          SourceLocation EndLoc);
11571   /// Called on well-formed 'nocontext' clause.
11572   OMPClause *ActOnOpenMPNocontextClause(Expr *Condition,
11573                                         SourceLocation StartLoc,
11574                                         SourceLocation LParenLoc,
11575                                         SourceLocation EndLoc);
11576   /// Called on well-formed 'filter' clause.
11577   OMPClause *ActOnOpenMPFilterClause(Expr *ThreadID, SourceLocation StartLoc,
11578                                      SourceLocation LParenLoc,
11579                                      SourceLocation EndLoc);
11580   /// Called on well-formed 'threads' clause.
11581   OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
11582                                       SourceLocation EndLoc);
11583   /// Called on well-formed 'simd' clause.
11584   OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
11585                                    SourceLocation EndLoc);
11586   /// Called on well-formed 'nogroup' clause.
11587   OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
11588                                       SourceLocation EndLoc);
11589   /// Called on well-formed 'unified_address' clause.
11590   OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
11591                                              SourceLocation EndLoc);
11592 
11593   /// Called on well-formed 'unified_address' clause.
11594   OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
11595                                                   SourceLocation EndLoc);
11596 
11597   /// Called on well-formed 'reverse_offload' clause.
11598   OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
11599                                              SourceLocation EndLoc);
11600 
11601   /// Called on well-formed 'dynamic_allocators' clause.
11602   OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
11603                                                 SourceLocation EndLoc);
11604 
11605   /// Called on well-formed 'atomic_default_mem_order' clause.
11606   OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause(
11607       OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc,
11608       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
11609 
11610   /// Data used for processing a list of variables in OpenMP clauses.
11611   struct OpenMPVarListDataTy final {
11612     Expr *DepModOrTailExpr = nullptr;
11613     SourceLocation ColonLoc;
11614     SourceLocation RLoc;
11615     CXXScopeSpec ReductionOrMapperIdScopeSpec;
11616     DeclarationNameInfo ReductionOrMapperId;
11617     int ExtraModifier = -1; ///< Additional modifier for linear, map, depend or
11618                             ///< lastprivate clause.
11619     SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers>
11620         MapTypeModifiers;
11621     SmallVector<SourceLocation, NumberOfOMPMapClauseModifiers>
11622         MapTypeModifiersLoc;
11623     SmallVector<OpenMPMotionModifierKind, NumberOfOMPMotionModifiers>
11624         MotionModifiers;
11625     SmallVector<SourceLocation, NumberOfOMPMotionModifiers> MotionModifiersLoc;
11626     bool IsMapTypeImplicit = false;
11627     SourceLocation ExtraModifierLoc;
11628     SourceLocation OmpAllMemoryLoc;
11629   };
11630 
11631   OMPClause *ActOnOpenMPVarListClause(OpenMPClauseKind Kind,
11632                                       ArrayRef<Expr *> Vars,
11633                                       const OMPVarListLocTy &Locs,
11634                                       OpenMPVarListDataTy &Data);
11635   /// Called on well-formed 'inclusive' clause.
11636   OMPClause *ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList,
11637                                         SourceLocation StartLoc,
11638                                         SourceLocation LParenLoc,
11639                                         SourceLocation EndLoc);
11640   /// Called on well-formed 'exclusive' clause.
11641   OMPClause *ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList,
11642                                         SourceLocation StartLoc,
11643                                         SourceLocation LParenLoc,
11644                                         SourceLocation EndLoc);
11645   /// Called on well-formed 'allocate' clause.
11646   OMPClause *
11647   ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList,
11648                             SourceLocation StartLoc, SourceLocation ColonLoc,
11649                             SourceLocation LParenLoc, SourceLocation EndLoc);
11650   /// Called on well-formed 'private' clause.
11651   OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
11652                                       SourceLocation StartLoc,
11653                                       SourceLocation LParenLoc,
11654                                       SourceLocation EndLoc);
11655   /// Called on well-formed 'firstprivate' clause.
11656   OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
11657                                            SourceLocation StartLoc,
11658                                            SourceLocation LParenLoc,
11659                                            SourceLocation EndLoc);
11660   /// Called on well-formed 'lastprivate' clause.
11661   OMPClause *ActOnOpenMPLastprivateClause(
11662       ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
11663       SourceLocation LPKindLoc, SourceLocation ColonLoc,
11664       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
11665   /// Called on well-formed 'shared' clause.
11666   OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
11667                                      SourceLocation StartLoc,
11668                                      SourceLocation LParenLoc,
11669                                      SourceLocation EndLoc);
11670   /// Called on well-formed 'reduction' clause.
11671   OMPClause *ActOnOpenMPReductionClause(
11672       ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
11673       SourceLocation StartLoc, SourceLocation LParenLoc,
11674       SourceLocation ModifierLoc, SourceLocation ColonLoc,
11675       SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
11676       const DeclarationNameInfo &ReductionId,
11677       ArrayRef<Expr *> UnresolvedReductions = llvm::None);
11678   /// Called on well-formed 'task_reduction' clause.
11679   OMPClause *ActOnOpenMPTaskReductionClause(
11680       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11681       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
11682       CXXScopeSpec &ReductionIdScopeSpec,
11683       const DeclarationNameInfo &ReductionId,
11684       ArrayRef<Expr *> UnresolvedReductions = llvm::None);
11685   /// Called on well-formed 'in_reduction' clause.
11686   OMPClause *ActOnOpenMPInReductionClause(
11687       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11688       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
11689       CXXScopeSpec &ReductionIdScopeSpec,
11690       const DeclarationNameInfo &ReductionId,
11691       ArrayRef<Expr *> UnresolvedReductions = llvm::None);
11692   /// Called on well-formed 'linear' clause.
11693   OMPClause *
11694   ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
11695                           SourceLocation StartLoc, SourceLocation LParenLoc,
11696                           OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
11697                           SourceLocation ColonLoc, SourceLocation EndLoc);
11698   /// Called on well-formed 'aligned' clause.
11699   OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
11700                                       Expr *Alignment,
11701                                       SourceLocation StartLoc,
11702                                       SourceLocation LParenLoc,
11703                                       SourceLocation ColonLoc,
11704                                       SourceLocation EndLoc);
11705   /// Called on well-formed 'copyin' clause.
11706   OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
11707                                      SourceLocation StartLoc,
11708                                      SourceLocation LParenLoc,
11709                                      SourceLocation EndLoc);
11710   /// Called on well-formed 'copyprivate' clause.
11711   OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
11712                                           SourceLocation StartLoc,
11713                                           SourceLocation LParenLoc,
11714                                           SourceLocation EndLoc);
11715   /// Called on well-formed 'flush' pseudo clause.
11716   OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
11717                                     SourceLocation StartLoc,
11718                                     SourceLocation LParenLoc,
11719                                     SourceLocation EndLoc);
11720   /// Called on well-formed 'depobj' pseudo clause.
11721   OMPClause *ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
11722                                      SourceLocation LParenLoc,
11723                                      SourceLocation EndLoc);
11724   /// Called on well-formed 'depend' clause.
11725   OMPClause *ActOnOpenMPDependClause(const OMPDependClause::DependDataTy &Data,
11726                                      Expr *DepModifier,
11727                                      ArrayRef<Expr *> VarList,
11728                                      SourceLocation StartLoc,
11729                                      SourceLocation LParenLoc,
11730                                      SourceLocation EndLoc);
11731   /// Called on well-formed 'device' clause.
11732   OMPClause *ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
11733                                      Expr *Device, SourceLocation StartLoc,
11734                                      SourceLocation LParenLoc,
11735                                      SourceLocation ModifierLoc,
11736                                      SourceLocation EndLoc);
11737   /// Called on well-formed 'map' clause.
11738   OMPClause *ActOnOpenMPMapClause(
11739       ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
11740       ArrayRef<SourceLocation> MapTypeModifiersLoc,
11741       CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
11742       OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
11743       SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
11744       const OMPVarListLocTy &Locs, bool NoDiagnose = false,
11745       ArrayRef<Expr *> UnresolvedMappers = llvm::None);
11746   /// Called on well-formed 'num_teams' clause.
11747   OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
11748                                        SourceLocation LParenLoc,
11749                                        SourceLocation EndLoc);
11750   /// Called on well-formed 'thread_limit' clause.
11751   OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
11752                                           SourceLocation StartLoc,
11753                                           SourceLocation LParenLoc,
11754                                           SourceLocation EndLoc);
11755   /// Called on well-formed 'priority' clause.
11756   OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
11757                                        SourceLocation LParenLoc,
11758                                        SourceLocation EndLoc);
11759   /// Called on well-formed 'dist_schedule' clause.
11760   OMPClause *ActOnOpenMPDistScheduleClause(
11761       OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
11762       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
11763       SourceLocation CommaLoc, SourceLocation EndLoc);
11764   /// Called on well-formed 'defaultmap' clause.
11765   OMPClause *ActOnOpenMPDefaultmapClause(
11766       OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
11767       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
11768       SourceLocation KindLoc, SourceLocation EndLoc);
11769   /// Called on well-formed 'to' clause.
11770   OMPClause *
11771   ActOnOpenMPToClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
11772                       ArrayRef<SourceLocation> MotionModifiersLoc,
11773                       CXXScopeSpec &MapperIdScopeSpec,
11774                       DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
11775                       ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
11776                       ArrayRef<Expr *> UnresolvedMappers = llvm::None);
11777   /// Called on well-formed 'from' clause.
11778   OMPClause *
11779   ActOnOpenMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
11780                         ArrayRef<SourceLocation> MotionModifiersLoc,
11781                         CXXScopeSpec &MapperIdScopeSpec,
11782                         DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
11783                         ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
11784                         ArrayRef<Expr *> UnresolvedMappers = llvm::None);
11785   /// Called on well-formed 'use_device_ptr' clause.
11786   OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
11787                                            const OMPVarListLocTy &Locs);
11788   /// Called on well-formed 'use_device_addr' clause.
11789   OMPClause *ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
11790                                             const OMPVarListLocTy &Locs);
11791   /// Called on well-formed 'is_device_ptr' clause.
11792   OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
11793                                           const OMPVarListLocTy &Locs);
11794   /// Called on well-formed 'has_device_addr' clause.
11795   OMPClause *ActOnOpenMPHasDeviceAddrClause(ArrayRef<Expr *> VarList,
11796                                             const OMPVarListLocTy &Locs);
11797   /// Called on well-formed 'nontemporal' clause.
11798   OMPClause *ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
11799                                           SourceLocation StartLoc,
11800                                           SourceLocation LParenLoc,
11801                                           SourceLocation EndLoc);
11802 
11803   /// Data for list of allocators.
11804   struct UsesAllocatorsData {
11805     /// Allocator.
11806     Expr *Allocator = nullptr;
11807     /// Allocator traits.
11808     Expr *AllocatorTraits = nullptr;
11809     /// Locations of '(' and ')' symbols.
11810     SourceLocation LParenLoc, RParenLoc;
11811   };
11812   /// Called on well-formed 'uses_allocators' clause.
11813   OMPClause *ActOnOpenMPUsesAllocatorClause(SourceLocation StartLoc,
11814                                             SourceLocation LParenLoc,
11815                                             SourceLocation EndLoc,
11816                                             ArrayRef<UsesAllocatorsData> Data);
11817   /// Called on well-formed 'affinity' clause.
11818   OMPClause *ActOnOpenMPAffinityClause(SourceLocation StartLoc,
11819                                        SourceLocation LParenLoc,
11820                                        SourceLocation ColonLoc,
11821                                        SourceLocation EndLoc, Expr *Modifier,
11822                                        ArrayRef<Expr *> Locators);
11823   /// Called on a well-formed 'bind' clause.
11824   OMPClause *ActOnOpenMPBindClause(OpenMPBindClauseKind Kind,
11825                                    SourceLocation KindLoc,
11826                                    SourceLocation StartLoc,
11827                                    SourceLocation LParenLoc,
11828                                    SourceLocation EndLoc);
11829 
11830   /// The kind of conversion being performed.
11831   enum CheckedConversionKind {
11832     /// An implicit conversion.
11833     CCK_ImplicitConversion,
11834     /// A C-style cast.
11835     CCK_CStyleCast,
11836     /// A functional-style cast.
11837     CCK_FunctionalCast,
11838     /// A cast other than a C-style cast.
11839     CCK_OtherCast,
11840     /// A conversion for an operand of a builtin overloaded operator.
11841     CCK_ForBuiltinOverloadedOp
11842   };
11843 
11844   static bool isCast(CheckedConversionKind CCK) {
11845     return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast ||
11846            CCK == CCK_OtherCast;
11847   }
11848 
11849   /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
11850   /// cast.  If there is already an implicit cast, merge into the existing one.
11851   /// If isLvalue, the result of the cast is an lvalue.
11852   ExprResult
11853   ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
11854                     ExprValueKind VK = VK_PRValue,
11855                     const CXXCastPath *BasePath = nullptr,
11856                     CheckedConversionKind CCK = CCK_ImplicitConversion);
11857 
11858   /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
11859   /// to the conversion from scalar type ScalarTy to the Boolean type.
11860   static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
11861 
11862   /// IgnoredValueConversions - Given that an expression's result is
11863   /// syntactically ignored, perform any conversions that are
11864   /// required.
11865   ExprResult IgnoredValueConversions(Expr *E);
11866 
11867   // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
11868   // functions and arrays to their respective pointers (C99 6.3.2.1).
11869   ExprResult UsualUnaryConversions(Expr *E);
11870 
11871   /// CallExprUnaryConversions - a special case of an unary conversion
11872   /// performed on a function designator of a call expression.
11873   ExprResult CallExprUnaryConversions(Expr *E);
11874 
11875   // DefaultFunctionArrayConversion - converts functions and arrays
11876   // to their respective pointers (C99 6.3.2.1).
11877   ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
11878 
11879   // DefaultFunctionArrayLvalueConversion - converts functions and
11880   // arrays to their respective pointers and performs the
11881   // lvalue-to-rvalue conversion.
11882   ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
11883                                                   bool Diagnose = true);
11884 
11885   // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
11886   // the operand. This function is a no-op if the operand has a function type
11887   // or an array type.
11888   ExprResult DefaultLvalueConversion(Expr *E);
11889 
11890   // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
11891   // do not have a prototype. Integer promotions are performed on each
11892   // argument, and arguments that have type float are promoted to double.
11893   ExprResult DefaultArgumentPromotion(Expr *E);
11894 
11895   /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
11896   /// it as an xvalue. In C++98, the result will still be a prvalue, because
11897   /// we don't have xvalues there.
11898   ExprResult TemporaryMaterializationConversion(Expr *E);
11899 
11900   // Used for emitting the right warning by DefaultVariadicArgumentPromotion
11901   enum VariadicCallType {
11902     VariadicFunction,
11903     VariadicBlock,
11904     VariadicMethod,
11905     VariadicConstructor,
11906     VariadicDoesNotApply
11907   };
11908 
11909   VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
11910                                        const FunctionProtoType *Proto,
11911                                        Expr *Fn);
11912 
11913   // Used for determining in which context a type is allowed to be passed to a
11914   // vararg function.
11915   enum VarArgKind {
11916     VAK_Valid,
11917     VAK_ValidInCXX11,
11918     VAK_Undefined,
11919     VAK_MSVCUndefined,
11920     VAK_Invalid
11921   };
11922 
11923   // Determines which VarArgKind fits an expression.
11924   VarArgKind isValidVarArgType(const QualType &Ty);
11925 
11926   /// Check to see if the given expression is a valid argument to a variadic
11927   /// function, issuing a diagnostic if not.
11928   void checkVariadicArgument(const Expr *E, VariadicCallType CT);
11929 
11930   /// Check whether the given statement can have musttail applied to it,
11931   /// issuing a diagnostic and returning false if not. In the success case,
11932   /// the statement is rewritten to remove implicit nodes from the return
11933   /// value.
11934   bool checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA);
11935 
11936 private:
11937   /// Check whether the given statement can have musttail applied to it,
11938   /// issuing a diagnostic and returning false if not.
11939   bool checkMustTailAttr(const Stmt *St, const Attr &MTA);
11940 
11941 public:
11942   /// Check to see if a given expression could have '.c_str()' called on it.
11943   bool hasCStrMethod(const Expr *E);
11944 
11945   /// GatherArgumentsForCall - Collector argument expressions for various
11946   /// form of call prototypes.
11947   bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
11948                               const FunctionProtoType *Proto,
11949                               unsigned FirstParam, ArrayRef<Expr *> Args,
11950                               SmallVectorImpl<Expr *> &AllArgs,
11951                               VariadicCallType CallType = VariadicDoesNotApply,
11952                               bool AllowExplicit = false,
11953                               bool IsListInitialization = false);
11954 
11955   // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
11956   // will create a runtime trap if the resulting type is not a POD type.
11957   ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
11958                                               FunctionDecl *FDecl);
11959 
11960   /// Context in which we're performing a usual arithmetic conversion.
11961   enum ArithConvKind {
11962     /// An arithmetic operation.
11963     ACK_Arithmetic,
11964     /// A bitwise operation.
11965     ACK_BitwiseOp,
11966     /// A comparison.
11967     ACK_Comparison,
11968     /// A conditional (?:) operator.
11969     ACK_Conditional,
11970     /// A compound assignment expression.
11971     ACK_CompAssign,
11972   };
11973 
11974   // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
11975   // operands and then handles various conversions that are common to binary
11976   // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
11977   // routine returns the first non-arithmetic type found. The client is
11978   // responsible for emitting appropriate error diagnostics.
11979   QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
11980                                       SourceLocation Loc, ArithConvKind ACK);
11981 
11982   /// AssignConvertType - All of the 'assignment' semantic checks return this
11983   /// enum to indicate whether the assignment was allowed.  These checks are
11984   /// done for simple assignments, as well as initialization, return from
11985   /// function, argument passing, etc.  The query is phrased in terms of a
11986   /// source and destination type.
11987   enum AssignConvertType {
11988     /// Compatible - the types are compatible according to the standard.
11989     Compatible,
11990 
11991     /// PointerToInt - The assignment converts a pointer to an int, which we
11992     /// accept as an extension.
11993     PointerToInt,
11994 
11995     /// IntToPointer - The assignment converts an int to a pointer, which we
11996     /// accept as an extension.
11997     IntToPointer,
11998 
11999     /// FunctionVoidPointer - The assignment is between a function pointer and
12000     /// void*, which the standard doesn't allow, but we accept as an extension.
12001     FunctionVoidPointer,
12002 
12003     /// IncompatiblePointer - The assignment is between two pointers types that
12004     /// are not compatible, but we accept them as an extension.
12005     IncompatiblePointer,
12006 
12007     /// IncompatibleFunctionPointer - The assignment is between two function
12008     /// pointers types that are not compatible, but we accept them as an
12009     /// extension.
12010     IncompatibleFunctionPointer,
12011 
12012     /// IncompatiblePointerSign - The assignment is between two pointers types
12013     /// which point to integers which have a different sign, but are otherwise
12014     /// identical. This is a subset of the above, but broken out because it's by
12015     /// far the most common case of incompatible pointers.
12016     IncompatiblePointerSign,
12017 
12018     /// CompatiblePointerDiscardsQualifiers - The assignment discards
12019     /// c/v/r qualifiers, which we accept as an extension.
12020     CompatiblePointerDiscardsQualifiers,
12021 
12022     /// IncompatiblePointerDiscardsQualifiers - The assignment
12023     /// discards qualifiers that we don't permit to be discarded,
12024     /// like address spaces.
12025     IncompatiblePointerDiscardsQualifiers,
12026 
12027     /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment
12028     /// changes address spaces in nested pointer types which is not allowed.
12029     /// For instance, converting __private int ** to __generic int ** is
12030     /// illegal even though __private could be converted to __generic.
12031     IncompatibleNestedPointerAddressSpaceMismatch,
12032 
12033     /// IncompatibleNestedPointerQualifiers - The assignment is between two
12034     /// nested pointer types, and the qualifiers other than the first two
12035     /// levels differ e.g. char ** -> const char **, but we accept them as an
12036     /// extension.
12037     IncompatibleNestedPointerQualifiers,
12038 
12039     /// IncompatibleVectors - The assignment is between two vector types that
12040     /// have the same size, which we accept as an extension.
12041     IncompatibleVectors,
12042 
12043     /// IntToBlockPointer - The assignment converts an int to a block
12044     /// pointer. We disallow this.
12045     IntToBlockPointer,
12046 
12047     /// IncompatibleBlockPointer - The assignment is between two block
12048     /// pointers types that are not compatible.
12049     IncompatibleBlockPointer,
12050 
12051     /// IncompatibleObjCQualifiedId - The assignment is between a qualified
12052     /// id type and something else (that is incompatible with it). For example,
12053     /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
12054     IncompatibleObjCQualifiedId,
12055 
12056     /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
12057     /// object with __weak qualifier.
12058     IncompatibleObjCWeakRef,
12059 
12060     /// Incompatible - We reject this conversion outright, it is invalid to
12061     /// represent it in the AST.
12062     Incompatible
12063   };
12064 
12065   /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
12066   /// assignment conversion type specified by ConvTy.  This returns true if the
12067   /// conversion was invalid or false if the conversion was accepted.
12068   bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
12069                                 SourceLocation Loc,
12070                                 QualType DstType, QualType SrcType,
12071                                 Expr *SrcExpr, AssignmentAction Action,
12072                                 bool *Complained = nullptr);
12073 
12074   /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
12075   /// enum. If AllowMask is true, then we also allow the complement of a valid
12076   /// value, to be used as a mask.
12077   bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
12078                          bool AllowMask) const;
12079 
12080   /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
12081   /// integer not in the range of enum values.
12082   void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
12083                               Expr *SrcExpr);
12084 
12085   /// CheckAssignmentConstraints - Perform type checking for assignment,
12086   /// argument passing, variable initialization, and function return values.
12087   /// C99 6.5.16.
12088   AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
12089                                                QualType LHSType,
12090                                                QualType RHSType);
12091 
12092   /// Check assignment constraints and optionally prepare for a conversion of
12093   /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
12094   /// is true.
12095   AssignConvertType CheckAssignmentConstraints(QualType LHSType,
12096                                                ExprResult &RHS,
12097                                                CastKind &Kind,
12098                                                bool ConvertRHS = true);
12099 
12100   /// Check assignment constraints for an assignment of RHS to LHSType.
12101   ///
12102   /// \param LHSType The destination type for the assignment.
12103   /// \param RHS The source expression for the assignment.
12104   /// \param Diagnose If \c true, diagnostics may be produced when checking
12105   ///        for assignability. If a diagnostic is produced, \p RHS will be
12106   ///        set to ExprError(). Note that this function may still return
12107   ///        without producing a diagnostic, even for an invalid assignment.
12108   /// \param DiagnoseCFAudited If \c true, the target is a function parameter
12109   ///        in an audited Core Foundation API and does not need to be checked
12110   ///        for ARC retain issues.
12111   /// \param ConvertRHS If \c true, \p RHS will be updated to model the
12112   ///        conversions necessary to perform the assignment. If \c false,
12113   ///        \p Diagnose must also be \c false.
12114   AssignConvertType CheckSingleAssignmentConstraints(
12115       QualType LHSType, ExprResult &RHS, bool Diagnose = true,
12116       bool DiagnoseCFAudited = false, bool ConvertRHS = true);
12117 
12118   // If the lhs type is a transparent union, check whether we
12119   // can initialize the transparent union with the given expression.
12120   AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
12121                                                              ExprResult &RHS);
12122 
12123   bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
12124 
12125   bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
12126 
12127   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
12128                                        AssignmentAction Action,
12129                                        bool AllowExplicit = false);
12130   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
12131                                        const ImplicitConversionSequence& ICS,
12132                                        AssignmentAction Action,
12133                                        CheckedConversionKind CCK
12134                                           = CCK_ImplicitConversion);
12135   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
12136                                        const StandardConversionSequence& SCS,
12137                                        AssignmentAction Action,
12138                                        CheckedConversionKind CCK);
12139 
12140   ExprResult PerformQualificationConversion(
12141       Expr *E, QualType Ty, ExprValueKind VK = VK_PRValue,
12142       CheckedConversionKind CCK = CCK_ImplicitConversion);
12143 
12144   /// the following "Check" methods will return a valid/converted QualType
12145   /// or a null QualType (indicating an error diagnostic was issued).
12146 
12147   /// type checking binary operators (subroutines of CreateBuiltinBinOp).
12148   QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
12149                            ExprResult &RHS);
12150   QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
12151                                  ExprResult &RHS);
12152   QualType CheckPointerToMemberOperands( // C++ 5.5
12153     ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
12154     SourceLocation OpLoc, bool isIndirect);
12155   QualType CheckMultiplyDivideOperands( // C99 6.5.5
12156     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
12157     bool IsDivide);
12158   QualType CheckRemainderOperands( // C99 6.5.5
12159     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
12160     bool IsCompAssign = false);
12161   QualType CheckAdditionOperands( // C99 6.5.6
12162     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
12163     BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
12164   QualType CheckSubtractionOperands( // C99 6.5.6
12165     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
12166     QualType* CompLHSTy = nullptr);
12167   QualType CheckShiftOperands( // C99 6.5.7
12168     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
12169     BinaryOperatorKind Opc, bool IsCompAssign = false);
12170   void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE);
12171   QualType CheckCompareOperands( // C99 6.5.8/9
12172       ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
12173       BinaryOperatorKind Opc);
12174   QualType CheckBitwiseOperands( // C99 6.5.[10...12]
12175       ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
12176       BinaryOperatorKind Opc);
12177   QualType CheckLogicalOperands( // C99 6.5.[13,14]
12178     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
12179     BinaryOperatorKind Opc);
12180   // CheckAssignmentOperands is used for both simple and compound assignment.
12181   // For simple assignment, pass both expressions and a null converted type.
12182   // For compound assignment, pass both expressions and the converted type.
12183   QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
12184       Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType,
12185       BinaryOperatorKind Opc);
12186 
12187   ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
12188                                      UnaryOperatorKind Opcode, Expr *Op);
12189   ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
12190                                          BinaryOperatorKind Opcode,
12191                                          Expr *LHS, Expr *RHS);
12192   ExprResult checkPseudoObjectRValue(Expr *E);
12193   Expr *recreateSyntacticForm(PseudoObjectExpr *E);
12194 
12195   QualType CheckConditionalOperands( // C99 6.5.15
12196     ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
12197     ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
12198   QualType CXXCheckConditionalOperands( // C++ 5.16
12199     ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
12200     ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
12201   QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
12202                                        ExprResult &RHS,
12203                                        SourceLocation QuestionLoc);
12204 
12205   QualType CheckSizelessVectorConditionalTypes(ExprResult &Cond,
12206                                                ExprResult &LHS, ExprResult &RHS,
12207                                                SourceLocation QuestionLoc);
12208   QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
12209                                     bool ConvertArgs = true);
12210   QualType FindCompositePointerType(SourceLocation Loc,
12211                                     ExprResult &E1, ExprResult &E2,
12212                                     bool ConvertArgs = true) {
12213     Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
12214     QualType Composite =
12215         FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
12216     E1 = E1Tmp;
12217     E2 = E2Tmp;
12218     return Composite;
12219   }
12220 
12221   QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
12222                                         SourceLocation QuestionLoc);
12223 
12224   bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
12225                                   SourceLocation QuestionLoc);
12226 
12227   void DiagnoseAlwaysNonNullPointer(Expr *E,
12228                                     Expr::NullPointerConstantKind NullType,
12229                                     bool IsEqual, SourceRange Range);
12230 
12231   /// type checking for vector binary operators.
12232   QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
12233                                SourceLocation Loc, bool IsCompAssign,
12234                                bool AllowBothBool, bool AllowBoolConversion,
12235                                bool AllowBoolOperation, bool ReportInvalid);
12236   QualType GetSignedVectorType(QualType V);
12237   QualType GetSignedSizelessVectorType(QualType V);
12238   QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
12239                                       SourceLocation Loc,
12240                                       BinaryOperatorKind Opc);
12241   QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
12242                                               SourceLocation Loc,
12243                                               BinaryOperatorKind Opc);
12244   QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12245                                       SourceLocation Loc);
12246 
12247   // type checking for sizeless vector binary operators.
12248   QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
12249                                        SourceLocation Loc, bool IsCompAssign,
12250                                        ArithConvKind OperationKind);
12251 
12252   /// Type checking for matrix binary operators.
12253   QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12254                                           SourceLocation Loc,
12255                                           bool IsCompAssign);
12256   QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12257                                        SourceLocation Loc, bool IsCompAssign);
12258 
12259   bool isValidSveBitcast(QualType srcType, QualType destType);
12260 
12261   bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy);
12262 
12263   bool areVectorTypesSameSize(QualType srcType, QualType destType);
12264   bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
12265   bool isLaxVectorConversion(QualType srcType, QualType destType);
12266   bool areSameVectorElemTypes(QualType srcType, QualType destType);
12267   bool anyAltivecTypes(QualType srcType, QualType destType);
12268 
12269   /// type checking declaration initializers (C99 6.7.8)
12270   bool CheckForConstantInitializer(Expr *e, QualType t);
12271 
12272   // type checking C++ declaration initializers (C++ [dcl.init]).
12273 
12274   /// ReferenceCompareResult - Expresses the result of comparing two
12275   /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
12276   /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
12277   enum ReferenceCompareResult {
12278     /// Ref_Incompatible - The two types are incompatible, so direct
12279     /// reference binding is not possible.
12280     Ref_Incompatible = 0,
12281     /// Ref_Related - The two types are reference-related, which means
12282     /// that their unqualified forms (T1 and T2) are either the same
12283     /// or T1 is a base class of T2.
12284     Ref_Related,
12285     /// Ref_Compatible - The two types are reference-compatible.
12286     Ref_Compatible
12287   };
12288 
12289   // Fake up a scoped enumeration that still contextually converts to bool.
12290   struct ReferenceConversionsScope {
12291     /// The conversions that would be performed on an lvalue of type T2 when
12292     /// binding a reference of type T1 to it, as determined when evaluating
12293     /// whether T1 is reference-compatible with T2.
12294     enum ReferenceConversions {
12295       Qualification = 0x1,
12296       NestedQualification = 0x2,
12297       Function = 0x4,
12298       DerivedToBase = 0x8,
12299       ObjC = 0x10,
12300       ObjCLifetime = 0x20,
12301 
12302       LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime)
12303     };
12304   };
12305   using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions;
12306 
12307   ReferenceCompareResult
12308   CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2,
12309                                ReferenceConversions *Conv = nullptr);
12310 
12311   ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
12312                                  Expr *CastExpr, CastKind &CastKind,
12313                                  ExprValueKind &VK, CXXCastPath &Path);
12314 
12315   /// Force an expression with unknown-type to an expression of the
12316   /// given type.
12317   ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
12318 
12319   /// Type-check an expression that's being passed to an
12320   /// __unknown_anytype parameter.
12321   ExprResult checkUnknownAnyArg(SourceLocation callLoc,
12322                                 Expr *result, QualType &paramType);
12323 
12324   // CheckMatrixCast - Check type constraints for matrix casts.
12325   // We allow casting between matrixes of the same dimensions i.e. when they
12326   // have the same number of rows and column. Returns true if the cast is
12327   // invalid.
12328   bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
12329                        CastKind &Kind);
12330 
12331   // CheckVectorCast - check type constraints for vectors.
12332   // Since vectors are an extension, there are no C standard reference for this.
12333   // We allow casting between vectors and integer datatypes of the same size.
12334   // returns true if the cast is invalid
12335   bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
12336                        CastKind &Kind);
12337 
12338   /// Prepare `SplattedExpr` for a vector splat operation, adding
12339   /// implicit casts if necessary.
12340   ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
12341 
12342   // CheckExtVectorCast - check type constraints for extended vectors.
12343   // Since vectors are an extension, there are no C standard reference for this.
12344   // We allow casting between vectors and integer datatypes of the same size,
12345   // or vectors and the element type of that vector.
12346   // returns the cast expr
12347   ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
12348                                 CastKind &Kind);
12349 
12350   ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
12351                                         SourceLocation LParenLoc,
12352                                         Expr *CastExpr,
12353                                         SourceLocation RParenLoc);
12354 
12355   enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
12356 
12357   /// Checks for invalid conversions and casts between
12358   /// retainable pointers and other pointer kinds for ARC and Weak.
12359   ARCConversionResult CheckObjCConversion(SourceRange castRange,
12360                                           QualType castType, Expr *&op,
12361                                           CheckedConversionKind CCK,
12362                                           bool Diagnose = true,
12363                                           bool DiagnoseCFAudited = false,
12364                                           BinaryOperatorKind Opc = BO_PtrMemD
12365                                           );
12366 
12367   Expr *stripARCUnbridgedCast(Expr *e);
12368   void diagnoseARCUnbridgedCast(Expr *e);
12369 
12370   bool CheckObjCARCUnavailableWeakConversion(QualType castType,
12371                                              QualType ExprType);
12372 
12373   /// checkRetainCycles - Check whether an Objective-C message send
12374   /// might create an obvious retain cycle.
12375   void checkRetainCycles(ObjCMessageExpr *msg);
12376   void checkRetainCycles(Expr *receiver, Expr *argument);
12377   void checkRetainCycles(VarDecl *Var, Expr *Init);
12378 
12379   /// checkUnsafeAssigns - Check whether +1 expr is being assigned
12380   /// to weak/__unsafe_unretained type.
12381   bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
12382 
12383   /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
12384   /// to weak/__unsafe_unretained expression.
12385   void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
12386 
12387   /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
12388   /// \param Method - May be null.
12389   /// \param [out] ReturnType - The return type of the send.
12390   /// \return true iff there were any incompatible types.
12391   bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType,
12392                                  MultiExprArg Args, Selector Sel,
12393                                  ArrayRef<SourceLocation> SelectorLocs,
12394                                  ObjCMethodDecl *Method, bool isClassMessage,
12395                                  bool isSuperMessage, SourceLocation lbrac,
12396                                  SourceLocation rbrac, SourceRange RecRange,
12397                                  QualType &ReturnType, ExprValueKind &VK);
12398 
12399   /// Determine the result of a message send expression based on
12400   /// the type of the receiver, the method expected to receive the message,
12401   /// and the form of the message send.
12402   QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType,
12403                                     ObjCMethodDecl *Method, bool isClassMessage,
12404                                     bool isSuperMessage);
12405 
12406   /// If the given expression involves a message send to a method
12407   /// with a related result type, emit a note describing what happened.
12408   void EmitRelatedResultTypeNote(const Expr *E);
12409 
12410   /// Given that we had incompatible pointer types in a return
12411   /// statement, check whether we're in a method with a related result
12412   /// type, and if so, emit a note describing what happened.
12413   void EmitRelatedResultTypeNoteForReturn(QualType destType);
12414 
12415   class ConditionResult {
12416     Decl *ConditionVar;
12417     FullExprArg Condition;
12418     bool Invalid;
12419     bool HasKnownValue;
12420     bool KnownValue;
12421 
12422     friend class Sema;
12423     ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
12424                     bool IsConstexpr)
12425         : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
12426           HasKnownValue(IsConstexpr && Condition.get() &&
12427                         !Condition.get()->isValueDependent()),
12428           KnownValue(HasKnownValue &&
12429                      !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
12430     explicit ConditionResult(bool Invalid)
12431         : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
12432           HasKnownValue(false), KnownValue(false) {}
12433 
12434   public:
12435     ConditionResult() : ConditionResult(false) {}
12436     bool isInvalid() const { return Invalid; }
12437     std::pair<VarDecl *, Expr *> get() const {
12438       return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
12439                             Condition.get());
12440     }
12441     llvm::Optional<bool> getKnownValue() const {
12442       if (!HasKnownValue)
12443         return None;
12444       return KnownValue;
12445     }
12446   };
12447   static ConditionResult ConditionError() { return ConditionResult(true); }
12448 
12449   enum class ConditionKind {
12450     Boolean,     ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
12451     ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
12452     Switch       ///< An integral condition for a 'switch' statement.
12453   };
12454   QualType PreferredConditionType(ConditionKind K) const {
12455     return K == ConditionKind::Switch ? Context.IntTy : Context.BoolTy;
12456   }
12457 
12458   ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr,
12459                                  ConditionKind CK, bool MissingOK = false);
12460 
12461   ConditionResult ActOnConditionVariable(Decl *ConditionVar,
12462                                          SourceLocation StmtLoc,
12463                                          ConditionKind CK);
12464 
12465   DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
12466 
12467   ExprResult CheckConditionVariable(VarDecl *ConditionVar,
12468                                     SourceLocation StmtLoc,
12469                                     ConditionKind CK);
12470   ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
12471 
12472   /// CheckBooleanCondition - Diagnose problems involving the use of
12473   /// the given expression as a boolean condition (e.g. in an if
12474   /// statement).  Also performs the standard function and array
12475   /// decays, possibly changing the input variable.
12476   ///
12477   /// \param Loc - A location associated with the condition, e.g. the
12478   /// 'if' keyword.
12479   /// \return true iff there were any errors
12480   ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
12481                                    bool IsConstexpr = false);
12482 
12483   /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression
12484   /// found in an explicit(bool) specifier.
12485   ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E);
12486 
12487   /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
12488   /// Returns true if the explicit specifier is now resolved.
12489   bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec);
12490 
12491   /// DiagnoseAssignmentAsCondition - Given that an expression is
12492   /// being used as a boolean condition, warn if it's an assignment.
12493   void DiagnoseAssignmentAsCondition(Expr *E);
12494 
12495   /// Redundant parentheses over an equality comparison can indicate
12496   /// that the user intended an assignment used as condition.
12497   void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
12498 
12499   /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
12500   ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
12501 
12502   /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
12503   /// the specified width and sign.  If an overflow occurs, detect it and emit
12504   /// the specified diagnostic.
12505   void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
12506                                           unsigned NewWidth, bool NewSign,
12507                                           SourceLocation Loc, unsigned DiagID);
12508 
12509   /// Checks that the Objective-C declaration is declared in the global scope.
12510   /// Emits an error and marks the declaration as invalid if it's not declared
12511   /// in the global scope.
12512   bool CheckObjCDeclScope(Decl *D);
12513 
12514   /// Abstract base class used for diagnosing integer constant
12515   /// expression violations.
12516   class VerifyICEDiagnoser {
12517   public:
12518     bool Suppress;
12519 
12520     VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
12521 
12522     virtual SemaDiagnosticBuilder
12523     diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T);
12524     virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
12525                                                  SourceLocation Loc) = 0;
12526     virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc);
12527     virtual ~VerifyICEDiagnoser() {}
12528   };
12529 
12530   enum AllowFoldKind {
12531     NoFold,
12532     AllowFold,
12533   };
12534 
12535   /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
12536   /// and reports the appropriate diagnostics. Returns false on success.
12537   /// Can optionally return the value of the expression.
12538   ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12539                                              VerifyICEDiagnoser &Diagnoser,
12540                                              AllowFoldKind CanFold = NoFold);
12541   ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12542                                              unsigned DiagID,
12543                                              AllowFoldKind CanFold = NoFold);
12544   ExprResult VerifyIntegerConstantExpression(Expr *E,
12545                                              llvm::APSInt *Result = nullptr,
12546                                              AllowFoldKind CanFold = NoFold);
12547   ExprResult VerifyIntegerConstantExpression(Expr *E,
12548                                              AllowFoldKind CanFold = NoFold) {
12549     return VerifyIntegerConstantExpression(E, nullptr, CanFold);
12550   }
12551 
12552   /// VerifyBitField - verifies that a bit field expression is an ICE and has
12553   /// the correct width, and that the field type is valid.
12554   /// Returns false on success.
12555   ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
12556                             QualType FieldTy, bool IsMsStruct, Expr *BitWidth);
12557 
12558 private:
12559   unsigned ForceCUDAHostDeviceDepth = 0;
12560 
12561 public:
12562   /// Increments our count of the number of times we've seen a pragma forcing
12563   /// functions to be __host__ __device__.  So long as this count is greater
12564   /// than zero, all functions encountered will be __host__ __device__.
12565   void PushForceCUDAHostDevice();
12566 
12567   /// Decrements our count of the number of times we've seen a pragma forcing
12568   /// functions to be __host__ __device__.  Returns false if the count is 0
12569   /// before incrementing, so you can emit an error.
12570   bool PopForceCUDAHostDevice();
12571 
12572   /// Diagnostics that are emitted only if we discover that the given function
12573   /// must be codegen'ed.  Because handling these correctly adds overhead to
12574   /// compilation, this is currently only enabled for CUDA compilations.
12575   llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
12576                  std::vector<PartialDiagnosticAt>>
12577       DeviceDeferredDiags;
12578 
12579   /// A pair of a canonical FunctionDecl and a SourceLocation.  When used as the
12580   /// key in a hashtable, both the FD and location are hashed.
12581   struct FunctionDeclAndLoc {
12582     CanonicalDeclPtr<FunctionDecl> FD;
12583     SourceLocation Loc;
12584   };
12585 
12586   /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
12587   /// (maybe deferred) "bad call" diagnostic.  We use this to avoid emitting the
12588   /// same deferred diag twice.
12589   llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
12590 
12591   /// An inverse call graph, mapping known-emitted functions to one of their
12592   /// known-emitted callers (plus the location of the call).
12593   ///
12594   /// Functions that we can tell a priori must be emitted aren't added to this
12595   /// map.
12596   llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
12597                  /* Caller = */ FunctionDeclAndLoc>
12598       DeviceKnownEmittedFns;
12599 
12600   /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
12601   /// context is "used as device code".
12602   ///
12603   /// - If CurContext is a __host__ function, does not emit any diagnostics
12604   ///   unless \p EmitOnBothSides is true.
12605   /// - If CurContext is a __device__ or __global__ function, emits the
12606   ///   diagnostics immediately.
12607   /// - If CurContext is a __host__ __device__ function and we are compiling for
12608   ///   the device, creates a diagnostic which is emitted if and when we realize
12609   ///   that the function will be codegen'ed.
12610   ///
12611   /// Example usage:
12612   ///
12613   ///  // Variable-length arrays are not allowed in CUDA device code.
12614   ///  if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
12615   ///    return ExprError();
12616   ///  // Otherwise, continue parsing as normal.
12617   SemaDiagnosticBuilder CUDADiagIfDeviceCode(SourceLocation Loc,
12618                                              unsigned DiagID);
12619 
12620   /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
12621   /// context is "used as host code".
12622   ///
12623   /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
12624   SemaDiagnosticBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
12625 
12626   /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
12627   /// context is "used as device code".
12628   ///
12629   /// - If CurContext is a `declare target` function or it is known that the
12630   /// function is emitted for the device, emits the diagnostics immediately.
12631   /// - If CurContext is a non-`declare target` function and we are compiling
12632   ///   for the device, creates a diagnostic which is emitted if and when we
12633   ///   realize that the function will be codegen'ed.
12634   ///
12635   /// Example usage:
12636   ///
12637   ///  // Variable-length arrays are not allowed in NVPTX device code.
12638   ///  if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported))
12639   ///    return ExprError();
12640   ///  // Otherwise, continue parsing as normal.
12641   SemaDiagnosticBuilder
12642   diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID, FunctionDecl *FD);
12643 
12644   /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
12645   /// context is "used as host code".
12646   ///
12647   /// - If CurContext is a `declare target` function or it is known that the
12648   /// function is emitted for the host, emits the diagnostics immediately.
12649   /// - If CurContext is a non-host function, just ignore it.
12650   ///
12651   /// Example usage:
12652   ///
12653   ///  // Variable-length arrays are not allowed in NVPTX device code.
12654   ///  if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported))
12655   ///    return ExprError();
12656   ///  // Otherwise, continue parsing as normal.
12657   SemaDiagnosticBuilder diagIfOpenMPHostCode(SourceLocation Loc,
12658                                              unsigned DiagID, FunctionDecl *FD);
12659 
12660   SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID,
12661                                    FunctionDecl *FD = nullptr);
12662   SemaDiagnosticBuilder targetDiag(SourceLocation Loc,
12663                                    const PartialDiagnostic &PD,
12664                                    FunctionDecl *FD = nullptr) {
12665     return targetDiag(Loc, PD.getDiagID(), FD) << PD;
12666   }
12667 
12668   /// Check if the type is allowed to be used for the current target.
12669   void checkTypeSupport(QualType Ty, SourceLocation Loc,
12670                         ValueDecl *D = nullptr);
12671 
12672   enum CUDAFunctionTarget {
12673     CFT_Device,
12674     CFT_Global,
12675     CFT_Host,
12676     CFT_HostDevice,
12677     CFT_InvalidTarget
12678   };
12679 
12680   /// Determines whether the given function is a CUDA device/host/kernel/etc.
12681   /// function.
12682   ///
12683   /// Use this rather than examining the function's attributes yourself -- you
12684   /// will get it wrong.  Returns CFT_Host if D is null.
12685   CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
12686                                         bool IgnoreImplicitHDAttr = false);
12687   CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs);
12688 
12689   enum CUDAVariableTarget {
12690     CVT_Device,  /// Emitted on device side with a shadow variable on host side
12691     CVT_Host,    /// Emitted on host side only
12692     CVT_Both,    /// Emitted on both sides with different addresses
12693     CVT_Unified, /// Emitted as a unified address, e.g. managed variables
12694   };
12695   /// Determines whether the given variable is emitted on host or device side.
12696   CUDAVariableTarget IdentifyCUDATarget(const VarDecl *D);
12697 
12698   /// Gets the CUDA target for the current context.
12699   CUDAFunctionTarget CurrentCUDATarget() {
12700     return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
12701   }
12702 
12703   static bool isCUDAImplicitHostDeviceFunction(const FunctionDecl *D);
12704 
12705   // CUDA function call preference. Must be ordered numerically from
12706   // worst to best.
12707   enum CUDAFunctionPreference {
12708     CFP_Never,      // Invalid caller/callee combination.
12709     CFP_WrongSide,  // Calls from host-device to host or device
12710                     // function that do not match current compilation
12711                     // mode.
12712     CFP_HostDevice, // Any calls to host/device functions.
12713     CFP_SameSide,   // Calls from host-device to host or device
12714                     // function matching current compilation mode.
12715     CFP_Native,     // host-to-host or device-to-device calls.
12716   };
12717 
12718   /// Identifies relative preference of a given Caller/Callee
12719   /// combination, based on their host/device attributes.
12720   /// \param Caller function which needs address of \p Callee.
12721   ///               nullptr in case of global context.
12722   /// \param Callee target function
12723   ///
12724   /// \returns preference value for particular Caller/Callee combination.
12725   CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
12726                                                 const FunctionDecl *Callee);
12727 
12728   /// Determines whether Caller may invoke Callee, based on their CUDA
12729   /// host/device attributes.  Returns false if the call is not allowed.
12730   ///
12731   /// Note: Will return true for CFP_WrongSide calls.  These may appear in
12732   /// semantically correct CUDA programs, but only if they're never codegen'ed.
12733   bool IsAllowedCUDACall(const FunctionDecl *Caller,
12734                          const FunctionDecl *Callee) {
12735     return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
12736   }
12737 
12738   /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
12739   /// depending on FD and the current compilation settings.
12740   void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
12741                                    const LookupResult &Previous);
12742 
12743   /// May add implicit CUDAConstantAttr attribute to VD, depending on VD
12744   /// and current compilation settings.
12745   void MaybeAddCUDAConstantAttr(VarDecl *VD);
12746 
12747 public:
12748   /// Check whether we're allowed to call Callee from the current context.
12749   ///
12750   /// - If the call is never allowed in a semantically-correct program
12751   ///   (CFP_Never), emits an error and returns false.
12752   ///
12753   /// - If the call is allowed in semantically-correct programs, but only if
12754   ///   it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
12755   ///   be emitted if and when the caller is codegen'ed, and returns true.
12756   ///
12757   ///   Will only create deferred diagnostics for a given SourceLocation once,
12758   ///   so you can safely call this multiple times without generating duplicate
12759   ///   deferred errors.
12760   ///
12761   /// - Otherwise, returns true without emitting any diagnostics.
12762   bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
12763 
12764   void CUDACheckLambdaCapture(CXXMethodDecl *D, const sema::Capture &Capture);
12765 
12766   /// Set __device__ or __host__ __device__ attributes on the given lambda
12767   /// operator() method.
12768   ///
12769   /// CUDA lambdas by default is host device function unless it has explicit
12770   /// host or device attribute.
12771   void CUDASetLambdaAttrs(CXXMethodDecl *Method);
12772 
12773   /// Finds a function in \p Matches with highest calling priority
12774   /// from \p Caller context and erases all functions with lower
12775   /// calling priority.
12776   void EraseUnwantedCUDAMatches(
12777       const FunctionDecl *Caller,
12778       SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
12779 
12780   /// Given a implicit special member, infer its CUDA target from the
12781   /// calls it needs to make to underlying base/field special members.
12782   /// \param ClassDecl the class for which the member is being created.
12783   /// \param CSM the kind of special member.
12784   /// \param MemberDecl the special member itself.
12785   /// \param ConstRHS true if this is a copy operation with a const object on
12786   ///        its RHS.
12787   /// \param Diagnose true if this call should emit diagnostics.
12788   /// \return true if there was an error inferring.
12789   /// The result of this call is implicit CUDA target attribute(s) attached to
12790   /// the member declaration.
12791   bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
12792                                                CXXSpecialMember CSM,
12793                                                CXXMethodDecl *MemberDecl,
12794                                                bool ConstRHS,
12795                                                bool Diagnose);
12796 
12797   /// \return true if \p CD can be considered empty according to CUDA
12798   /// (E.2.3.1 in CUDA 7.5 Programming guide).
12799   bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
12800   bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
12801 
12802   // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In
12803   // case of error emits appropriate diagnostic and invalidates \p Var.
12804   //
12805   // \details CUDA allows only empty constructors as initializers for global
12806   // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all
12807   // __shared__ variables whether they are local or not (they all are implicitly
12808   // static in CUDA). One exception is that CUDA allows constant initializers
12809   // for __constant__ and __device__ variables.
12810   void checkAllowedCUDAInitializer(VarDecl *VD);
12811 
12812   /// Check whether NewFD is a valid overload for CUDA. Emits
12813   /// diagnostics and invalidates NewFD if not.
12814   void checkCUDATargetOverload(FunctionDecl *NewFD,
12815                                const LookupResult &Previous);
12816   /// Copies target attributes from the template TD to the function FD.
12817   void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
12818 
12819   /// Returns the name of the launch configuration function.  This is the name
12820   /// of the function that will be called to configure kernel call, with the
12821   /// parameters specified via <<<>>>.
12822   std::string getCudaConfigureFuncName() const;
12823 
12824   /// \name Code completion
12825   //@{
12826   /// Describes the context in which code completion occurs.
12827   enum ParserCompletionContext {
12828     /// Code completion occurs at top-level or namespace context.
12829     PCC_Namespace,
12830     /// Code completion occurs within a class, struct, or union.
12831     PCC_Class,
12832     /// Code completion occurs within an Objective-C interface, protocol,
12833     /// or category.
12834     PCC_ObjCInterface,
12835     /// Code completion occurs within an Objective-C implementation or
12836     /// category implementation
12837     PCC_ObjCImplementation,
12838     /// Code completion occurs within the list of instance variables
12839     /// in an Objective-C interface, protocol, category, or implementation.
12840     PCC_ObjCInstanceVariableList,
12841     /// Code completion occurs following one or more template
12842     /// headers.
12843     PCC_Template,
12844     /// Code completion occurs following one or more template
12845     /// headers within a class.
12846     PCC_MemberTemplate,
12847     /// Code completion occurs within an expression.
12848     PCC_Expression,
12849     /// Code completion occurs within a statement, which may
12850     /// also be an expression or a declaration.
12851     PCC_Statement,
12852     /// Code completion occurs at the beginning of the
12853     /// initialization statement (or expression) in a for loop.
12854     PCC_ForInit,
12855     /// Code completion occurs within the condition of an if,
12856     /// while, switch, or for statement.
12857     PCC_Condition,
12858     /// Code completion occurs within the body of a function on a
12859     /// recovery path, where we do not have a specific handle on our position
12860     /// in the grammar.
12861     PCC_RecoveryInFunction,
12862     /// Code completion occurs where only a type is permitted.
12863     PCC_Type,
12864     /// Code completion occurs in a parenthesized expression, which
12865     /// might also be a type cast.
12866     PCC_ParenthesizedExpression,
12867     /// Code completion occurs within a sequence of declaration
12868     /// specifiers within a function, method, or block.
12869     PCC_LocalDeclarationSpecifiers
12870   };
12871 
12872   void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
12873   void CodeCompleteOrdinaryName(Scope *S,
12874                                 ParserCompletionContext CompletionContext);
12875   void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
12876                             bool AllowNonIdentifiers,
12877                             bool AllowNestedNameSpecifiers);
12878 
12879   struct CodeCompleteExpressionData;
12880   void CodeCompleteExpression(Scope *S,
12881                               const CodeCompleteExpressionData &Data);
12882   void CodeCompleteExpression(Scope *S, QualType PreferredType,
12883                               bool IsParenthesized = false);
12884   void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase,
12885                                        SourceLocation OpLoc, bool IsArrow,
12886                                        bool IsBaseExprStatement,
12887                                        QualType PreferredType);
12888   void CodeCompletePostfixExpression(Scope *S, ExprResult LHS,
12889                                      QualType PreferredType);
12890   void CodeCompleteTag(Scope *S, unsigned TagSpec);
12891   void CodeCompleteTypeQualifiers(DeclSpec &DS);
12892   void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
12893                                       const VirtSpecifiers *VS = nullptr);
12894   void CodeCompleteBracketDeclarator(Scope *S);
12895   void CodeCompleteCase(Scope *S);
12896   enum class AttributeCompletion {
12897     Attribute,
12898     Scope,
12899     None,
12900   };
12901   void CodeCompleteAttribute(
12902       AttributeCommonInfo::Syntax Syntax,
12903       AttributeCompletion Completion = AttributeCompletion::Attribute,
12904       const IdentifierInfo *Scope = nullptr);
12905   /// Determines the preferred type of the current function argument, by
12906   /// examining the signatures of all possible overloads.
12907   /// Returns null if unknown or ambiguous, or if code completion is off.
12908   ///
12909   /// If the code completion point has been reached, also reports the function
12910   /// signatures that were considered.
12911   ///
12912   /// FIXME: rename to GuessCallArgumentType to reduce confusion.
12913   QualType ProduceCallSignatureHelp(Expr *Fn, ArrayRef<Expr *> Args,
12914                                     SourceLocation OpenParLoc);
12915   QualType ProduceConstructorSignatureHelp(QualType Type, SourceLocation Loc,
12916                                            ArrayRef<Expr *> Args,
12917                                            SourceLocation OpenParLoc,
12918                                            bool Braced);
12919   QualType ProduceCtorInitMemberSignatureHelp(
12920       Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy,
12921       ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc,
12922       bool Braced);
12923   QualType ProduceTemplateArgumentSignatureHelp(
12924       TemplateTy, ArrayRef<ParsedTemplateArgument>, SourceLocation LAngleLoc);
12925   void CodeCompleteInitializer(Scope *S, Decl *D);
12926   /// Trigger code completion for a record of \p BaseType. \p InitExprs are
12927   /// expressions in the initializer list seen so far and \p D is the current
12928   /// Designation being parsed.
12929   void CodeCompleteDesignator(const QualType BaseType,
12930                               llvm::ArrayRef<Expr *> InitExprs,
12931                               const Designation &D);
12932   void CodeCompleteAfterIf(Scope *S, bool IsBracedThen);
12933 
12934   void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext,
12935                                bool IsUsingDeclaration, QualType BaseType,
12936                                QualType PreferredType);
12937   void CodeCompleteUsing(Scope *S);
12938   void CodeCompleteUsingDirective(Scope *S);
12939   void CodeCompleteNamespaceDecl(Scope *S);
12940   void CodeCompleteNamespaceAliasDecl(Scope *S);
12941   void CodeCompleteOperatorName(Scope *S);
12942   void CodeCompleteConstructorInitializer(
12943                                 Decl *Constructor,
12944                                 ArrayRef<CXXCtorInitializer *> Initializers);
12945 
12946   void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
12947                                     bool AfterAmpersand);
12948   void CodeCompleteAfterFunctionEquals(Declarator &D);
12949 
12950   void CodeCompleteObjCAtDirective(Scope *S);
12951   void CodeCompleteObjCAtVisibility(Scope *S);
12952   void CodeCompleteObjCAtStatement(Scope *S);
12953   void CodeCompleteObjCAtExpression(Scope *S);
12954   void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
12955   void CodeCompleteObjCPropertyGetter(Scope *S);
12956   void CodeCompleteObjCPropertySetter(Scope *S);
12957   void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
12958                                    bool IsParameter);
12959   void CodeCompleteObjCMessageReceiver(Scope *S);
12960   void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
12961                                     ArrayRef<IdentifierInfo *> SelIdents,
12962                                     bool AtArgumentExpression);
12963   void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
12964                                     ArrayRef<IdentifierInfo *> SelIdents,
12965                                     bool AtArgumentExpression,
12966                                     bool IsSuper = false);
12967   void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
12968                                        ArrayRef<IdentifierInfo *> SelIdents,
12969                                        bool AtArgumentExpression,
12970                                        ObjCInterfaceDecl *Super = nullptr);
12971   void CodeCompleteObjCForCollection(Scope *S,
12972                                      DeclGroupPtrTy IterationVar);
12973   void CodeCompleteObjCSelector(Scope *S,
12974                                 ArrayRef<IdentifierInfo *> SelIdents);
12975   void CodeCompleteObjCProtocolReferences(
12976                                          ArrayRef<IdentifierLocPair> Protocols);
12977   void CodeCompleteObjCProtocolDecl(Scope *S);
12978   void CodeCompleteObjCInterfaceDecl(Scope *S);
12979   void CodeCompleteObjCSuperclass(Scope *S,
12980                                   IdentifierInfo *ClassName,
12981                                   SourceLocation ClassNameLoc);
12982   void CodeCompleteObjCImplementationDecl(Scope *S);
12983   void CodeCompleteObjCInterfaceCategory(Scope *S,
12984                                          IdentifierInfo *ClassName,
12985                                          SourceLocation ClassNameLoc);
12986   void CodeCompleteObjCImplementationCategory(Scope *S,
12987                                               IdentifierInfo *ClassName,
12988                                               SourceLocation ClassNameLoc);
12989   void CodeCompleteObjCPropertyDefinition(Scope *S);
12990   void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
12991                                               IdentifierInfo *PropertyName);
12992   void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod,
12993                                   ParsedType ReturnType);
12994   void CodeCompleteObjCMethodDeclSelector(Scope *S,
12995                                           bool IsInstanceMethod,
12996                                           bool AtParameterName,
12997                                           ParsedType ReturnType,
12998                                           ArrayRef<IdentifierInfo *> SelIdents);
12999   void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
13000                                             SourceLocation ClassNameLoc,
13001                                             bool IsBaseExprStatement);
13002   void CodeCompletePreprocessorDirective(bool InConditional);
13003   void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
13004   void CodeCompletePreprocessorMacroName(bool IsDefinition);
13005   void CodeCompletePreprocessorExpression();
13006   void CodeCompletePreprocessorMacroArgument(Scope *S,
13007                                              IdentifierInfo *Macro,
13008                                              MacroInfo *MacroInfo,
13009                                              unsigned Argument);
13010   void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled);
13011   void CodeCompleteNaturalLanguage();
13012   void CodeCompleteAvailabilityPlatformName();
13013   void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
13014                                    CodeCompletionTUInfo &CCTUInfo,
13015                   SmallVectorImpl<CodeCompletionResult> &Results);
13016   //@}
13017 
13018   //===--------------------------------------------------------------------===//
13019   // Extra semantic analysis beyond the C type system
13020 
13021 public:
13022   SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
13023                                                 unsigned ByteNo) const;
13024 
13025   enum FormatArgumentPassingKind {
13026     FAPK_Fixed,    // values to format are fixed (no C-style variadic arguments)
13027     FAPK_Variadic, // values to format are passed as variadic arguments
13028     FAPK_VAList,   // values to format are passed in a va_list
13029   };
13030 
13031   // Used to grab the relevant information from a FormatAttr and a
13032   // FunctionDeclaration.
13033   struct FormatStringInfo {
13034     unsigned FormatIdx;
13035     unsigned FirstDataArg;
13036     FormatArgumentPassingKind ArgPassingKind;
13037   };
13038 
13039   static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
13040                                   bool IsVariadic, FormatStringInfo *FSI);
13041 
13042 private:
13043   void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
13044                         const ArraySubscriptExpr *ASE = nullptr,
13045                         bool AllowOnePastEnd = true, bool IndexNegated = false);
13046   void CheckArrayAccess(const Expr *E);
13047 
13048   bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
13049                          const FunctionProtoType *Proto);
13050   bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
13051                            ArrayRef<const Expr *> Args);
13052   bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
13053                         const FunctionProtoType *Proto);
13054   bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
13055   void CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
13056                             ArrayRef<const Expr *> Args,
13057                             const FunctionProtoType *Proto, SourceLocation Loc);
13058 
13059   void checkAIXMemberAlignment(SourceLocation Loc, const Expr *Arg);
13060 
13061   void CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
13062                          StringRef ParamName, QualType ArgTy, QualType ParamTy);
13063 
13064   void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
13065                  const Expr *ThisArg, ArrayRef<const Expr *> Args,
13066                  bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
13067                  VariadicCallType CallType);
13068 
13069   bool CheckObjCString(Expr *Arg);
13070   ExprResult CheckOSLogFormatStringArg(Expr *Arg);
13071 
13072   ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
13073                                       unsigned BuiltinID, CallExpr *TheCall);
13074 
13075   bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
13076                                   CallExpr *TheCall);
13077 
13078   void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
13079 
13080   bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
13081                                     unsigned MaxWidth);
13082   bool CheckNeonBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
13083                                     CallExpr *TheCall);
13084   bool CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
13085   bool CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
13086   bool CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
13087                                    CallExpr *TheCall);
13088   bool CheckARMCoprocessorImmediate(const TargetInfo &TI, const Expr *CoprocArg,
13089                                     bool WantCDE);
13090   bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
13091                                    CallExpr *TheCall);
13092 
13093   bool CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
13094                                        CallExpr *TheCall);
13095   bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
13096   bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
13097   bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
13098   bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
13099                                     CallExpr *TheCall);
13100   bool CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
13101                            CallExpr *TheCall);
13102   bool CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
13103   bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
13104   bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
13105   bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
13106   bool CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall);
13107   bool CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
13108                                          ArrayRef<int> ArgNums);
13109   bool CheckX86BuiltinTileDuplicate(CallExpr *TheCall, ArrayRef<int> ArgNums);
13110   bool CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
13111                                             ArrayRef<int> ArgNums);
13112   bool CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
13113                                    CallExpr *TheCall);
13114   bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
13115                                    CallExpr *TheCall);
13116   bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
13117   bool CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum);
13118   bool CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
13119                                      CallExpr *TheCall);
13120 
13121   bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
13122   bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call);
13123   bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
13124   bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
13125   bool SemaBuiltinComplex(CallExpr *TheCall);
13126   bool SemaBuiltinVSX(CallExpr *TheCall);
13127   bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
13128   bool SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum);
13129 
13130 public:
13131   // Used by C++ template instantiation.
13132   ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
13133   ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
13134                                    SourceLocation BuiltinLoc,
13135                                    SourceLocation RParenLoc);
13136 
13137 private:
13138   bool SemaBuiltinPrefetch(CallExpr *TheCall);
13139   bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
13140   bool SemaBuiltinArithmeticFence(CallExpr *TheCall);
13141   bool SemaBuiltinAssume(CallExpr *TheCall);
13142   bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
13143   bool SemaBuiltinLongjmp(CallExpr *TheCall);
13144   bool SemaBuiltinSetjmp(CallExpr *TheCall);
13145   ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
13146   ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
13147   ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
13148                                      AtomicExpr::AtomicOp Op);
13149   ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
13150                                                     bool IsDelete);
13151   bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
13152                               llvm::APSInt &Result);
13153   bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low,
13154                                    int High, bool RangeIsError = true);
13155   bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
13156                                       unsigned Multiple);
13157   bool SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum);
13158   bool SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
13159                                          unsigned ArgBits);
13160   bool SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum,
13161                                                unsigned ArgBits);
13162   bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
13163                                 int ArgNum, unsigned ExpectedFieldNum,
13164                                 bool AllowName);
13165   bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall);
13166   bool SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID,
13167                              const char *TypeDesc);
13168 
13169   bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc);
13170 
13171   bool SemaBuiltinElementwiseMath(CallExpr *TheCall);
13172   bool PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall);
13173   bool PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall);
13174 
13175   // Matrix builtin handling.
13176   ExprResult SemaBuiltinMatrixTranspose(CallExpr *TheCall,
13177                                         ExprResult CallResult);
13178   ExprResult SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
13179                                               ExprResult CallResult);
13180   ExprResult SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
13181                                                ExprResult CallResult);
13182 
13183 public:
13184   enum FormatStringType {
13185     FST_Scanf,
13186     FST_Printf,
13187     FST_NSString,
13188     FST_Strftime,
13189     FST_Strfmon,
13190     FST_Kprintf,
13191     FST_FreeBSDKPrintf,
13192     FST_OSTrace,
13193     FST_OSLog,
13194     FST_Unknown
13195   };
13196   static FormatStringType GetFormatStringType(const FormatAttr *Format);
13197 
13198   bool FormatStringHasSArg(const StringLiteral *FExpr);
13199 
13200   static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
13201 
13202 private:
13203   bool CheckFormatArguments(const FormatAttr *Format,
13204                             ArrayRef<const Expr *> Args, bool IsCXXMember,
13205                             VariadicCallType CallType, SourceLocation Loc,
13206                             SourceRange Range,
13207                             llvm::SmallBitVector &CheckedVarArgs);
13208   bool CheckFormatArguments(ArrayRef<const Expr *> Args,
13209                             FormatArgumentPassingKind FAPK, unsigned format_idx,
13210                             unsigned firstDataArg, FormatStringType Type,
13211                             VariadicCallType CallType, SourceLocation Loc,
13212                             SourceRange range,
13213                             llvm::SmallBitVector &CheckedVarArgs);
13214 
13215   void CheckAbsoluteValueFunction(const CallExpr *Call,
13216                                   const FunctionDecl *FDecl);
13217 
13218   void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
13219 
13220   void CheckMemaccessArguments(const CallExpr *Call,
13221                                unsigned BId,
13222                                IdentifierInfo *FnName);
13223 
13224   void CheckStrlcpycatArguments(const CallExpr *Call,
13225                                 IdentifierInfo *FnName);
13226 
13227   void CheckStrncatArguments(const CallExpr *Call,
13228                              IdentifierInfo *FnName);
13229 
13230   void CheckFreeArguments(const CallExpr *E);
13231 
13232   void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
13233                           SourceLocation ReturnLoc,
13234                           bool isObjCMethod = false,
13235                           const AttrVec *Attrs = nullptr,
13236                           const FunctionDecl *FD = nullptr);
13237 
13238 public:
13239   void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS,
13240                             BinaryOperatorKind Opcode);
13241 
13242 private:
13243   void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
13244   void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
13245   void CheckForIntOverflow(Expr *E);
13246   void CheckUnsequencedOperations(const Expr *E);
13247 
13248   /// Perform semantic checks on a completed expression. This will either
13249   /// be a full-expression or a default argument expression.
13250   void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
13251                           bool IsConstexpr = false);
13252 
13253   void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
13254                                    Expr *Init);
13255 
13256   /// Check if there is a field shadowing.
13257   void CheckShadowInheritedFields(const SourceLocation &Loc,
13258                                   DeclarationName FieldName,
13259                                   const CXXRecordDecl *RD,
13260                                   bool DeclIsField = true);
13261 
13262   /// Check if the given expression contains 'break' or 'continue'
13263   /// statement that produces control flow different from GCC.
13264   void CheckBreakContinueBinding(Expr *E);
13265 
13266   /// Check whether receiver is mutable ObjC container which
13267   /// attempts to add itself into the container
13268   void CheckObjCCircularContainer(ObjCMessageExpr *Message);
13269 
13270   void CheckTCBEnforcement(const SourceLocation CallExprLoc,
13271                            const NamedDecl *Callee);
13272 
13273   void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
13274   void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
13275                                  bool DeleteWasArrayForm);
13276 public:
13277   /// Register a magic integral constant to be used as a type tag.
13278   void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
13279                                   uint64_t MagicValue, QualType Type,
13280                                   bool LayoutCompatible, bool MustBeNull);
13281 
13282   struct TypeTagData {
13283     TypeTagData() {}
13284 
13285     TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
13286         Type(Type), LayoutCompatible(LayoutCompatible),
13287         MustBeNull(MustBeNull)
13288     {}
13289 
13290     QualType Type;
13291 
13292     /// If true, \c Type should be compared with other expression's types for
13293     /// layout-compatibility.
13294     unsigned LayoutCompatible : 1;
13295     unsigned MustBeNull : 1;
13296   };
13297 
13298   /// A pair of ArgumentKind identifier and magic value.  This uniquely
13299   /// identifies the magic value.
13300   typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
13301 
13302 private:
13303   /// A map from magic value to type information.
13304   std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
13305       TypeTagForDatatypeMagicValues;
13306 
13307   /// Peform checks on a call of a function with argument_with_type_tag
13308   /// or pointer_with_type_tag attributes.
13309   void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
13310                                 const ArrayRef<const Expr *> ExprArgs,
13311                                 SourceLocation CallSiteLoc);
13312 
13313   /// Check if we are taking the address of a packed field
13314   /// as this may be a problem if the pointer value is dereferenced.
13315   void CheckAddressOfPackedMember(Expr *rhs);
13316 
13317   /// The parser's current scope.
13318   ///
13319   /// The parser maintains this state here.
13320   Scope *CurScope;
13321 
13322   mutable IdentifierInfo *Ident_super;
13323   mutable IdentifierInfo *Ident___float128;
13324 
13325   /// Nullability type specifiers.
13326   IdentifierInfo *Ident__Nonnull = nullptr;
13327   IdentifierInfo *Ident__Nullable = nullptr;
13328   IdentifierInfo *Ident__Nullable_result = nullptr;
13329   IdentifierInfo *Ident__Null_unspecified = nullptr;
13330 
13331   IdentifierInfo *Ident_NSError = nullptr;
13332 
13333   /// The handler for the FileChanged preprocessor events.
13334   ///
13335   /// Used for diagnostics that implement custom semantic analysis for #include
13336   /// directives, like -Wpragma-pack.
13337   sema::SemaPPCallbacks *SemaPPCallbackHandler;
13338 
13339 protected:
13340   friend class Parser;
13341   friend class InitializationSequence;
13342   friend class ASTReader;
13343   friend class ASTDeclReader;
13344   friend class ASTWriter;
13345 
13346 public:
13347   /// Retrieve the keyword associated
13348   IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
13349 
13350   /// The struct behind the CFErrorRef pointer.
13351   RecordDecl *CFError = nullptr;
13352   bool isCFError(RecordDecl *D);
13353 
13354   /// Retrieve the identifier "NSError".
13355   IdentifierInfo *getNSErrorIdent();
13356 
13357   /// Retrieve the parser's current scope.
13358   ///
13359   /// This routine must only be used when it is certain that semantic analysis
13360   /// and the parser are in precisely the same context, which is not the case
13361   /// when, e.g., we are performing any kind of template instantiation.
13362   /// Therefore, the only safe places to use this scope are in the parser
13363   /// itself and in routines directly invoked from the parser and *never* from
13364   /// template substitution or instantiation.
13365   Scope *getCurScope() const { return CurScope; }
13366 
13367   void incrementMSManglingNumber() const {
13368     return CurScope->incrementMSManglingNumber();
13369   }
13370 
13371   IdentifierInfo *getSuperIdentifier() const;
13372   IdentifierInfo *getFloat128Identifier() const;
13373 
13374   ObjCContainerDecl *getObjCDeclContext() const;
13375 
13376   DeclContext *getCurLexicalContext() const {
13377     return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
13378   }
13379 
13380   const DeclContext *getCurObjCLexicalContext() const {
13381     const DeclContext *DC = getCurLexicalContext();
13382     // A category implicitly has the attribute of the interface.
13383     if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
13384       DC = CatD->getClassInterface();
13385     return DC;
13386   }
13387 
13388   /// Determine the number of levels of enclosing template parameters. This is
13389   /// only usable while parsing. Note that this does not include dependent
13390   /// contexts in which no template parameters have yet been declared, such as
13391   /// in a terse function template or generic lambda before the first 'auto' is
13392   /// encountered.
13393   unsigned getTemplateDepth(Scope *S) const;
13394 
13395   /// To be used for checking whether the arguments being passed to
13396   /// function exceeds the number of parameters expected for it.
13397   static bool TooManyArguments(size_t NumParams, size_t NumArgs,
13398                                bool PartialOverloading = false) {
13399     // We check whether we're just after a comma in code-completion.
13400     if (NumArgs > 0 && PartialOverloading)
13401       return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
13402     return NumArgs > NumParams;
13403   }
13404 
13405   // Emitting members of dllexported classes is delayed until the class
13406   // (including field initializers) is fully parsed.
13407   SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
13408   SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions;
13409 
13410 private:
13411   int ParsingClassDepth = 0;
13412 
13413   class SavePendingParsedClassStateRAII {
13414   public:
13415     SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
13416 
13417     ~SavePendingParsedClassStateRAII() {
13418       assert(S.DelayedOverridingExceptionSpecChecks.empty() &&
13419              "there shouldn't be any pending delayed exception spec checks");
13420       assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&
13421              "there shouldn't be any pending delayed exception spec checks");
13422       swapSavedState();
13423     }
13424 
13425   private:
13426     Sema &S;
13427     decltype(DelayedOverridingExceptionSpecChecks)
13428         SavedOverridingExceptionSpecChecks;
13429     decltype(DelayedEquivalentExceptionSpecChecks)
13430         SavedEquivalentExceptionSpecChecks;
13431 
13432     void swapSavedState() {
13433       SavedOverridingExceptionSpecChecks.swap(
13434           S.DelayedOverridingExceptionSpecChecks);
13435       SavedEquivalentExceptionSpecChecks.swap(
13436           S.DelayedEquivalentExceptionSpecChecks);
13437     }
13438   };
13439 
13440   /// Helper class that collects misaligned member designations and
13441   /// their location info for delayed diagnostics.
13442   struct MisalignedMember {
13443     Expr *E;
13444     RecordDecl *RD;
13445     ValueDecl *MD;
13446     CharUnits Alignment;
13447 
13448     MisalignedMember() : E(), RD(), MD() {}
13449     MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
13450                      CharUnits Alignment)
13451         : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
13452     explicit MisalignedMember(Expr *E)
13453         : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
13454 
13455     bool operator==(const MisalignedMember &m) { return this->E == m.E; }
13456   };
13457   /// Small set of gathered accesses to potentially misaligned members
13458   /// due to the packed attribute.
13459   SmallVector<MisalignedMember, 4> MisalignedMembers;
13460 
13461   /// Adds an expression to the set of gathered misaligned members.
13462   void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
13463                                      CharUnits Alignment);
13464 
13465 public:
13466   /// Diagnoses the current set of gathered accesses. This typically
13467   /// happens at full expression level. The set is cleared after emitting the
13468   /// diagnostics.
13469   void DiagnoseMisalignedMembers();
13470 
13471   /// This function checks if the expression is in the sef of potentially
13472   /// misaligned members and it is converted to some pointer type T with lower
13473   /// or equal alignment requirements. If so it removes it. This is used when
13474   /// we do not want to diagnose such misaligned access (e.g. in conversions to
13475   /// void*).
13476   void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
13477 
13478   /// This function calls Action when it determines that E designates a
13479   /// misaligned member due to the packed attribute. This is used to emit
13480   /// local diagnostics like in reference binding.
13481   void RefersToMemberWithReducedAlignment(
13482       Expr *E,
13483       llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
13484           Action);
13485 
13486   /// Describes the reason a calling convention specification was ignored, used
13487   /// for diagnostics.
13488   enum class CallingConventionIgnoredReason {
13489     ForThisTarget = 0,
13490     VariadicFunction,
13491     ConstructorDestructor,
13492     BuiltinFunction
13493   };
13494   /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
13495   /// context is "used as device code".
13496   ///
13497   /// - If CurLexicalContext is a kernel function or it is known that the
13498   ///   function will be emitted for the device, emits the diagnostics
13499   ///   immediately.
13500   /// - If CurLexicalContext is a function and we are compiling
13501   ///   for the device, but we don't know that this function will be codegen'ed
13502   ///   for devive yet, creates a diagnostic which is emitted if and when we
13503   ///   realize that the function will be codegen'ed.
13504   ///
13505   /// Example usage:
13506   ///
13507   /// Diagnose __float128 type usage only from SYCL device code if the current
13508   /// target doesn't support it
13509   /// if (!S.Context.getTargetInfo().hasFloat128Type() &&
13510   ///     S.getLangOpts().SYCLIsDevice)
13511   ///   SYCLDiagIfDeviceCode(Loc, diag::err_type_unsupported) << "__float128";
13512   SemaDiagnosticBuilder SYCLDiagIfDeviceCode(SourceLocation Loc,
13513                                              unsigned DiagID);
13514 
13515   /// Check whether we're allowed to call Callee from the current context.
13516   ///
13517   /// - If the call is never allowed in a semantically-correct program
13518   ///   emits an error and returns false.
13519   ///
13520   /// - If the call is allowed in semantically-correct programs, but only if
13521   ///   it's never codegen'ed, creates a deferred diagnostic to be emitted if
13522   ///   and when the caller is codegen'ed, and returns true.
13523   ///
13524   /// - Otherwise, returns true without emitting any diagnostics.
13525   ///
13526   /// Adds Callee to DeviceCallGraph if we don't know if its caller will be
13527   /// codegen'ed yet.
13528   bool checkSYCLDeviceFunction(SourceLocation Loc, FunctionDecl *Callee);
13529   void deepTypeCheckForSYCLDevice(SourceLocation UsedAt,
13530                                   llvm::DenseSet<QualType> Visited,
13531                                   ValueDecl *DeclToCheck);
13532 };
13533 
13534 /// RAII object that enters a new expression evaluation context.
13535 class EnterExpressionEvaluationContext {
13536   Sema &Actions;
13537   bool Entered = true;
13538 
13539 public:
13540   EnterExpressionEvaluationContext(
13541       Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
13542       Decl *LambdaContextDecl = nullptr,
13543       Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
13544           Sema::ExpressionEvaluationContextRecord::EK_Other,
13545       bool ShouldEnter = true)
13546       : Actions(Actions), Entered(ShouldEnter) {
13547     if (Entered)
13548       Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
13549                                               ExprContext);
13550   }
13551   EnterExpressionEvaluationContext(
13552       Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
13553       Sema::ReuseLambdaContextDecl_t,
13554       Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
13555           Sema::ExpressionEvaluationContextRecord::EK_Other)
13556       : Actions(Actions) {
13557     Actions.PushExpressionEvaluationContext(
13558         NewContext, Sema::ReuseLambdaContextDecl, ExprContext);
13559   }
13560 
13561   enum InitListTag { InitList };
13562   EnterExpressionEvaluationContext(Sema &Actions, InitListTag,
13563                                    bool ShouldEnter = true)
13564       : Actions(Actions), Entered(false) {
13565     // In C++11 onwards, narrowing checks are performed on the contents of
13566     // braced-init-lists, even when they occur within unevaluated operands.
13567     // Therefore we still need to instantiate constexpr functions used in such
13568     // a context.
13569     if (ShouldEnter && Actions.isUnevaluatedContext() &&
13570         Actions.getLangOpts().CPlusPlus11) {
13571       Actions.PushExpressionEvaluationContext(
13572           Sema::ExpressionEvaluationContext::UnevaluatedList);
13573       Entered = true;
13574     }
13575   }
13576 
13577   ~EnterExpressionEvaluationContext() {
13578     if (Entered)
13579       Actions.PopExpressionEvaluationContext();
13580   }
13581 };
13582 
13583 DeductionFailureInfo
13584 MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
13585                          sema::TemplateDeductionInfo &Info);
13586 
13587 /// Contains a late templated function.
13588 /// Will be parsed at the end of the translation unit, used by Sema & Parser.
13589 struct LateParsedTemplate {
13590   CachedTokens Toks;
13591   /// The template function declaration to be late parsed.
13592   Decl *D;
13593 };
13594 
13595 template <>
13596 void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation,
13597                                                  PragmaMsStackAction Action,
13598                                                  llvm::StringRef StackSlotLabel,
13599                                                  AlignPackInfo Value);
13600 
13601 std::unique_ptr<sema::RISCVIntrinsicManager>
13602 CreateRISCVIntrinsicManager(Sema &S);
13603 } // end namespace clang
13604 
13605 namespace llvm {
13606 // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
13607 // SourceLocation.
13608 template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
13609   using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
13610   using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
13611 
13612   static FunctionDeclAndLoc getEmptyKey() {
13613     return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
13614   }
13615 
13616   static FunctionDeclAndLoc getTombstoneKey() {
13617     return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
13618   }
13619 
13620   static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
13621     return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
13622                         FDL.Loc.getHashValue());
13623   }
13624 
13625   static bool isEqual(const FunctionDeclAndLoc &LHS,
13626                       const FunctionDeclAndLoc &RHS) {
13627     return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
13628   }
13629 };
13630 } // namespace llvm
13631 
13632 #endif
13633