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> struct DenseMapInfo;
78   template <typename ValueT, typename ValueInfoT> class DenseSet;
79   class SmallBitVector;
80   struct InlineAsmIdentifierInfo;
81 }
82 
83 namespace clang {
84   class ADLResult;
85   class ASTConsumer;
86   class ASTContext;
87   class ASTMutationListener;
88   class ASTReader;
89   class ASTWriter;
90   class ArrayType;
91   class ParsedAttr;
92   class BindingDecl;
93   class BlockDecl;
94   class CapturedDecl;
95   class CXXBasePath;
96   class CXXBasePaths;
97   class CXXBindTemporaryExpr;
98   typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
99   class CXXConstructorDecl;
100   class CXXConversionDecl;
101   class CXXDeleteExpr;
102   class CXXDestructorDecl;
103   class CXXFieldCollector;
104   class CXXMemberCallExpr;
105   class CXXMethodDecl;
106   class CXXScopeSpec;
107   class CXXTemporary;
108   class CXXTryStmt;
109   class CallExpr;
110   class ClassTemplateDecl;
111   class ClassTemplatePartialSpecializationDecl;
112   class ClassTemplateSpecializationDecl;
113   class VarTemplatePartialSpecializationDecl;
114   class CodeCompleteConsumer;
115   class CodeCompletionAllocator;
116   class CodeCompletionTUInfo;
117   class CodeCompletionResult;
118   class CoroutineBodyStmt;
119   class Decl;
120   class DeclAccessPair;
121   class DeclContext;
122   class DeclRefExpr;
123   class DeclaratorDecl;
124   class DeducedTemplateArgument;
125   class DependentDiagnostic;
126   class DesignatedInitExpr;
127   class Designation;
128   class EnableIfAttr;
129   class EnumConstantDecl;
130   class Expr;
131   class ExtVectorType;
132   class FormatAttr;
133   class FriendDecl;
134   class FunctionDecl;
135   class FunctionProtoType;
136   class FunctionTemplateDecl;
137   class ImplicitConversionSequence;
138   typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
139   class InitListExpr;
140   class InitializationKind;
141   class InitializationSequence;
142   class InitializedEntity;
143   class IntegerLiteral;
144   class LabelStmt;
145   class LambdaExpr;
146   class LangOptions;
147   class LocalInstantiationScope;
148   class LookupResult;
149   class MacroInfo;
150   typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
151   class ModuleLoader;
152   class MultiLevelTemplateArgumentList;
153   class NamedDecl;
154   class ObjCCategoryDecl;
155   class ObjCCategoryImplDecl;
156   class ObjCCompatibleAliasDecl;
157   class ObjCContainerDecl;
158   class ObjCImplDecl;
159   class ObjCImplementationDecl;
160   class ObjCInterfaceDecl;
161   class ObjCIvarDecl;
162   template <class T> class ObjCList;
163   class ObjCMessageExpr;
164   class ObjCMethodDecl;
165   class ObjCPropertyDecl;
166   class ObjCProtocolDecl;
167   class OMPThreadPrivateDecl;
168   class OMPRequiresDecl;
169   class OMPDeclareReductionDecl;
170   class OMPDeclareSimdDecl;
171   class OMPClause;
172   struct OMPVarListLocTy;
173   struct OverloadCandidate;
174   enum class OverloadCandidateParamOrder : char;
175   enum OverloadCandidateRewriteKind : unsigned;
176   class OverloadCandidateSet;
177   class OverloadExpr;
178   class ParenListExpr;
179   class ParmVarDecl;
180   class Preprocessor;
181   class PseudoDestructorTypeStorage;
182   class PseudoObjectExpr;
183   class QualType;
184   class StandardConversionSequence;
185   class Stmt;
186   class StringLiteral;
187   class SwitchStmt;
188   class TemplateArgument;
189   class TemplateArgumentList;
190   class TemplateArgumentLoc;
191   class TemplateDecl;
192   class TemplateInstantiationCallback;
193   class TemplateParameterList;
194   class TemplatePartialOrderingContext;
195   class TemplateTemplateParmDecl;
196   class Token;
197   class TypeAliasDecl;
198   class TypedefDecl;
199   class TypedefNameDecl;
200   class TypeLoc;
201   class TypoCorrectionConsumer;
202   class UnqualifiedId;
203   class UnresolvedLookupExpr;
204   class UnresolvedMemberExpr;
205   class UnresolvedSetImpl;
206   class UnresolvedSetIterator;
207   class UsingDecl;
208   class UsingShadowDecl;
209   class ValueDecl;
210   class VarDecl;
211   class VarTemplateSpecializationDecl;
212   class VisibilityAttr;
213   class VisibleDeclConsumer;
214   class IndirectFieldDecl;
215   struct DeductionFailureInfo;
216   class TemplateSpecCandidateSet;
217 
218 namespace sema {
219   class AccessedEntity;
220   class BlockScopeInfo;
221   class Capture;
222   class CapturedRegionScopeInfo;
223   class CapturingScopeInfo;
224   class CompoundScopeInfo;
225   class DelayedDiagnostic;
226   class DelayedDiagnosticPool;
227   class FunctionScopeInfo;
228   class LambdaScopeInfo;
229   class PossiblyUnreachableDiag;
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:
PreferredTypeBuilder(bool Enabled)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).
get(SourceLocation Tok)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   bool isVisibleSlow(const NamedDecl *D);
368 
369   /// Determine whether two declarations should be linked together, given that
370   /// the old declaration might not be visible and the new declaration might
371   /// not have external linkage.
shouldLinkPossiblyHiddenDecl(const NamedDecl * Old,const NamedDecl * New)372   bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
373                                     const NamedDecl *New) {
374     if (isVisible(Old))
375      return true;
376     // See comment in below overload for why it's safe to compute the linkage
377     // of the new declaration here.
378     if (New->isExternallyDeclarable()) {
379       assert(Old->isExternallyDeclarable() &&
380              "should not have found a non-externally-declarable previous decl");
381       return true;
382     }
383     return false;
384   }
385   bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
386 
387   void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
388                                       QualType ResultTy,
389                                       ArrayRef<QualType> Args);
390 
391 public:
392   /// The maximum alignment, same as in llvm::Value. We duplicate them here
393   /// because that allows us not to duplicate the constants in clang code,
394   /// which we must to since we can't directly use the llvm constants.
395   /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
396   ///
397   /// This is the greatest alignment value supported by load, store, and alloca
398   /// instructions, and global values.
399   static const unsigned MaxAlignmentExponent = 32;
400   static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent;
401 
402   typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
403   typedef OpaquePtr<TemplateName> TemplateTy;
404   typedef OpaquePtr<QualType> TypeTy;
405 
406   OpenCLOptions OpenCLFeatures;
407   FPOptions CurFPFeatures;
408 
409   const LangOptions &LangOpts;
410   Preprocessor &PP;
411   ASTContext &Context;
412   ASTConsumer &Consumer;
413   DiagnosticsEngine &Diags;
414   SourceManager &SourceMgr;
415 
416   /// Flag indicating whether or not to collect detailed statistics.
417   bool CollectStats;
418 
419   /// Code-completion consumer.
420   CodeCompleteConsumer *CodeCompleter;
421 
422   /// CurContext - This is the current declaration context of parsing.
423   DeclContext *CurContext;
424 
425   /// Generally null except when we temporarily switch decl contexts,
426   /// like in \see ActOnObjCTemporaryExitContainerContext.
427   DeclContext *OriginalLexicalContext;
428 
429   /// VAListTagName - The declaration name corresponding to __va_list_tag.
430   /// This is used as part of a hack to omit that class from ADL results.
431   DeclarationName VAListTagName;
432 
433   bool MSStructPragmaOn; // True when \#pragma ms_struct on
434 
435   /// Controls member pointer representation format under the MS ABI.
436   LangOptions::PragmaMSPointersToMembersKind
437       MSPointerToMemberRepresentationMethod;
438 
439   /// Stack of active SEH __finally scopes.  Can be empty.
440   SmallVector<Scope*, 2> CurrentSEHFinally;
441 
442   /// Source location for newly created implicit MSInheritanceAttrs
443   SourceLocation ImplicitMSInheritanceAttrLoc;
444 
445   /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
446   /// `TransformTypos` in order to keep track of any TypoExprs that are created
447   /// recursively during typo correction and wipe them away if the correction
448   /// fails.
449   llvm::SmallVector<TypoExpr *, 2> TypoExprs;
450 
451   /// pragma clang section kind
452   enum PragmaClangSectionKind {
453     PCSK_Invalid      = 0,
454     PCSK_BSS          = 1,
455     PCSK_Data         = 2,
456     PCSK_Rodata       = 3,
457     PCSK_Text         = 4,
458     PCSK_Relro        = 5
459    };
460 
461   enum PragmaClangSectionAction {
462     PCSA_Set     = 0,
463     PCSA_Clear   = 1
464   };
465 
466   struct PragmaClangSection {
467     std::string SectionName;
468     bool Valid = false;
469     SourceLocation PragmaLocation;
470   };
471 
472    PragmaClangSection PragmaClangBSSSection;
473    PragmaClangSection PragmaClangDataSection;
474    PragmaClangSection PragmaClangRodataSection;
475    PragmaClangSection PragmaClangRelroSection;
476    PragmaClangSection PragmaClangTextSection;
477 
478   enum PragmaMsStackAction {
479     PSK_Reset     = 0x0,                // #pragma ()
480     PSK_Set       = 0x1,                // #pragma (value)
481     PSK_Push      = 0x2,                // #pragma (push[, id])
482     PSK_Pop       = 0x4,                // #pragma (pop[, id])
483     PSK_Show      = 0x8,                // #pragma (show) -- only for "pack"!
484     PSK_Push_Set  = PSK_Push | PSK_Set, // #pragma (push[, id], value)
485     PSK_Pop_Set   = PSK_Pop | PSK_Set,  // #pragma (pop[, id], value)
486   };
487 
488   // #pragma pack and align.
489   class AlignPackInfo {
490   public:
491     // `Native` represents default align mode, which may vary based on the
492     // platform.
493     enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
494 
495     // #pragma pack info constructor
AlignPackInfo(AlignPackInfo::Mode M,unsigned Num,bool IsXL)496     AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
497         : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
498       assert(Num == PackNumber && "The pack number has been truncated.");
499     }
500 
501     // #pragma align info constructor
AlignPackInfo(AlignPackInfo::Mode M,bool IsXL)502     AlignPackInfo(AlignPackInfo::Mode M, bool IsXL)
503         : PackAttr(false), AlignMode(M),
504           PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
505 
AlignPackInfo(bool IsXL)506     explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
507 
AlignPackInfo()508     AlignPackInfo() : AlignPackInfo(Native, false) {}
509 
510     // When a AlignPackInfo itself cannot be used, this returns an 32-bit
511     // integer encoding for it. This should only be passed to
512     // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
getRawEncoding(const AlignPackInfo & Info)513     static uint32_t getRawEncoding(const AlignPackInfo &Info) {
514       std::uint32_t Encoding{};
515       if (Info.IsXLStack())
516         Encoding |= IsXLMask;
517 
518       Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
519 
520       if (Info.IsPackAttr())
521         Encoding |= PackAttrMask;
522 
523       Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
524 
525       return Encoding;
526     }
527 
getFromRawEncoding(unsigned Encoding)528     static AlignPackInfo getFromRawEncoding(unsigned Encoding) {
529       bool IsXL = static_cast<bool>(Encoding & IsXLMask);
530       AlignPackInfo::Mode M =
531           static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
532       int PackNumber = (Encoding & PackNumMask) >> 4;
533 
534       if (Encoding & PackAttrMask)
535         return AlignPackInfo(M, PackNumber, IsXL);
536 
537       return AlignPackInfo(M, IsXL);
538     }
539 
IsPackAttr()540     bool IsPackAttr() const { return PackAttr; }
541 
IsAlignAttr()542     bool IsAlignAttr() const { return !PackAttr; }
543 
getAlignMode()544     Mode getAlignMode() const { return AlignMode; }
545 
getPackNumber()546     unsigned getPackNumber() const { return PackNumber; }
547 
IsPackSet()548     bool IsPackSet() const {
549       // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
550       // attriute on a decl.
551       return PackNumber != UninitPackVal && PackNumber != 0;
552     }
553 
IsXLStack()554     bool IsXLStack() const { return XLStack; }
555 
556     bool operator==(const AlignPackInfo &Info) const {
557       return std::tie(AlignMode, PackNumber, PackAttr, XLStack) ==
558              std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr,
559                       Info.XLStack);
560     }
561 
562     bool operator!=(const AlignPackInfo &Info) const {
563       return !(*this == Info);
564     }
565 
566   private:
567     /// \brief True if this is a pragma pack attribute,
568     ///         not a pragma align attribute.
569     bool PackAttr;
570 
571     /// \brief The alignment mode that is in effect.
572     Mode AlignMode;
573 
574     /// \brief The pack number of the stack.
575     unsigned char PackNumber;
576 
577     /// \brief True if it is a XL #pragma align/pack stack.
578     bool XLStack;
579 
580     /// \brief Uninitialized pack value.
581     static constexpr unsigned char UninitPackVal = -1;
582 
583     // Masks to encode and decode an AlignPackInfo.
584     static constexpr uint32_t IsXLMask{0x0000'0001};
585     static constexpr uint32_t AlignModeMask{0x0000'0006};
586     static constexpr uint32_t PackAttrMask{0x00000'0008};
587     static constexpr uint32_t PackNumMask{0x0000'01F0};
588   };
589 
590   template<typename ValueType>
591   struct PragmaStack {
592     struct Slot {
593       llvm::StringRef StackSlotLabel;
594       ValueType Value;
595       SourceLocation PragmaLocation;
596       SourceLocation PragmaPushLocation;
SlotPragmaStack::Slot597       Slot(llvm::StringRef StackSlotLabel, ValueType Value,
598            SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
599           : StackSlotLabel(StackSlotLabel), Value(Value),
600             PragmaLocation(PragmaLocation),
601             PragmaPushLocation(PragmaPushLocation) {}
602     };
603 
ActPragmaStack604     void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
605              llvm::StringRef StackSlotLabel, ValueType Value) {
606       if (Action == PSK_Reset) {
607         CurrentValue = DefaultValue;
608         CurrentPragmaLocation = PragmaLocation;
609         return;
610       }
611       if (Action & PSK_Push)
612         Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
613                            PragmaLocation);
614       else if (Action & PSK_Pop) {
615         if (!StackSlotLabel.empty()) {
616           // If we've got a label, try to find it and jump there.
617           auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
618             return x.StackSlotLabel == StackSlotLabel;
619           });
620           // If we found the label so pop from there.
621           if (I != Stack.rend()) {
622             CurrentValue = I->Value;
623             CurrentPragmaLocation = I->PragmaLocation;
624             Stack.erase(std::prev(I.base()), Stack.end());
625           }
626         } else if (!Stack.empty()) {
627           // We do not have a label, just pop the last entry.
628           CurrentValue = Stack.back().Value;
629           CurrentPragmaLocation = Stack.back().PragmaLocation;
630           Stack.pop_back();
631         }
632       }
633       if (Action & PSK_Set) {
634         CurrentValue = Value;
635         CurrentPragmaLocation = PragmaLocation;
636       }
637     }
638 
639     // MSVC seems to add artificial slots to #pragma stacks on entering a C++
640     // method body to restore the stacks on exit, so it works like this:
641     //
642     //   struct S {
643     //     #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
644     //     void Method {}
645     //     #pragma <name>(pop, InternalPragmaSlot)
646     //   };
647     //
648     // It works even with #pragma vtordisp, although MSVC doesn't support
649     //   #pragma vtordisp(push [, id], n)
650     // syntax.
651     //
652     // Push / pop a named sentinel slot.
SentinelActionPragmaStack653     void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
654       assert((Action == PSK_Push || Action == PSK_Pop) &&
655              "Can only push / pop #pragma stack sentinels!");
656       Act(CurrentPragmaLocation, Action, Label, CurrentValue);
657     }
658 
659     // Constructors.
PragmaStackPragmaStack660     explicit PragmaStack(const ValueType &Default)
661         : DefaultValue(Default), CurrentValue(Default) {}
662 
hasValuePragmaStack663     bool hasValue() const { return CurrentValue != DefaultValue; }
664 
665     SmallVector<Slot, 2> Stack;
666     ValueType DefaultValue; // Value used for PSK_Reset action.
667     ValueType CurrentValue;
668     SourceLocation CurrentPragmaLocation;
669   };
670   // FIXME: We should serialize / deserialize these if they occur in a PCH (but
671   // we shouldn't do so if they're in a module).
672 
673   /// Whether to insert vtordisps prior to virtual bases in the Microsoft
674   /// C++ ABI.  Possible values are 0, 1, and 2, which mean:
675   ///
676   /// 0: Suppress all vtordisps
677   /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
678   ///    structors
679   /// 2: Always insert vtordisps to support RTTI on partially constructed
680   ///    objects
681   PragmaStack<MSVtorDispMode> VtorDispStack;
682   PragmaStack<AlignPackInfo> AlignPackStack;
683   // The current #pragma align/pack values and locations at each #include.
684   struct AlignPackIncludeState {
685     AlignPackInfo CurrentValue;
686     SourceLocation CurrentPragmaLocation;
687     bool HasNonDefaultValue, ShouldWarnOnInclude;
688   };
689   SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack;
690   // Segment #pragmas.
691   PragmaStack<StringLiteral *> DataSegStack;
692   PragmaStack<StringLiteral *> BSSSegStack;
693   PragmaStack<StringLiteral *> ConstSegStack;
694   PragmaStack<StringLiteral *> CodeSegStack;
695 
696   // This stack tracks the current state of Sema.CurFPFeatures.
697   PragmaStack<FPOptionsOverride> FpPragmaStack;
CurFPFeatureOverrides()698   FPOptionsOverride CurFPFeatureOverrides() {
699     FPOptionsOverride result;
700     if (!FpPragmaStack.hasValue()) {
701       result = FPOptionsOverride();
702     } else {
703       result = FpPragmaStack.CurrentValue;
704     }
705     return result;
706   }
707 
708   // RAII object to push / pop sentinel slots for all MS #pragma stacks.
709   // Actions should be performed only if we enter / exit a C++ method body.
710   class PragmaStackSentinelRAII {
711   public:
712     PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
713     ~PragmaStackSentinelRAII();
714 
715   private:
716     Sema &S;
717     StringRef SlotLabel;
718     bool ShouldAct;
719   };
720 
721   /// A mapping that describes the nullability we've seen in each header file.
722   FileNullabilityMap NullabilityMap;
723 
724   /// Last section used with #pragma init_seg.
725   StringLiteral *CurInitSeg;
726   SourceLocation CurInitSegLoc;
727 
728   /// VisContext - Manages the stack for \#pragma GCC visibility.
729   void *VisContext; // Really a "PragmaVisStack*"
730 
731   /// This an attribute introduced by \#pragma clang attribute.
732   struct PragmaAttributeEntry {
733     SourceLocation Loc;
734     ParsedAttr *Attribute;
735     SmallVector<attr::SubjectMatchRule, 4> MatchRules;
736     bool IsUsed;
737   };
738 
739   /// A push'd group of PragmaAttributeEntries.
740   struct PragmaAttributeGroup {
741     /// The location of the push attribute.
742     SourceLocation Loc;
743     /// The namespace of this push group.
744     const IdentifierInfo *Namespace;
745     SmallVector<PragmaAttributeEntry, 2> Entries;
746   };
747 
748   SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
749 
750   /// The declaration that is currently receiving an attribute from the
751   /// #pragma attribute stack.
752   const Decl *PragmaAttributeCurrentTargetDecl;
753 
754   /// This represents the last location of a "#pragma clang optimize off"
755   /// directive if such a directive has not been closed by an "on" yet. If
756   /// optimizations are currently "on", this is set to an invalid location.
757   SourceLocation OptimizeOffPragmaLocation;
758 
759   /// Flag indicating if Sema is building a recovery call expression.
760   ///
761   /// This flag is used to avoid building recovery call expressions
762   /// if Sema is already doing so, which would cause infinite recursions.
763   bool IsBuildingRecoveryCallExpr;
764 
765   /// Used to control the generation of ExprWithCleanups.
766   CleanupInfo Cleanup;
767 
768   /// ExprCleanupObjects - This is the stack of objects requiring
769   /// cleanup that are created by the current full expression.
770   SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects;
771 
772   /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
773   /// to a variable (constant) that may or may not be odr-used in this Expr, and
774   /// we won't know until all lvalue-to-rvalue and discarded value conversions
775   /// have been applied to all subexpressions of the enclosing full expression.
776   /// This is cleared at the end of each full expression.
777   using MaybeODRUseExprSet = llvm::SetVector<Expr *, SmallVector<Expr *, 4>,
778                                              llvm::SmallPtrSet<Expr *, 4>>;
779   MaybeODRUseExprSet MaybeODRUseExprs;
780 
781   std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
782 
783   /// Stack containing information about each of the nested
784   /// function, block, and method scopes that are currently active.
785   SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
786 
787   /// The index of the first FunctionScope that corresponds to the current
788   /// context.
789   unsigned FunctionScopesStart = 0;
790 
getFunctionScopes()791   ArrayRef<sema::FunctionScopeInfo*> getFunctionScopes() const {
792     return llvm::makeArrayRef(FunctionScopes.begin() + FunctionScopesStart,
793                               FunctionScopes.end());
794   }
795 
796   /// Stack containing information needed when in C++2a an 'auto' is encountered
797   /// in a function declaration parameter type specifier in order to invent a
798   /// corresponding template parameter in the enclosing abbreviated function
799   /// template. This information is also present in LambdaScopeInfo, stored in
800   /// the FunctionScopes stack.
801   SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos;
802 
803   /// The index of the first InventedParameterInfo that refers to the current
804   /// context.
805   unsigned InventedParameterInfosStart = 0;
806 
getInventedParameterInfos()807   ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const {
808     return llvm::makeArrayRef(InventedParameterInfos.begin() +
809                                   InventedParameterInfosStart,
810                               InventedParameterInfos.end());
811   }
812 
813   typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
814                      &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
815     ExtVectorDeclsType;
816 
817   /// ExtVectorDecls - This is a list all the extended vector types. This allows
818   /// us to associate a raw vector type with one of the ext_vector type names.
819   /// This is only necessary for issuing pretty diagnostics.
820   ExtVectorDeclsType ExtVectorDecls;
821 
822   /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
823   std::unique_ptr<CXXFieldCollector> FieldCollector;
824 
825   typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType;
826 
827   /// Set containing all declared private fields that are not used.
828   NamedDeclSetType UnusedPrivateFields;
829 
830   /// Set containing all typedefs that are likely unused.
831   llvm::SmallSetVector<const TypedefNameDecl *, 4>
832       UnusedLocalTypedefNameCandidates;
833 
834   /// Delete-expressions to be analyzed at the end of translation unit
835   ///
836   /// This list contains class members, and locations of delete-expressions
837   /// that could not be proven as to whether they mismatch with new-expression
838   /// used in initializer of the field.
839   typedef std::pair<SourceLocation, bool> DeleteExprLoc;
840   typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
841   llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
842 
843   typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
844 
845   /// PureVirtualClassDiagSet - a set of class declarations which we have
846   /// emitted a list of pure virtual functions. Used to prevent emitting the
847   /// same list more than once.
848   std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
849 
850   /// ParsingInitForAutoVars - a set of declarations with auto types for which
851   /// we are currently parsing the initializer.
852   llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
853 
854   /// Look for a locally scoped extern "C" declaration by the given name.
855   NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
856 
857   typedef LazyVector<VarDecl *, ExternalSemaSource,
858                      &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
859     TentativeDefinitionsType;
860 
861   /// All the tentative definitions encountered in the TU.
862   TentativeDefinitionsType TentativeDefinitions;
863 
864   /// All the external declarations encoutered and used in the TU.
865   SmallVector<VarDecl *, 4> ExternalDeclarations;
866 
867   typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
868                      &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
869     UnusedFileScopedDeclsType;
870 
871   /// The set of file scoped decls seen so far that have not been used
872   /// and must warn if not used. Only contains the first declaration.
873   UnusedFileScopedDeclsType UnusedFileScopedDecls;
874 
875   typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
876                      &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
877     DelegatingCtorDeclsType;
878 
879   /// All the delegating constructors seen so far in the file, used for
880   /// cycle detection at the end of the TU.
881   DelegatingCtorDeclsType DelegatingCtorDecls;
882 
883   /// All the overriding functions seen during a class definition
884   /// that had their exception spec checks delayed, plus the overridden
885   /// function.
886   SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
887     DelayedOverridingExceptionSpecChecks;
888 
889   /// All the function redeclarations seen during a class definition that had
890   /// their exception spec checks delayed, plus the prior declaration they
891   /// should be checked against. Except during error recovery, the new decl
892   /// should always be a friend declaration, as that's the only valid way to
893   /// redeclare a special member before its class is complete.
894   SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2>
895     DelayedEquivalentExceptionSpecChecks;
896 
897   typedef llvm::MapVector<const FunctionDecl *,
898                           std::unique_ptr<LateParsedTemplate>>
899       LateParsedTemplateMapT;
900   LateParsedTemplateMapT LateParsedTemplateMap;
901 
902   /// Callback to the parser to parse templated functions when needed.
903   typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
904   typedef void LateTemplateParserCleanupCB(void *P);
905   LateTemplateParserCB *LateTemplateParser;
906   LateTemplateParserCleanupCB *LateTemplateParserCleanup;
907   void *OpaqueParser;
908 
SetLateTemplateParser(LateTemplateParserCB * LTP,LateTemplateParserCleanupCB * LTPCleanup,void * P)909   void SetLateTemplateParser(LateTemplateParserCB *LTP,
910                              LateTemplateParserCleanupCB *LTPCleanup,
911                              void *P) {
912     LateTemplateParser = LTP;
913     LateTemplateParserCleanup = LTPCleanup;
914     OpaqueParser = P;
915   }
916 
917   class DelayedDiagnostics;
918 
919   class DelayedDiagnosticsState {
920     sema::DelayedDiagnosticPool *SavedPool;
921     friend class Sema::DelayedDiagnostics;
922   };
923   typedef DelayedDiagnosticsState ParsingDeclState;
924   typedef DelayedDiagnosticsState ProcessingContextState;
925 
926   /// A class which encapsulates the logic for delaying diagnostics
927   /// during parsing and other processing.
928   class DelayedDiagnostics {
929     /// The current pool of diagnostics into which delayed
930     /// diagnostics should go.
931     sema::DelayedDiagnosticPool *CurPool;
932 
933   public:
DelayedDiagnostics()934     DelayedDiagnostics() : CurPool(nullptr) {}
935 
936     /// Adds a delayed diagnostic.
937     void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
938 
939     /// Determines whether diagnostics should be delayed.
shouldDelayDiagnostics()940     bool shouldDelayDiagnostics() { return CurPool != nullptr; }
941 
942     /// Returns the current delayed-diagnostics pool.
getCurrentPool()943     sema::DelayedDiagnosticPool *getCurrentPool() const {
944       return CurPool;
945     }
946 
947     /// Enter a new scope.  Access and deprecation diagnostics will be
948     /// collected in this pool.
push(sema::DelayedDiagnosticPool & pool)949     DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
950       DelayedDiagnosticsState state;
951       state.SavedPool = CurPool;
952       CurPool = &pool;
953       return state;
954     }
955 
956     /// Leave a delayed-diagnostic state that was previously pushed.
957     /// Do not emit any of the diagnostics.  This is performed as part
958     /// of the bookkeeping of popping a pool "properly".
popWithoutEmitting(DelayedDiagnosticsState state)959     void popWithoutEmitting(DelayedDiagnosticsState state) {
960       CurPool = state.SavedPool;
961     }
962 
963     /// Enter a new scope where access and deprecation diagnostics are
964     /// not delayed.
pushUndelayed()965     DelayedDiagnosticsState pushUndelayed() {
966       DelayedDiagnosticsState state;
967       state.SavedPool = CurPool;
968       CurPool = nullptr;
969       return state;
970     }
971 
972     /// Undo a previous pushUndelayed().
popUndelayed(DelayedDiagnosticsState state)973     void popUndelayed(DelayedDiagnosticsState state) {
974       assert(CurPool == nullptr);
975       CurPool = state.SavedPool;
976     }
977   } DelayedDiagnostics;
978 
979   /// A RAII object to temporarily push a declaration context.
980   class ContextRAII {
981   private:
982     Sema &S;
983     DeclContext *SavedContext;
984     ProcessingContextState SavedContextState;
985     QualType SavedCXXThisTypeOverride;
986     unsigned SavedFunctionScopesStart;
987     unsigned SavedInventedParameterInfosStart;
988 
989   public:
990     ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
S(S)991       : S(S), SavedContext(S.CurContext),
992         SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
993         SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
994         SavedFunctionScopesStart(S.FunctionScopesStart),
995         SavedInventedParameterInfosStart(S.InventedParameterInfosStart)
996     {
997       assert(ContextToPush && "pushing null context");
998       S.CurContext = ContextToPush;
999       if (NewThisContext)
1000         S.CXXThisTypeOverride = QualType();
1001       // Any saved FunctionScopes do not refer to this context.
1002       S.FunctionScopesStart = S.FunctionScopes.size();
1003       S.InventedParameterInfosStart = S.InventedParameterInfos.size();
1004     }
1005 
pop()1006     void pop() {
1007       if (!SavedContext) return;
1008       S.CurContext = SavedContext;
1009       S.DelayedDiagnostics.popUndelayed(SavedContextState);
1010       S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
1011       S.FunctionScopesStart = SavedFunctionScopesStart;
1012       S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
1013       SavedContext = nullptr;
1014     }
1015 
~ContextRAII()1016     ~ContextRAII() {
1017       pop();
1018     }
1019   };
1020 
1021   /// Whether the AST is currently being rebuilt to correct immediate
1022   /// invocations. Immediate invocation candidates and references to consteval
1023   /// functions aren't tracked when this is set.
1024   bool RebuildingImmediateInvocation = false;
1025 
1026   /// Used to change context to isConstantEvaluated without pushing a heavy
1027   /// ExpressionEvaluationContextRecord object.
1028   bool isConstantEvaluatedOverride;
1029 
isConstantEvaluated()1030   bool isConstantEvaluated() {
1031     return ExprEvalContexts.back().isConstantEvaluated() ||
1032            isConstantEvaluatedOverride;
1033   }
1034 
1035   /// RAII object to handle the state changes required to synthesize
1036   /// a function body.
1037   class SynthesizedFunctionScope {
1038     Sema &S;
1039     Sema::ContextRAII SavedContext;
1040     bool PushedCodeSynthesisContext = false;
1041 
1042   public:
SynthesizedFunctionScope(Sema & S,DeclContext * DC)1043     SynthesizedFunctionScope(Sema &S, DeclContext *DC)
1044         : S(S), SavedContext(S, DC) {
1045       S.PushFunctionScope();
1046       S.PushExpressionEvaluationContext(
1047           Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
1048       if (auto *FD = dyn_cast<FunctionDecl>(DC))
1049         FD->setWillHaveBody(true);
1050       else
1051         assert(isa<ObjCMethodDecl>(DC));
1052     }
1053 
addContextNote(SourceLocation UseLoc)1054     void addContextNote(SourceLocation UseLoc) {
1055       assert(!PushedCodeSynthesisContext);
1056 
1057       Sema::CodeSynthesisContext Ctx;
1058       Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
1059       Ctx.PointOfInstantiation = UseLoc;
1060       Ctx.Entity = cast<Decl>(S.CurContext);
1061       S.pushCodeSynthesisContext(Ctx);
1062 
1063       PushedCodeSynthesisContext = true;
1064     }
1065 
~SynthesizedFunctionScope()1066     ~SynthesizedFunctionScope() {
1067       if (PushedCodeSynthesisContext)
1068         S.popCodeSynthesisContext();
1069       if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
1070         FD->setWillHaveBody(false);
1071       S.PopExpressionEvaluationContext();
1072       S.PopFunctionScopeInfo();
1073     }
1074   };
1075 
1076   /// WeakUndeclaredIdentifiers - Identifiers contained in
1077   /// \#pragma weak before declared. rare. may alias another
1078   /// identifier, declared or undeclared
1079   llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
1080 
1081   /// ExtnameUndeclaredIdentifiers - Identifiers contained in
1082   /// \#pragma redefine_extname before declared.  Used in Solaris system headers
1083   /// to define functions that occur in multiple standards to call the version
1084   /// in the currently selected standard.
1085   llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
1086 
1087 
1088   /// Load weak undeclared identifiers from the external source.
1089   void LoadExternalWeakUndeclaredIdentifiers();
1090 
1091   /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
1092   /// \#pragma weak during processing of other Decls.
1093   /// I couldn't figure out a clean way to generate these in-line, so
1094   /// we store them here and handle separately -- which is a hack.
1095   /// It would be best to refactor this.
1096   SmallVector<Decl*,2> WeakTopLevelDecl;
1097 
1098   IdentifierResolver IdResolver;
1099 
1100   /// Translation Unit Scope - useful to Objective-C actions that need
1101   /// to lookup file scope declarations in the "ordinary" C decl namespace.
1102   /// For example, user-defined classes, built-in "id" type, etc.
1103   Scope *TUScope;
1104 
1105   /// The C++ "std" namespace, where the standard library resides.
1106   LazyDeclPtr StdNamespace;
1107 
1108   /// The C++ "std::bad_alloc" class, which is defined by the C++
1109   /// standard library.
1110   LazyDeclPtr StdBadAlloc;
1111 
1112   /// The C++ "std::align_val_t" enum class, which is defined by the C++
1113   /// standard library.
1114   LazyDeclPtr StdAlignValT;
1115 
1116   /// The C++ "std::experimental" namespace, where the experimental parts
1117   /// of the standard library resides.
1118   NamespaceDecl *StdExperimentalNamespaceCache;
1119 
1120   /// The C++ "std::initializer_list" template, which is defined in
1121   /// \<initializer_list>.
1122   ClassTemplateDecl *StdInitializerList;
1123 
1124   /// The C++ "std::coroutine_traits" template, which is defined in
1125   /// \<coroutine_traits>
1126   ClassTemplateDecl *StdCoroutineTraitsCache;
1127 
1128   /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
1129   RecordDecl *CXXTypeInfoDecl;
1130 
1131   /// The MSVC "_GUID" struct, which is defined in MSVC header files.
1132   RecordDecl *MSVCGuidDecl;
1133 
1134   /// Caches identifiers/selectors for NSFoundation APIs.
1135   std::unique_ptr<NSAPI> NSAPIObj;
1136 
1137   /// The declaration of the Objective-C NSNumber class.
1138   ObjCInterfaceDecl *NSNumberDecl;
1139 
1140   /// The declaration of the Objective-C NSValue class.
1141   ObjCInterfaceDecl *NSValueDecl;
1142 
1143   /// Pointer to NSNumber type (NSNumber *).
1144   QualType NSNumberPointer;
1145 
1146   /// Pointer to NSValue type (NSValue *).
1147   QualType NSValuePointer;
1148 
1149   /// The Objective-C NSNumber methods used to create NSNumber literals.
1150   ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
1151 
1152   /// The declaration of the Objective-C NSString class.
1153   ObjCInterfaceDecl *NSStringDecl;
1154 
1155   /// Pointer to NSString type (NSString *).
1156   QualType NSStringPointer;
1157 
1158   /// The declaration of the stringWithUTF8String: method.
1159   ObjCMethodDecl *StringWithUTF8StringMethod;
1160 
1161   /// The declaration of the valueWithBytes:objCType: method.
1162   ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
1163 
1164   /// The declaration of the Objective-C NSArray class.
1165   ObjCInterfaceDecl *NSArrayDecl;
1166 
1167   /// The declaration of the arrayWithObjects:count: method.
1168   ObjCMethodDecl *ArrayWithObjectsMethod;
1169 
1170   /// The declaration of the Objective-C NSDictionary class.
1171   ObjCInterfaceDecl *NSDictionaryDecl;
1172 
1173   /// The declaration of the dictionaryWithObjects:forKeys:count: method.
1174   ObjCMethodDecl *DictionaryWithObjectsMethod;
1175 
1176   /// id<NSCopying> type.
1177   QualType QIDNSCopying;
1178 
1179   /// will hold 'respondsToSelector:'
1180   Selector RespondsToSelectorSel;
1181 
1182   /// A flag to remember whether the implicit forms of operator new and delete
1183   /// have been declared.
1184   bool GlobalNewDeleteDeclared;
1185 
1186   /// Describes how the expressions currently being parsed are
1187   /// evaluated at run-time, if at all.
1188   enum class ExpressionEvaluationContext {
1189     /// The current expression and its subexpressions occur within an
1190     /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
1191     /// \c sizeof, where the type of the expression may be significant but
1192     /// no code will be generated to evaluate the value of the expression at
1193     /// run time.
1194     Unevaluated,
1195 
1196     /// The current expression occurs within a braced-init-list within
1197     /// an unevaluated operand. This is mostly like a regular unevaluated
1198     /// context, except that we still instantiate constexpr functions that are
1199     /// referenced here so that we can perform narrowing checks correctly.
1200     UnevaluatedList,
1201 
1202     /// The current expression occurs within a discarded statement.
1203     /// This behaves largely similarly to an unevaluated operand in preventing
1204     /// definitions from being required, but not in other ways.
1205     DiscardedStatement,
1206 
1207     /// The current expression occurs within an unevaluated
1208     /// operand that unconditionally permits abstract references to
1209     /// fields, such as a SIZE operator in MS-style inline assembly.
1210     UnevaluatedAbstract,
1211 
1212     /// The current context is "potentially evaluated" in C++11 terms,
1213     /// but the expression is evaluated at compile-time (like the values of
1214     /// cases in a switch statement).
1215     ConstantEvaluated,
1216 
1217     /// In addition of being constant evaluated, the current expression
1218     /// occurs in an immediate function context - either a consteval function
1219     /// or a consteval if function.
1220     ImmediateFunctionContext,
1221 
1222     /// The current expression is potentially evaluated at run time,
1223     /// which means that code may be generated to evaluate the value of the
1224     /// expression at run time.
1225     PotentiallyEvaluated,
1226 
1227     /// The current expression is potentially evaluated, but any
1228     /// declarations referenced inside that expression are only used if
1229     /// in fact the current expression is used.
1230     ///
1231     /// This value is used when parsing default function arguments, for which
1232     /// we would like to provide diagnostics (e.g., passing non-POD arguments
1233     /// through varargs) but do not want to mark declarations as "referenced"
1234     /// until the default argument is used.
1235     PotentiallyEvaluatedIfUsed
1236   };
1237 
1238   using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
1239 
1240   /// Data structure used to record current or nested
1241   /// expression evaluation contexts.
1242   struct ExpressionEvaluationContextRecord {
1243     /// The expression evaluation context.
1244     ExpressionEvaluationContext Context;
1245 
1246     /// Whether the enclosing context needed a cleanup.
1247     CleanupInfo ParentCleanup;
1248 
1249     /// The number of active cleanup objects when we entered
1250     /// this expression evaluation context.
1251     unsigned NumCleanupObjects;
1252 
1253     /// The number of typos encountered during this expression evaluation
1254     /// context (i.e. the number of TypoExprs created).
1255     unsigned NumTypos;
1256 
1257     MaybeODRUseExprSet SavedMaybeODRUseExprs;
1258 
1259     /// The lambdas that are present within this context, if it
1260     /// is indeed an unevaluated context.
1261     SmallVector<LambdaExpr *, 2> Lambdas;
1262 
1263     /// The declaration that provides context for lambda expressions
1264     /// and block literals if the normal declaration context does not
1265     /// suffice, e.g., in a default function argument.
1266     Decl *ManglingContextDecl;
1267 
1268     /// If we are processing a decltype type, a set of call expressions
1269     /// for which we have deferred checking the completeness of the return type.
1270     SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
1271 
1272     /// If we are processing a decltype type, a set of temporary binding
1273     /// expressions for which we have deferred checking the destructor.
1274     SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
1275 
1276     llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
1277 
1278     /// Expressions appearing as the LHS of a volatile assignment in this
1279     /// context. We produce a warning for these when popping the context if
1280     /// they are not discarded-value expressions nor unevaluated operands.
1281     SmallVector<Expr*, 2> VolatileAssignmentLHSs;
1282 
1283     /// Set of candidates for starting an immediate invocation.
1284     llvm::SmallVector<ImmediateInvocationCandidate, 4> ImmediateInvocationCandidates;
1285 
1286     /// Set of DeclRefExprs referencing a consteval function when used in a
1287     /// context not already known to be immediately invoked.
1288     llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval;
1289 
1290     /// \brief Describes whether we are in an expression constext which we have
1291     /// to handle differently.
1292     enum ExpressionKind {
1293       EK_Decltype, EK_TemplateArgument, EK_Other
1294     } ExprContext;
1295 
ExpressionEvaluationContextRecordExpressionEvaluationContextRecord1296     ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
1297                                       unsigned NumCleanupObjects,
1298                                       CleanupInfo ParentCleanup,
1299                                       Decl *ManglingContextDecl,
1300                                       ExpressionKind ExprContext)
1301         : Context(Context), ParentCleanup(ParentCleanup),
1302           NumCleanupObjects(NumCleanupObjects), NumTypos(0),
1303           ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {}
1304 
isUnevaluatedExpressionEvaluationContextRecord1305     bool isUnevaluated() const {
1306       return Context == ExpressionEvaluationContext::Unevaluated ||
1307              Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
1308              Context == ExpressionEvaluationContext::UnevaluatedList;
1309     }
1310 
isConstantEvaluatedExpressionEvaluationContextRecord1311     bool isConstantEvaluated() const {
1312       return Context == ExpressionEvaluationContext::ConstantEvaluated ||
1313              Context == ExpressionEvaluationContext::ImmediateFunctionContext;
1314     }
1315 
isImmediateFunctionContextExpressionEvaluationContextRecord1316     bool isImmediateFunctionContext() const {
1317       return Context == ExpressionEvaluationContext::ImmediateFunctionContext;
1318     }
1319   };
1320 
1321   /// A stack of expression evaluation contexts.
1322   SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
1323 
1324   /// Emit a warning for all pending noderef expressions that we recorded.
1325   void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
1326 
1327   /// Compute the mangling number context for a lambda expression or
1328   /// block literal. Also return the extra mangling decl if any.
1329   ///
1330   /// \param DC - The DeclContext containing the lambda expression or
1331   /// block literal.
1332   std::tuple<MangleNumberingContext *, Decl *>
1333   getCurrentMangleNumberContext(const DeclContext *DC);
1334 
1335 
1336   /// SpecialMemberOverloadResult - The overloading result for a special member
1337   /// function.
1338   ///
1339   /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1340   /// integer are used to determine whether overload resolution succeeded.
1341   class SpecialMemberOverloadResult {
1342   public:
1343     enum Kind {
1344       NoMemberOrDeleted,
1345       Ambiguous,
1346       Success
1347     };
1348 
1349   private:
1350     llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
1351 
1352   public:
SpecialMemberOverloadResult()1353     SpecialMemberOverloadResult() : Pair() {}
SpecialMemberOverloadResult(CXXMethodDecl * MD)1354     SpecialMemberOverloadResult(CXXMethodDecl *MD)
1355         : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1356 
getMethod()1357     CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
setMethod(CXXMethodDecl * MD)1358     void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1359 
getKind()1360     Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
setKind(Kind K)1361     void setKind(Kind K) { Pair.setInt(K); }
1362   };
1363 
1364   class SpecialMemberOverloadResultEntry
1365       : public llvm::FastFoldingSetNode,
1366         public SpecialMemberOverloadResult {
1367   public:
SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID & ID)1368     SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1369       : FastFoldingSetNode(ID)
1370     {}
1371   };
1372 
1373   /// A cache of special member function overload resolution results
1374   /// for C++ records.
1375   llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1376 
1377   /// A cache of the flags available in enumerations with the flag_bits
1378   /// attribute.
1379   mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1380 
1381   /// The kind of translation unit we are processing.
1382   ///
1383   /// When we're processing a complete translation unit, Sema will perform
1384   /// end-of-translation-unit semantic tasks (such as creating
1385   /// initializers for tentative definitions in C) once parsing has
1386   /// completed. Modules and precompiled headers perform different kinds of
1387   /// checks.
1388   const TranslationUnitKind TUKind;
1389 
1390   llvm::BumpPtrAllocator BumpAlloc;
1391 
1392   /// The number of SFINAE diagnostics that have been trapped.
1393   unsigned NumSFINAEErrors;
1394 
1395   typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1396     UnparsedDefaultArgInstantiationsMap;
1397 
1398   /// A mapping from parameters with unparsed default arguments to the
1399   /// set of instantiations of each parameter.
1400   ///
1401   /// This mapping is a temporary data structure used when parsing
1402   /// nested class templates or nested classes of class templates,
1403   /// where we might end up instantiating an inner class before the
1404   /// default arguments of its methods have been parsed.
1405   UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1406 
1407   // Contains the locations of the beginning of unparsed default
1408   // argument locations.
1409   llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1410 
1411   /// UndefinedInternals - all the used, undefined objects which require a
1412   /// definition in this translation unit.
1413   llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1414 
1415   /// Determine if VD, which must be a variable or function, is an external
1416   /// symbol that nonetheless can't be referenced from outside this translation
1417   /// unit because its type has no linkage and it's not extern "C".
1418   bool isExternalWithNoLinkageType(ValueDecl *VD);
1419 
1420   /// Obtain a sorted list of functions that are undefined but ODR-used.
1421   void getUndefinedButUsed(
1422       SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1423 
1424   /// Retrieves list of suspicious delete-expressions that will be checked at
1425   /// the end of translation unit.
1426   const llvm::MapVector<FieldDecl *, DeleteLocs> &
1427   getMismatchingDeleteExpressions() const;
1428 
1429   class GlobalMethodPool {
1430   public:
1431     using Lists = std::pair<ObjCMethodList, ObjCMethodList>;
1432     using iterator = llvm::DenseMap<Selector, Lists>::iterator;
begin()1433     iterator begin() { return Methods.begin(); }
end()1434     iterator end() { return Methods.end(); }
find(Selector Sel)1435     iterator find(Selector Sel) { return Methods.find(Sel); }
insert(std::pair<Selector,Lists> && Val)1436     std::pair<iterator, bool> insert(std::pair<Selector, Lists> &&Val) {
1437       return Methods.insert(Val);
1438     }
count(Selector Sel)1439     int count(Selector Sel) const { return Methods.count(Sel); }
empty()1440     bool empty() const { return Methods.empty(); }
1441 
1442   private:
1443     llvm::DenseMap<Selector, Lists> Methods;
1444   };
1445 
1446   /// Method Pool - allows efficient lookup when typechecking messages to "id".
1447   /// We need to maintain a list, since selectors can have differing signatures
1448   /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1449   /// of selectors are "overloaded").
1450   /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1451   /// methods inside categories with a particular selector.
1452   GlobalMethodPool MethodPool;
1453 
1454   /// Method selectors used in a \@selector expression. Used for implementation
1455   /// of -Wselector.
1456   llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1457 
1458   /// List of SourceLocations where 'self' is implicitly retained inside a
1459   /// block.
1460   llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
1461       ImplicitlyRetainedSelfLocs;
1462 
1463   /// Kinds of C++ special members.
1464   enum CXXSpecialMember {
1465     CXXDefaultConstructor,
1466     CXXCopyConstructor,
1467     CXXMoveConstructor,
1468     CXXCopyAssignment,
1469     CXXMoveAssignment,
1470     CXXDestructor,
1471     CXXInvalid
1472   };
1473 
1474   typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1475       SpecialMemberDecl;
1476 
1477   /// The C++ special members which we are currently in the process of
1478   /// declaring. If this process recursively triggers the declaration of the
1479   /// same special member, we should act as if it is not yet declared.
1480   llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1481 
1482   /// Kinds of defaulted comparison operator functions.
1483   enum class DefaultedComparisonKind : unsigned char {
1484     /// This is not a defaultable comparison operator.
1485     None,
1486     /// This is an operator== that should be implemented as a series of
1487     /// subobject comparisons.
1488     Equal,
1489     /// This is an operator<=> that should be implemented as a series of
1490     /// subobject comparisons.
1491     ThreeWay,
1492     /// This is an operator!= that should be implemented as a rewrite in terms
1493     /// of a == comparison.
1494     NotEqual,
1495     /// This is an <, <=, >, or >= that should be implemented as a rewrite in
1496     /// terms of a <=> comparison.
1497     Relational,
1498   };
1499 
1500   /// The function definitions which were renamed as part of typo-correction
1501   /// to match their respective declarations. We want to keep track of them
1502   /// to ensure that we don't emit a "redefinition" error if we encounter a
1503   /// correctly named definition after the renamed definition.
1504   llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1505 
1506   /// Stack of types that correspond to the parameter entities that are
1507   /// currently being copy-initialized. Can be empty.
1508   llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1509 
1510   void ReadMethodPool(Selector Sel);
1511   void updateOutOfDateSelector(Selector Sel);
1512 
1513   /// Private Helper predicate to check for 'self'.
1514   bool isSelfExpr(Expr *RExpr);
1515   bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1516 
1517   /// Cause the active diagnostic on the DiagosticsEngine to be
1518   /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1519   /// should not be used elsewhere.
1520   void EmitCurrentDiagnostic(unsigned DiagID);
1521 
1522   /// Records and restores the CurFPFeatures state on entry/exit of compound
1523   /// statements.
1524   class FPFeaturesStateRAII {
1525   public:
FPFeaturesStateRAII(Sema & S)1526     FPFeaturesStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.CurFPFeatures) {
1527       OldOverrides = S.FpPragmaStack.CurrentValue;
1528     }
~FPFeaturesStateRAII()1529     ~FPFeaturesStateRAII() {
1530       S.CurFPFeatures = OldFPFeaturesState;
1531       S.FpPragmaStack.CurrentValue = OldOverrides;
1532     }
getOverrides()1533     FPOptionsOverride getOverrides() { return OldOverrides; }
1534 
1535   private:
1536     Sema& S;
1537     FPOptions OldFPFeaturesState;
1538     FPOptionsOverride OldOverrides;
1539   };
1540 
1541   void addImplicitTypedef(StringRef Name, QualType T);
1542 
1543   bool WarnedStackExhausted = false;
1544 
1545   /// Increment when we find a reference; decrement when we find an ignored
1546   /// assignment.  Ultimately the value is 0 if every reference is an ignored
1547   /// assignment.
1548   llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments;
1549 
1550   Optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
1551 
1552 public:
1553   Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1554        TranslationUnitKind TUKind = TU_Complete,
1555        CodeCompleteConsumer *CompletionConsumer = nullptr);
1556   ~Sema();
1557 
1558   /// Perform initialization that occurs after the parser has been
1559   /// initialized but before it parses anything.
1560   void Initialize();
1561 
1562   /// This virtual key function only exists to limit the emission of debug info
1563   /// describing the Sema class. GCC and Clang only emit debug info for a class
1564   /// with a vtable when the vtable is emitted. Sema is final and not
1565   /// polymorphic, but the debug info size savings are so significant that it is
1566   /// worth adding a vtable just to take advantage of this optimization.
1567   virtual void anchor();
1568 
getLangOpts()1569   const LangOptions &getLangOpts() const { return LangOpts; }
getOpenCLOptions()1570   OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
getCurFPFeatures()1571   FPOptions     &getCurFPFeatures() { return CurFPFeatures; }
1572 
getDiagnostics()1573   DiagnosticsEngine &getDiagnostics() const { return Diags; }
getSourceManager()1574   SourceManager &getSourceManager() const { return SourceMgr; }
getPreprocessor()1575   Preprocessor &getPreprocessor() const { return PP; }
getASTContext()1576   ASTContext &getASTContext() const { return Context; }
getASTConsumer()1577   ASTConsumer &getASTConsumer() const { return Consumer; }
1578   ASTMutationListener *getASTMutationListener() const;
getExternalSource()1579   ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1580   DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc,
1581                                                          StringRef Platform);
1582 
1583   ///Registers an external source. If an external source already exists,
1584   /// creates a multiplex external source and appends to it.
1585   ///
1586   ///\param[in] E - A non-null external sema source.
1587   ///
1588   void addExternalSource(ExternalSemaSource *E);
1589 
1590   void PrintStats() const;
1591 
1592   /// Warn that the stack is nearly exhausted.
1593   void warnStackExhausted(SourceLocation Loc);
1594 
1595   /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1596   /// guaranteed). Produces a warning if we're low on stack space and allocates
1597   /// more in that case. Use this in code that may recurse deeply (for example,
1598   /// in template instantiation) to avoid stack overflow.
1599   void runWithSufficientStackSpace(SourceLocation Loc,
1600                                    llvm::function_ref<void()> Fn);
1601 
1602   /// Helper class that creates diagnostics with optional
1603   /// template instantiation stacks.
1604   ///
1605   /// This class provides a wrapper around the basic DiagnosticBuilder
1606   /// class that emits diagnostics. ImmediateDiagBuilder is
1607   /// responsible for emitting the diagnostic (as DiagnosticBuilder
1608   /// does) and, if the diagnostic comes from inside a template
1609   /// instantiation, printing the template instantiation stack as
1610   /// well.
1611   class ImmediateDiagBuilder : public DiagnosticBuilder {
1612     Sema &SemaRef;
1613     unsigned DiagID;
1614 
1615   public:
ImmediateDiagBuilder(DiagnosticBuilder & DB,Sema & SemaRef,unsigned DiagID)1616     ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1617         : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
ImmediateDiagBuilder(DiagnosticBuilder && DB,Sema & SemaRef,unsigned DiagID)1618     ImmediateDiagBuilder(DiagnosticBuilder &&DB, Sema &SemaRef, unsigned DiagID)
1619         : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1620 
1621     // This is a cunning lie. DiagnosticBuilder actually performs move
1622     // construction in its copy constructor (but due to varied uses, it's not
1623     // possible to conveniently express this as actual move construction). So
1624     // the default copy ctor here is fine, because the base class disables the
1625     // source anyway, so the user-defined ~ImmediateDiagBuilder is a safe no-op
1626     // in that case anwyay.
1627     ImmediateDiagBuilder(const ImmediateDiagBuilder &) = default;
1628 
~ImmediateDiagBuilder()1629     ~ImmediateDiagBuilder() {
1630       // If we aren't active, there is nothing to do.
1631       if (!isActive()) return;
1632 
1633       // Otherwise, we need to emit the diagnostic. First clear the diagnostic
1634       // builder itself so it won't emit the diagnostic in its own destructor.
1635       //
1636       // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1637       // do its own needless checks to see if the diagnostic needs to be
1638       // emitted. However, because we take care to ensure that the builder
1639       // objects never escape, a sufficiently smart compiler will be able to
1640       // eliminate that code.
1641       Clear();
1642 
1643       // Dispatch to Sema to emit the diagnostic.
1644       SemaRef.EmitCurrentDiagnostic(DiagID);
1645     }
1646 
1647     /// Teach operator<< to produce an object of the correct type.
1648     template <typename T>
1649     friend const ImmediateDiagBuilder &
1650     operator<<(const ImmediateDiagBuilder &Diag, const T &Value) {
1651       const DiagnosticBuilder &BaseDiag = Diag;
1652       BaseDiag << Value;
1653       return Diag;
1654     }
1655 
1656     // It is necessary to limit this to rvalue reference to avoid calling this
1657     // function with a bitfield lvalue argument since non-const reference to
1658     // bitfield is not allowed.
1659     template <typename T, typename = typename std::enable_if<
1660                               !std::is_lvalue_reference<T>::value>::type>
1661     const ImmediateDiagBuilder &operator<<(T &&V) const {
1662       const DiagnosticBuilder &BaseDiag = *this;
1663       BaseDiag << std::move(V);
1664       return *this;
1665     }
1666   };
1667 
1668   /// A generic diagnostic builder for errors which may or may not be deferred.
1669   ///
1670   /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
1671   /// which are not allowed to appear inside __device__ functions and are
1672   /// allowed to appear in __host__ __device__ functions only if the host+device
1673   /// function is never codegen'ed.
1674   ///
1675   /// To handle this, we use the notion of "deferred diagnostics", where we
1676   /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
1677   ///
1678   /// This class lets you emit either a regular diagnostic, a deferred
1679   /// diagnostic, or no diagnostic at all, according to an argument you pass to
1680   /// its constructor, thus simplifying the process of creating these "maybe
1681   /// deferred" diagnostics.
1682   class SemaDiagnosticBuilder {
1683   public:
1684     enum Kind {
1685       /// Emit no diagnostics.
1686       K_Nop,
1687       /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
1688       K_Immediate,
1689       /// Emit the diagnostic immediately, and, if it's a warning or error, also
1690       /// emit a call stack showing how this function can be reached by an a
1691       /// priori known-emitted function.
1692       K_ImmediateWithCallStack,
1693       /// Create a deferred diagnostic, which is emitted only if the function
1694       /// it's attached to is codegen'ed.  Also emit a call stack as with
1695       /// K_ImmediateWithCallStack.
1696       K_Deferred
1697     };
1698 
1699     SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
1700                           FunctionDecl *Fn, Sema &S);
1701     SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D);
1702     SemaDiagnosticBuilder(const SemaDiagnosticBuilder &) = default;
1703     ~SemaDiagnosticBuilder();
1704 
isImmediate()1705     bool isImmediate() const { return ImmediateDiag.hasValue(); }
1706 
1707     /// Convertible to bool: True if we immediately emitted an error, false if
1708     /// we didn't emit an error or we created a deferred error.
1709     ///
1710     /// Example usage:
1711     ///
1712     ///   if (SemaDiagnosticBuilder(...) << foo << bar)
1713     ///     return ExprError();
1714     ///
1715     /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
1716     /// want to use these instead of creating a SemaDiagnosticBuilder yourself.
1717     operator bool() const { return isImmediate(); }
1718 
1719     template <typename T>
1720     friend const SemaDiagnosticBuilder &
1721     operator<<(const SemaDiagnosticBuilder &Diag, const T &Value) {
1722       if (Diag.ImmediateDiag.hasValue())
1723         *Diag.ImmediateDiag << Value;
1724       else if (Diag.PartialDiagId.hasValue())
1725         Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
1726             << Value;
1727       return Diag;
1728     }
1729 
1730     // It is necessary to limit this to rvalue reference to avoid calling this
1731     // function with a bitfield lvalue argument since non-const reference to
1732     // bitfield is not allowed.
1733     template <typename T, typename = typename std::enable_if<
1734                               !std::is_lvalue_reference<T>::value>::type>
1735     const SemaDiagnosticBuilder &operator<<(T &&V) const {
1736       if (ImmediateDiag.hasValue())
1737         *ImmediateDiag << std::move(V);
1738       else if (PartialDiagId.hasValue())
1739         S.DeviceDeferredDiags[Fn][*PartialDiagId].second << std::move(V);
1740       return *this;
1741     }
1742 
1743     friend const SemaDiagnosticBuilder &
1744     operator<<(const SemaDiagnosticBuilder &Diag, const PartialDiagnostic &PD) {
1745       if (Diag.ImmediateDiag.hasValue())
1746         PD.Emit(*Diag.ImmediateDiag);
1747       else if (Diag.PartialDiagId.hasValue())
1748         Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second = PD;
1749       return Diag;
1750     }
1751 
AddFixItHint(const FixItHint & Hint)1752     void AddFixItHint(const FixItHint &Hint) const {
1753       if (ImmediateDiag.hasValue())
1754         ImmediateDiag->AddFixItHint(Hint);
1755       else if (PartialDiagId.hasValue())
1756         S.DeviceDeferredDiags[Fn][*PartialDiagId].second.AddFixItHint(Hint);
1757     }
1758 
ExprError(const SemaDiagnosticBuilder &)1759     friend ExprResult ExprError(const SemaDiagnosticBuilder &) {
1760       return ExprError();
1761     }
StmtError(const SemaDiagnosticBuilder &)1762     friend StmtResult StmtError(const SemaDiagnosticBuilder &) {
1763       return StmtError();
1764     }
ExprResult()1765     operator ExprResult() const { return ExprError(); }
StmtResult()1766     operator StmtResult() const { return StmtError(); }
TypeResult()1767     operator TypeResult() const { return TypeError(); }
DeclResult()1768     operator DeclResult() const { return DeclResult(true); }
MemInitResult()1769     operator MemInitResult() const { return MemInitResult(true); }
1770 
1771   private:
1772     Sema &S;
1773     SourceLocation Loc;
1774     unsigned DiagID;
1775     FunctionDecl *Fn;
1776     bool ShowCallStack;
1777 
1778     // Invariant: At most one of these Optionals has a value.
1779     // FIXME: Switch these to a Variant once that exists.
1780     llvm::Optional<ImmediateDiagBuilder> ImmediateDiag;
1781     llvm::Optional<unsigned> PartialDiagId;
1782   };
1783 
1784   /// Is the last error level diagnostic immediate. This is used to determined
1785   /// whether the next info diagnostic should be immediate.
1786   bool IsLastErrorImmediate = true;
1787 
1788   /// Emit a diagnostic.
1789   SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID,
1790                              bool DeferHint = false);
1791 
1792   /// Emit a partial diagnostic.
1793   SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic &PD,
1794                              bool DeferHint = false);
1795 
1796   /// Build a partial diagnostic.
1797   PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1798 
1799   /// Whether deferrable diagnostics should be deferred.
1800   bool DeferDiags = false;
1801 
1802   /// RAII class to control scope of DeferDiags.
1803   class DeferDiagsRAII {
1804     Sema &S;
1805     bool SavedDeferDiags = false;
1806 
1807   public:
DeferDiagsRAII(Sema & S,bool DeferDiags)1808     DeferDiagsRAII(Sema &S, bool DeferDiags)
1809         : S(S), SavedDeferDiags(S.DeferDiags) {
1810       S.DeferDiags = DeferDiags;
1811     }
~DeferDiagsRAII()1812     ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; }
1813   };
1814 
1815   /// Whether uncompilable error has occurred. This includes error happens
1816   /// in deferred diagnostics.
1817   bool hasUncompilableErrorOccurred() const;
1818 
1819   bool findMacroSpelling(SourceLocation &loc, StringRef name);
1820 
1821   /// Get a string to suggest for zero-initialization of a type.
1822   std::string
1823   getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1824   std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1825 
1826   /// Calls \c Lexer::getLocForEndOfToken()
1827   SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1828 
1829   /// Retrieve the module loader associated with the preprocessor.
1830   ModuleLoader &getModuleLoader() const;
1831 
1832   /// Invent a new identifier for parameters of abbreviated templates.
1833   IdentifierInfo *
1834   InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName,
1835                                              unsigned Index);
1836 
1837   void emitAndClearUnusedLocalTypedefWarnings();
1838 
1839   private:
1840     /// Function or variable declarations to be checked for whether the deferred
1841     /// diagnostics should be emitted.
1842     llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags;
1843 
1844   public:
1845   // Emit all deferred diagnostics.
1846   void emitDeferredDiags();
1847 
1848   enum TUFragmentKind {
1849     /// The global module fragment, between 'module;' and a module-declaration.
1850     Global,
1851     /// A normal translation unit fragment. For a non-module unit, this is the
1852     /// entire translation unit. Otherwise, it runs from the module-declaration
1853     /// to the private-module-fragment (if any) or the end of the TU (if not).
1854     Normal,
1855     /// The private module fragment, between 'module :private;' and the end of
1856     /// the translation unit.
1857     Private
1858   };
1859 
1860   void ActOnStartOfTranslationUnit();
1861   void ActOnEndOfTranslationUnit();
1862   void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1863 
1864   void CheckDelegatingCtorCycles();
1865 
1866   Scope *getScopeForContext(DeclContext *Ctx);
1867 
1868   void PushFunctionScope();
1869   void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1870   sema::LambdaScopeInfo *PushLambdaScope();
1871 
1872   /// This is used to inform Sema what the current TemplateParameterDepth
1873   /// is during Parsing.  Currently it is used to pass on the depth
1874   /// when parsing generic lambda 'auto' parameters.
1875   void RecordParsingTemplateParameterDepth(unsigned Depth);
1876 
1877   void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1878                                RecordDecl *RD, CapturedRegionKind K,
1879                                unsigned OpenMPCaptureLevel = 0);
1880 
1881   /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1882   /// time after they've been popped.
1883   class PoppedFunctionScopeDeleter {
1884     Sema *Self;
1885 
1886   public:
PoppedFunctionScopeDeleter(Sema * Self)1887     explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1888     void operator()(sema::FunctionScopeInfo *Scope) const;
1889   };
1890 
1891   using PoppedFunctionScopePtr =
1892       std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1893 
1894   PoppedFunctionScopePtr
1895   PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1896                        const Decl *D = nullptr,
1897                        QualType BlockType = QualType());
1898 
getCurFunction()1899   sema::FunctionScopeInfo *getCurFunction() const {
1900     return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1901   }
1902 
1903   sema::FunctionScopeInfo *getEnclosingFunction() const;
1904 
1905   void setFunctionHasBranchIntoScope();
1906   void setFunctionHasBranchProtectedScope();
1907   void setFunctionHasIndirectGoto();
1908   void setFunctionHasMustTail();
1909 
1910   void PushCompoundScope(bool IsStmtExpr);
1911   void PopCompoundScope();
1912 
1913   sema::CompoundScopeInfo &getCurCompoundScope() const;
1914 
1915   bool hasAnyUnrecoverableErrorsInThisFunction() const;
1916 
1917   /// Retrieve the current block, if any.
1918   sema::BlockScopeInfo *getCurBlock();
1919 
1920   /// Get the innermost lambda enclosing the current location, if any. This
1921   /// looks through intervening non-lambda scopes such as local functions and
1922   /// blocks.
1923   sema::LambdaScopeInfo *getEnclosingLambda() const;
1924 
1925   /// Retrieve the current lambda scope info, if any.
1926   /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1927   /// lambda scope info ignoring all inner capturing scopes that are not
1928   /// lambda scopes.
1929   sema::LambdaScopeInfo *
1930   getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1931 
1932   /// Retrieve the current generic lambda info, if any.
1933   sema::LambdaScopeInfo *getCurGenericLambda();
1934 
1935   /// Retrieve the current captured region, if any.
1936   sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1937 
1938   /// Retrieve the current function, if any, that should be analyzed for
1939   /// potential availability violations.
1940   sema::FunctionScopeInfo *getCurFunctionAvailabilityContext();
1941 
1942   /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
WeakTopLevelDecls()1943   SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1944 
1945   /// Called before parsing a function declarator belonging to a function
1946   /// declaration.
1947   void ActOnStartFunctionDeclarationDeclarator(Declarator &D,
1948                                                unsigned TemplateParameterDepth);
1949 
1950   /// Called after parsing a function declarator belonging to a function
1951   /// declaration.
1952   void ActOnFinishFunctionDeclarationDeclarator(Declarator &D);
1953 
1954   void ActOnComment(SourceRange Comment);
1955 
1956   //===--------------------------------------------------------------------===//
1957   // Type Analysis / Processing: SemaType.cpp.
1958   //
1959 
1960   QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1961                               const DeclSpec *DS = nullptr);
1962   QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1963                               const DeclSpec *DS = nullptr);
1964   QualType BuildPointerType(QualType T,
1965                             SourceLocation Loc, DeclarationName Entity);
1966   QualType BuildReferenceType(QualType T, bool LValueRef,
1967                               SourceLocation Loc, DeclarationName Entity);
1968   QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1969                           Expr *ArraySize, unsigned Quals,
1970                           SourceRange Brackets, DeclarationName Entity);
1971   QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
1972   QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1973                               SourceLocation AttrLoc);
1974   QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
1975                            SourceLocation AttrLoc);
1976 
1977   QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
1978                                  SourceLocation AttrLoc);
1979 
1980   /// Same as above, but constructs the AddressSpace index if not provided.
1981   QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
1982                                  SourceLocation AttrLoc);
1983 
1984   bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
1985 
1986   bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1987 
1988   /// Build a function type.
1989   ///
1990   /// This routine checks the function type according to C++ rules and
1991   /// under the assumption that the result type and parameter types have
1992   /// just been instantiated from a template. It therefore duplicates
1993   /// some of the behavior of GetTypeForDeclarator, but in a much
1994   /// simpler form that is only suitable for this narrow use case.
1995   ///
1996   /// \param T The return type of the function.
1997   ///
1998   /// \param ParamTypes The parameter types of the function. This array
1999   /// will be modified to account for adjustments to the types of the
2000   /// function parameters.
2001   ///
2002   /// \param Loc The location of the entity whose type involves this
2003   /// function type or, if there is no such entity, the location of the
2004   /// type that will have function type.
2005   ///
2006   /// \param Entity The name of the entity that involves the function
2007   /// type, if known.
2008   ///
2009   /// \param EPI Extra information about the function type. Usually this will
2010   /// be taken from an existing function with the same prototype.
2011   ///
2012   /// \returns A suitable function type, if there are no errors. The
2013   /// unqualified type will always be a FunctionProtoType.
2014   /// Otherwise, returns a NULL type.
2015   QualType BuildFunctionType(QualType T,
2016                              MutableArrayRef<QualType> ParamTypes,
2017                              SourceLocation Loc, DeclarationName Entity,
2018                              const FunctionProtoType::ExtProtoInfo &EPI);
2019 
2020   QualType BuildMemberPointerType(QualType T, QualType Class,
2021                                   SourceLocation Loc,
2022                                   DeclarationName Entity);
2023   QualType BuildBlockPointerType(QualType T,
2024                                  SourceLocation Loc, DeclarationName Entity);
2025   QualType BuildParenType(QualType T);
2026   QualType BuildAtomicType(QualType T, SourceLocation Loc);
2027   QualType BuildReadPipeType(QualType T,
2028                          SourceLocation Loc);
2029   QualType BuildWritePipeType(QualType T,
2030                          SourceLocation Loc);
2031   QualType BuildExtIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
2032 
2033   TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
2034   TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
2035 
2036   /// Package the given type and TSI into a ParsedType.
2037   ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
2038   DeclarationNameInfo GetNameForDeclarator(Declarator &D);
2039   DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
2040   static QualType GetTypeFromParser(ParsedType Ty,
2041                                     TypeSourceInfo **TInfo = nullptr);
2042   CanThrowResult canThrow(const Stmt *E);
2043   /// Determine whether the callee of a particular function call can throw.
2044   /// E, D and Loc are all optional.
2045   static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
2046                                        SourceLocation Loc = SourceLocation());
2047   const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
2048                                                 const FunctionProtoType *FPT);
2049   void UpdateExceptionSpec(FunctionDecl *FD,
2050                            const FunctionProtoType::ExceptionSpecInfo &ESI);
2051   bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
2052   bool CheckDistantExceptionSpec(QualType T);
2053   bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
2054   bool CheckEquivalentExceptionSpec(
2055       const FunctionProtoType *Old, SourceLocation OldLoc,
2056       const FunctionProtoType *New, SourceLocation NewLoc);
2057   bool CheckEquivalentExceptionSpec(
2058       const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
2059       const FunctionProtoType *Old, SourceLocation OldLoc,
2060       const FunctionProtoType *New, SourceLocation NewLoc);
2061   bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
2062   bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
2063                                 const PartialDiagnostic &NestedDiagID,
2064                                 const PartialDiagnostic &NoteID,
2065                                 const PartialDiagnostic &NoThrowDiagID,
2066                                 const FunctionProtoType *Superset,
2067                                 SourceLocation SuperLoc,
2068                                 const FunctionProtoType *Subset,
2069                                 SourceLocation SubLoc);
2070   bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
2071                                const PartialDiagnostic &NoteID,
2072                                const FunctionProtoType *Target,
2073                                SourceLocation TargetLoc,
2074                                const FunctionProtoType *Source,
2075                                SourceLocation SourceLoc);
2076 
2077   TypeResult ActOnTypeName(Scope *S, Declarator &D);
2078 
2079   /// The parser has parsed the context-sensitive type 'instancetype'
2080   /// in an Objective-C message declaration. Return the appropriate type.
2081   ParsedType ActOnObjCInstanceType(SourceLocation Loc);
2082 
2083   /// Abstract class used to diagnose incomplete types.
2084   struct TypeDiagnoser {
TypeDiagnoserTypeDiagnoser2085     TypeDiagnoser() {}
2086 
2087     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
~TypeDiagnoserTypeDiagnoser2088     virtual ~TypeDiagnoser() {}
2089   };
2090 
getPrintable(int I)2091   static int getPrintable(int I) { return I; }
getPrintable(unsigned I)2092   static unsigned getPrintable(unsigned I) { return I; }
getPrintable(bool B)2093   static bool getPrintable(bool B) { return B; }
getPrintable(const char * S)2094   static const char * getPrintable(const char *S) { return S; }
getPrintable(StringRef S)2095   static StringRef getPrintable(StringRef S) { return S; }
getPrintable(const std::string & S)2096   static const std::string &getPrintable(const std::string &S) { return S; }
getPrintable(const IdentifierInfo * II)2097   static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
2098     return II;
2099   }
getPrintable(DeclarationName N)2100   static DeclarationName getPrintable(DeclarationName N) { return N; }
getPrintable(QualType T)2101   static QualType getPrintable(QualType T) { return T; }
getPrintable(SourceRange R)2102   static SourceRange getPrintable(SourceRange R) { return R; }
getPrintable(SourceLocation L)2103   static SourceRange getPrintable(SourceLocation L) { return L; }
getPrintable(const Expr * E)2104   static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
getPrintable(TypeLoc TL)2105   static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
2106 
2107   template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
2108   protected:
2109     unsigned DiagID;
2110     std::tuple<const Ts &...> Args;
2111 
2112     template <std::size_t... Is>
emit(const SemaDiagnosticBuilder & DB,std::index_sequence<Is...>)2113     void emit(const SemaDiagnosticBuilder &DB,
2114               std::index_sequence<Is...>) const {
2115       // Apply all tuple elements to the builder in order.
2116       bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
2117       (void)Dummy;
2118     }
2119 
2120   public:
BoundTypeDiagnoser(unsigned DiagID,const Ts &...Args)2121     BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
2122         : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
2123       assert(DiagID != 0 && "no diagnostic for type diagnoser");
2124     }
2125 
diagnose(Sema & S,SourceLocation Loc,QualType T)2126     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2127       const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
2128       emit(DB, std::index_sequence_for<Ts...>());
2129       DB << T;
2130     }
2131   };
2132 
2133   /// Do a check to make sure \p Name looks like a legal argument for the
2134   /// swift_name attribute applied to decl \p D.  Raise a diagnostic if the name
2135   /// is invalid for the given declaration.
2136   ///
2137   /// \p AL is used to provide caret diagnostics in case of a malformed name.
2138   ///
2139   /// \returns true if the name is a valid swift name for \p D, false otherwise.
2140   bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc,
2141                          const ParsedAttr &AL, bool IsAsync);
2142 
2143   /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
2144   /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
2145   /// For example, a diagnostic with no other parameters would generally have
2146   /// the form "...%select{incomplete|sizeless}0 type %1...".
2147   template <typename... Ts>
2148   class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> {
2149   public:
SizelessTypeDiagnoser(unsigned DiagID,const Ts &...Args)2150     SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args)
2151         : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
2152 
diagnose(Sema & S,SourceLocation Loc,QualType T)2153     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2154       const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
2155       this->emit(DB, std::index_sequence_for<Ts...>());
2156       DB << T->isSizelessType() << T;
2157     }
2158   };
2159 
2160   enum class CompleteTypeKind {
2161     /// Apply the normal rules for complete types.  In particular,
2162     /// treat all sizeless types as incomplete.
2163     Normal,
2164 
2165     /// Relax the normal rules for complete types so that they include
2166     /// sizeless built-in types.
2167     AcceptSizeless,
2168 
2169     // FIXME: Eventually we should flip the default to Normal and opt in
2170     // to AcceptSizeless rather than opt out of it.
2171     Default = AcceptSizeless
2172   };
2173 
2174 private:
2175   /// Methods for marking which expressions involve dereferencing a pointer
2176   /// marked with the 'noderef' attribute. Expressions are checked bottom up as
2177   /// they are parsed, meaning that a noderef pointer may not be accessed. For
2178   /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
2179   /// `*p`, but need to check that `address of` is called on it. This requires
2180   /// keeping a container of all pending expressions and checking if the address
2181   /// of them are eventually taken.
2182   void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
2183   void CheckAddressOfNoDeref(const Expr *E);
2184   void CheckMemberAccessOfNoDeref(const MemberExpr *E);
2185 
2186   bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
2187                                CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
2188 
2189   struct ModuleScope {
2190     SourceLocation BeginLoc;
2191     clang::Module *Module = nullptr;
2192     bool ModuleInterface = false;
2193     bool ImplicitGlobalModuleFragment = false;
2194     VisibleModuleSet OuterVisibleModules;
2195   };
2196   /// The modules we're currently parsing.
2197   llvm::SmallVector<ModuleScope, 16> ModuleScopes;
2198 
2199   /// Namespace definitions that we will export when they finish.
2200   llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
2201 
2202   /// Get the module whose scope we are currently within.
getCurrentModule()2203   Module *getCurrentModule() const {
2204     return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
2205   }
2206 
2207   VisibleModuleSet VisibleModules;
2208 
2209 public:
2210   /// Get the module owning an entity.
getOwningModule(const Decl * Entity)2211   Module *getOwningModule(const Decl *Entity) {
2212     return Entity->getOwningModule();
2213   }
2214 
2215   /// Make a merged definition of an existing hidden definition \p ND
2216   /// visible at the specified location.
2217   void makeMergedDefinitionVisible(NamedDecl *ND);
2218 
2219   bool isModuleVisible(const Module *M, bool ModulePrivate = false);
2220 
2221   // When loading a non-modular PCH files, this is used to restore module
2222   // visibility.
makeModuleVisible(Module * Mod,SourceLocation ImportLoc)2223   void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) {
2224     VisibleModules.setVisible(Mod, ImportLoc);
2225   }
2226 
2227   /// Determine whether a declaration is visible to name lookup.
isVisible(const NamedDecl * D)2228   bool isVisible(const NamedDecl *D) {
2229     return D->isUnconditionallyVisible() || isVisibleSlow(D);
2230   }
2231 
2232   /// Determine whether any declaration of an entity is visible.
2233   bool
2234   hasVisibleDeclaration(const NamedDecl *D,
2235                         llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
2236     return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
2237   }
2238   bool hasVisibleDeclarationSlow(const NamedDecl *D,
2239                                  llvm::SmallVectorImpl<Module *> *Modules);
2240 
2241   bool hasVisibleMergedDefinition(NamedDecl *Def);
2242   bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
2243 
2244   /// Determine if \p D and \p Suggested have a structurally compatible
2245   /// layout as described in C11 6.2.7/1.
2246   bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
2247 
2248   /// Determine if \p D has a visible definition. If not, suggest a declaration
2249   /// that should be made visible to expose the definition.
2250   bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
2251                             bool OnlyNeedComplete = false);
hasVisibleDefinition(const NamedDecl * D)2252   bool hasVisibleDefinition(const NamedDecl *D) {
2253     NamedDecl *Hidden;
2254     return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
2255   }
2256 
2257   /// Determine if the template parameter \p D has a visible default argument.
2258   bool
2259   hasVisibleDefaultArgument(const NamedDecl *D,
2260                             llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2261 
2262   /// Determine if there is a visible declaration of \p D that is an explicit
2263   /// specialization declaration for a specialization of a template. (For a
2264   /// member specialization, use hasVisibleMemberSpecialization.)
2265   bool hasVisibleExplicitSpecialization(
2266       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2267 
2268   /// Determine if there is a visible declaration of \p D that is a member
2269   /// specialization declaration (as opposed to an instantiated declaration).
2270   bool hasVisibleMemberSpecialization(
2271       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2272 
2273   /// Determine if \p A and \p B are equivalent internal linkage declarations
2274   /// from different modules, and thus an ambiguity error can be downgraded to
2275   /// an extension warning.
2276   bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
2277                                               const NamedDecl *B);
2278   void diagnoseEquivalentInternalLinkageDeclarations(
2279       SourceLocation Loc, const NamedDecl *D,
2280       ArrayRef<const NamedDecl *> Equiv);
2281 
2282   bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
2283 
2284   bool isCompleteType(SourceLocation Loc, QualType T,
2285                       CompleteTypeKind Kind = CompleteTypeKind::Default) {
2286     return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr);
2287   }
2288   bool RequireCompleteType(SourceLocation Loc, QualType T,
2289                            CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
2290   bool RequireCompleteType(SourceLocation Loc, QualType T,
2291                            CompleteTypeKind Kind, unsigned DiagID);
2292 
RequireCompleteType(SourceLocation Loc,QualType T,TypeDiagnoser & Diagnoser)2293   bool RequireCompleteType(SourceLocation Loc, QualType T,
2294                            TypeDiagnoser &Diagnoser) {
2295     return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser);
2296   }
RequireCompleteType(SourceLocation Loc,QualType T,unsigned DiagID)2297   bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
2298     return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID);
2299   }
2300 
2301   template <typename... Ts>
RequireCompleteType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)2302   bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
2303                            const Ts &...Args) {
2304     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2305     return RequireCompleteType(Loc, T, Diagnoser);
2306   }
2307 
2308   template <typename... Ts>
RequireCompleteSizedType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)2309   bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID,
2310                                 const Ts &... Args) {
2311     SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2312     return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
2313   }
2314 
2315   /// Get the type of expression E, triggering instantiation to complete the
2316   /// type if necessary -- that is, if the expression refers to a templated
2317   /// static data member of incomplete array type.
2318   ///
2319   /// May still return an incomplete type if instantiation was not possible or
2320   /// if the type is incomplete for a different reason. Use
2321   /// RequireCompleteExprType instead if a diagnostic is expected for an
2322   /// incomplete expression type.
2323   QualType getCompletedType(Expr *E);
2324 
2325   void completeExprArrayBound(Expr *E);
2326   bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
2327                                TypeDiagnoser &Diagnoser);
2328   bool RequireCompleteExprType(Expr *E, unsigned DiagID);
2329 
2330   template <typename... Ts>
RequireCompleteExprType(Expr * E,unsigned DiagID,const Ts &...Args)2331   bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
2332     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2333     return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
2334   }
2335 
2336   template <typename... Ts>
RequireCompleteSizedExprType(Expr * E,unsigned DiagID,const Ts &...Args)2337   bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
2338                                     const Ts &... Args) {
2339     SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2340     return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser);
2341   }
2342 
2343   bool RequireLiteralType(SourceLocation Loc, QualType T,
2344                           TypeDiagnoser &Diagnoser);
2345   bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
2346 
2347   template <typename... Ts>
RequireLiteralType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)2348   bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
2349                           const Ts &...Args) {
2350     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2351     return RequireLiteralType(Loc, T, Diagnoser);
2352   }
2353 
2354   QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
2355                              const CXXScopeSpec &SS, QualType T,
2356                              TagDecl *OwnedTagDecl = nullptr);
2357 
2358   QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
2359   /// If AsUnevaluated is false, E is treated as though it were an evaluated
2360   /// context, such as when building a type for decltype(auto).
2361   QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
2362                              bool AsUnevaluated = true);
2363   QualType BuildUnaryTransformType(QualType BaseType,
2364                                    UnaryTransformType::UTTKind UKind,
2365                                    SourceLocation Loc);
2366 
2367   //===--------------------------------------------------------------------===//
2368   // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
2369   //
2370 
2371   struct SkipBodyInfo {
SkipBodyInfoSkipBodyInfo2372     SkipBodyInfo()
2373         : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
2374           New(nullptr) {}
2375     bool ShouldSkip;
2376     bool CheckSameAsPrevious;
2377     NamedDecl *Previous;
2378     NamedDecl *New;
2379   };
2380 
2381   DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
2382 
2383   void DiagnoseUseOfUnimplementedSelectors();
2384 
2385   bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
2386 
2387   ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
2388                          Scope *S, CXXScopeSpec *SS = nullptr,
2389                          bool isClassName = false, bool HasTrailingDot = false,
2390                          ParsedType ObjectType = nullptr,
2391                          bool IsCtorOrDtorName = false,
2392                          bool WantNontrivialTypeSourceInfo = false,
2393                          bool IsClassTemplateDeductionContext = true,
2394                          IdentifierInfo **CorrectedII = nullptr);
2395   TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
2396   bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
2397   void DiagnoseUnknownTypeName(IdentifierInfo *&II,
2398                                SourceLocation IILoc,
2399                                Scope *S,
2400                                CXXScopeSpec *SS,
2401                                ParsedType &SuggestedType,
2402                                bool IsTemplateName = false);
2403 
2404   /// Attempt to behave like MSVC in situations where lookup of an unqualified
2405   /// type name has failed in a dependent context. In these situations, we
2406   /// automatically form a DependentTypeName that will retry lookup in a related
2407   /// scope during instantiation.
2408   ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
2409                                       SourceLocation NameLoc,
2410                                       bool IsTemplateTypeArg);
2411 
2412   /// Describes the result of the name lookup and resolution performed
2413   /// by \c ClassifyName().
2414   enum NameClassificationKind {
2415     /// This name is not a type or template in this context, but might be
2416     /// something else.
2417     NC_Unknown,
2418     /// Classification failed; an error has been produced.
2419     NC_Error,
2420     /// The name has been typo-corrected to a keyword.
2421     NC_Keyword,
2422     /// The name was classified as a type.
2423     NC_Type,
2424     /// The name was classified as a specific non-type, non-template
2425     /// declaration. ActOnNameClassifiedAsNonType should be called to
2426     /// convert the declaration to an expression.
2427     NC_NonType,
2428     /// The name was classified as an ADL-only function name.
2429     /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
2430     /// result to an expression.
2431     NC_UndeclaredNonType,
2432     /// The name denotes a member of a dependent type that could not be
2433     /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
2434     /// convert the result to an expression.
2435     NC_DependentNonType,
2436     /// The name was classified as an overload set, and an expression
2437     /// representing that overload set has been formed.
2438     /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
2439     /// expression referencing the overload set.
2440     NC_OverloadSet,
2441     /// The name was classified as a template whose specializations are types.
2442     NC_TypeTemplate,
2443     /// The name was classified as a variable template name.
2444     NC_VarTemplate,
2445     /// The name was classified as a function template name.
2446     NC_FunctionTemplate,
2447     /// The name was classified as an ADL-only function template name.
2448     NC_UndeclaredTemplate,
2449     /// The name was classified as a concept name.
2450     NC_Concept,
2451   };
2452 
2453   class NameClassification {
2454     NameClassificationKind Kind;
2455     union {
2456       ExprResult Expr;
2457       NamedDecl *NonTypeDecl;
2458       TemplateName Template;
2459       ParsedType Type;
2460     };
2461 
NameClassification(NameClassificationKind Kind)2462     explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
2463 
2464   public:
NameClassification(ParsedType Type)2465     NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
2466 
NameClassification(const IdentifierInfo * Keyword)2467     NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
2468 
Error()2469     static NameClassification Error() {
2470       return NameClassification(NC_Error);
2471     }
2472 
Unknown()2473     static NameClassification Unknown() {
2474       return NameClassification(NC_Unknown);
2475     }
2476 
OverloadSet(ExprResult E)2477     static NameClassification OverloadSet(ExprResult E) {
2478       NameClassification Result(NC_OverloadSet);
2479       Result.Expr = E;
2480       return Result;
2481     }
2482 
NonType(NamedDecl * D)2483     static NameClassification NonType(NamedDecl *D) {
2484       NameClassification Result(NC_NonType);
2485       Result.NonTypeDecl = D;
2486       return Result;
2487     }
2488 
UndeclaredNonType()2489     static NameClassification UndeclaredNonType() {
2490       return NameClassification(NC_UndeclaredNonType);
2491     }
2492 
DependentNonType()2493     static NameClassification DependentNonType() {
2494       return NameClassification(NC_DependentNonType);
2495     }
2496 
TypeTemplate(TemplateName Name)2497     static NameClassification TypeTemplate(TemplateName Name) {
2498       NameClassification Result(NC_TypeTemplate);
2499       Result.Template = Name;
2500       return Result;
2501     }
2502 
VarTemplate(TemplateName Name)2503     static NameClassification VarTemplate(TemplateName Name) {
2504       NameClassification Result(NC_VarTemplate);
2505       Result.Template = Name;
2506       return Result;
2507     }
2508 
FunctionTemplate(TemplateName Name)2509     static NameClassification FunctionTemplate(TemplateName Name) {
2510       NameClassification Result(NC_FunctionTemplate);
2511       Result.Template = Name;
2512       return Result;
2513     }
2514 
Concept(TemplateName Name)2515     static NameClassification Concept(TemplateName Name) {
2516       NameClassification Result(NC_Concept);
2517       Result.Template = Name;
2518       return Result;
2519     }
2520 
UndeclaredTemplate(TemplateName Name)2521     static NameClassification UndeclaredTemplate(TemplateName Name) {
2522       NameClassification Result(NC_UndeclaredTemplate);
2523       Result.Template = Name;
2524       return Result;
2525     }
2526 
getKind()2527     NameClassificationKind getKind() const { return Kind; }
2528 
getExpression()2529     ExprResult getExpression() const {
2530       assert(Kind == NC_OverloadSet);
2531       return Expr;
2532     }
2533 
getType()2534     ParsedType getType() const {
2535       assert(Kind == NC_Type);
2536       return Type;
2537     }
2538 
getNonTypeDecl()2539     NamedDecl *getNonTypeDecl() const {
2540       assert(Kind == NC_NonType);
2541       return NonTypeDecl;
2542     }
2543 
getTemplateName()2544     TemplateName getTemplateName() const {
2545       assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
2546              Kind == NC_VarTemplate || Kind == NC_Concept ||
2547              Kind == NC_UndeclaredTemplate);
2548       return Template;
2549     }
2550 
getTemplateNameKind()2551     TemplateNameKind getTemplateNameKind() const {
2552       switch (Kind) {
2553       case NC_TypeTemplate:
2554         return TNK_Type_template;
2555       case NC_FunctionTemplate:
2556         return TNK_Function_template;
2557       case NC_VarTemplate:
2558         return TNK_Var_template;
2559       case NC_Concept:
2560         return TNK_Concept_template;
2561       case NC_UndeclaredTemplate:
2562         return TNK_Undeclared_template;
2563       default:
2564         llvm_unreachable("unsupported name classification.");
2565       }
2566     }
2567   };
2568 
2569   /// Perform name lookup on the given name, classifying it based on
2570   /// the results of name lookup and the following token.
2571   ///
2572   /// This routine is used by the parser to resolve identifiers and help direct
2573   /// parsing. When the identifier cannot be found, this routine will attempt
2574   /// to correct the typo and classify based on the resulting name.
2575   ///
2576   /// \param S The scope in which we're performing name lookup.
2577   ///
2578   /// \param SS The nested-name-specifier that precedes the name.
2579   ///
2580   /// \param Name The identifier. If typo correction finds an alternative name,
2581   /// this pointer parameter will be updated accordingly.
2582   ///
2583   /// \param NameLoc The location of the identifier.
2584   ///
2585   /// \param NextToken The token following the identifier. Used to help
2586   /// disambiguate the name.
2587   ///
2588   /// \param CCC The correction callback, if typo correction is desired.
2589   NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
2590                                   IdentifierInfo *&Name, SourceLocation NameLoc,
2591                                   const Token &NextToken,
2592                                   CorrectionCandidateCallback *CCC = nullptr);
2593 
2594   /// Act on the result of classifying a name as an undeclared (ADL-only)
2595   /// non-type declaration.
2596   ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
2597                                                     SourceLocation NameLoc);
2598   /// Act on the result of classifying a name as an undeclared member of a
2599   /// dependent base class.
2600   ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
2601                                                    IdentifierInfo *Name,
2602                                                    SourceLocation NameLoc,
2603                                                    bool IsAddressOfOperand);
2604   /// Act on the result of classifying a name as a specific non-type
2605   /// declaration.
2606   ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
2607                                           NamedDecl *Found,
2608                                           SourceLocation NameLoc,
2609                                           const Token &NextToken);
2610   /// Act on the result of classifying a name as an overload set.
2611   ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet);
2612 
2613   /// Describes the detailed kind of a template name. Used in diagnostics.
2614   enum class TemplateNameKindForDiagnostics {
2615     ClassTemplate,
2616     FunctionTemplate,
2617     VarTemplate,
2618     AliasTemplate,
2619     TemplateTemplateParam,
2620     Concept,
2621     DependentTemplate
2622   };
2623   TemplateNameKindForDiagnostics
2624   getTemplateNameKindForDiagnostics(TemplateName Name);
2625 
2626   /// Determine whether it's plausible that E was intended to be a
2627   /// template-name.
mightBeIntendedToBeTemplateName(ExprResult E,bool & Dependent)2628   bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
2629     if (!getLangOpts().CPlusPlus || E.isInvalid())
2630       return false;
2631     Dependent = false;
2632     if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
2633       return !DRE->hasExplicitTemplateArgs();
2634     if (auto *ME = dyn_cast<MemberExpr>(E.get()))
2635       return !ME->hasExplicitTemplateArgs();
2636     Dependent = true;
2637     if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2638       return !DSDRE->hasExplicitTemplateArgs();
2639     if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2640       return !DSME->hasExplicitTemplateArgs();
2641     // Any additional cases recognized here should also be handled by
2642     // diagnoseExprIntendedAsTemplateName.
2643     return false;
2644   }
2645   void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
2646                                           SourceLocation Less,
2647                                           SourceLocation Greater);
2648 
2649   void warnOnReservedIdentifier(const NamedDecl *D);
2650 
2651   Decl *ActOnDeclarator(Scope *S, Declarator &D);
2652 
2653   NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
2654                               MultiTemplateParamsArg TemplateParameterLists);
2655   bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
2656                                        QualType &T, SourceLocation Loc,
2657                                        unsigned FailedFoldDiagID);
2658   void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
2659   bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
2660   bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
2661                                     DeclarationName Name, SourceLocation Loc,
2662                                     bool IsTemplateId);
2663   void
2664   diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2665                             SourceLocation FallbackLoc,
2666                             SourceLocation ConstQualLoc = SourceLocation(),
2667                             SourceLocation VolatileQualLoc = SourceLocation(),
2668                             SourceLocation RestrictQualLoc = SourceLocation(),
2669                             SourceLocation AtomicQualLoc = SourceLocation(),
2670                             SourceLocation UnalignedQualLoc = SourceLocation());
2671 
2672   static bool adjustContextForLocalExternDecl(DeclContext *&DC);
2673   void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2674   NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
2675                                     const LookupResult &R);
2676   NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
2677   NamedDecl *getShadowedDeclaration(const BindingDecl *D,
2678                                     const LookupResult &R);
2679   void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2680                    const LookupResult &R);
2681   void CheckShadow(Scope *S, VarDecl *D);
2682 
2683   /// Warn if 'E', which is an expression that is about to be modified, refers
2684   /// to a shadowing declaration.
2685   void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
2686 
2687   void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
2688 
2689 private:
2690   /// Map of current shadowing declarations to shadowed declarations. Warn if
2691   /// it looks like the user is trying to modify the shadowing declaration.
2692   llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2693 
2694 public:
2695   void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2696   void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2697   void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2698                                     TypedefNameDecl *NewTD);
2699   void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
2700   NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2701                                     TypeSourceInfo *TInfo,
2702                                     LookupResult &Previous);
2703   NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
2704                                   LookupResult &Previous, bool &Redeclaration);
2705   NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
2706                                      TypeSourceInfo *TInfo,
2707                                      LookupResult &Previous,
2708                                      MultiTemplateParamsArg TemplateParamLists,
2709                                      bool &AddToScope,
2710                                      ArrayRef<BindingDecl *> Bindings = None);
2711   NamedDecl *
2712   ActOnDecompositionDeclarator(Scope *S, Declarator &D,
2713                                MultiTemplateParamsArg TemplateParamLists);
2714   // Returns true if the variable declaration is a redeclaration
2715   bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
2716   void CheckVariableDeclarationType(VarDecl *NewVD);
2717   bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
2718                                      Expr *Init);
2719   void CheckCompleteVariableDeclaration(VarDecl *VD);
2720   void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
2721   void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
2722 
2723   NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2724                                      TypeSourceInfo *TInfo,
2725                                      LookupResult &Previous,
2726                                      MultiTemplateParamsArg TemplateParamLists,
2727                                      bool &AddToScope);
2728   bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
2729 
2730   enum class CheckConstexprKind {
2731     /// Diagnose issues that are non-constant or that are extensions.
2732     Diagnose,
2733     /// Identify whether this function satisfies the formal rules for constexpr
2734     /// functions in the current lanugage mode (with no extensions).
2735     CheckValid
2736   };
2737 
2738   bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
2739                                         CheckConstexprKind Kind);
2740 
2741   void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
2742   void FindHiddenVirtualMethods(CXXMethodDecl *MD,
2743                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2744   void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
2745                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2746   // Returns true if the function declaration is a redeclaration
2747   bool CheckFunctionDeclaration(Scope *S,
2748                                 FunctionDecl *NewFD, LookupResult &Previous,
2749                                 bool IsMemberSpecialization);
2750   bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
2751   bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
2752                                       QualType NewT, QualType OldT);
2753   void CheckMain(FunctionDecl *FD, const DeclSpec &D);
2754   void CheckMSVCRTEntryPoint(FunctionDecl *FD);
2755   Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
2756                                                    bool IsDefinition);
2757   void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
2758   Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
2759   ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
2760                                           SourceLocation Loc,
2761                                           QualType T);
2762   ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
2763                               SourceLocation NameLoc, IdentifierInfo *Name,
2764                               QualType T, TypeSourceInfo *TSInfo,
2765                               StorageClass SC);
2766   void ActOnParamDefaultArgument(Decl *param,
2767                                  SourceLocation EqualLoc,
2768                                  Expr *defarg);
2769   void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc,
2770                                          SourceLocation ArgLoc);
2771   void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
2772   ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2773                                          SourceLocation EqualLoc);
2774   void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2775                                SourceLocation EqualLoc);
2776 
2777   // Contexts where using non-trivial C union types can be disallowed. This is
2778   // passed to err_non_trivial_c_union_in_invalid_context.
2779   enum NonTrivialCUnionContext {
2780     // Function parameter.
2781     NTCUC_FunctionParam,
2782     // Function return.
2783     NTCUC_FunctionReturn,
2784     // Default-initialized object.
2785     NTCUC_DefaultInitializedObject,
2786     // Variable with automatic storage duration.
2787     NTCUC_AutoVar,
2788     // Initializer expression that might copy from another object.
2789     NTCUC_CopyInit,
2790     // Assignment.
2791     NTCUC_Assignment,
2792     // Compound literal.
2793     NTCUC_CompoundLiteral,
2794     // Block capture.
2795     NTCUC_BlockCapture,
2796     // lvalue-to-rvalue conversion of volatile type.
2797     NTCUC_LValueToRValueVolatile,
2798   };
2799 
2800   /// Emit diagnostics if the initializer or any of its explicit or
2801   /// implicitly-generated subexpressions require copying or
2802   /// default-initializing a type that is or contains a C union type that is
2803   /// non-trivial to copy or default-initialize.
2804   void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
2805 
2806   // These flags are passed to checkNonTrivialCUnion.
2807   enum NonTrivialCUnionKind {
2808     NTCUK_Init = 0x1,
2809     NTCUK_Destruct = 0x2,
2810     NTCUK_Copy = 0x4,
2811   };
2812 
2813   /// Emit diagnostics if a non-trivial C union type or a struct that contains
2814   /// a non-trivial C union is used in an invalid context.
2815   void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
2816                              NonTrivialCUnionContext UseContext,
2817                              unsigned NonTrivialKind);
2818 
2819   void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
2820   void ActOnUninitializedDecl(Decl *dcl);
2821   void ActOnInitializerError(Decl *Dcl);
2822 
2823   void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
2824   void ActOnCXXForRangeDecl(Decl *D);
2825   StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
2826                                         IdentifierInfo *Ident,
2827                                         ParsedAttributes &Attrs,
2828                                         SourceLocation AttrEnd);
2829   void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
2830   void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
2831   void CheckStaticLocalForDllExport(VarDecl *VD);
2832   void FinalizeDeclaration(Decl *D);
2833   DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
2834                                          ArrayRef<Decl *> Group);
2835   DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
2836 
2837   /// Should be called on all declarations that might have attached
2838   /// documentation comments.
2839   void ActOnDocumentableDecl(Decl *D);
2840   void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
2841 
2842   void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
2843                                        SourceLocation LocAfterDecls);
2844   void CheckForFunctionRedefinition(
2845       FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
2846       SkipBodyInfo *SkipBody = nullptr);
2847   Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
2848                                 MultiTemplateParamsArg TemplateParamLists,
2849                                 SkipBodyInfo *SkipBody = nullptr);
2850   Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
2851                                 SkipBodyInfo *SkipBody = nullptr);
2852   void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D);
2853   ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr);
2854   ExprResult ActOnRequiresClause(ExprResult ConstraintExpr);
2855   void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
isObjCMethodDecl(Decl * D)2856   bool isObjCMethodDecl(Decl *D) {
2857     return D && isa<ObjCMethodDecl>(D);
2858   }
2859 
2860   /// Determine whether we can delay parsing the body of a function or
2861   /// function template until it is used, assuming we don't care about emitting
2862   /// code for that function.
2863   ///
2864   /// This will be \c false if we may need the body of the function in the
2865   /// middle of parsing an expression (where it's impractical to switch to
2866   /// parsing a different function), for instance, if it's constexpr in C++11
2867   /// or has an 'auto' return type in C++14. These cases are essentially bugs.
2868   bool canDelayFunctionBody(const Declarator &D);
2869 
2870   /// Determine whether we can skip parsing the body of a function
2871   /// definition, assuming we don't care about analyzing its body or emitting
2872   /// code for that function.
2873   ///
2874   /// This will be \c false only if we may need the body of the function in
2875   /// order to parse the rest of the program (for instance, if it is
2876   /// \c constexpr in C++11 or has an 'auto' return type in C++14).
2877   bool canSkipFunctionBody(Decl *D);
2878 
2879   void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
2880   Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
2881   Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
2882   Decl *ActOnSkippedFunctionBody(Decl *Decl);
2883   void ActOnFinishInlineFunctionDef(FunctionDecl *D);
2884 
2885   /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
2886   /// attribute for which parsing is delayed.
2887   void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
2888 
2889   /// Diagnose any unused parameters in the given sequence of
2890   /// ParmVarDecl pointers.
2891   void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
2892 
2893   /// Diagnose whether the size of parameters or return value of a
2894   /// function or obj-c method definition is pass-by-value and larger than a
2895   /// specified threshold.
2896   void
2897   DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
2898                                          QualType ReturnTy, NamedDecl *D);
2899 
2900   void DiagnoseInvalidJumps(Stmt *Body);
2901   Decl *ActOnFileScopeAsmDecl(Expr *expr,
2902                               SourceLocation AsmLoc,
2903                               SourceLocation RParenLoc);
2904 
2905   /// Handle a C++11 empty-declaration and attribute-declaration.
2906   Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
2907                               SourceLocation SemiLoc);
2908 
2909   enum class ModuleDeclKind {
2910     Interface,      ///< 'export module X;'
2911     Implementation, ///< 'module X;'
2912   };
2913 
2914   /// The parser has processed a module-declaration that begins the definition
2915   /// of a module interface or implementation.
2916   DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
2917                                  SourceLocation ModuleLoc, ModuleDeclKind MDK,
2918                                  ModuleIdPath Path, bool IsFirstDecl);
2919 
2920   /// The parser has processed a global-module-fragment declaration that begins
2921   /// the definition of the global module fragment of the current module unit.
2922   /// \param ModuleLoc The location of the 'module' keyword.
2923   DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
2924 
2925   /// The parser has processed a private-module-fragment declaration that begins
2926   /// the definition of the private module fragment of the current module unit.
2927   /// \param ModuleLoc The location of the 'module' keyword.
2928   /// \param PrivateLoc The location of the 'private' keyword.
2929   DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
2930                                                 SourceLocation PrivateLoc);
2931 
2932   /// The parser has processed a module import declaration.
2933   ///
2934   /// \param StartLoc The location of the first token in the declaration. This
2935   ///        could be the location of an '@', 'export', or 'import'.
2936   /// \param ExportLoc The location of the 'export' keyword, if any.
2937   /// \param ImportLoc The location of the 'import' keyword.
2938   /// \param Path The module access path.
2939   DeclResult ActOnModuleImport(SourceLocation StartLoc,
2940                                SourceLocation ExportLoc,
2941                                SourceLocation ImportLoc, ModuleIdPath Path);
2942   DeclResult ActOnModuleImport(SourceLocation StartLoc,
2943                                SourceLocation ExportLoc,
2944                                SourceLocation ImportLoc, Module *M,
2945                                ModuleIdPath Path = {});
2946 
2947   /// The parser has processed a module import translated from a
2948   /// #include or similar preprocessing directive.
2949   void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2950   void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2951 
2952   /// The parsed has entered a submodule.
2953   void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
2954   /// The parser has left a submodule.
2955   void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
2956 
2957   /// Create an implicit import of the given module at the given
2958   /// source location, for error recovery, if possible.
2959   ///
2960   /// This routine is typically used when an entity found by name lookup
2961   /// is actually hidden within a module that we know about but the user
2962   /// has forgotten to import.
2963   void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
2964                                                   Module *Mod);
2965 
2966   /// Kinds of missing import. Note, the values of these enumerators correspond
2967   /// to %select values in diagnostics.
2968   enum class MissingImportKind {
2969     Declaration,
2970     Definition,
2971     DefaultArgument,
2972     ExplicitSpecialization,
2973     PartialSpecialization
2974   };
2975 
2976   /// Diagnose that the specified declaration needs to be visible but
2977   /// isn't, and suggest a module import that would resolve the problem.
2978   void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2979                              MissingImportKind MIK, bool Recover = true);
2980   void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2981                              SourceLocation DeclLoc, ArrayRef<Module *> Modules,
2982                              MissingImportKind MIK, bool Recover);
2983 
2984   Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
2985                              SourceLocation LBraceLoc);
2986   Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
2987                               SourceLocation RBraceLoc);
2988 
2989   /// We've found a use of a templated declaration that would trigger an
2990   /// implicit instantiation. Check that any relevant explicit specializations
2991   /// and partial specializations are visible, and diagnose if not.
2992   void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
2993 
2994   /// Retrieve a suitable printing policy for diagnostics.
getPrintingPolicy()2995   PrintingPolicy getPrintingPolicy() const {
2996     return getPrintingPolicy(Context, PP);
2997   }
2998 
2999   /// Retrieve a suitable printing policy for diagnostics.
3000   static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
3001                                           const Preprocessor &PP);
3002 
3003   /// Scope actions.
3004   void ActOnPopScope(SourceLocation Loc, Scope *S);
3005   void ActOnTranslationUnitScope(Scope *S);
3006 
3007   Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3008                                    RecordDecl *&AnonRecord);
3009   Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3010                                    MultiTemplateParamsArg TemplateParams,
3011                                    bool IsExplicitInstantiation,
3012                                    RecordDecl *&AnonRecord);
3013 
3014   Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
3015                                     AccessSpecifier AS,
3016                                     RecordDecl *Record,
3017                                     const PrintingPolicy &Policy);
3018 
3019   Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3020                                        RecordDecl *Record);
3021 
3022   /// Common ways to introduce type names without a tag for use in diagnostics.
3023   /// Keep in sync with err_tag_reference_non_tag.
3024   enum NonTagKind {
3025     NTK_NonStruct,
3026     NTK_NonClass,
3027     NTK_NonUnion,
3028     NTK_NonEnum,
3029     NTK_Typedef,
3030     NTK_TypeAlias,
3031     NTK_Template,
3032     NTK_TypeAliasTemplate,
3033     NTK_TemplateTemplateArgument,
3034   };
3035 
3036   /// Given a non-tag type declaration, returns an enum useful for indicating
3037   /// what kind of non-tag type this is.
3038   NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
3039 
3040   bool isAcceptableTagRedeclaration(const TagDecl *Previous,
3041                                     TagTypeKind NewTag, bool isDefinition,
3042                                     SourceLocation NewTagLoc,
3043                                     const IdentifierInfo *Name);
3044 
3045   enum TagUseKind {
3046     TUK_Reference,   // Reference to a tag:  'struct foo *X;'
3047     TUK_Declaration, // Fwd decl of a tag:   'struct foo;'
3048     TUK_Definition,  // Definition of a tag: 'struct foo { int X; } Y;'
3049     TUK_Friend       // Friend declaration:  'friend struct foo;'
3050   };
3051 
3052   Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
3053                  SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
3054                  SourceLocation NameLoc, const ParsedAttributesView &Attr,
3055                  AccessSpecifier AS, SourceLocation ModulePrivateLoc,
3056                  MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
3057                  bool &IsDependent, SourceLocation ScopedEnumKWLoc,
3058                  bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
3059                  bool IsTypeSpecifier, bool IsTemplateParamOrArg,
3060                  SkipBodyInfo *SkipBody = nullptr);
3061 
3062   Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
3063                                 unsigned TagSpec, SourceLocation TagLoc,
3064                                 CXXScopeSpec &SS, IdentifierInfo *Name,
3065                                 SourceLocation NameLoc,
3066                                 const ParsedAttributesView &Attr,
3067                                 MultiTemplateParamsArg TempParamLists);
3068 
3069   TypeResult ActOnDependentTag(Scope *S,
3070                                unsigned TagSpec,
3071                                TagUseKind TUK,
3072                                const CXXScopeSpec &SS,
3073                                IdentifierInfo *Name,
3074                                SourceLocation TagLoc,
3075                                SourceLocation NameLoc);
3076 
3077   void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
3078                  IdentifierInfo *ClassName,
3079                  SmallVectorImpl<Decl *> &Decls);
3080   Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
3081                    Declarator &D, Expr *BitfieldWidth);
3082 
3083   FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
3084                          Declarator &D, Expr *BitfieldWidth,
3085                          InClassInitStyle InitStyle,
3086                          AccessSpecifier AS);
3087   MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
3088                                    SourceLocation DeclStart, Declarator &D,
3089                                    Expr *BitfieldWidth,
3090                                    InClassInitStyle InitStyle,
3091                                    AccessSpecifier AS,
3092                                    const ParsedAttr &MSPropertyAttr);
3093 
3094   FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
3095                             TypeSourceInfo *TInfo,
3096                             RecordDecl *Record, SourceLocation Loc,
3097                             bool Mutable, Expr *BitfieldWidth,
3098                             InClassInitStyle InitStyle,
3099                             SourceLocation TSSL,
3100                             AccessSpecifier AS, NamedDecl *PrevDecl,
3101                             Declarator *D = nullptr);
3102 
3103   bool CheckNontrivialField(FieldDecl *FD);
3104   void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
3105 
3106   enum TrivialABIHandling {
3107     /// The triviality of a method unaffected by "trivial_abi".
3108     TAH_IgnoreTrivialABI,
3109 
3110     /// The triviality of a method affected by "trivial_abi".
3111     TAH_ConsiderTrivialABI
3112   };
3113 
3114   bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
3115                               TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
3116                               bool Diagnose = false);
3117 
3118   /// For a defaulted function, the kind of defaulted function that it is.
3119   class DefaultedFunctionKind {
3120     CXXSpecialMember SpecialMember : 8;
3121     DefaultedComparisonKind Comparison : 8;
3122 
3123   public:
DefaultedFunctionKind()3124     DefaultedFunctionKind()
3125         : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) {
3126     }
DefaultedFunctionKind(CXXSpecialMember CSM)3127     DefaultedFunctionKind(CXXSpecialMember CSM)
3128         : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {}
DefaultedFunctionKind(DefaultedComparisonKind Comp)3129     DefaultedFunctionKind(DefaultedComparisonKind Comp)
3130         : SpecialMember(CXXInvalid), Comparison(Comp) {}
3131 
isSpecialMember()3132     bool isSpecialMember() const { return SpecialMember != CXXInvalid; }
isComparison()3133     bool isComparison() const {
3134       return Comparison != DefaultedComparisonKind::None;
3135     }
3136 
3137     explicit operator bool() const {
3138       return isSpecialMember() || isComparison();
3139     }
3140 
asSpecialMember()3141     CXXSpecialMember asSpecialMember() const { return SpecialMember; }
asComparison()3142     DefaultedComparisonKind asComparison() const { return Comparison; }
3143 
3144     /// Get the index of this function kind for use in diagnostics.
getDiagnosticIndex()3145     unsigned getDiagnosticIndex() const {
3146       static_assert(CXXInvalid > CXXDestructor,
3147                     "invalid should have highest index");
3148       static_assert((unsigned)DefaultedComparisonKind::None == 0,
3149                     "none should be equal to zero");
3150       return SpecialMember + (unsigned)Comparison;
3151     }
3152   };
3153 
3154   DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
3155 
getSpecialMember(const CXXMethodDecl * MD)3156   CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) {
3157     return getDefaultedFunctionKind(MD).asSpecialMember();
3158   }
getDefaultedComparisonKind(const FunctionDecl * FD)3159   DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) {
3160     return getDefaultedFunctionKind(FD).asComparison();
3161   }
3162 
3163   void ActOnLastBitfield(SourceLocation DeclStart,
3164                          SmallVectorImpl<Decl *> &AllIvarDecls);
3165   Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
3166                   Declarator &D, Expr *BitfieldWidth,
3167                   tok::ObjCKeywordKind visibility);
3168 
3169   // This is used for both record definitions and ObjC interface declarations.
3170   void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
3171                    ArrayRef<Decl *> Fields, SourceLocation LBrac,
3172                    SourceLocation RBrac, const ParsedAttributesView &AttrList);
3173 
3174   /// ActOnTagStartDefinition - Invoked when we have entered the
3175   /// scope of a tag's definition (e.g., for an enumeration, class,
3176   /// struct, or union).
3177   void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
3178 
3179   /// Perform ODR-like check for C/ObjC when merging tag types from modules.
3180   /// Differently from C++, actually parse the body and reject / error out
3181   /// in case of a structural mismatch.
3182   bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
3183                                 SkipBodyInfo &SkipBody);
3184 
3185   typedef void *SkippedDefinitionContext;
3186 
3187   /// Invoked when we enter a tag definition that we're skipping.
3188   SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
3189 
3190   Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
3191 
3192   /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
3193   /// C++ record definition's base-specifiers clause and are starting its
3194   /// member declarations.
3195   void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
3196                                        SourceLocation FinalLoc,
3197                                        bool IsFinalSpelledSealed,
3198                                        bool IsAbstract,
3199                                        SourceLocation LBraceLoc);
3200 
3201   /// ActOnTagFinishDefinition - Invoked once we have finished parsing
3202   /// the definition of a tag (enumeration, class, struct, or union).
3203   void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
3204                                 SourceRange BraceRange);
3205 
3206   void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
3207 
3208   void ActOnObjCContainerFinishDefinition();
3209 
3210   /// Invoked when we must temporarily exit the objective-c container
3211   /// scope for parsing/looking-up C constructs.
3212   ///
3213   /// Must be followed by a call to \see ActOnObjCReenterContainerContext
3214   void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
3215   void ActOnObjCReenterContainerContext(DeclContext *DC);
3216 
3217   /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
3218   /// error parsing the definition of a tag.
3219   void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
3220 
3221   EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
3222                                       EnumConstantDecl *LastEnumConst,
3223                                       SourceLocation IdLoc,
3224                                       IdentifierInfo *Id,
3225                                       Expr *val);
3226   bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
3227   bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
3228                               QualType EnumUnderlyingTy, bool IsFixed,
3229                               const EnumDecl *Prev);
3230 
3231   /// Determine whether the body of an anonymous enumeration should be skipped.
3232   /// \param II The name of the first enumerator.
3233   SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
3234                                       SourceLocation IILoc);
3235 
3236   Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
3237                           SourceLocation IdLoc, IdentifierInfo *Id,
3238                           const ParsedAttributesView &Attrs,
3239                           SourceLocation EqualLoc, Expr *Val);
3240   void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
3241                      Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
3242                      const ParsedAttributesView &Attr);
3243 
3244   /// Set the current declaration context until it gets popped.
3245   void PushDeclContext(Scope *S, DeclContext *DC);
3246   void PopDeclContext();
3247 
3248   /// EnterDeclaratorContext - Used when we must lookup names in the context
3249   /// of a declarator's nested name specifier.
3250   void EnterDeclaratorContext(Scope *S, DeclContext *DC);
3251   void ExitDeclaratorContext(Scope *S);
3252 
3253   /// Enter a template parameter scope, after it's been associated with a particular
3254   /// DeclContext. Causes lookup within the scope to chain through enclosing contexts
3255   /// in the correct order.
3256   void EnterTemplatedContext(Scope *S, DeclContext *DC);
3257 
3258   /// Push the parameters of D, which must be a function, into scope.
3259   void ActOnReenterFunctionContext(Scope* S, Decl* D);
3260   void ActOnExitFunctionContext();
3261 
3262   DeclContext *getFunctionLevelDeclContext();
3263 
3264   /// getCurFunctionDecl - If inside of a function body, this returns a pointer
3265   /// to the function decl for the function being parsed.  If we're currently
3266   /// in a 'block', this returns the containing context.
3267   FunctionDecl *getCurFunctionDecl();
3268 
3269   /// getCurMethodDecl - If inside of a method body, this returns a pointer to
3270   /// the method decl for the method being parsed.  If we're currently
3271   /// in a 'block', this returns the containing context.
3272   ObjCMethodDecl *getCurMethodDecl();
3273 
3274   /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
3275   /// or C function we're in, otherwise return null.  If we're currently
3276   /// in a 'block', this returns the containing context.
3277   NamedDecl *getCurFunctionOrMethodDecl();
3278 
3279   /// Add this decl to the scope shadowed decl chains.
3280   void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
3281 
3282   /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
3283   /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
3284   /// true if 'D' belongs to the given declaration context.
3285   ///
3286   /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
3287   ///        enclosing namespace set of the context, rather than contained
3288   ///        directly within it.
3289   bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
3290                      bool AllowInlineNamespace = false);
3291 
3292   /// Finds the scope corresponding to the given decl context, if it
3293   /// happens to be an enclosing scope.  Otherwise return NULL.
3294   static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
3295 
3296   /// Subroutines of ActOnDeclarator().
3297   TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
3298                                 TypeSourceInfo *TInfo);
3299   bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
3300 
3301   /// Describes the kind of merge to perform for availability
3302   /// attributes (including "deprecated", "unavailable", and "availability").
3303   enum AvailabilityMergeKind {
3304     /// Don't merge availability attributes at all.
3305     AMK_None,
3306     /// Merge availability attributes for a redeclaration, which requires
3307     /// an exact match.
3308     AMK_Redeclaration,
3309     /// Merge availability attributes for an override, which requires
3310     /// an exact match or a weakening of constraints.
3311     AMK_Override,
3312     /// Merge availability attributes for an implementation of
3313     /// a protocol requirement.
3314     AMK_ProtocolImplementation,
3315     /// Merge availability attributes for an implementation of
3316     /// an optional protocol requirement.
3317     AMK_OptionalProtocolImplementation
3318   };
3319 
3320   /// Describes the kind of priority given to an availability attribute.
3321   ///
3322   /// The sum of priorities deteremines the final priority of the attribute.
3323   /// The final priority determines how the attribute will be merged.
3324   /// An attribute with a lower priority will always remove higher priority
3325   /// attributes for the specified platform when it is being applied. An
3326   /// attribute with a higher priority will not be applied if the declaration
3327   /// already has an availability attribute with a lower priority for the
3328   /// specified platform. The final prirority values are not expected to match
3329   /// the values in this enumeration, but instead should be treated as a plain
3330   /// integer value. This enumeration just names the priority weights that are
3331   /// used to calculate that final vaue.
3332   enum AvailabilityPriority : int {
3333     /// The availability attribute was specified explicitly next to the
3334     /// declaration.
3335     AP_Explicit = 0,
3336 
3337     /// The availability attribute was applied using '#pragma clang attribute'.
3338     AP_PragmaClangAttribute = 1,
3339 
3340     /// The availability attribute for a specific platform was inferred from
3341     /// an availability attribute for another platform.
3342     AP_InferredFromOtherPlatform = 2
3343   };
3344 
3345   /// Attribute merging methods. Return true if a new attribute was added.
3346   AvailabilityAttr *
3347   mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
3348                         IdentifierInfo *Platform, bool Implicit,
3349                         VersionTuple Introduced, VersionTuple Deprecated,
3350                         VersionTuple Obsoleted, bool IsUnavailable,
3351                         StringRef Message, bool IsStrict, StringRef Replacement,
3352                         AvailabilityMergeKind AMK, int Priority);
3353   TypeVisibilityAttr *
3354   mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3355                           TypeVisibilityAttr::VisibilityType Vis);
3356   VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3357                                       VisibilityAttr::VisibilityType Vis);
3358   UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
3359                           StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
3360   DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
3361   DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
3362   MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
3363                                             const AttributeCommonInfo &CI,
3364                                             bool BestCase,
3365                                             MSInheritanceModel Model);
3366   ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
3367                             StringRef NewUserDiagnostic);
3368   FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
3369                               IdentifierInfo *Format, int FormatIdx,
3370                               int FirstArg);
3371   SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
3372                                 StringRef Name);
3373   CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
3374                                 StringRef Name);
3375   AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
3376                                           const AttributeCommonInfo &CI,
3377                                           const IdentifierInfo *Ident);
3378   MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
3379   SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
3380                                     StringRef Name);
3381   OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
3382                                           const AttributeCommonInfo &CI);
3383   InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
3384   InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
3385                                                 const InternalLinkageAttr &AL);
3386   WebAssemblyImportNameAttr *mergeImportNameAttr(
3387       Decl *D, const WebAssemblyImportNameAttr &AL);
3388   WebAssemblyImportModuleAttr *mergeImportModuleAttr(
3389       Decl *D, const WebAssemblyImportModuleAttr &AL);
3390   EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
3391   EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
3392                                               const EnforceTCBLeafAttr &AL);
3393   BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL);
3394 
3395   void mergeDeclAttributes(NamedDecl *New, Decl *Old,
3396                            AvailabilityMergeKind AMK = AMK_Redeclaration);
3397   void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
3398                             LookupResult &OldDecls);
3399   bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
3400                          bool MergeTypeWithOld);
3401   bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3402                                     Scope *S, bool MergeTypeWithOld);
3403   void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
3404   void MergeVarDecl(VarDecl *New, LookupResult &Previous);
3405   void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
3406   void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
3407   bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
3408   void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
3409   bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
3410 
3411   // AssignmentAction - This is used by all the assignment diagnostic functions
3412   // to represent what is actually causing the operation
3413   enum AssignmentAction {
3414     AA_Assigning,
3415     AA_Passing,
3416     AA_Returning,
3417     AA_Converting,
3418     AA_Initializing,
3419     AA_Sending,
3420     AA_Casting,
3421     AA_Passing_CFAudited
3422   };
3423 
3424   /// C++ Overloading.
3425   enum OverloadKind {
3426     /// This is a legitimate overload: the existing declarations are
3427     /// functions or function templates with different signatures.
3428     Ovl_Overload,
3429 
3430     /// This is not an overload because the signature exactly matches
3431     /// an existing declaration.
3432     Ovl_Match,
3433 
3434     /// This is not an overload because the lookup results contain a
3435     /// non-function.
3436     Ovl_NonFunction
3437   };
3438   OverloadKind CheckOverload(Scope *S,
3439                              FunctionDecl *New,
3440                              const LookupResult &OldDecls,
3441                              NamedDecl *&OldDecl,
3442                              bool IsForUsingDecl);
3443   bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
3444                   bool ConsiderCudaAttrs = true,
3445                   bool ConsiderRequiresClauses = true);
3446 
3447   enum class AllowedExplicit {
3448     /// Allow no explicit functions to be used.
3449     None,
3450     /// Allow explicit conversion functions but not explicit constructors.
3451     Conversions,
3452     /// Allow both explicit conversion functions and explicit constructors.
3453     All
3454   };
3455 
3456   ImplicitConversionSequence
3457   TryImplicitConversion(Expr *From, QualType ToType,
3458                         bool SuppressUserConversions,
3459                         AllowedExplicit AllowExplicit,
3460                         bool InOverloadResolution,
3461                         bool CStyle,
3462                         bool AllowObjCWritebackConversion);
3463 
3464   bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
3465   bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
3466   bool IsComplexPromotion(QualType FromType, QualType ToType);
3467   bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
3468                            bool InOverloadResolution,
3469                            QualType& ConvertedType, bool &IncompatibleObjC);
3470   bool isObjCPointerConversion(QualType FromType, QualType ToType,
3471                                QualType& ConvertedType, bool &IncompatibleObjC);
3472   bool isObjCWritebackConversion(QualType FromType, QualType ToType,
3473                                  QualType &ConvertedType);
3474   bool IsBlockPointerConversion(QualType FromType, QualType ToType,
3475                                 QualType& ConvertedType);
3476   bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3477                                   const FunctionProtoType *NewType,
3478                                   unsigned *ArgPos = nullptr);
3479   void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
3480                                   QualType FromType, QualType ToType);
3481 
3482   void maybeExtendBlockObject(ExprResult &E);
3483   CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
3484   bool CheckPointerConversion(Expr *From, QualType ToType,
3485                               CastKind &Kind,
3486                               CXXCastPath& BasePath,
3487                               bool IgnoreBaseAccess,
3488                               bool Diagnose = true);
3489   bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
3490                                  bool InOverloadResolution,
3491                                  QualType &ConvertedType);
3492   bool CheckMemberPointerConversion(Expr *From, QualType ToType,
3493                                     CastKind &Kind,
3494                                     CXXCastPath &BasePath,
3495                                     bool IgnoreBaseAccess);
3496   bool IsQualificationConversion(QualType FromType, QualType ToType,
3497                                  bool CStyle, bool &ObjCLifetimeConversion);
3498   bool IsFunctionConversion(QualType FromType, QualType ToType,
3499                             QualType &ResultTy);
3500   bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
3501   bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
3502 
3503   bool CanPerformAggregateInitializationForOverloadResolution(
3504       const InitializedEntity &Entity, InitListExpr *From);
3505 
3506   bool IsStringInit(Expr *Init, const ArrayType *AT);
3507 
3508   bool CanPerformCopyInitialization(const InitializedEntity &Entity,
3509                                     ExprResult Init);
3510   ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
3511                                        SourceLocation EqualLoc,
3512                                        ExprResult Init,
3513                                        bool TopLevelOfInitList = false,
3514                                        bool AllowExplicit = false);
3515   ExprResult PerformObjectArgumentInitialization(Expr *From,
3516                                                  NestedNameSpecifier *Qualifier,
3517                                                  NamedDecl *FoundDecl,
3518                                                  CXXMethodDecl *Method);
3519 
3520   /// Check that the lifetime of the initializer (and its subobjects) is
3521   /// sufficient for initializing the entity, and perform lifetime extension
3522   /// (when permitted) if not.
3523   void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
3524 
3525   ExprResult PerformContextuallyConvertToBool(Expr *From);
3526   ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
3527 
3528   /// Contexts in which a converted constant expression is required.
3529   enum CCEKind {
3530     CCEK_CaseValue,    ///< Expression in a case label.
3531     CCEK_Enumerator,   ///< Enumerator value with fixed underlying type.
3532     CCEK_TemplateArg,  ///< Value of a non-type template parameter.
3533     CCEK_ArrayBound,   ///< Array bound in array declarator or new-expression.
3534     CCEK_ExplicitBool, ///< Condition in an explicit(bool) specifier.
3535     CCEK_Noexcept      ///< Condition in a noexcept(bool) specifier.
3536   };
3537   ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
3538                                               llvm::APSInt &Value, CCEKind CCE);
3539   ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
3540                                               APValue &Value, CCEKind CCE,
3541                                               NamedDecl *Dest = nullptr);
3542 
3543   /// Abstract base class used to perform a contextual implicit
3544   /// conversion from an expression to any type passing a filter.
3545   class ContextualImplicitConverter {
3546   public:
3547     bool Suppress;
3548     bool SuppressConversion;
3549 
3550     ContextualImplicitConverter(bool Suppress = false,
3551                                 bool SuppressConversion = false)
Suppress(Suppress)3552         : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
3553 
3554     /// Determine whether the specified type is a valid destination type
3555     /// for this conversion.
3556     virtual bool match(QualType T) = 0;
3557 
3558     /// Emits a diagnostic complaining that the expression does not have
3559     /// integral or enumeration type.
3560     virtual SemaDiagnosticBuilder
3561     diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
3562 
3563     /// Emits a diagnostic when the expression has incomplete class type.
3564     virtual SemaDiagnosticBuilder
3565     diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
3566 
3567     /// Emits a diagnostic when the only matching conversion function
3568     /// is explicit.
3569     virtual SemaDiagnosticBuilder diagnoseExplicitConv(
3570         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3571 
3572     /// Emits a note for the explicit conversion function.
3573     virtual SemaDiagnosticBuilder
3574     noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3575 
3576     /// Emits a diagnostic when there are multiple possible conversion
3577     /// functions.
3578     virtual SemaDiagnosticBuilder
3579     diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
3580 
3581     /// Emits a note for one of the candidate conversions.
3582     virtual SemaDiagnosticBuilder
3583     noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3584 
3585     /// Emits a diagnostic when we picked a conversion function
3586     /// (for cases when we are not allowed to pick a conversion function).
3587     virtual SemaDiagnosticBuilder diagnoseConversion(
3588         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3589 
~ContextualImplicitConverter()3590     virtual ~ContextualImplicitConverter() {}
3591   };
3592 
3593   class ICEConvertDiagnoser : public ContextualImplicitConverter {
3594     bool AllowScopedEnumerations;
3595 
3596   public:
ICEConvertDiagnoser(bool AllowScopedEnumerations,bool Suppress,bool SuppressConversion)3597     ICEConvertDiagnoser(bool AllowScopedEnumerations,
3598                         bool Suppress, bool SuppressConversion)
3599         : ContextualImplicitConverter(Suppress, SuppressConversion),
3600           AllowScopedEnumerations(AllowScopedEnumerations) {}
3601 
3602     /// Match an integral or (possibly scoped) enumeration type.
3603     bool match(QualType T) override;
3604 
3605     SemaDiagnosticBuilder
diagnoseNoMatch(Sema & S,SourceLocation Loc,QualType T)3606     diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
3607       return diagnoseNotInt(S, Loc, T);
3608     }
3609 
3610     /// Emits a diagnostic complaining that the expression does not have
3611     /// integral or enumeration type.
3612     virtual SemaDiagnosticBuilder
3613     diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
3614   };
3615 
3616   /// Perform a contextual implicit conversion.
3617   ExprResult PerformContextualImplicitConversion(
3618       SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
3619 
3620 
3621   enum ObjCSubscriptKind {
3622     OS_Array,
3623     OS_Dictionary,
3624     OS_Error
3625   };
3626   ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
3627 
3628   // Note that LK_String is intentionally after the other literals, as
3629   // this is used for diagnostics logic.
3630   enum ObjCLiteralKind {
3631     LK_Array,
3632     LK_Dictionary,
3633     LK_Numeric,
3634     LK_Boxed,
3635     LK_String,
3636     LK_Block,
3637     LK_None
3638   };
3639   ObjCLiteralKind CheckLiteralKind(Expr *FromE);
3640 
3641   ExprResult PerformObjectMemberConversion(Expr *From,
3642                                            NestedNameSpecifier *Qualifier,
3643                                            NamedDecl *FoundDecl,
3644                                            NamedDecl *Member);
3645 
3646   // Members have to be NamespaceDecl* or TranslationUnitDecl*.
3647   // TODO: make this is a typesafe union.
3648   typedef llvm::SmallSetVector<DeclContext   *, 16> AssociatedNamespaceSet;
3649   typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
3650 
3651   using ADLCallKind = CallExpr::ADLCallKind;
3652 
3653   void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl,
3654                             ArrayRef<Expr *> Args,
3655                             OverloadCandidateSet &CandidateSet,
3656                             bool SuppressUserConversions = false,
3657                             bool PartialOverloading = false,
3658                             bool AllowExplicit = true,
3659                             bool AllowExplicitConversion = false,
3660                             ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3661                             ConversionSequenceList EarlyConversions = None,
3662                             OverloadCandidateParamOrder PO = {});
3663   void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
3664                       ArrayRef<Expr *> Args,
3665                       OverloadCandidateSet &CandidateSet,
3666                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3667                       bool SuppressUserConversions = false,
3668                       bool PartialOverloading = false,
3669                       bool FirstArgumentIsBase = false);
3670   void AddMethodCandidate(DeclAccessPair FoundDecl,
3671                           QualType ObjectType,
3672                           Expr::Classification ObjectClassification,
3673                           ArrayRef<Expr *> Args,
3674                           OverloadCandidateSet& CandidateSet,
3675                           bool SuppressUserConversion = false,
3676                           OverloadCandidateParamOrder PO = {});
3677   void AddMethodCandidate(CXXMethodDecl *Method,
3678                           DeclAccessPair FoundDecl,
3679                           CXXRecordDecl *ActingContext, QualType ObjectType,
3680                           Expr::Classification ObjectClassification,
3681                           ArrayRef<Expr *> Args,
3682                           OverloadCandidateSet& CandidateSet,
3683                           bool SuppressUserConversions = false,
3684                           bool PartialOverloading = false,
3685                           ConversionSequenceList EarlyConversions = None,
3686                           OverloadCandidateParamOrder PO = {});
3687   void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
3688                                   DeclAccessPair FoundDecl,
3689                                   CXXRecordDecl *ActingContext,
3690                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
3691                                   QualType ObjectType,
3692                                   Expr::Classification ObjectClassification,
3693                                   ArrayRef<Expr *> Args,
3694                                   OverloadCandidateSet& CandidateSet,
3695                                   bool SuppressUserConversions = false,
3696                                   bool PartialOverloading = false,
3697                                   OverloadCandidateParamOrder PO = {});
3698   void AddTemplateOverloadCandidate(
3699       FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3700       TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
3701       OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
3702       bool PartialOverloading = false, bool AllowExplicit = true,
3703       ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3704       OverloadCandidateParamOrder PO = {});
3705   bool CheckNonDependentConversions(
3706       FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
3707       ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
3708       ConversionSequenceList &Conversions, bool SuppressUserConversions,
3709       CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
3710       Expr::Classification ObjectClassification = {},
3711       OverloadCandidateParamOrder PO = {});
3712   void AddConversionCandidate(
3713       CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
3714       CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3715       OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3716       bool AllowExplicit, bool AllowResultConversion = true);
3717   void AddTemplateConversionCandidate(
3718       FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3719       CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3720       OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3721       bool AllowExplicit, bool AllowResultConversion = true);
3722   void AddSurrogateCandidate(CXXConversionDecl *Conversion,
3723                              DeclAccessPair FoundDecl,
3724                              CXXRecordDecl *ActingContext,
3725                              const FunctionProtoType *Proto,
3726                              Expr *Object, ArrayRef<Expr *> Args,
3727                              OverloadCandidateSet& CandidateSet);
3728   void AddNonMemberOperatorCandidates(
3729       const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
3730       OverloadCandidateSet &CandidateSet,
3731       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
3732   void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3733                                    SourceLocation OpLoc, ArrayRef<Expr *> Args,
3734                                    OverloadCandidateSet &CandidateSet,
3735                                    OverloadCandidateParamOrder PO = {});
3736   void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
3737                            OverloadCandidateSet& CandidateSet,
3738                            bool IsAssignmentOperator = false,
3739                            unsigned NumContextualBoolArguments = 0);
3740   void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
3741                                     SourceLocation OpLoc, ArrayRef<Expr *> Args,
3742                                     OverloadCandidateSet& CandidateSet);
3743   void AddArgumentDependentLookupCandidates(DeclarationName Name,
3744                                             SourceLocation Loc,
3745                                             ArrayRef<Expr *> Args,
3746                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
3747                                             OverloadCandidateSet& CandidateSet,
3748                                             bool PartialOverloading = false);
3749 
3750   // Emit as a 'note' the specific overload candidate
3751   void NoteOverloadCandidate(
3752       NamedDecl *Found, FunctionDecl *Fn,
3753       OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(),
3754       QualType DestType = QualType(), bool TakingAddress = false);
3755 
3756   // Emit as a series of 'note's all template and non-templates identified by
3757   // the expression Expr
3758   void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
3759                                  bool TakingAddress = false);
3760 
3761   /// Check the enable_if expressions on the given function. Returns the first
3762   /// failing attribute, or NULL if they were all successful.
3763   EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc,
3764                               ArrayRef<Expr *> Args,
3765                               bool MissingImplicitThis = false);
3766 
3767   /// Find the failed Boolean condition within a given Boolean
3768   /// constant expression, and describe it with a string.
3769   std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
3770 
3771   /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3772   /// non-ArgDependent DiagnoseIfAttrs.
3773   ///
3774   /// Argument-dependent diagnose_if attributes should be checked each time a
3775   /// function is used as a direct callee of a function call.
3776   ///
3777   /// Returns true if any errors were emitted.
3778   bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
3779                                            const Expr *ThisArg,
3780                                            ArrayRef<const Expr *> Args,
3781                                            SourceLocation Loc);
3782 
3783   /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3784   /// ArgDependent DiagnoseIfAttrs.
3785   ///
3786   /// Argument-independent diagnose_if attributes should be checked on every use
3787   /// of a function.
3788   ///
3789   /// Returns true if any errors were emitted.
3790   bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
3791                                              SourceLocation Loc);
3792 
3793   /// Returns whether the given function's address can be taken or not,
3794   /// optionally emitting a diagnostic if the address can't be taken.
3795   ///
3796   /// Returns false if taking the address of the function is illegal.
3797   bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
3798                                          bool Complain = false,
3799                                          SourceLocation Loc = SourceLocation());
3800 
3801   // [PossiblyAFunctionType]  -->   [Return]
3802   // NonFunctionType --> NonFunctionType
3803   // R (A) --> R(A)
3804   // R (*)(A) --> R (A)
3805   // R (&)(A) --> R (A)
3806   // R (S::*)(A) --> R (A)
3807   QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
3808 
3809   FunctionDecl *
3810   ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
3811                                      QualType TargetType,
3812                                      bool Complain,
3813                                      DeclAccessPair &Found,
3814                                      bool *pHadMultipleCandidates = nullptr);
3815 
3816   FunctionDecl *
3817   resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
3818 
3819   bool resolveAndFixAddressOfSingleOverloadCandidate(
3820       ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
3821 
3822   FunctionDecl *
3823   ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
3824                                               bool Complain = false,
3825                                               DeclAccessPair *Found = nullptr);
3826 
3827   bool ResolveAndFixSingleFunctionTemplateSpecialization(
3828                       ExprResult &SrcExpr,
3829                       bool DoFunctionPointerConverion = false,
3830                       bool Complain = false,
3831                       SourceRange OpRangeForComplaining = SourceRange(),
3832                       QualType DestTypeForComplaining = QualType(),
3833                       unsigned DiagIDForComplaining = 0);
3834 
3835 
3836   Expr *FixOverloadedFunctionReference(Expr *E,
3837                                        DeclAccessPair FoundDecl,
3838                                        FunctionDecl *Fn);
3839   ExprResult FixOverloadedFunctionReference(ExprResult,
3840                                             DeclAccessPair FoundDecl,
3841                                             FunctionDecl *Fn);
3842 
3843   void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
3844                                    ArrayRef<Expr *> Args,
3845                                    OverloadCandidateSet &CandidateSet,
3846                                    bool PartialOverloading = false);
3847   void AddOverloadedCallCandidates(
3848       LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
3849       ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet);
3850 
3851   // An enum used to represent the different possible results of building a
3852   // range-based for loop.
3853   enum ForRangeStatus {
3854     FRS_Success,
3855     FRS_NoViableFunction,
3856     FRS_DiagnosticIssued
3857   };
3858 
3859   ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
3860                                            SourceLocation RangeLoc,
3861                                            const DeclarationNameInfo &NameInfo,
3862                                            LookupResult &MemberLookup,
3863                                            OverloadCandidateSet *CandidateSet,
3864                                            Expr *Range, ExprResult *CallExpr);
3865 
3866   ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
3867                                      UnresolvedLookupExpr *ULE,
3868                                      SourceLocation LParenLoc,
3869                                      MultiExprArg Args,
3870                                      SourceLocation RParenLoc,
3871                                      Expr *ExecConfig,
3872                                      bool AllowTypoCorrection=true,
3873                                      bool CalleesAddressIsTaken=false);
3874 
3875   bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
3876                               MultiExprArg Args, SourceLocation RParenLoc,
3877                               OverloadCandidateSet *CandidateSet,
3878                               ExprResult *Result);
3879 
3880   ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
3881                                         NestedNameSpecifierLoc NNSLoc,
3882                                         DeclarationNameInfo DNI,
3883                                         const UnresolvedSetImpl &Fns,
3884                                         bool PerformADL = true);
3885 
3886   ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
3887                                      UnaryOperatorKind Opc,
3888                                      const UnresolvedSetImpl &Fns,
3889                                      Expr *input, bool RequiresADL = true);
3890 
3891   void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
3892                              OverloadedOperatorKind Op,
3893                              const UnresolvedSetImpl &Fns,
3894                              ArrayRef<Expr *> Args, bool RequiresADL = true);
3895   ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
3896                                    BinaryOperatorKind Opc,
3897                                    const UnresolvedSetImpl &Fns,
3898                                    Expr *LHS, Expr *RHS,
3899                                    bool RequiresADL = true,
3900                                    bool AllowRewrittenCandidates = true,
3901                                    FunctionDecl *DefaultedFn = nullptr);
3902   ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc,
3903                                                 const UnresolvedSetImpl &Fns,
3904                                                 Expr *LHS, Expr *RHS,
3905                                                 FunctionDecl *DefaultedFn);
3906 
3907   ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
3908                                                 SourceLocation RLoc,
3909                                                 Expr *Base,Expr *Idx);
3910 
3911   ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
3912                                        SourceLocation LParenLoc,
3913                                        MultiExprArg Args,
3914                                        SourceLocation RParenLoc,
3915                                        Expr *ExecConfig = nullptr,
3916                                        bool IsExecConfig = false,
3917                                        bool AllowRecovery = false);
3918   ExprResult
3919   BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
3920                                MultiExprArg Args,
3921                                SourceLocation RParenLoc);
3922 
3923   ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
3924                                       SourceLocation OpLoc,
3925                                       bool *NoArrowOperatorFound = nullptr);
3926 
3927   /// CheckCallReturnType - Checks that a call expression's return type is
3928   /// complete. Returns true on failure. The location passed in is the location
3929   /// that best represents the call.
3930   bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
3931                            CallExpr *CE, FunctionDecl *FD);
3932 
3933   /// Helpers for dealing with blocks and functions.
3934   bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
3935                                 bool CheckParameterNames);
3936   void CheckCXXDefaultArguments(FunctionDecl *FD);
3937   void CheckExtraCXXDefaultArguments(Declarator &D);
3938   Scope *getNonFieldDeclScope(Scope *S);
3939 
3940   /// \name Name lookup
3941   ///
3942   /// These routines provide name lookup that is used during semantic
3943   /// analysis to resolve the various kinds of names (identifiers,
3944   /// overloaded operator names, constructor names, etc.) into zero or
3945   /// more declarations within a particular scope. The major entry
3946   /// points are LookupName, which performs unqualified name lookup,
3947   /// and LookupQualifiedName, which performs qualified name lookup.
3948   ///
3949   /// All name lookup is performed based on some specific criteria,
3950   /// which specify what names will be visible to name lookup and how
3951   /// far name lookup should work. These criteria are important both
3952   /// for capturing language semantics (certain lookups will ignore
3953   /// certain names, for example) and for performance, since name
3954   /// lookup is often a bottleneck in the compilation of C++. Name
3955   /// lookup criteria is specified via the LookupCriteria enumeration.
3956   ///
3957   /// The results of name lookup can vary based on the kind of name
3958   /// lookup performed, the current language, and the translation
3959   /// unit. In C, for example, name lookup will either return nothing
3960   /// (no entity found) or a single declaration. In C++, name lookup
3961   /// can additionally refer to a set of overloaded functions or
3962   /// result in an ambiguity. All of the possible results of name
3963   /// lookup are captured by the LookupResult class, which provides
3964   /// the ability to distinguish among them.
3965   //@{
3966 
3967   /// Describes the kind of name lookup to perform.
3968   enum LookupNameKind {
3969     /// Ordinary name lookup, which finds ordinary names (functions,
3970     /// variables, typedefs, etc.) in C and most kinds of names
3971     /// (functions, variables, members, types, etc.) in C++.
3972     LookupOrdinaryName = 0,
3973     /// Tag name lookup, which finds the names of enums, classes,
3974     /// structs, and unions.
3975     LookupTagName,
3976     /// Label name lookup.
3977     LookupLabel,
3978     /// Member name lookup, which finds the names of
3979     /// class/struct/union members.
3980     LookupMemberName,
3981     /// Look up of an operator name (e.g., operator+) for use with
3982     /// operator overloading. This lookup is similar to ordinary name
3983     /// lookup, but will ignore any declarations that are class members.
3984     LookupOperatorName,
3985     /// Look up a name following ~ in a destructor name. This is an ordinary
3986     /// lookup, but prefers tags to typedefs.
3987     LookupDestructorName,
3988     /// Look up of a name that precedes the '::' scope resolution
3989     /// operator in C++. This lookup completely ignores operator, object,
3990     /// function, and enumerator names (C++ [basic.lookup.qual]p1).
3991     LookupNestedNameSpecifierName,
3992     /// Look up a namespace name within a C++ using directive or
3993     /// namespace alias definition, ignoring non-namespace names (C++
3994     /// [basic.lookup.udir]p1).
3995     LookupNamespaceName,
3996     /// Look up all declarations in a scope with the given name,
3997     /// including resolved using declarations.  This is appropriate
3998     /// for checking redeclarations for a using declaration.
3999     LookupUsingDeclName,
4000     /// Look up an ordinary name that is going to be redeclared as a
4001     /// name with linkage. This lookup ignores any declarations that
4002     /// are outside of the current scope unless they have linkage. See
4003     /// C99 6.2.2p4-5 and C++ [basic.link]p6.
4004     LookupRedeclarationWithLinkage,
4005     /// Look up a friend of a local class. This lookup does not look
4006     /// outside the innermost non-class scope. See C++11 [class.friend]p11.
4007     LookupLocalFriendName,
4008     /// Look up the name of an Objective-C protocol.
4009     LookupObjCProtocolName,
4010     /// Look up implicit 'self' parameter of an objective-c method.
4011     LookupObjCImplicitSelfParam,
4012     /// Look up the name of an OpenMP user-defined reduction operation.
4013     LookupOMPReductionName,
4014     /// Look up the name of an OpenMP user-defined mapper.
4015     LookupOMPMapperName,
4016     /// Look up any declaration with any name.
4017     LookupAnyName
4018   };
4019 
4020   /// Specifies whether (or how) name lookup is being performed for a
4021   /// redeclaration (vs. a reference).
4022   enum RedeclarationKind {
4023     /// The lookup is a reference to this name that is not for the
4024     /// purpose of redeclaring the name.
4025     NotForRedeclaration = 0,
4026     /// The lookup results will be used for redeclaration of a name,
4027     /// if an entity by that name already exists and is visible.
4028     ForVisibleRedeclaration,
4029     /// The lookup results will be used for redeclaration of a name
4030     /// with external linkage; non-visible lookup results with external linkage
4031     /// may also be found.
4032     ForExternalRedeclaration
4033   };
4034 
forRedeclarationInCurContext()4035   RedeclarationKind forRedeclarationInCurContext() {
4036     // A declaration with an owning module for linkage can never link against
4037     // anything that is not visible. We don't need to check linkage here; if
4038     // the context has internal linkage, redeclaration lookup won't find things
4039     // from other TUs, and we can't safely compute linkage yet in general.
4040     if (cast<Decl>(CurContext)
4041             ->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
4042       return ForVisibleRedeclaration;
4043     return ForExternalRedeclaration;
4044   }
4045 
4046   /// The possible outcomes of name lookup for a literal operator.
4047   enum LiteralOperatorLookupResult {
4048     /// The lookup resulted in an error.
4049     LOLR_Error,
4050     /// The lookup found no match but no diagnostic was issued.
4051     LOLR_ErrorNoDiagnostic,
4052     /// The lookup found a single 'cooked' literal operator, which
4053     /// expects a normal literal to be built and passed to it.
4054     LOLR_Cooked,
4055     /// The lookup found a single 'raw' literal operator, which expects
4056     /// a string literal containing the spelling of the literal token.
4057     LOLR_Raw,
4058     /// The lookup found an overload set of literal operator templates,
4059     /// which expect the characters of the spelling of the literal token to be
4060     /// passed as a non-type template argument pack.
4061     LOLR_Template,
4062     /// The lookup found an overload set of literal operator templates,
4063     /// which expect the character type and characters of the spelling of the
4064     /// string literal token to be passed as template arguments.
4065     LOLR_StringTemplatePack,
4066   };
4067 
4068   SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
4069                                                   CXXSpecialMember SM,
4070                                                   bool ConstArg,
4071                                                   bool VolatileArg,
4072                                                   bool RValueThis,
4073                                                   bool ConstThis,
4074                                                   bool VolatileThis);
4075 
4076   typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
4077   typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
4078       TypoRecoveryCallback;
4079 
4080 private:
4081   bool CppLookupName(LookupResult &R, Scope *S);
4082 
4083   struct TypoExprState {
4084     std::unique_ptr<TypoCorrectionConsumer> Consumer;
4085     TypoDiagnosticGenerator DiagHandler;
4086     TypoRecoveryCallback RecoveryHandler;
4087     TypoExprState();
4088     TypoExprState(TypoExprState &&other) noexcept;
4089     TypoExprState &operator=(TypoExprState &&other) noexcept;
4090   };
4091 
4092   /// The set of unhandled TypoExprs and their associated state.
4093   llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
4094 
4095   /// Creates a new TypoExpr AST node.
4096   TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
4097                               TypoDiagnosticGenerator TDG,
4098                               TypoRecoveryCallback TRC, SourceLocation TypoLoc);
4099 
4100   // The set of known/encountered (unique, canonicalized) NamespaceDecls.
4101   //
4102   // The boolean value will be true to indicate that the namespace was loaded
4103   // from an AST/PCH file, or false otherwise.
4104   llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
4105 
4106   /// Whether we have already loaded known namespaces from an extenal
4107   /// source.
4108   bool LoadedExternalKnownNamespaces;
4109 
4110   /// Helper for CorrectTypo and CorrectTypoDelayed used to create and
4111   /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
4112   /// should be skipped entirely.
4113   std::unique_ptr<TypoCorrectionConsumer>
4114   makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
4115                              Sema::LookupNameKind LookupKind, Scope *S,
4116                              CXXScopeSpec *SS,
4117                              CorrectionCandidateCallback &CCC,
4118                              DeclContext *MemberContext, bool EnteringContext,
4119                              const ObjCObjectPointerType *OPT,
4120                              bool ErrorRecovery);
4121 
4122 public:
4123   const TypoExprState &getTypoExprState(TypoExpr *TE) const;
4124 
4125   /// Clears the state of the given TypoExpr.
4126   void clearDelayedTypo(TypoExpr *TE);
4127 
4128   /// Look up a name, looking for a single declaration.  Return
4129   /// null if the results were absent, ambiguous, or overloaded.
4130   ///
4131   /// It is preferable to use the elaborated form and explicitly handle
4132   /// ambiguity and overloaded.
4133   NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
4134                               SourceLocation Loc,
4135                               LookupNameKind NameKind,
4136                               RedeclarationKind Redecl
4137                                 = NotForRedeclaration);
4138   bool LookupBuiltin(LookupResult &R);
4139   void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID);
4140   bool LookupName(LookupResult &R, Scope *S,
4141                   bool AllowBuiltinCreation = false);
4142   bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
4143                            bool InUnqualifiedLookup = false);
4144   bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
4145                            CXXScopeSpec &SS);
4146   bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
4147                         bool AllowBuiltinCreation = false,
4148                         bool EnteringContext = false);
4149   ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
4150                                    RedeclarationKind Redecl
4151                                      = NotForRedeclaration);
4152   bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
4153 
4154   void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
4155                                     UnresolvedSetImpl &Functions);
4156 
4157   LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
4158                                  SourceLocation GnuLabelLoc = SourceLocation());
4159 
4160   DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
4161   CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
4162   CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
4163                                                unsigned Quals);
4164   CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
4165                                          bool RValueThis, unsigned ThisQuals);
4166   CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
4167                                               unsigned Quals);
4168   CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
4169                                         bool RValueThis, unsigned ThisQuals);
4170   CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
4171 
4172   bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id,
4173                               bool IsUDSuffix);
4174   LiteralOperatorLookupResult
4175   LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys,
4176                         bool AllowRaw, bool AllowTemplate,
4177                         bool AllowStringTemplate, bool DiagnoseMissing,
4178                         StringLiteral *StringLit = nullptr);
4179   bool isKnownName(StringRef name);
4180 
4181   /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
4182   enum class FunctionEmissionStatus {
4183     Emitted,
4184     CUDADiscarded,     // Discarded due to CUDA/HIP hostness
4185     OMPDiscarded,      // Discarded due to OpenMP hostness
4186     TemplateDiscarded, // Discarded due to uninstantiated templates
4187     Unknown,
4188   };
4189   FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl,
4190                                            bool Final = false);
4191 
4192   // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
4193   bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee);
4194 
4195   void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
4196                                ArrayRef<Expr *> Args, ADLResult &Functions);
4197 
4198   void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
4199                           VisibleDeclConsumer &Consumer,
4200                           bool IncludeGlobalScope = true,
4201                           bool LoadExternal = true);
4202   void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
4203                           VisibleDeclConsumer &Consumer,
4204                           bool IncludeGlobalScope = true,
4205                           bool IncludeDependentBases = false,
4206                           bool LoadExternal = true);
4207 
4208   enum CorrectTypoKind {
4209     CTK_NonError,     // CorrectTypo used in a non error recovery situation.
4210     CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
4211   };
4212 
4213   TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
4214                              Sema::LookupNameKind LookupKind,
4215                              Scope *S, CXXScopeSpec *SS,
4216                              CorrectionCandidateCallback &CCC,
4217                              CorrectTypoKind Mode,
4218                              DeclContext *MemberContext = nullptr,
4219                              bool EnteringContext = false,
4220                              const ObjCObjectPointerType *OPT = nullptr,
4221                              bool RecordFailure = true);
4222 
4223   TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
4224                                Sema::LookupNameKind LookupKind, Scope *S,
4225                                CXXScopeSpec *SS,
4226                                CorrectionCandidateCallback &CCC,
4227                                TypoDiagnosticGenerator TDG,
4228                                TypoRecoveryCallback TRC, CorrectTypoKind Mode,
4229                                DeclContext *MemberContext = nullptr,
4230                                bool EnteringContext = false,
4231                                const ObjCObjectPointerType *OPT = nullptr);
4232 
4233   /// Process any TypoExprs in the given Expr and its children,
4234   /// generating diagnostics as appropriate and returning a new Expr if there
4235   /// were typos that were all successfully corrected and ExprError if one or
4236   /// more typos could not be corrected.
4237   ///
4238   /// \param E The Expr to check for TypoExprs.
4239   ///
4240   /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
4241   /// initializer.
4242   ///
4243   /// \param RecoverUncorrectedTypos If true, when typo correction fails, it
4244   /// will rebuild the given Expr with all TypoExprs degraded to RecoveryExprs.
4245   ///
4246   /// \param Filter A function applied to a newly rebuilt Expr to determine if
4247   /// it is an acceptable/usable result from a single combination of typo
4248   /// corrections. As long as the filter returns ExprError, different
4249   /// combinations of corrections will be tried until all are exhausted.
4250   ExprResult CorrectDelayedTyposInExpr(
4251       Expr *E, VarDecl *InitDecl = nullptr,
4252       bool RecoverUncorrectedTypos = false,
4253       llvm::function_ref<ExprResult(Expr *)> Filter =
4254           [](Expr *E) -> ExprResult { return E; });
4255 
4256   ExprResult CorrectDelayedTyposInExpr(
4257       ExprResult ER, VarDecl *InitDecl = nullptr,
4258       bool RecoverUncorrectedTypos = false,
4259       llvm::function_ref<ExprResult(Expr *)> Filter =
4260           [](Expr *E) -> ExprResult { return E; }) {
4261     return ER.isInvalid()
4262                ? ER
4263                : CorrectDelayedTyposInExpr(ER.get(), InitDecl,
4264                                            RecoverUncorrectedTypos, Filter);
4265   }
4266 
4267   void diagnoseTypo(const TypoCorrection &Correction,
4268                     const PartialDiagnostic &TypoDiag,
4269                     bool ErrorRecovery = true);
4270 
4271   void diagnoseTypo(const TypoCorrection &Correction,
4272                     const PartialDiagnostic &TypoDiag,
4273                     const PartialDiagnostic &PrevNote,
4274                     bool ErrorRecovery = true);
4275 
4276   void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
4277 
4278   void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
4279                                           ArrayRef<Expr *> Args,
4280                                    AssociatedNamespaceSet &AssociatedNamespaces,
4281                                    AssociatedClassSet &AssociatedClasses);
4282 
4283   void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
4284                             bool ConsiderLinkage, bool AllowInlineNamespace);
4285 
4286   bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
4287 
4288   void DiagnoseAmbiguousLookup(LookupResult &Result);
4289   //@}
4290 
4291   /// Attempts to produce a RecoveryExpr after some AST node cannot be created.
4292   ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
4293                                 ArrayRef<Expr *> SubExprs,
4294                                 QualType T = QualType());
4295 
4296   ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
4297                                           SourceLocation IdLoc,
4298                                           bool TypoCorrection = false);
4299   FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID,
4300                               SourceLocation Loc);
4301   NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
4302                                  Scope *S, bool ForRedeclaration,
4303                                  SourceLocation Loc);
4304   NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
4305                                       Scope *S);
4306   void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
4307       FunctionDecl *FD);
4308   void AddKnownFunctionAttributes(FunctionDecl *FD);
4309 
4310   // More parsing and symbol table subroutines.
4311 
4312   void ProcessPragmaWeak(Scope *S, Decl *D);
4313   // Decl attributes - this routine is the top level dispatcher.
4314   void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
4315   // Helper for delayed processing of attributes.
4316   void ProcessDeclAttributeDelayed(Decl *D,
4317                                    const ParsedAttributesView &AttrList);
4318   void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL,
4319                              bool IncludeCXX11Attributes = true);
4320   bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
4321                                    const ParsedAttributesView &AttrList);
4322 
4323   void checkUnusedDeclAttributes(Declarator &D);
4324 
4325   /// Handles semantic checking for features that are common to all attributes,
4326   /// such as checking whether a parameter was properly specified, or the
4327   /// correct number of arguments were passed, etc. Returns true if the
4328   /// attribute has been diagnosed.
4329   bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A);
4330   bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A);
4331 
4332   /// Determine if type T is a valid subject for a nonnull and similar
4333   /// attributes. By default, we look through references (the behavior used by
4334   /// nonnull), but if the second parameter is true, then we treat a reference
4335   /// type as valid.
4336   bool isValidPointerAttrType(QualType T, bool RefOkay = false);
4337 
4338   bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
4339   bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC,
4340                             const FunctionDecl *FD = nullptr);
4341   bool CheckAttrTarget(const ParsedAttr &CurrAttr);
4342   bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
4343   bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
4344                                       StringRef &Str,
4345                                       SourceLocation *ArgLocation = nullptr);
4346   llvm::Error isValidSectionSpecifier(StringRef Str);
4347   bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
4348   bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
4349   bool checkMSInheritanceAttrOnDefinition(
4350       CXXRecordDecl *RD, SourceRange Range, bool BestCase,
4351       MSInheritanceModel SemanticSpelling);
4352 
4353   void CheckAlignasUnderalignment(Decl *D);
4354 
4355   /// Adjust the calling convention of a method to be the ABI default if it
4356   /// wasn't specified explicitly.  This handles method types formed from
4357   /// function type typedefs and typename template arguments.
4358   void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
4359                               SourceLocation Loc);
4360 
4361   // Check if there is an explicit attribute, but only look through parens.
4362   // The intent is to look for an attribute on the current declarator, but not
4363   // one that came from a typedef.
4364   bool hasExplicitCallingConv(QualType T);
4365 
4366   /// Get the outermost AttributedType node that sets a calling convention.
4367   /// Valid types should not have multiple attributes with different CCs.
4368   const AttributedType *getCallingConvAttributedType(QualType T) const;
4369 
4370   /// Process the attributes before creating an attributed statement. Returns
4371   /// the semantic attributes that have been processed.
4372   void ProcessStmtAttributes(Stmt *Stmt,
4373                              const ParsedAttributesWithRange &InAttrs,
4374                              SmallVectorImpl<const Attr *> &OutAttrs);
4375 
4376   void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
4377                                    ObjCMethodDecl *MethodDecl,
4378                                    bool IsProtocolMethodDecl);
4379 
4380   void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
4381                                    ObjCMethodDecl *Overridden,
4382                                    bool IsProtocolMethodDecl);
4383 
4384   /// WarnExactTypedMethods - This routine issues a warning if method
4385   /// implementation declaration matches exactly that of its declaration.
4386   void WarnExactTypedMethods(ObjCMethodDecl *Method,
4387                              ObjCMethodDecl *MethodDecl,
4388                              bool IsProtocolMethodDecl);
4389 
4390   typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
4391 
4392   /// CheckImplementationIvars - This routine checks if the instance variables
4393   /// listed in the implelementation match those listed in the interface.
4394   void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
4395                                 ObjCIvarDecl **Fields, unsigned nIvars,
4396                                 SourceLocation Loc);
4397 
4398   /// ImplMethodsVsClassMethods - This is main routine to warn if any method
4399   /// remains unimplemented in the class or category \@implementation.
4400   void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
4401                                  ObjCContainerDecl* IDecl,
4402                                  bool IncompleteImpl = false);
4403 
4404   /// DiagnoseUnimplementedProperties - This routine warns on those properties
4405   /// which must be implemented by this implementation.
4406   void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
4407                                        ObjCContainerDecl *CDecl,
4408                                        bool SynthesizeProperties);
4409 
4410   /// Diagnose any null-resettable synthesized setters.
4411   void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
4412 
4413   /// DefaultSynthesizeProperties - This routine default synthesizes all
4414   /// properties which must be synthesized in the class's \@implementation.
4415   void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
4416                                    ObjCInterfaceDecl *IDecl,
4417                                    SourceLocation AtEnd);
4418   void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd);
4419 
4420   /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
4421   /// an ivar synthesized for 'Method' and 'Method' is a property accessor
4422   /// declared in class 'IFace'.
4423   bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
4424                                       ObjCMethodDecl *Method, ObjCIvarDecl *IV);
4425 
4426   /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
4427   /// backs the property is not used in the property's accessor.
4428   void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
4429                                            const ObjCImplementationDecl *ImplD);
4430 
4431   /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
4432   /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
4433   /// It also returns ivar's property on success.
4434   ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
4435                                                const ObjCPropertyDecl *&PDecl) const;
4436 
4437   /// Called by ActOnProperty to handle \@property declarations in
4438   /// class extensions.
4439   ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
4440                       SourceLocation AtLoc,
4441                       SourceLocation LParenLoc,
4442                       FieldDeclarator &FD,
4443                       Selector GetterSel,
4444                       SourceLocation GetterNameLoc,
4445                       Selector SetterSel,
4446                       SourceLocation SetterNameLoc,
4447                       const bool isReadWrite,
4448                       unsigned &Attributes,
4449                       const unsigned AttributesAsWritten,
4450                       QualType T,
4451                       TypeSourceInfo *TSI,
4452                       tok::ObjCKeywordKind MethodImplKind);
4453 
4454   /// Called by ActOnProperty and HandlePropertyInClassExtension to
4455   /// handle creating the ObjcPropertyDecl for a category or \@interface.
4456   ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
4457                                        ObjCContainerDecl *CDecl,
4458                                        SourceLocation AtLoc,
4459                                        SourceLocation LParenLoc,
4460                                        FieldDeclarator &FD,
4461                                        Selector GetterSel,
4462                                        SourceLocation GetterNameLoc,
4463                                        Selector SetterSel,
4464                                        SourceLocation SetterNameLoc,
4465                                        const bool isReadWrite,
4466                                        const unsigned Attributes,
4467                                        const unsigned AttributesAsWritten,
4468                                        QualType T,
4469                                        TypeSourceInfo *TSI,
4470                                        tok::ObjCKeywordKind MethodImplKind,
4471                                        DeclContext *lexicalDC = nullptr);
4472 
4473   /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
4474   /// warning) when atomic property has one but not the other user-declared
4475   /// setter or getter.
4476   void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
4477                                        ObjCInterfaceDecl* IDecl);
4478 
4479   void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
4480 
4481   void DiagnoseMissingDesignatedInitOverrides(
4482                                           const ObjCImplementationDecl *ImplD,
4483                                           const ObjCInterfaceDecl *IFD);
4484 
4485   void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
4486 
4487   enum MethodMatchStrategy {
4488     MMS_loose,
4489     MMS_strict
4490   };
4491 
4492   /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
4493   /// true, or false, accordingly.
4494   bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
4495                                   const ObjCMethodDecl *PrevMethod,
4496                                   MethodMatchStrategy strategy = MMS_strict);
4497 
4498   /// MatchAllMethodDeclarations - Check methods declaraed in interface or
4499   /// or protocol against those declared in their implementations.
4500   void MatchAllMethodDeclarations(const SelectorSet &InsMap,
4501                                   const SelectorSet &ClsMap,
4502                                   SelectorSet &InsMapSeen,
4503                                   SelectorSet &ClsMapSeen,
4504                                   ObjCImplDecl* IMPDecl,
4505                                   ObjCContainerDecl* IDecl,
4506                                   bool &IncompleteImpl,
4507                                   bool ImmediateClass,
4508                                   bool WarnCategoryMethodImpl=false);
4509 
4510   /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
4511   /// category matches with those implemented in its primary class and
4512   /// warns each time an exact match is found.
4513   void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
4514 
4515   /// Add the given method to the list of globally-known methods.
4516   void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
4517 
4518   /// Returns default addr space for method qualifiers.
4519   LangAS getDefaultCXXMethodAddrSpace() const;
4520 
4521 private:
4522   /// AddMethodToGlobalPool - Add an instance or factory method to the global
4523   /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
4524   void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
4525 
4526   /// LookupMethodInGlobalPool - Returns the instance or factory method and
4527   /// optionally warns if there are multiple signatures.
4528   ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
4529                                            bool receiverIdOrClass,
4530                                            bool instance);
4531 
4532 public:
4533   /// - Returns instance or factory methods in global method pool for
4534   /// given selector. It checks the desired kind first, if none is found, and
4535   /// parameter checkTheOther is set, it then checks the other kind. If no such
4536   /// method or only one method is found, function returns false; otherwise, it
4537   /// returns true.
4538   bool
4539   CollectMultipleMethodsInGlobalPool(Selector Sel,
4540                                      SmallVectorImpl<ObjCMethodDecl*>& Methods,
4541                                      bool InstanceFirst, bool CheckTheOther,
4542                                      const ObjCObjectType *TypeBound = nullptr);
4543 
4544   bool
4545   AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
4546                                  SourceRange R, bool receiverIdOrClass,
4547                                  SmallVectorImpl<ObjCMethodDecl*>& Methods);
4548 
4549   void
4550   DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
4551                                      Selector Sel, SourceRange R,
4552                                      bool receiverIdOrClass);
4553 
4554 private:
4555   /// - Returns a selector which best matches given argument list or
4556   /// nullptr if none could be found
4557   ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
4558                                    bool IsInstance,
4559                                    SmallVectorImpl<ObjCMethodDecl*>& Methods);
4560 
4561 
4562   /// Record the typo correction failure and return an empty correction.
4563   TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
4564                                   bool RecordFailure = true) {
4565     if (RecordFailure)
4566       TypoCorrectionFailures[Typo].insert(TypoLoc);
4567     return TypoCorrection();
4568   }
4569 
4570 public:
4571   /// AddInstanceMethodToGlobalPool - All instance methods in a translation
4572   /// unit are added to a global pool. This allows us to efficiently associate
4573   /// a selector with a method declaraation for purposes of typechecking
4574   /// messages sent to "id" (where the class of the object is unknown).
4575   void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
4576     AddMethodToGlobalPool(Method, impl, /*instance*/true);
4577   }
4578 
4579   /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
4580   void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
4581     AddMethodToGlobalPool(Method, impl, /*instance*/false);
4582   }
4583 
4584   /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
4585   /// pool.
4586   void AddAnyMethodToGlobalPool(Decl *D);
4587 
4588   /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
4589   /// there are multiple signatures.
4590   ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
4591                                                    bool receiverIdOrClass=false) {
4592     return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
4593                                     /*instance*/true);
4594   }
4595 
4596   /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
4597   /// there are multiple signatures.
4598   ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
4599                                                   bool receiverIdOrClass=false) {
4600     return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
4601                                     /*instance*/false);
4602   }
4603 
4604   const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
4605                               QualType ObjectType=QualType());
4606   /// LookupImplementedMethodInGlobalPool - Returns the method which has an
4607   /// implementation.
4608   ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
4609 
4610   /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
4611   /// initialization.
4612   void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
4613                                   SmallVectorImpl<ObjCIvarDecl*> &Ivars);
4614 
4615   //===--------------------------------------------------------------------===//
4616   // Statement Parsing Callbacks: SemaStmt.cpp.
4617 public:
4618   class FullExprArg {
4619   public:
FullExprArg()4620     FullExprArg() : E(nullptr) { }
FullExprArg(Sema & actions)4621     FullExprArg(Sema &actions) : E(nullptr) { }
4622 
release()4623     ExprResult release() {
4624       return E;
4625     }
4626 
get()4627     Expr *get() const { return E; }
4628 
4629     Expr *operator->() {
4630       return E;
4631     }
4632 
4633   private:
4634     // FIXME: No need to make the entire Sema class a friend when it's just
4635     // Sema::MakeFullExpr that needs access to the constructor below.
4636     friend class Sema;
4637 
FullExprArg(Expr * expr)4638     explicit FullExprArg(Expr *expr) : E(expr) {}
4639 
4640     Expr *E;
4641   };
4642 
MakeFullExpr(Expr * Arg)4643   FullExprArg MakeFullExpr(Expr *Arg) {
4644     return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
4645   }
MakeFullExpr(Expr * Arg,SourceLocation CC)4646   FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
4647     return FullExprArg(
4648         ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get());
4649   }
MakeFullDiscardedValueExpr(Expr * Arg)4650   FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
4651     ExprResult FE =
4652         ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
4653                             /*DiscardedValue*/ true);
4654     return FullExprArg(FE.get());
4655   }
4656 
4657   StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
4658   StmtResult ActOnExprStmtError();
4659 
4660   StmtResult ActOnNullStmt(SourceLocation SemiLoc,
4661                            bool HasLeadingEmptyMacro = false);
4662 
4663   void ActOnStartOfCompoundStmt(bool IsStmtExpr);
4664   void ActOnAfterCompoundStatementLeadingPragmas();
4665   void ActOnFinishOfCompoundStmt();
4666   StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
4667                                ArrayRef<Stmt *> Elts, bool isStmtExpr);
4668 
4669   /// A RAII object to enter scope of a compound statement.
4670   class CompoundScopeRAII {
4671   public:
S(S)4672     CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
4673       S.ActOnStartOfCompoundStmt(IsStmtExpr);
4674     }
4675 
~CompoundScopeRAII()4676     ~CompoundScopeRAII() {
4677       S.ActOnFinishOfCompoundStmt();
4678     }
4679 
4680   private:
4681     Sema &S;
4682   };
4683 
4684   /// An RAII helper that pops function a function scope on exit.
4685   struct FunctionScopeRAII {
4686     Sema &S;
4687     bool Active;
FunctionScopeRAIIFunctionScopeRAII4688     FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
~FunctionScopeRAIIFunctionScopeRAII4689     ~FunctionScopeRAII() {
4690       if (Active)
4691         S.PopFunctionScopeInfo();
4692     }
disableFunctionScopeRAII4693     void disable() { Active = false; }
4694   };
4695 
4696   StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
4697                                    SourceLocation StartLoc,
4698                                    SourceLocation EndLoc);
4699   void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
4700   StmtResult ActOnForEachLValueExpr(Expr *E);
4701   ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
4702   StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
4703                            SourceLocation DotDotDotLoc, ExprResult RHS,
4704                            SourceLocation ColonLoc);
4705   void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
4706 
4707   StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
4708                                       SourceLocation ColonLoc,
4709                                       Stmt *SubStmt, Scope *CurScope);
4710   StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
4711                             SourceLocation ColonLoc, Stmt *SubStmt);
4712 
4713   StmtResult BuildAttributedStmt(SourceLocation AttrsLoc,
4714                                  ArrayRef<const Attr *> Attrs, Stmt *SubStmt);
4715   StmtResult ActOnAttributedStmt(const ParsedAttributesWithRange &AttrList,
4716                                  Stmt *SubStmt);
4717 
4718   class ConditionResult;
4719 
4720   StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind,
4721                          SourceLocation LParenLoc, Stmt *InitStmt,
4722                          ConditionResult Cond, SourceLocation RParenLoc,
4723                          Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
4724   StmtResult BuildIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind,
4725                          SourceLocation LParenLoc, Stmt *InitStmt,
4726                          ConditionResult Cond, SourceLocation RParenLoc,
4727                          Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
4728   StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
4729                                     SourceLocation LParenLoc, Stmt *InitStmt,
4730                                     ConditionResult Cond,
4731                                     SourceLocation RParenLoc);
4732   StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
4733                                            Stmt *Switch, Stmt *Body);
4734   StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
4735                             ConditionResult Cond, SourceLocation RParenLoc,
4736                             Stmt *Body);
4737   StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
4738                          SourceLocation WhileLoc, SourceLocation CondLParen,
4739                          Expr *Cond, SourceLocation CondRParen);
4740 
4741   StmtResult ActOnForStmt(SourceLocation ForLoc,
4742                           SourceLocation LParenLoc,
4743                           Stmt *First,
4744                           ConditionResult Second,
4745                           FullExprArg Third,
4746                           SourceLocation RParenLoc,
4747                           Stmt *Body);
4748   ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
4749                                            Expr *collection);
4750   StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
4751                                         Stmt *First, Expr *collection,
4752                                         SourceLocation RParenLoc);
4753   StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
4754 
4755   enum BuildForRangeKind {
4756     /// Initial building of a for-range statement.
4757     BFRK_Build,
4758     /// Instantiation or recovery rebuild of a for-range statement. Don't
4759     /// attempt any typo-correction.
4760     BFRK_Rebuild,
4761     /// Determining whether a for-range statement could be built. Avoid any
4762     /// unnecessary or irreversible actions.
4763     BFRK_Check
4764   };
4765 
4766   StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
4767                                   SourceLocation CoawaitLoc,
4768                                   Stmt *InitStmt,
4769                                   Stmt *LoopVar,
4770                                   SourceLocation ColonLoc, Expr *Collection,
4771                                   SourceLocation RParenLoc,
4772                                   BuildForRangeKind Kind);
4773   StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
4774                                   SourceLocation CoawaitLoc,
4775                                   Stmt *InitStmt,
4776                                   SourceLocation ColonLoc,
4777                                   Stmt *RangeDecl, Stmt *Begin, Stmt *End,
4778                                   Expr *Cond, Expr *Inc,
4779                                   Stmt *LoopVarDecl,
4780                                   SourceLocation RParenLoc,
4781                                   BuildForRangeKind Kind);
4782   StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
4783 
4784   StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
4785                            SourceLocation LabelLoc,
4786                            LabelDecl *TheDecl);
4787   StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
4788                                    SourceLocation StarLoc,
4789                                    Expr *DestExp);
4790   StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
4791   StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
4792 
4793   void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4794                                 CapturedRegionKind Kind, unsigned NumParams);
4795   typedef std::pair<StringRef, QualType> CapturedParamNameType;
4796   void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4797                                 CapturedRegionKind Kind,
4798                                 ArrayRef<CapturedParamNameType> Params,
4799                                 unsigned OpenMPCaptureLevel = 0);
4800   StmtResult ActOnCapturedRegionEnd(Stmt *S);
4801   void ActOnCapturedRegionError();
4802   RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
4803                                            SourceLocation Loc,
4804                                            unsigned NumParams);
4805 
4806   struct NamedReturnInfo {
4807     const VarDecl *Candidate;
4808 
4809     enum Status : uint8_t { None, MoveEligible, MoveEligibleAndCopyElidable };
4810     Status S;
4811 
isMoveEligibleNamedReturnInfo4812     bool isMoveEligible() const { return S != None; };
isCopyElidableNamedReturnInfo4813     bool isCopyElidable() const { return S == MoveEligibleAndCopyElidable; }
4814   };
4815   enum class SimplerImplicitMoveMode { ForceOff, Normal, ForceOn };
4816   NamedReturnInfo getNamedReturnInfo(
4817       Expr *&E, SimplerImplicitMoveMode Mode = SimplerImplicitMoveMode::Normal);
4818   NamedReturnInfo getNamedReturnInfo(const VarDecl *VD);
4819   const VarDecl *getCopyElisionCandidate(NamedReturnInfo &Info,
4820                                          QualType ReturnType);
4821 
4822   ExprResult
4823   PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
4824                                   const NamedReturnInfo &NRInfo, Expr *Value,
4825                                   bool SupressSimplerImplicitMoves = false);
4826 
4827   StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
4828                              Scope *CurScope);
4829   StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
4830   StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
4831                                      NamedReturnInfo &NRInfo,
4832                                      bool SupressSimplerImplicitMoves);
4833 
4834   StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
4835                              bool IsVolatile, unsigned NumOutputs,
4836                              unsigned NumInputs, IdentifierInfo **Names,
4837                              MultiExprArg Constraints, MultiExprArg Exprs,
4838                              Expr *AsmString, MultiExprArg Clobbers,
4839                              unsigned NumLabels,
4840                              SourceLocation RParenLoc);
4841 
4842   void FillInlineAsmIdentifierInfo(Expr *Res,
4843                                    llvm::InlineAsmIdentifierInfo &Info);
4844   ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
4845                                        SourceLocation TemplateKWLoc,
4846                                        UnqualifiedId &Id,
4847                                        bool IsUnevaluatedContext);
4848   bool LookupInlineAsmField(StringRef Base, StringRef Member,
4849                             unsigned &Offset, SourceLocation AsmLoc);
4850   ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
4851                                          SourceLocation AsmLoc);
4852   StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
4853                             ArrayRef<Token> AsmToks,
4854                             StringRef AsmString,
4855                             unsigned NumOutputs, unsigned NumInputs,
4856                             ArrayRef<StringRef> Constraints,
4857                             ArrayRef<StringRef> Clobbers,
4858                             ArrayRef<Expr*> Exprs,
4859                             SourceLocation EndLoc);
4860   LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
4861                                    SourceLocation Location,
4862                                    bool AlwaysCreate);
4863 
4864   VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
4865                                   SourceLocation StartLoc,
4866                                   SourceLocation IdLoc, IdentifierInfo *Id,
4867                                   bool Invalid = false);
4868 
4869   Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
4870 
4871   StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
4872                                   Decl *Parm, Stmt *Body);
4873 
4874   StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
4875 
4876   StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
4877                                 MultiStmtArg Catch, Stmt *Finally);
4878 
4879   StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
4880   StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
4881                                   Scope *CurScope);
4882   ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
4883                                             Expr *operand);
4884   StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
4885                                          Expr *SynchExpr,
4886                                          Stmt *SynchBody);
4887 
4888   StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
4889 
4890   VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
4891                                      SourceLocation StartLoc,
4892                                      SourceLocation IdLoc,
4893                                      IdentifierInfo *Id);
4894 
4895   Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
4896 
4897   StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
4898                                 Decl *ExDecl, Stmt *HandlerBlock);
4899   StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
4900                               ArrayRef<Stmt *> Handlers);
4901 
4902   StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
4903                               SourceLocation TryLoc, Stmt *TryBlock,
4904                               Stmt *Handler);
4905   StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
4906                                  Expr *FilterExpr,
4907                                  Stmt *Block);
4908   void ActOnStartSEHFinallyBlock();
4909   void ActOnAbortSEHFinallyBlock();
4910   StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
4911   StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
4912 
4913   void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
4914 
4915   bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
4916 
4917   /// If it's a file scoped decl that must warn if not used, keep track
4918   /// of it.
4919   void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
4920 
4921   /// DiagnoseUnusedExprResult - If the statement passed in is an expression
4922   /// whose result is unused, warn.
4923   void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID);
4924   void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
4925   void DiagnoseUnusedDecl(const NamedDecl *ND);
4926 
4927   /// If VD is set but not otherwise used, diagnose, for a parameter or a
4928   /// variable.
4929   void DiagnoseUnusedButSetDecl(const VarDecl *VD);
4930 
4931   /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
4932   /// statement as a \p Body, and it is located on the same line.
4933   ///
4934   /// This helps prevent bugs due to typos, such as:
4935   ///     if (condition);
4936   ///       do_stuff();
4937   void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
4938                              const Stmt *Body,
4939                              unsigned DiagID);
4940 
4941   /// Warn if a for/while loop statement \p S, which is followed by
4942   /// \p PossibleBody, has a suspicious null statement as a body.
4943   void DiagnoseEmptyLoopBody(const Stmt *S,
4944                              const Stmt *PossibleBody);
4945 
4946   /// Warn if a value is moved to itself.
4947   void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
4948                         SourceLocation OpLoc);
4949 
4950   /// Warn if we're implicitly casting from a _Nullable pointer type to a
4951   /// _Nonnull one.
4952   void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
4953                                            SourceLocation Loc);
4954 
4955   /// Warn when implicitly casting 0 to nullptr.
4956   void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
4957 
PushParsingDeclaration(sema::DelayedDiagnosticPool & pool)4958   ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
4959     return DelayedDiagnostics.push(pool);
4960   }
4961   void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
4962 
4963   typedef ProcessingContextState ParsingClassState;
PushParsingClass()4964   ParsingClassState PushParsingClass() {
4965     ParsingClassDepth++;
4966     return DelayedDiagnostics.pushUndelayed();
4967   }
PopParsingClass(ParsingClassState state)4968   void PopParsingClass(ParsingClassState state) {
4969     ParsingClassDepth--;
4970     DelayedDiagnostics.popUndelayed(state);
4971   }
4972 
4973   void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
4974 
4975   void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
4976                                   const ObjCInterfaceDecl *UnknownObjCClass,
4977                                   bool ObjCPropertyAccess,
4978                                   bool AvoidPartialAvailabilityChecks = false,
4979                                   ObjCInterfaceDecl *ClassReceiver = nullptr);
4980 
4981   bool makeUnavailableInSystemHeader(SourceLocation loc,
4982                                      UnavailableAttr::ImplicitReason reason);
4983 
4984   /// Issue any -Wunguarded-availability warnings in \c FD
4985   void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
4986 
4987   void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
4988 
4989   //===--------------------------------------------------------------------===//
4990   // Expression Parsing Callbacks: SemaExpr.cpp.
4991 
4992   bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
4993   bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
4994                          const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
4995                          bool ObjCPropertyAccess = false,
4996                          bool AvoidPartialAvailabilityChecks = false,
4997                          ObjCInterfaceDecl *ClassReciever = nullptr);
4998   void NoteDeletedFunction(FunctionDecl *FD);
4999   void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
5000   bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
5001                                         ObjCMethodDecl *Getter,
5002                                         SourceLocation Loc);
5003   void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
5004                              ArrayRef<Expr *> Args);
5005 
5006   void PushExpressionEvaluationContext(
5007       ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
5008       ExpressionEvaluationContextRecord::ExpressionKind Type =
5009           ExpressionEvaluationContextRecord::EK_Other);
5010   enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
5011   void PushExpressionEvaluationContext(
5012       ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
5013       ExpressionEvaluationContextRecord::ExpressionKind Type =
5014           ExpressionEvaluationContextRecord::EK_Other);
5015   void PopExpressionEvaluationContext();
5016 
5017   void DiscardCleanupsInEvaluationContext();
5018 
5019   ExprResult TransformToPotentiallyEvaluated(Expr *E);
5020   ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
5021 
5022   ExprResult CheckUnevaluatedOperand(Expr *E);
5023   void CheckUnusedVolatileAssignment(Expr *E);
5024 
5025   ExprResult ActOnConstantExpression(ExprResult Res);
5026 
5027   // Functions for marking a declaration referenced.  These functions also
5028   // contain the relevant logic for marking if a reference to a function or
5029   // variable is an odr-use (in the C++11 sense).  There are separate variants
5030   // for expressions referring to a decl; these exist because odr-use marking
5031   // needs to be delayed for some constant variables when we build one of the
5032   // named expressions.
5033   //
5034   // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
5035   // should usually be true. This only needs to be set to false if the lack of
5036   // odr-use cannot be determined from the current context (for instance,
5037   // because the name denotes a virtual function and was written without an
5038   // explicit nested-name-specifier).
5039   void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
5040   void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
5041                               bool MightBeOdrUse = true);
5042   void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
5043   void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
5044   void MarkMemberReferenced(MemberExpr *E);
5045   void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E);
5046   void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc,
5047                                          unsigned CapturingScopeIndex);
5048 
5049   ExprResult CheckLValueToRValueConversionOperand(Expr *E);
5050   void CleanupVarDeclMarking();
5051 
5052   enum TryCaptureKind {
5053     TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
5054   };
5055 
5056   /// Try to capture the given variable.
5057   ///
5058   /// \param Var The variable to capture.
5059   ///
5060   /// \param Loc The location at which the capture occurs.
5061   ///
5062   /// \param Kind The kind of capture, which may be implicit (for either a
5063   /// block or a lambda), or explicit by-value or by-reference (for a lambda).
5064   ///
5065   /// \param EllipsisLoc The location of the ellipsis, if one is provided in
5066   /// an explicit lambda capture.
5067   ///
5068   /// \param BuildAndDiagnose Whether we are actually supposed to add the
5069   /// captures or diagnose errors. If false, this routine merely check whether
5070   /// the capture can occur without performing the capture itself or complaining
5071   /// if the variable cannot be captured.
5072   ///
5073   /// \param CaptureType Will be set to the type of the field used to capture
5074   /// this variable in the innermost block or lambda. Only valid when the
5075   /// variable can be captured.
5076   ///
5077   /// \param DeclRefType Will be set to the type of a reference to the capture
5078   /// from within the current scope. Only valid when the variable can be
5079   /// captured.
5080   ///
5081   /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
5082   /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
5083   /// This is useful when enclosing lambdas must speculatively capture
5084   /// variables that may or may not be used in certain specializations of
5085   /// a nested generic lambda.
5086   ///
5087   /// \returns true if an error occurred (i.e., the variable cannot be
5088   /// captured) and false if the capture succeeded.
5089   bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
5090                           SourceLocation EllipsisLoc, bool BuildAndDiagnose,
5091                           QualType &CaptureType,
5092                           QualType &DeclRefType,
5093                           const unsigned *const FunctionScopeIndexToStopAt);
5094 
5095   /// Try to capture the given variable.
5096   bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
5097                           TryCaptureKind Kind = TryCapture_Implicit,
5098                           SourceLocation EllipsisLoc = SourceLocation());
5099 
5100   /// Checks if the variable must be captured.
5101   bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
5102 
5103   /// Given a variable, determine the type that a reference to that
5104   /// variable will have in the given scope.
5105   QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
5106 
5107   /// Mark all of the declarations referenced within a particular AST node as
5108   /// referenced. Used when template instantiation instantiates a non-dependent
5109   /// type -- entities referenced by the type are now referenced.
5110   void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
5111   void MarkDeclarationsReferencedInExpr(Expr *E,
5112                                         bool SkipLocalVariables = false);
5113 
5114   /// Try to recover by turning the given expression into a
5115   /// call.  Returns true if recovery was attempted or an error was
5116   /// emitted; this may also leave the ExprResult invalid.
5117   bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
5118                             bool ForceComplain = false,
5119                             bool (*IsPlausibleResult)(QualType) = nullptr);
5120 
5121   /// Figure out if an expression could be turned into a call.
5122   bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
5123                      UnresolvedSetImpl &NonTemplateOverloads);
5124 
5125   /// Try to convert an expression \p E to type \p Ty. Returns the result of the
5126   /// conversion.
5127   ExprResult tryConvertExprToType(Expr *E, QualType Ty);
5128 
5129   /// Conditionally issue a diagnostic based on the statements's reachability
5130   /// analysis.
5131   ///
5132   /// \param Stmts If Stmts is non-empty, delay reporting the diagnostic until
5133   /// the function body is parsed, and then do a basic reachability analysis to
5134   /// determine if the statement is reachable. If it is unreachable, the
5135   /// diagnostic will not be emitted.
5136   bool DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
5137                        const PartialDiagnostic &PD);
5138 
5139   /// Conditionally issue a diagnostic based on the current
5140   /// evaluation context.
5141   ///
5142   /// \param Statement If Statement is non-null, delay reporting the
5143   /// diagnostic until the function body is parsed, and then do a basic
5144   /// reachability analysis to determine if the statement is reachable.
5145   /// If it is unreachable, the diagnostic will not be emitted.
5146   bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
5147                            const PartialDiagnostic &PD);
5148   /// Similar, but diagnostic is only produced if all the specified statements
5149   /// are reachable.
5150   bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
5151                            const PartialDiagnostic &PD);
5152 
5153   // Primary Expressions.
5154   SourceRange getExprRange(Expr *E) const;
5155 
5156   ExprResult ActOnIdExpression(
5157       Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5158       UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
5159       CorrectionCandidateCallback *CCC = nullptr,
5160       bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
5161 
5162   void DecomposeUnqualifiedId(const UnqualifiedId &Id,
5163                               TemplateArgumentListInfo &Buffer,
5164                               DeclarationNameInfo &NameInfo,
5165                               const TemplateArgumentListInfo *&TemplateArgs);
5166 
5167   bool DiagnoseDependentMemberLookup(LookupResult &R);
5168 
5169   bool
5170   DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
5171                       CorrectionCandidateCallback &CCC,
5172                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
5173                       ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
5174 
5175   DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
5176                                     IdentifierInfo *II);
5177   ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV);
5178 
5179   ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
5180                                 IdentifierInfo *II,
5181                                 bool AllowBuiltinCreation=false);
5182 
5183   ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
5184                                         SourceLocation TemplateKWLoc,
5185                                         const DeclarationNameInfo &NameInfo,
5186                                         bool isAddressOfOperand,
5187                                 const TemplateArgumentListInfo *TemplateArgs);
5188 
5189   /// If \p D cannot be odr-used in the current expression evaluation context,
5190   /// return a reason explaining why. Otherwise, return NOUR_None.
5191   NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D);
5192 
5193   DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
5194                                 SourceLocation Loc,
5195                                 const CXXScopeSpec *SS = nullptr);
5196   DeclRefExpr *
5197   BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
5198                    const DeclarationNameInfo &NameInfo,
5199                    const CXXScopeSpec *SS = nullptr,
5200                    NamedDecl *FoundD = nullptr,
5201                    SourceLocation TemplateKWLoc = SourceLocation(),
5202                    const TemplateArgumentListInfo *TemplateArgs = nullptr);
5203   DeclRefExpr *
5204   BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
5205                    const DeclarationNameInfo &NameInfo,
5206                    NestedNameSpecifierLoc NNS,
5207                    NamedDecl *FoundD = nullptr,
5208                    SourceLocation TemplateKWLoc = SourceLocation(),
5209                    const TemplateArgumentListInfo *TemplateArgs = nullptr);
5210 
5211   ExprResult
5212   BuildAnonymousStructUnionMemberReference(
5213       const CXXScopeSpec &SS,
5214       SourceLocation nameLoc,
5215       IndirectFieldDecl *indirectField,
5216       DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
5217       Expr *baseObjectExpr = nullptr,
5218       SourceLocation opLoc = SourceLocation());
5219 
5220   ExprResult BuildPossibleImplicitMemberExpr(
5221       const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R,
5222       const TemplateArgumentListInfo *TemplateArgs, const Scope *S,
5223       UnresolvedLookupExpr *AsULE = nullptr);
5224   ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
5225                                      SourceLocation TemplateKWLoc,
5226                                      LookupResult &R,
5227                                 const TemplateArgumentListInfo *TemplateArgs,
5228                                      bool IsDefiniteInstance,
5229                                      const Scope *S);
5230   bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
5231                                   const LookupResult &R,
5232                                   bool HasTrailingLParen);
5233 
5234   ExprResult
5235   BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
5236                                     const DeclarationNameInfo &NameInfo,
5237                                     bool IsAddressOfOperand, const Scope *S,
5238                                     TypeSourceInfo **RecoveryTSI = nullptr);
5239 
5240   ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
5241                                        SourceLocation TemplateKWLoc,
5242                                 const DeclarationNameInfo &NameInfo,
5243                                 const TemplateArgumentListInfo *TemplateArgs);
5244 
5245   ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
5246                                       LookupResult &R,
5247                                       bool NeedsADL,
5248                                       bool AcceptInvalidDecl = false);
5249   ExprResult BuildDeclarationNameExpr(
5250       const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
5251       NamedDecl *FoundD = nullptr,
5252       const TemplateArgumentListInfo *TemplateArgs = nullptr,
5253       bool AcceptInvalidDecl = false);
5254 
5255   ExprResult BuildLiteralOperatorCall(LookupResult &R,
5256                       DeclarationNameInfo &SuffixInfo,
5257                       ArrayRef<Expr *> Args,
5258                       SourceLocation LitEndLoc,
5259                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
5260 
5261   ExprResult BuildPredefinedExpr(SourceLocation Loc,
5262                                  PredefinedExpr::IdentKind IK);
5263   ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
5264   ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
5265 
5266   ExprResult BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
5267                                            SourceLocation LParen,
5268                                            SourceLocation RParen,
5269                                            TypeSourceInfo *TSI);
5270   ExprResult ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
5271                                            SourceLocation LParen,
5272                                            SourceLocation RParen,
5273                                            ParsedType ParsedTy);
5274 
5275   bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
5276 
5277   ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
5278   ExprResult ActOnCharacterConstant(const Token &Tok,
5279                                     Scope *UDLScope = nullptr);
5280   ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
5281   ExprResult ActOnParenListExpr(SourceLocation L,
5282                                 SourceLocation R,
5283                                 MultiExprArg Val);
5284 
5285   /// ActOnStringLiteral - The specified tokens were lexed as pasted string
5286   /// fragments (e.g. "foo" "bar" L"baz").
5287   ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
5288                                 Scope *UDLScope = nullptr);
5289 
5290   ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
5291                                        SourceLocation DefaultLoc,
5292                                        SourceLocation RParenLoc,
5293                                        Expr *ControllingExpr,
5294                                        ArrayRef<ParsedType> ArgTypes,
5295                                        ArrayRef<Expr *> ArgExprs);
5296   ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
5297                                         SourceLocation DefaultLoc,
5298                                         SourceLocation RParenLoc,
5299                                         Expr *ControllingExpr,
5300                                         ArrayRef<TypeSourceInfo *> Types,
5301                                         ArrayRef<Expr *> Exprs);
5302 
5303   // Binary/Unary Operators.  'Tok' is the token for the operator.
5304   ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
5305                                   Expr *InputExpr);
5306   ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
5307                           UnaryOperatorKind Opc, Expr *Input);
5308   ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5309                           tok::TokenKind Op, Expr *Input);
5310 
5311   bool isQualifiedMemberAccess(Expr *E);
5312   QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
5313 
5314   ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
5315                                             SourceLocation OpLoc,
5316                                             UnaryExprOrTypeTrait ExprKind,
5317                                             SourceRange R);
5318   ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
5319                                             UnaryExprOrTypeTrait ExprKind);
5320   ExprResult
5321     ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
5322                                   UnaryExprOrTypeTrait ExprKind,
5323                                   bool IsType, void *TyOrEx,
5324                                   SourceRange ArgRange);
5325 
5326   ExprResult CheckPlaceholderExpr(Expr *E);
5327   bool CheckVecStepExpr(Expr *E);
5328 
5329   bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
5330   bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
5331                                         SourceRange ExprRange,
5332                                         UnaryExprOrTypeTrait ExprKind);
5333   ExprResult ActOnSizeofParameterPackExpr(Scope *S,
5334                                           SourceLocation OpLoc,
5335                                           IdentifierInfo &Name,
5336                                           SourceLocation NameLoc,
5337                                           SourceLocation RParenLoc);
5338   ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
5339                                  tok::TokenKind Kind, Expr *Input);
5340 
5341   ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
5342                                      Expr *Idx, SourceLocation RLoc);
5343   ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5344                                              Expr *Idx, SourceLocation RLoc);
5345 
5346   ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
5347                                               Expr *ColumnIdx,
5348                                               SourceLocation RBLoc);
5349 
5350   ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
5351                                       Expr *LowerBound,
5352                                       SourceLocation ColonLocFirst,
5353                                       SourceLocation ColonLocSecond,
5354                                       Expr *Length, Expr *Stride,
5355                                       SourceLocation RBLoc);
5356   ExprResult ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5357                                       SourceLocation RParenLoc,
5358                                       ArrayRef<Expr *> Dims,
5359                                       ArrayRef<SourceRange> Brackets);
5360 
5361   /// Data structure for iterator expression.
5362   struct OMPIteratorData {
5363     IdentifierInfo *DeclIdent = nullptr;
5364     SourceLocation DeclIdentLoc;
5365     ParsedType Type;
5366     OMPIteratorExpr::IteratorRange Range;
5367     SourceLocation AssignLoc;
5368     SourceLocation ColonLoc;
5369     SourceLocation SecColonLoc;
5370   };
5371 
5372   ExprResult ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5373                                   SourceLocation LLoc, SourceLocation RLoc,
5374                                   ArrayRef<OMPIteratorData> Data);
5375 
5376   // This struct is for use by ActOnMemberAccess to allow
5377   // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
5378   // changing the access operator from a '.' to a '->' (to see if that is the
5379   // change needed to fix an error about an unknown member, e.g. when the class
5380   // defines a custom operator->).
5381   struct ActOnMemberAccessExtraArgs {
5382     Scope *S;
5383     UnqualifiedId &Id;
5384     Decl *ObjCImpDecl;
5385   };
5386 
5387   ExprResult BuildMemberReferenceExpr(
5388       Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
5389       CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5390       NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
5391       const TemplateArgumentListInfo *TemplateArgs,
5392       const Scope *S,
5393       ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
5394 
5395   ExprResult
5396   BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
5397                            bool IsArrow, const CXXScopeSpec &SS,
5398                            SourceLocation TemplateKWLoc,
5399                            NamedDecl *FirstQualifierInScope, LookupResult &R,
5400                            const TemplateArgumentListInfo *TemplateArgs,
5401                            const Scope *S,
5402                            bool SuppressQualifierCheck = false,
5403                            ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
5404 
5405   ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
5406                                      SourceLocation OpLoc,
5407                                      const CXXScopeSpec &SS, FieldDecl *Field,
5408                                      DeclAccessPair FoundDecl,
5409                                      const DeclarationNameInfo &MemberNameInfo);
5410 
5411   ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
5412 
5413   bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
5414                                      const CXXScopeSpec &SS,
5415                                      const LookupResult &R);
5416 
5417   ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
5418                                       bool IsArrow, SourceLocation OpLoc,
5419                                       const CXXScopeSpec &SS,
5420                                       SourceLocation TemplateKWLoc,
5421                                       NamedDecl *FirstQualifierInScope,
5422                                const DeclarationNameInfo &NameInfo,
5423                                const TemplateArgumentListInfo *TemplateArgs);
5424 
5425   ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
5426                                    SourceLocation OpLoc,
5427                                    tok::TokenKind OpKind,
5428                                    CXXScopeSpec &SS,
5429                                    SourceLocation TemplateKWLoc,
5430                                    UnqualifiedId &Member,
5431                                    Decl *ObjCImpDecl);
5432 
5433   MemberExpr *
5434   BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
5435                   const CXXScopeSpec *SS, SourceLocation TemplateKWLoc,
5436                   ValueDecl *Member, DeclAccessPair FoundDecl,
5437                   bool HadMultipleCandidates,
5438                   const DeclarationNameInfo &MemberNameInfo, QualType Ty,
5439                   ExprValueKind VK, ExprObjectKind OK,
5440                   const TemplateArgumentListInfo *TemplateArgs = nullptr);
5441   MemberExpr *
5442   BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
5443                   NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
5444                   ValueDecl *Member, DeclAccessPair FoundDecl,
5445                   bool HadMultipleCandidates,
5446                   const DeclarationNameInfo &MemberNameInfo, QualType Ty,
5447                   ExprValueKind VK, ExprObjectKind OK,
5448                   const TemplateArgumentListInfo *TemplateArgs = nullptr);
5449 
5450   void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
5451   bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5452                                FunctionDecl *FDecl,
5453                                const FunctionProtoType *Proto,
5454                                ArrayRef<Expr *> Args,
5455                                SourceLocation RParenLoc,
5456                                bool ExecConfig = false);
5457   void CheckStaticArrayArgument(SourceLocation CallLoc,
5458                                 ParmVarDecl *Param,
5459                                 const Expr *ArgExpr);
5460 
5461   /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5462   /// This provides the location of the left/right parens and a list of comma
5463   /// locations.
5464   ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
5465                            MultiExprArg ArgExprs, SourceLocation RParenLoc,
5466                            Expr *ExecConfig = nullptr);
5467   ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
5468                            MultiExprArg ArgExprs, SourceLocation RParenLoc,
5469                            Expr *ExecConfig = nullptr,
5470                            bool IsExecConfig = false,
5471                            bool AllowRecovery = false);
5472   Expr *BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
5473                              MultiExprArg CallArgs);
5474   enum class AtomicArgumentOrder { API, AST };
5475   ExprResult
5476   BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5477                   SourceLocation RParenLoc, MultiExprArg Args,
5478                   AtomicExpr::AtomicOp Op,
5479                   AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API);
5480   ExprResult
5481   BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
5482                         ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
5483                         Expr *Config = nullptr, bool IsExecConfig = false,
5484                         ADLCallKind UsesADL = ADLCallKind::NotADL);
5485 
5486   ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
5487                                      MultiExprArg ExecConfig,
5488                                      SourceLocation GGGLoc);
5489 
5490   ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5491                            Declarator &D, ParsedType &Ty,
5492                            SourceLocation RParenLoc, Expr *CastExpr);
5493   ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
5494                                  TypeSourceInfo *Ty,
5495                                  SourceLocation RParenLoc,
5496                                  Expr *Op);
5497   CastKind PrepareScalarCast(ExprResult &src, QualType destType);
5498 
5499   /// Build an altivec or OpenCL literal.
5500   ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
5501                                 SourceLocation RParenLoc, Expr *E,
5502                                 TypeSourceInfo *TInfo);
5503 
5504   ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
5505 
5506   ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
5507                                   ParsedType Ty,
5508                                   SourceLocation RParenLoc,
5509                                   Expr *InitExpr);
5510 
5511   ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
5512                                       TypeSourceInfo *TInfo,
5513                                       SourceLocation RParenLoc,
5514                                       Expr *LiteralExpr);
5515 
5516   ExprResult ActOnInitList(SourceLocation LBraceLoc,
5517                            MultiExprArg InitArgList,
5518                            SourceLocation RBraceLoc);
5519 
5520   ExprResult BuildInitList(SourceLocation LBraceLoc,
5521                            MultiExprArg InitArgList,
5522                            SourceLocation RBraceLoc);
5523 
5524   ExprResult ActOnDesignatedInitializer(Designation &Desig,
5525                                         SourceLocation EqualOrColonLoc,
5526                                         bool GNUSyntax,
5527                                         ExprResult Init);
5528 
5529 private:
5530   static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
5531 
5532 public:
5533   ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
5534                         tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
5535   ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
5536                         BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
5537   ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
5538                                 Expr *LHSExpr, Expr *RHSExpr);
5539   void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
5540                    UnresolvedSetImpl &Functions);
5541 
5542   void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
5543 
5544   /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
5545   /// in the case of a the GNU conditional expr extension.
5546   ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
5547                                 SourceLocation ColonLoc,
5548                                 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
5549 
5550   /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
5551   ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
5552                             LabelDecl *TheDecl);
5553 
5554   void ActOnStartStmtExpr();
5555   ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
5556                            SourceLocation RPLoc);
5557   ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
5558                            SourceLocation RPLoc, unsigned TemplateDepth);
5559   // Handle the final expression in a statement expression.
5560   ExprResult ActOnStmtExprResult(ExprResult E);
5561   void ActOnStmtExprError();
5562 
5563   // __builtin_offsetof(type, identifier(.identifier|[expr])*)
5564   struct OffsetOfComponent {
5565     SourceLocation LocStart, LocEnd;
5566     bool isBrackets;  // true if [expr], false if .ident
5567     union {
5568       IdentifierInfo *IdentInfo;
5569       Expr *E;
5570     } U;
5571   };
5572 
5573   /// __builtin_offsetof(type, a.b[123][456].c)
5574   ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
5575                                   TypeSourceInfo *TInfo,
5576                                   ArrayRef<OffsetOfComponent> Components,
5577                                   SourceLocation RParenLoc);
5578   ExprResult ActOnBuiltinOffsetOf(Scope *S,
5579                                   SourceLocation BuiltinLoc,
5580                                   SourceLocation TypeLoc,
5581                                   ParsedType ParsedArgTy,
5582                                   ArrayRef<OffsetOfComponent> Components,
5583                                   SourceLocation RParenLoc);
5584 
5585   // __builtin_choose_expr(constExpr, expr1, expr2)
5586   ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
5587                              Expr *CondExpr, Expr *LHSExpr,
5588                              Expr *RHSExpr, SourceLocation RPLoc);
5589 
5590   // __builtin_va_arg(expr, type)
5591   ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
5592                         SourceLocation RPLoc);
5593   ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
5594                             TypeSourceInfo *TInfo, SourceLocation RPLoc);
5595 
5596   // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(),
5597   // __builtin_COLUMN()
5598   ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
5599                                 SourceLocation BuiltinLoc,
5600                                 SourceLocation RPLoc);
5601 
5602   // Build a potentially resolved SourceLocExpr.
5603   ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
5604                                 SourceLocation BuiltinLoc, SourceLocation RPLoc,
5605                                 DeclContext *ParentContext);
5606 
5607   // __null
5608   ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
5609 
5610   bool CheckCaseExpression(Expr *E);
5611 
5612   /// Describes the result of an "if-exists" condition check.
5613   enum IfExistsResult {
5614     /// The symbol exists.
5615     IER_Exists,
5616 
5617     /// The symbol does not exist.
5618     IER_DoesNotExist,
5619 
5620     /// The name is a dependent name, so the results will differ
5621     /// from one instantiation to the next.
5622     IER_Dependent,
5623 
5624     /// An error occurred.
5625     IER_Error
5626   };
5627 
5628   IfExistsResult
5629   CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
5630                                const DeclarationNameInfo &TargetNameInfo);
5631 
5632   IfExistsResult
5633   CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
5634                                bool IsIfExists, CXXScopeSpec &SS,
5635                                UnqualifiedId &Name);
5636 
5637   StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
5638                                         bool IsIfExists,
5639                                         NestedNameSpecifierLoc QualifierLoc,
5640                                         DeclarationNameInfo NameInfo,
5641                                         Stmt *Nested);
5642   StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
5643                                         bool IsIfExists,
5644                                         CXXScopeSpec &SS, UnqualifiedId &Name,
5645                                         Stmt *Nested);
5646 
5647   //===------------------------- "Block" Extension ------------------------===//
5648 
5649   /// ActOnBlockStart - This callback is invoked when a block literal is
5650   /// started.
5651   void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
5652 
5653   /// ActOnBlockArguments - This callback allows processing of block arguments.
5654   /// If there are no arguments, this is still invoked.
5655   void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
5656                            Scope *CurScope);
5657 
5658   /// ActOnBlockError - If there is an error parsing a block, this callback
5659   /// is invoked to pop the information about the block from the action impl.
5660   void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
5661 
5662   /// ActOnBlockStmtExpr - This is called when the body of a block statement
5663   /// literal was successfully completed.  ^(int x){...}
5664   ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
5665                                 Scope *CurScope);
5666 
5667   //===---------------------------- Clang Extensions ----------------------===//
5668 
5669   /// __builtin_convertvector(...)
5670   ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5671                                     SourceLocation BuiltinLoc,
5672                                     SourceLocation RParenLoc);
5673 
5674   //===---------------------------- OpenCL Features -----------------------===//
5675 
5676   /// __builtin_astype(...)
5677   ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5678                              SourceLocation BuiltinLoc,
5679                              SourceLocation RParenLoc);
5680   ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy,
5681                              SourceLocation BuiltinLoc,
5682                              SourceLocation RParenLoc);
5683 
5684   //===---------------------------- C++ Features --------------------------===//
5685 
5686   // Act on C++ namespaces
5687   Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
5688                                SourceLocation NamespaceLoc,
5689                                SourceLocation IdentLoc, IdentifierInfo *Ident,
5690                                SourceLocation LBrace,
5691                                const ParsedAttributesView &AttrList,
5692                                UsingDirectiveDecl *&UsingDecl);
5693   void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
5694 
5695   NamespaceDecl *getStdNamespace() const;
5696   NamespaceDecl *getOrCreateStdNamespace();
5697 
5698   NamespaceDecl *lookupStdExperimentalNamespace();
5699 
5700   CXXRecordDecl *getStdBadAlloc() const;
5701   EnumDecl *getStdAlignValT() const;
5702 
5703 private:
5704   // A cache representing if we've fully checked the various comparison category
5705   // types stored in ASTContext. The bit-index corresponds to the integer value
5706   // of a ComparisonCategoryType enumerator.
5707   llvm::SmallBitVector FullyCheckedComparisonCategories;
5708 
5709   ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
5710                                          CXXScopeSpec &SS,
5711                                          ParsedType TemplateTypeTy,
5712                                          IdentifierInfo *MemberOrBase);
5713 
5714 public:
5715   enum class ComparisonCategoryUsage {
5716     /// The '<=>' operator was used in an expression and a builtin operator
5717     /// was selected.
5718     OperatorInExpression,
5719     /// A defaulted 'operator<=>' needed the comparison category. This
5720     /// typically only applies to 'std::strong_ordering', due to the implicit
5721     /// fallback return value.
5722     DefaultedOperator,
5723   };
5724 
5725   /// Lookup the specified comparison category types in the standard
5726   ///   library, an check the VarDecls possibly returned by the operator<=>
5727   ///   builtins for that type.
5728   ///
5729   /// \return The type of the comparison category type corresponding to the
5730   ///   specified Kind, or a null type if an error occurs
5731   QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
5732                                        SourceLocation Loc,
5733                                        ComparisonCategoryUsage Usage);
5734 
5735   /// Tests whether Ty is an instance of std::initializer_list and, if
5736   /// it is and Element is not NULL, assigns the element type to Element.
5737   bool isStdInitializerList(QualType Ty, QualType *Element);
5738 
5739   /// Looks for the std::initializer_list template and instantiates it
5740   /// with Element, or emits an error if it's not found.
5741   ///
5742   /// \returns The instantiated template, or null on error.
5743   QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
5744 
5745   /// Determine whether Ctor is an initializer-list constructor, as
5746   /// defined in [dcl.init.list]p2.
5747   bool isInitListConstructor(const FunctionDecl *Ctor);
5748 
5749   Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
5750                             SourceLocation NamespcLoc, CXXScopeSpec &SS,
5751                             SourceLocation IdentLoc,
5752                             IdentifierInfo *NamespcName,
5753                             const ParsedAttributesView &AttrList);
5754 
5755   void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
5756 
5757   Decl *ActOnNamespaceAliasDef(Scope *CurScope,
5758                                SourceLocation NamespaceLoc,
5759                                SourceLocation AliasLoc,
5760                                IdentifierInfo *Alias,
5761                                CXXScopeSpec &SS,
5762                                SourceLocation IdentLoc,
5763                                IdentifierInfo *Ident);
5764 
5765   void FilterUsingLookup(Scope *S, LookupResult &lookup);
5766   void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
5767   bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target,
5768                             const LookupResult &PreviousDecls,
5769                             UsingShadowDecl *&PrevShadow);
5770   UsingShadowDecl *BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
5771                                         NamedDecl *Target,
5772                                         UsingShadowDecl *PrevDecl);
5773 
5774   bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5775                                    bool HasTypenameKeyword,
5776                                    const CXXScopeSpec &SS,
5777                                    SourceLocation NameLoc,
5778                                    const LookupResult &Previous);
5779   bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
5780                                const CXXScopeSpec &SS,
5781                                const DeclarationNameInfo &NameInfo,
5782                                SourceLocation NameLoc,
5783                                const LookupResult *R = nullptr,
5784                                const UsingDecl *UD = nullptr);
5785 
5786   NamedDecl *BuildUsingDeclaration(
5787       Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
5788       bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
5789       DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
5790       const ParsedAttributesView &AttrList, bool IsInstantiation,
5791       bool IsUsingIfExists);
5792   NamedDecl *BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
5793                                        SourceLocation UsingLoc,
5794                                        SourceLocation EnumLoc,
5795                                        SourceLocation NameLoc, EnumDecl *ED);
5796   NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
5797                                 ArrayRef<NamedDecl *> Expansions);
5798 
5799   bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
5800 
5801   /// Given a derived-class using shadow declaration for a constructor and the
5802   /// correspnding base class constructor, find or create the implicit
5803   /// synthesized derived class constructor to use for this initialization.
5804   CXXConstructorDecl *
5805   findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
5806                             ConstructorUsingShadowDecl *DerivedShadow);
5807 
5808   Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
5809                               SourceLocation UsingLoc,
5810                               SourceLocation TypenameLoc, CXXScopeSpec &SS,
5811                               UnqualifiedId &Name, SourceLocation EllipsisLoc,
5812                               const ParsedAttributesView &AttrList);
5813   Decl *ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS,
5814                                   SourceLocation UsingLoc,
5815                                   SourceLocation EnumLoc, const DeclSpec &);
5816   Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
5817                               MultiTemplateParamsArg TemplateParams,
5818                               SourceLocation UsingLoc, UnqualifiedId &Name,
5819                               const ParsedAttributesView &AttrList,
5820                               TypeResult Type, Decl *DeclFromDeclSpec);
5821 
5822   /// BuildCXXConstructExpr - Creates a complete call to a constructor,
5823   /// including handling of its default argument expressions.
5824   ///
5825   /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
5826   ExprResult
5827   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5828                         NamedDecl *FoundDecl,
5829                         CXXConstructorDecl *Constructor, MultiExprArg Exprs,
5830                         bool HadMultipleCandidates, bool IsListInitialization,
5831                         bool IsStdInitListInitialization,
5832                         bool RequiresZeroInit, unsigned ConstructKind,
5833                         SourceRange ParenRange);
5834 
5835   /// Build a CXXConstructExpr whose constructor has already been resolved if
5836   /// it denotes an inherited constructor.
5837   ExprResult
5838   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5839                         CXXConstructorDecl *Constructor, bool Elidable,
5840                         MultiExprArg Exprs,
5841                         bool HadMultipleCandidates, bool IsListInitialization,
5842                         bool IsStdInitListInitialization,
5843                         bool RequiresZeroInit, unsigned ConstructKind,
5844                         SourceRange ParenRange);
5845 
5846   // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
5847   // the constructor can be elidable?
5848   ExprResult
5849   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5850                         NamedDecl *FoundDecl,
5851                         CXXConstructorDecl *Constructor, bool Elidable,
5852                         MultiExprArg Exprs, bool HadMultipleCandidates,
5853                         bool IsListInitialization,
5854                         bool IsStdInitListInitialization, bool RequiresZeroInit,
5855                         unsigned ConstructKind, SourceRange ParenRange);
5856 
5857   ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
5858 
5859 
5860   /// Instantiate or parse a C++ default argument expression as necessary.
5861   /// Return true on error.
5862   bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5863                               ParmVarDecl *Param);
5864 
5865   /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
5866   /// the default expr if needed.
5867   ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5868                                     FunctionDecl *FD,
5869                                     ParmVarDecl *Param);
5870 
5871   /// FinalizeVarWithDestructor - Prepare for calling destructor on the
5872   /// constructed variable.
5873   void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
5874 
5875   /// Helper class that collects exception specifications for
5876   /// implicitly-declared special member functions.
5877   class ImplicitExceptionSpecification {
5878     // Pointer to allow copying
5879     Sema *Self;
5880     // We order exception specifications thus:
5881     // noexcept is the most restrictive, but is only used in C++11.
5882     // throw() comes next.
5883     // Then a throw(collected exceptions)
5884     // Finally no specification, which is expressed as noexcept(false).
5885     // throw(...) is used instead if any called function uses it.
5886     ExceptionSpecificationType ComputedEST;
5887     llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
5888     SmallVector<QualType, 4> Exceptions;
5889 
ClearExceptions()5890     void ClearExceptions() {
5891       ExceptionsSeen.clear();
5892       Exceptions.clear();
5893     }
5894 
5895   public:
ImplicitExceptionSpecification(Sema & Self)5896     explicit ImplicitExceptionSpecification(Sema &Self)
5897       : Self(&Self), ComputedEST(EST_BasicNoexcept) {
5898       if (!Self.getLangOpts().CPlusPlus11)
5899         ComputedEST = EST_DynamicNone;
5900     }
5901 
5902     /// Get the computed exception specification type.
getExceptionSpecType()5903     ExceptionSpecificationType getExceptionSpecType() const {
5904       assert(!isComputedNoexcept(ComputedEST) &&
5905              "noexcept(expr) should not be a possible result");
5906       return ComputedEST;
5907     }
5908 
5909     /// The number of exceptions in the exception specification.
size()5910     unsigned size() const { return Exceptions.size(); }
5911 
5912     /// The set of exceptions in the exception specification.
data()5913     const QualType *data() const { return Exceptions.data(); }
5914 
5915     /// Integrate another called method into the collected data.
5916     void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
5917 
5918     /// Integrate an invoked expression into the collected data.
CalledExpr(Expr * E)5919     void CalledExpr(Expr *E) { CalledStmt(E); }
5920 
5921     /// Integrate an invoked statement into the collected data.
5922     void CalledStmt(Stmt *S);
5923 
5924     /// Overwrite an EPI's exception specification with this
5925     /// computed exception specification.
getExceptionSpec()5926     FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
5927       FunctionProtoType::ExceptionSpecInfo ESI;
5928       ESI.Type = getExceptionSpecType();
5929       if (ESI.Type == EST_Dynamic) {
5930         ESI.Exceptions = Exceptions;
5931       } else if (ESI.Type == EST_None) {
5932         /// C++11 [except.spec]p14:
5933         ///   The exception-specification is noexcept(false) if the set of
5934         ///   potential exceptions of the special member function contains "any"
5935         ESI.Type = EST_NoexceptFalse;
5936         ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
5937                                                      tok::kw_false).get();
5938       }
5939       return ESI;
5940     }
5941   };
5942 
5943   /// Evaluate the implicit exception specification for a defaulted
5944   /// special member function.
5945   void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD);
5946 
5947   /// Check the given noexcept-specifier, convert its expression, and compute
5948   /// the appropriate ExceptionSpecificationType.
5949   ExprResult ActOnNoexceptSpec(Expr *NoexceptExpr,
5950                                ExceptionSpecificationType &EST);
5951 
5952   /// Check the given exception-specification and update the
5953   /// exception specification information with the results.
5954   void checkExceptionSpecification(bool IsTopLevel,
5955                                    ExceptionSpecificationType EST,
5956                                    ArrayRef<ParsedType> DynamicExceptions,
5957                                    ArrayRef<SourceRange> DynamicExceptionRanges,
5958                                    Expr *NoexceptExpr,
5959                                    SmallVectorImpl<QualType> &Exceptions,
5960                                    FunctionProtoType::ExceptionSpecInfo &ESI);
5961 
5962   /// Determine if we're in a case where we need to (incorrectly) eagerly
5963   /// parse an exception specification to work around a libstdc++ bug.
5964   bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
5965 
5966   /// Add an exception-specification to the given member function
5967   /// (or member function template). The exception-specification was parsed
5968   /// after the method itself was declared.
5969   void actOnDelayedExceptionSpecification(Decl *Method,
5970          ExceptionSpecificationType EST,
5971          SourceRange SpecificationRange,
5972          ArrayRef<ParsedType> DynamicExceptions,
5973          ArrayRef<SourceRange> DynamicExceptionRanges,
5974          Expr *NoexceptExpr);
5975 
5976   class InheritedConstructorInfo;
5977 
5978   /// Determine if a special member function should have a deleted
5979   /// definition when it is defaulted.
5980   bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5981                                  InheritedConstructorInfo *ICI = nullptr,
5982                                  bool Diagnose = false);
5983 
5984   /// Produce notes explaining why a defaulted function was defined as deleted.
5985   void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD);
5986 
5987   /// Declare the implicit default constructor for the given class.
5988   ///
5989   /// \param ClassDecl The class declaration into which the implicit
5990   /// default constructor will be added.
5991   ///
5992   /// \returns The implicitly-declared default constructor.
5993   CXXConstructorDecl *DeclareImplicitDefaultConstructor(
5994                                                      CXXRecordDecl *ClassDecl);
5995 
5996   /// DefineImplicitDefaultConstructor - Checks for feasibility of
5997   /// defining this constructor as the default constructor.
5998   void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
5999                                         CXXConstructorDecl *Constructor);
6000 
6001   /// Declare the implicit destructor for the given class.
6002   ///
6003   /// \param ClassDecl The class declaration into which the implicit
6004   /// destructor will be added.
6005   ///
6006   /// \returns The implicitly-declared destructor.
6007   CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
6008 
6009   /// DefineImplicitDestructor - Checks for feasibility of
6010   /// defining this destructor as the default destructor.
6011   void DefineImplicitDestructor(SourceLocation CurrentLocation,
6012                                 CXXDestructorDecl *Destructor);
6013 
6014   /// Build an exception spec for destructors that don't have one.
6015   ///
6016   /// C++11 says that user-defined destructors with no exception spec get one
6017   /// that looks as if the destructor was implicitly declared.
6018   void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor);
6019 
6020   /// Define the specified inheriting constructor.
6021   void DefineInheritingConstructor(SourceLocation UseLoc,
6022                                    CXXConstructorDecl *Constructor);
6023 
6024   /// Declare the implicit copy constructor for the given class.
6025   ///
6026   /// \param ClassDecl The class declaration into which the implicit
6027   /// copy constructor will be added.
6028   ///
6029   /// \returns The implicitly-declared copy constructor.
6030   CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
6031 
6032   /// DefineImplicitCopyConstructor - Checks for feasibility of
6033   /// defining this constructor as the copy constructor.
6034   void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
6035                                      CXXConstructorDecl *Constructor);
6036 
6037   /// Declare the implicit move constructor for the given class.
6038   ///
6039   /// \param ClassDecl The Class declaration into which the implicit
6040   /// move constructor will be added.
6041   ///
6042   /// \returns The implicitly-declared move constructor, or NULL if it wasn't
6043   /// declared.
6044   CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
6045 
6046   /// DefineImplicitMoveConstructor - Checks for feasibility of
6047   /// defining this constructor as the move constructor.
6048   void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
6049                                      CXXConstructorDecl *Constructor);
6050 
6051   /// Declare the implicit copy assignment operator for the given class.
6052   ///
6053   /// \param ClassDecl The class declaration into which the implicit
6054   /// copy assignment operator will be added.
6055   ///
6056   /// \returns The implicitly-declared copy assignment operator.
6057   CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
6058 
6059   /// Defines an implicitly-declared copy assignment operator.
6060   void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
6061                                     CXXMethodDecl *MethodDecl);
6062 
6063   /// Declare the implicit move assignment operator for the given class.
6064   ///
6065   /// \param ClassDecl The Class declaration into which the implicit
6066   /// move assignment operator will be added.
6067   ///
6068   /// \returns The implicitly-declared move assignment operator, or NULL if it
6069   /// wasn't declared.
6070   CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
6071 
6072   /// Defines an implicitly-declared move assignment operator.
6073   void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
6074                                     CXXMethodDecl *MethodDecl);
6075 
6076   /// Force the declaration of any implicitly-declared members of this
6077   /// class.
6078   void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
6079 
6080   /// Check a completed declaration of an implicit special member.
6081   void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
6082 
6083   /// Determine whether the given function is an implicitly-deleted
6084   /// special member function.
6085   bool isImplicitlyDeleted(FunctionDecl *FD);
6086 
6087   /// Check whether 'this' shows up in the type of a static member
6088   /// function after the (naturally empty) cv-qualifier-seq would be.
6089   ///
6090   /// \returns true if an error occurred.
6091   bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
6092 
6093   /// Whether this' shows up in the exception specification of a static
6094   /// member function.
6095   bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
6096 
6097   /// Check whether 'this' shows up in the attributes of the given
6098   /// static member function.
6099   ///
6100   /// \returns true if an error occurred.
6101   bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
6102 
6103   /// MaybeBindToTemporary - If the passed in expression has a record type with
6104   /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
6105   /// it simply returns the passed in expression.
6106   ExprResult MaybeBindToTemporary(Expr *E);
6107 
6108   /// Wrap the expression in a ConstantExpr if it is a potential immediate
6109   /// invocation.
6110   ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl);
6111 
6112   bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
6113                                QualType DeclInitType, MultiExprArg ArgsPtr,
6114                                SourceLocation Loc,
6115                                SmallVectorImpl<Expr *> &ConvertedArgs,
6116                                bool AllowExplicit = false,
6117                                bool IsListInitialization = false);
6118 
6119   ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
6120                                           SourceLocation NameLoc,
6121                                           IdentifierInfo &Name);
6122 
6123   ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc,
6124                                 Scope *S, CXXScopeSpec &SS,
6125                                 bool EnteringContext);
6126   ParsedType getDestructorName(SourceLocation TildeLoc,
6127                                IdentifierInfo &II, SourceLocation NameLoc,
6128                                Scope *S, CXXScopeSpec &SS,
6129                                ParsedType ObjectType,
6130                                bool EnteringContext);
6131 
6132   ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
6133                                           ParsedType ObjectType);
6134 
6135   // Checks that reinterpret casts don't have undefined behavior.
6136   void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
6137                                       bool IsDereference, SourceRange Range);
6138 
6139   // Checks that the vector type should be initialized from a scalar
6140   // by splatting the value rather than populating a single element.
6141   // This is the case for AltiVecVector types as well as with
6142   // AltiVecPixel and AltiVecBool when -faltivec-src-compat=xl is specified.
6143   bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy);
6144 
6145   // Checks if the -faltivec-src-compat=gcc option is specified.
6146   // If so, AltiVecVector, AltiVecBool and AltiVecPixel types are
6147   // treated the same way as they are when trying to initialize
6148   // these vectors on gcc (an error is emitted).
6149   bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy,
6150                                   QualType SrcTy);
6151 
6152   /// ActOnCXXNamedCast - Parse
6153   /// {dynamic,static,reinterpret,const,addrspace}_cast's.
6154   ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
6155                                tok::TokenKind Kind,
6156                                SourceLocation LAngleBracketLoc,
6157                                Declarator &D,
6158                                SourceLocation RAngleBracketLoc,
6159                                SourceLocation LParenLoc,
6160                                Expr *E,
6161                                SourceLocation RParenLoc);
6162 
6163   ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
6164                                tok::TokenKind Kind,
6165                                TypeSourceInfo *Ty,
6166                                Expr *E,
6167                                SourceRange AngleBrackets,
6168                                SourceRange Parens);
6169 
6170   ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl,
6171                                      ExprResult Operand,
6172                                      SourceLocation RParenLoc);
6173 
6174   ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI,
6175                                      Expr *Operand, SourceLocation RParenLoc);
6176 
6177   ExprResult BuildCXXTypeId(QualType TypeInfoType,
6178                             SourceLocation TypeidLoc,
6179                             TypeSourceInfo *Operand,
6180                             SourceLocation RParenLoc);
6181   ExprResult BuildCXXTypeId(QualType TypeInfoType,
6182                             SourceLocation TypeidLoc,
6183                             Expr *Operand,
6184                             SourceLocation RParenLoc);
6185 
6186   /// ActOnCXXTypeid - Parse typeid( something ).
6187   ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
6188                             SourceLocation LParenLoc, bool isType,
6189                             void *TyOrExpr,
6190                             SourceLocation RParenLoc);
6191 
6192   ExprResult BuildCXXUuidof(QualType TypeInfoType,
6193                             SourceLocation TypeidLoc,
6194                             TypeSourceInfo *Operand,
6195                             SourceLocation RParenLoc);
6196   ExprResult BuildCXXUuidof(QualType TypeInfoType,
6197                             SourceLocation TypeidLoc,
6198                             Expr *Operand,
6199                             SourceLocation RParenLoc);
6200 
6201   /// ActOnCXXUuidof - Parse __uuidof( something ).
6202   ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
6203                             SourceLocation LParenLoc, bool isType,
6204                             void *TyOrExpr,
6205                             SourceLocation RParenLoc);
6206 
6207   /// Handle a C++1z fold-expression: ( expr op ... op expr ).
6208   ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS,
6209                               tok::TokenKind Operator,
6210                               SourceLocation EllipsisLoc, Expr *RHS,
6211                               SourceLocation RParenLoc);
6212   ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee,
6213                               SourceLocation LParenLoc, Expr *LHS,
6214                               BinaryOperatorKind Operator,
6215                               SourceLocation EllipsisLoc, Expr *RHS,
6216                               SourceLocation RParenLoc,
6217                               Optional<unsigned> NumExpansions);
6218   ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
6219                                    BinaryOperatorKind Operator);
6220 
6221   //// ActOnCXXThis -  Parse 'this' pointer.
6222   ExprResult ActOnCXXThis(SourceLocation loc);
6223 
6224   /// Build a CXXThisExpr and mark it referenced in the current context.
6225   Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
6226   void MarkThisReferenced(CXXThisExpr *This);
6227 
6228   /// Try to retrieve the type of the 'this' pointer.
6229   ///
6230   /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
6231   QualType getCurrentThisType();
6232 
6233   /// When non-NULL, the C++ 'this' expression is allowed despite the
6234   /// current context not being a non-static member function. In such cases,
6235   /// this provides the type used for 'this'.
6236   QualType CXXThisTypeOverride;
6237 
6238   /// RAII object used to temporarily allow the C++ 'this' expression
6239   /// to be used, with the given qualifiers on the current class type.
6240   class CXXThisScopeRAII {
6241     Sema &S;
6242     QualType OldCXXThisTypeOverride;
6243     bool Enabled;
6244 
6245   public:
6246     /// Introduce a new scope where 'this' may be allowed (when enabled),
6247     /// using the given declaration (which is either a class template or a
6248     /// class) along with the given qualifiers.
6249     /// along with the qualifiers placed on '*this'.
6250     CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
6251                      bool Enabled = true);
6252 
6253     ~CXXThisScopeRAII();
6254   };
6255 
6256   /// Make sure the value of 'this' is actually available in the current
6257   /// context, if it is a potentially evaluated context.
6258   ///
6259   /// \param Loc The location at which the capture of 'this' occurs.
6260   ///
6261   /// \param Explicit Whether 'this' is explicitly captured in a lambda
6262   /// capture list.
6263   ///
6264   /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
6265   /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
6266   /// This is useful when enclosing lambdas must speculatively capture
6267   /// 'this' that may or may not be used in certain specializations of
6268   /// a nested generic lambda (depending on whether the name resolves to
6269   /// a non-static member function or a static function).
6270   /// \return returns 'true' if failed, 'false' if success.
6271   bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
6272       bool BuildAndDiagnose = true,
6273       const unsigned *const FunctionScopeIndexToStopAt = nullptr,
6274       bool ByCopy = false);
6275 
6276   /// Determine whether the given type is the type of *this that is used
6277   /// outside of the body of a member function for a type that is currently
6278   /// being defined.
6279   bool isThisOutsideMemberFunctionBody(QualType BaseType);
6280 
6281   /// ActOnCXXBoolLiteral - Parse {true,false} literals.
6282   ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
6283 
6284 
6285   /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
6286   ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
6287 
6288   ExprResult
6289   ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
6290                                  SourceLocation AtLoc, SourceLocation RParen);
6291 
6292   /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
6293   ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
6294 
6295   //// ActOnCXXThrow -  Parse throw expressions.
6296   ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
6297   ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
6298                            bool IsThrownVarInScope);
6299   bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
6300 
6301   /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
6302   /// Can be interpreted either as function-style casting ("int(x)")
6303   /// or class type construction ("ClassType(x,y,z)")
6304   /// or creation of a value-initialized type ("int()").
6305   ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
6306                                        SourceLocation LParenOrBraceLoc,
6307                                        MultiExprArg Exprs,
6308                                        SourceLocation RParenOrBraceLoc,
6309                                        bool ListInitialization);
6310 
6311   ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
6312                                        SourceLocation LParenLoc,
6313                                        MultiExprArg Exprs,
6314                                        SourceLocation RParenLoc,
6315                                        bool ListInitialization);
6316 
6317   /// ActOnCXXNew - Parsed a C++ 'new' expression.
6318   ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
6319                          SourceLocation PlacementLParen,
6320                          MultiExprArg PlacementArgs,
6321                          SourceLocation PlacementRParen,
6322                          SourceRange TypeIdParens, Declarator &D,
6323                          Expr *Initializer);
6324   ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
6325                          SourceLocation PlacementLParen,
6326                          MultiExprArg PlacementArgs,
6327                          SourceLocation PlacementRParen,
6328                          SourceRange TypeIdParens,
6329                          QualType AllocType,
6330                          TypeSourceInfo *AllocTypeInfo,
6331                          Optional<Expr *> ArraySize,
6332                          SourceRange DirectInitRange,
6333                          Expr *Initializer);
6334 
6335   /// Determine whether \p FD is an aligned allocation or deallocation
6336   /// function that is unavailable.
6337   bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const;
6338 
6339   /// Produce diagnostics if \p FD is an aligned allocation or deallocation
6340   /// function that is unavailable.
6341   void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
6342                                             SourceLocation Loc);
6343 
6344   bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
6345                           SourceRange R);
6346 
6347   /// The scope in which to find allocation functions.
6348   enum AllocationFunctionScope {
6349     /// Only look for allocation functions in the global scope.
6350     AFS_Global,
6351     /// Only look for allocation functions in the scope of the
6352     /// allocated class.
6353     AFS_Class,
6354     /// Look for allocation functions in both the global scope
6355     /// and in the scope of the allocated class.
6356     AFS_Both
6357   };
6358 
6359   /// Finds the overloads of operator new and delete that are appropriate
6360   /// for the allocation.
6361   bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
6362                                AllocationFunctionScope NewScope,
6363                                AllocationFunctionScope DeleteScope,
6364                                QualType AllocType, bool IsArray,
6365                                bool &PassAlignment, MultiExprArg PlaceArgs,
6366                                FunctionDecl *&OperatorNew,
6367                                FunctionDecl *&OperatorDelete,
6368                                bool Diagnose = true);
6369   void DeclareGlobalNewDelete();
6370   void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
6371                                        ArrayRef<QualType> Params);
6372 
6373   bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
6374                                 DeclarationName Name, FunctionDecl* &Operator,
6375                                 bool Diagnose = true);
6376   FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
6377                                               bool CanProvideSize,
6378                                               bool Overaligned,
6379                                               DeclarationName Name);
6380   FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
6381                                                       CXXRecordDecl *RD);
6382 
6383   /// ActOnCXXDelete - Parsed a C++ 'delete' expression
6384   ExprResult ActOnCXXDelete(SourceLocation StartLoc,
6385                             bool UseGlobal, bool ArrayForm,
6386                             Expr *Operand);
6387   void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
6388                             bool IsDelete, bool CallCanBeVirtual,
6389                             bool WarnOnNonAbstractTypes,
6390                             SourceLocation DtorLoc);
6391 
6392   ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
6393                                Expr *Operand, SourceLocation RParen);
6394   ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
6395                                   SourceLocation RParen);
6396 
6397   /// Parsed one of the type trait support pseudo-functions.
6398   ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
6399                             ArrayRef<ParsedType> Args,
6400                             SourceLocation RParenLoc);
6401   ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
6402                             ArrayRef<TypeSourceInfo *> Args,
6403                             SourceLocation RParenLoc);
6404 
6405   /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
6406   /// pseudo-functions.
6407   ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
6408                                  SourceLocation KWLoc,
6409                                  ParsedType LhsTy,
6410                                  Expr *DimExpr,
6411                                  SourceLocation RParen);
6412 
6413   ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
6414                                  SourceLocation KWLoc,
6415                                  TypeSourceInfo *TSInfo,
6416                                  Expr *DimExpr,
6417                                  SourceLocation RParen);
6418 
6419   /// ActOnExpressionTrait - Parsed one of the unary type trait support
6420   /// pseudo-functions.
6421   ExprResult ActOnExpressionTrait(ExpressionTrait OET,
6422                                   SourceLocation KWLoc,
6423                                   Expr *Queried,
6424                                   SourceLocation RParen);
6425 
6426   ExprResult BuildExpressionTrait(ExpressionTrait OET,
6427                                   SourceLocation KWLoc,
6428                                   Expr *Queried,
6429                                   SourceLocation RParen);
6430 
6431   ExprResult ActOnStartCXXMemberReference(Scope *S,
6432                                           Expr *Base,
6433                                           SourceLocation OpLoc,
6434                                           tok::TokenKind OpKind,
6435                                           ParsedType &ObjectType,
6436                                           bool &MayBePseudoDestructor);
6437 
6438   ExprResult BuildPseudoDestructorExpr(Expr *Base,
6439                                        SourceLocation OpLoc,
6440                                        tok::TokenKind OpKind,
6441                                        const CXXScopeSpec &SS,
6442                                        TypeSourceInfo *ScopeType,
6443                                        SourceLocation CCLoc,
6444                                        SourceLocation TildeLoc,
6445                                      PseudoDestructorTypeStorage DestroyedType);
6446 
6447   ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6448                                        SourceLocation OpLoc,
6449                                        tok::TokenKind OpKind,
6450                                        CXXScopeSpec &SS,
6451                                        UnqualifiedId &FirstTypeName,
6452                                        SourceLocation CCLoc,
6453                                        SourceLocation TildeLoc,
6454                                        UnqualifiedId &SecondTypeName);
6455 
6456   ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6457                                        SourceLocation OpLoc,
6458                                        tok::TokenKind OpKind,
6459                                        SourceLocation TildeLoc,
6460                                        const DeclSpec& DS);
6461 
6462   /// MaybeCreateExprWithCleanups - If the current full-expression
6463   /// requires any cleanups, surround it with a ExprWithCleanups node.
6464   /// Otherwise, just returns the passed-in expression.
6465   Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
6466   Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
6467   ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
6468 
6469   MaterializeTemporaryExpr *
6470   CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
6471                                  bool BoundToLvalueReference);
6472 
ActOnFinishFullExpr(Expr * Expr,bool DiscardedValue)6473   ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
6474     return ActOnFinishFullExpr(
6475         Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
6476   }
6477   ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
6478                                  bool DiscardedValue, bool IsConstexpr = false);
6479   StmtResult ActOnFinishFullStmt(Stmt *Stmt);
6480 
6481   // Marks SS invalid if it represents an incomplete type.
6482   bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
6483   // Complete an enum decl, maybe without a scope spec.
6484   bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L,
6485                                CXXScopeSpec *SS = nullptr);
6486 
6487   DeclContext *computeDeclContext(QualType T);
6488   DeclContext *computeDeclContext(const CXXScopeSpec &SS,
6489                                   bool EnteringContext = false);
6490   bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
6491   CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
6492 
6493   /// The parser has parsed a global nested-name-specifier '::'.
6494   ///
6495   /// \param CCLoc The location of the '::'.
6496   ///
6497   /// \param SS The nested-name-specifier, which will be updated in-place
6498   /// to reflect the parsed nested-name-specifier.
6499   ///
6500   /// \returns true if an error occurred, false otherwise.
6501   bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
6502 
6503   /// The parser has parsed a '__super' nested-name-specifier.
6504   ///
6505   /// \param SuperLoc The location of the '__super' keyword.
6506   ///
6507   /// \param ColonColonLoc The location of the '::'.
6508   ///
6509   /// \param SS The nested-name-specifier, which will be updated in-place
6510   /// to reflect the parsed nested-name-specifier.
6511   ///
6512   /// \returns true if an error occurred, false otherwise.
6513   bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
6514                                 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
6515 
6516   bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
6517                                        bool *CanCorrect = nullptr);
6518   NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
6519 
6520   /// Keeps information about an identifier in a nested-name-spec.
6521   ///
6522   struct NestedNameSpecInfo {
6523     /// The type of the object, if we're parsing nested-name-specifier in
6524     /// a member access expression.
6525     ParsedType ObjectType;
6526 
6527     /// The identifier preceding the '::'.
6528     IdentifierInfo *Identifier;
6529 
6530     /// The location of the identifier.
6531     SourceLocation IdentifierLoc;
6532 
6533     /// The location of the '::'.
6534     SourceLocation CCLoc;
6535 
6536     /// Creates info object for the most typical case.
6537     NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
6538              SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
ObjectTypeNestedNameSpecInfo6539       : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
6540         CCLoc(ColonColonLoc) {
6541     }
6542 
NestedNameSpecInfoNestedNameSpecInfo6543     NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
6544                        SourceLocation ColonColonLoc, QualType ObjectType)
6545       : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
6546         IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
6547     }
6548   };
6549 
6550   bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
6551                                     NestedNameSpecInfo &IdInfo);
6552 
6553   bool BuildCXXNestedNameSpecifier(Scope *S,
6554                                    NestedNameSpecInfo &IdInfo,
6555                                    bool EnteringContext,
6556                                    CXXScopeSpec &SS,
6557                                    NamedDecl *ScopeLookupResult,
6558                                    bool ErrorRecoveryLookup,
6559                                    bool *IsCorrectedToColon = nullptr,
6560                                    bool OnlyNamespace = false);
6561 
6562   /// The parser has parsed a nested-name-specifier 'identifier::'.
6563   ///
6564   /// \param S The scope in which this nested-name-specifier occurs.
6565   ///
6566   /// \param IdInfo Parser information about an identifier in the
6567   /// nested-name-spec.
6568   ///
6569   /// \param EnteringContext Whether we're entering the context nominated by
6570   /// this nested-name-specifier.
6571   ///
6572   /// \param SS The nested-name-specifier, which is both an input
6573   /// parameter (the nested-name-specifier before this type) and an
6574   /// output parameter (containing the full nested-name-specifier,
6575   /// including this new type).
6576   ///
6577   /// \param ErrorRecoveryLookup If true, then this method is called to improve
6578   /// error recovery. In this case do not emit error message.
6579   ///
6580   /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
6581   /// are allowed.  The bool value pointed by this parameter is set to 'true'
6582   /// if the identifier is treated as if it was followed by ':', not '::'.
6583   ///
6584   /// \param OnlyNamespace If true, only considers namespaces in lookup.
6585   ///
6586   /// \returns true if an error occurred, false otherwise.
6587   bool ActOnCXXNestedNameSpecifier(Scope *S,
6588                                    NestedNameSpecInfo &IdInfo,
6589                                    bool EnteringContext,
6590                                    CXXScopeSpec &SS,
6591                                    bool ErrorRecoveryLookup = false,
6592                                    bool *IsCorrectedToColon = nullptr,
6593                                    bool OnlyNamespace = false);
6594 
6595   ExprResult ActOnDecltypeExpression(Expr *E);
6596 
6597   bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
6598                                            const DeclSpec &DS,
6599                                            SourceLocation ColonColonLoc);
6600 
6601   bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
6602                                  NestedNameSpecInfo &IdInfo,
6603                                  bool EnteringContext);
6604 
6605   /// The parser has parsed a nested-name-specifier
6606   /// 'template[opt] template-name < template-args >::'.
6607   ///
6608   /// \param S The scope in which this nested-name-specifier occurs.
6609   ///
6610   /// \param SS The nested-name-specifier, which is both an input
6611   /// parameter (the nested-name-specifier before this type) and an
6612   /// output parameter (containing the full nested-name-specifier,
6613   /// including this new type).
6614   ///
6615   /// \param TemplateKWLoc the location of the 'template' keyword, if any.
6616   /// \param TemplateName the template name.
6617   /// \param TemplateNameLoc The location of the template name.
6618   /// \param LAngleLoc The location of the opening angle bracket  ('<').
6619   /// \param TemplateArgs The template arguments.
6620   /// \param RAngleLoc The location of the closing angle bracket  ('>').
6621   /// \param CCLoc The location of the '::'.
6622   ///
6623   /// \param EnteringContext Whether we're entering the context of the
6624   /// nested-name-specifier.
6625   ///
6626   ///
6627   /// \returns true if an error occurred, false otherwise.
6628   bool ActOnCXXNestedNameSpecifier(Scope *S,
6629                                    CXXScopeSpec &SS,
6630                                    SourceLocation TemplateKWLoc,
6631                                    TemplateTy TemplateName,
6632                                    SourceLocation TemplateNameLoc,
6633                                    SourceLocation LAngleLoc,
6634                                    ASTTemplateArgsPtr TemplateArgs,
6635                                    SourceLocation RAngleLoc,
6636                                    SourceLocation CCLoc,
6637                                    bool EnteringContext);
6638 
6639   /// Given a C++ nested-name-specifier, produce an annotation value
6640   /// that the parser can use later to reconstruct the given
6641   /// nested-name-specifier.
6642   ///
6643   /// \param SS A nested-name-specifier.
6644   ///
6645   /// \returns A pointer containing all of the information in the
6646   /// nested-name-specifier \p SS.
6647   void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
6648 
6649   /// Given an annotation pointer for a nested-name-specifier, restore
6650   /// the nested-name-specifier structure.
6651   ///
6652   /// \param Annotation The annotation pointer, produced by
6653   /// \c SaveNestedNameSpecifierAnnotation().
6654   ///
6655   /// \param AnnotationRange The source range corresponding to the annotation.
6656   ///
6657   /// \param SS The nested-name-specifier that will be updated with the contents
6658   /// of the annotation pointer.
6659   void RestoreNestedNameSpecifierAnnotation(void *Annotation,
6660                                             SourceRange AnnotationRange,
6661                                             CXXScopeSpec &SS);
6662 
6663   bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
6664 
6665   /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
6666   /// scope or nested-name-specifier) is parsed, part of a declarator-id.
6667   /// After this method is called, according to [C++ 3.4.3p3], names should be
6668   /// looked up in the declarator-id's scope, until the declarator is parsed and
6669   /// ActOnCXXExitDeclaratorScope is called.
6670   /// The 'SS' should be a non-empty valid CXXScopeSpec.
6671   bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
6672 
6673   /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
6674   /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
6675   /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
6676   /// Used to indicate that names should revert to being looked up in the
6677   /// defining scope.
6678   void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
6679 
6680   /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
6681   /// initializer for the declaration 'Dcl'.
6682   /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6683   /// static data member of class X, names should be looked up in the scope of
6684   /// class X.
6685   void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
6686 
6687   /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
6688   /// initializer for the declaration 'Dcl'.
6689   void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
6690 
6691   /// Create a new lambda closure type.
6692   CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
6693                                          TypeSourceInfo *Info,
6694                                          bool KnownDependent,
6695                                          LambdaCaptureDefault CaptureDefault);
6696 
6697   /// Start the definition of a lambda expression.
6698   CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
6699                                        SourceRange IntroducerRange,
6700                                        TypeSourceInfo *MethodType,
6701                                        SourceLocation EndLoc,
6702                                        ArrayRef<ParmVarDecl *> Params,
6703                                        ConstexprSpecKind ConstexprKind,
6704                                        Expr *TrailingRequiresClause);
6705 
6706   /// Number lambda for linkage purposes if necessary.
6707   void handleLambdaNumbering(
6708       CXXRecordDecl *Class, CXXMethodDecl *Method,
6709       Optional<std::tuple<bool, unsigned, unsigned, Decl *>> Mangling = None);
6710 
6711   /// Endow the lambda scope info with the relevant properties.
6712   void buildLambdaScope(sema::LambdaScopeInfo *LSI,
6713                         CXXMethodDecl *CallOperator,
6714                         SourceRange IntroducerRange,
6715                         LambdaCaptureDefault CaptureDefault,
6716                         SourceLocation CaptureDefaultLoc,
6717                         bool ExplicitParams,
6718                         bool ExplicitResultType,
6719                         bool Mutable);
6720 
6721   /// Perform initialization analysis of the init-capture and perform
6722   /// any implicit conversions such as an lvalue-to-rvalue conversion if
6723   /// not being used to initialize a reference.
actOnLambdaInitCaptureInitialization(SourceLocation Loc,bool ByRef,SourceLocation EllipsisLoc,IdentifierInfo * Id,LambdaCaptureInitKind InitKind,Expr * & Init)6724   ParsedType actOnLambdaInitCaptureInitialization(
6725       SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
6726       IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
6727     return ParsedType::make(buildLambdaInitCaptureInitialization(
6728         Loc, ByRef, EllipsisLoc, None, Id,
6729         InitKind != LambdaCaptureInitKind::CopyInit, Init));
6730   }
6731   QualType buildLambdaInitCaptureInitialization(
6732       SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
6733       Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit,
6734       Expr *&Init);
6735 
6736   /// Create a dummy variable within the declcontext of the lambda's
6737   ///  call operator, for name lookup purposes for a lambda init capture.
6738   ///
6739   ///  CodeGen handles emission of lambda captures, ignoring these dummy
6740   ///  variables appropriately.
6741   VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
6742                                           QualType InitCaptureType,
6743                                           SourceLocation EllipsisLoc,
6744                                           IdentifierInfo *Id,
6745                                           unsigned InitStyle, Expr *Init);
6746 
6747   /// Add an init-capture to a lambda scope.
6748   void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var);
6749 
6750   /// Note that we have finished the explicit captures for the
6751   /// given lambda.
6752   void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
6753 
6754   /// \brief This is called after parsing the explicit template parameter list
6755   /// on a lambda (if it exists) in C++2a.
6756   void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc,
6757                                                 ArrayRef<NamedDecl *> TParams,
6758                                                 SourceLocation RAngleLoc,
6759                                                 ExprResult RequiresClause);
6760 
6761   /// Introduce the lambda parameters into scope.
6762   void addLambdaParameters(
6763       ArrayRef<LambdaIntroducer::LambdaCapture> Captures,
6764       CXXMethodDecl *CallOperator, Scope *CurScope);
6765 
6766   /// Deduce a block or lambda's return type based on the return
6767   /// statements present in the body.
6768   void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
6769 
6770   /// ActOnStartOfLambdaDefinition - This is called just before we start
6771   /// parsing the body of a lambda; it analyzes the explicit captures and
6772   /// arguments, and sets up various data-structures for the body of the
6773   /// lambda.
6774   void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
6775                                     Declarator &ParamInfo, Scope *CurScope);
6776 
6777   /// ActOnLambdaError - If there is an error parsing a lambda, this callback
6778   /// is invoked to pop the information about the lambda.
6779   void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
6780                         bool IsInstantiation = false);
6781 
6782   /// ActOnLambdaExpr - This is called when the body of a lambda expression
6783   /// was successfully completed.
6784   ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
6785                              Scope *CurScope);
6786 
6787   /// Does copying/destroying the captured variable have side effects?
6788   bool CaptureHasSideEffects(const sema::Capture &From);
6789 
6790   /// Diagnose if an explicit lambda capture is unused. Returns true if a
6791   /// diagnostic is emitted.
6792   bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
6793                                    const sema::Capture &From);
6794 
6795   /// Build a FieldDecl suitable to hold the given capture.
6796   FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture);
6797 
6798   /// Initialize the given capture with a suitable expression.
6799   ExprResult BuildCaptureInit(const sema::Capture &Capture,
6800                               SourceLocation ImplicitCaptureLoc,
6801                               bool IsOpenMPMapping = false);
6802 
6803   /// Complete a lambda-expression having processed and attached the
6804   /// lambda body.
6805   ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
6806                              sema::LambdaScopeInfo *LSI);
6807 
6808   /// Get the return type to use for a lambda's conversion function(s) to
6809   /// function pointer type, given the type of the call operator.
6810   QualType
6811   getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType,
6812                                         CallingConv CC);
6813 
6814   /// Define the "body" of the conversion from a lambda object to a
6815   /// function pointer.
6816   ///
6817   /// This routine doesn't actually define a sensible body; rather, it fills
6818   /// in the initialization expression needed to copy the lambda object into
6819   /// the block, and IR generation actually generates the real body of the
6820   /// block pointer conversion.
6821   void DefineImplicitLambdaToFunctionPointerConversion(
6822          SourceLocation CurrentLoc, CXXConversionDecl *Conv);
6823 
6824   /// Define the "body" of the conversion from a lambda object to a
6825   /// block pointer.
6826   ///
6827   /// This routine doesn't actually define a sensible body; rather, it fills
6828   /// in the initialization expression needed to copy the lambda object into
6829   /// the block, and IR generation actually generates the real body of the
6830   /// block pointer conversion.
6831   void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
6832                                                     CXXConversionDecl *Conv);
6833 
6834   ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
6835                                            SourceLocation ConvLocation,
6836                                            CXXConversionDecl *Conv,
6837                                            Expr *Src);
6838 
6839   /// Check whether the given expression is a valid constraint expression.
6840   /// A diagnostic is emitted if it is not, false is returned, and
6841   /// PossibleNonPrimary will be set to true if the failure might be due to a
6842   /// non-primary expression being used as an atomic constraint.
6843   bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(),
6844                                  bool *PossibleNonPrimary = nullptr,
6845                                  bool IsTrailingRequiresClause = false);
6846 
6847 private:
6848   /// Caches pairs of template-like decls whose associated constraints were
6849   /// checked for subsumption and whether or not the first's constraints did in
6850   /// fact subsume the second's.
6851   llvm::DenseMap<std::pair<NamedDecl *, NamedDecl *>, bool> SubsumptionCache;
6852   /// Caches the normalized associated constraints of declarations (concepts or
6853   /// constrained declarations). If an error occurred while normalizing the
6854   /// associated constraints of the template or concept, nullptr will be cached
6855   /// here.
6856   llvm::DenseMap<NamedDecl *, NormalizedConstraint *>
6857       NormalizationCache;
6858 
6859   llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &>
6860       SatisfactionCache;
6861 
6862 public:
6863   const NormalizedConstraint *
6864   getNormalizedAssociatedConstraints(
6865       NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints);
6866 
6867   /// \brief Check whether the given declaration's associated constraints are
6868   /// at least as constrained than another declaration's according to the
6869   /// partial ordering of constraints.
6870   ///
6871   /// \param Result If no error occurred, receives the result of true if D1 is
6872   /// at least constrained than D2, and false otherwise.
6873   ///
6874   /// \returns true if an error occurred, false otherwise.
6875   bool IsAtLeastAsConstrained(NamedDecl *D1, ArrayRef<const Expr *> AC1,
6876                               NamedDecl *D2, ArrayRef<const Expr *> AC2,
6877                               bool &Result);
6878 
6879   /// If D1 was not at least as constrained as D2, but would've been if a pair
6880   /// of atomic constraints involved had been declared in a concept and not
6881   /// repeated in two separate places in code.
6882   /// \returns true if such a diagnostic was emitted, false otherwise.
6883   bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1,
6884       ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2);
6885 
6886   /// \brief Check whether the given list of constraint expressions are
6887   /// satisfied (as if in a 'conjunction') given template arguments.
6888   /// \param Template the template-like entity that triggered the constraints
6889   /// check (either a concept or a constrained entity).
6890   /// \param ConstraintExprs a list of constraint expressions, treated as if
6891   /// they were 'AND'ed together.
6892   /// \param TemplateArgs the list of template arguments to substitute into the
6893   /// constraint expression.
6894   /// \param TemplateIDRange The source range of the template id that
6895   /// caused the constraints check.
6896   /// \param Satisfaction if true is returned, will contain details of the
6897   /// satisfaction, with enough information to diagnose an unsatisfied
6898   /// expression.
6899   /// \returns true if an error occurred and satisfaction could not be checked,
6900   /// false otherwise.
6901   bool CheckConstraintSatisfaction(
6902       const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs,
6903       ArrayRef<TemplateArgument> TemplateArgs,
6904       SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction);
6905 
6906   /// \brief Check whether the given non-dependent constraint expression is
6907   /// satisfied. Returns false and updates Satisfaction with the satisfaction
6908   /// verdict if successful, emits a diagnostic and returns true if an error
6909   /// occured and satisfaction could not be determined.
6910   ///
6911   /// \returns true if an error occurred, false otherwise.
6912   bool CheckConstraintSatisfaction(const Expr *ConstraintExpr,
6913                                    ConstraintSatisfaction &Satisfaction);
6914 
6915   /// Check whether the given function decl's trailing requires clause is
6916   /// satisfied, if any. Returns false and updates Satisfaction with the
6917   /// satisfaction verdict if successful, emits a diagnostic and returns true if
6918   /// an error occured and satisfaction could not be determined.
6919   ///
6920   /// \returns true if an error occurred, false otherwise.
6921   bool CheckFunctionConstraints(const FunctionDecl *FD,
6922                                 ConstraintSatisfaction &Satisfaction,
6923                                 SourceLocation UsageLoc = SourceLocation());
6924 
6925 
6926   /// \brief Ensure that the given template arguments satisfy the constraints
6927   /// associated with the given template, emitting a diagnostic if they do not.
6928   ///
6929   /// \param Template The template to which the template arguments are being
6930   /// provided.
6931   ///
6932   /// \param TemplateArgs The converted, canonicalized template arguments.
6933   ///
6934   /// \param TemplateIDRange The source range of the template id that
6935   /// caused the constraints check.
6936   ///
6937   /// \returns true if the constrains are not satisfied or could not be checked
6938   /// for satisfaction, false if the constraints are satisfied.
6939   bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template,
6940                                        ArrayRef<TemplateArgument> TemplateArgs,
6941                                              SourceRange TemplateIDRange);
6942 
6943   /// \brief Emit diagnostics explaining why a constraint expression was deemed
6944   /// unsatisfied.
6945   /// \param First whether this is the first time an unsatisfied constraint is
6946   /// diagnosed for this error.
6947   void
6948   DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction,
6949                                 bool First = true);
6950 
6951   /// \brief Emit diagnostics explaining why a constraint expression was deemed
6952   /// unsatisfied.
6953   void
6954   DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction &Satisfaction,
6955                                 bool First = true);
6956 
6957   // ParseObjCStringLiteral - Parse Objective-C string literals.
6958   ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
6959                                     ArrayRef<Expr *> Strings);
6960 
6961   ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
6962 
6963   /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
6964   /// numeric literal expression. Type of the expression will be "NSNumber *"
6965   /// or "id" if NSNumber is unavailable.
6966   ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
6967   ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
6968                                   bool Value);
6969   ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
6970 
6971   /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
6972   /// '@' prefixed parenthesized expression. The type of the expression will
6973   /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
6974   /// of ValueType, which is allowed to be a built-in numeric type, "char *",
6975   /// "const char *" or C structure with attribute 'objc_boxable'.
6976   ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
6977 
6978   ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
6979                                           Expr *IndexExpr,
6980                                           ObjCMethodDecl *getterMethod,
6981                                           ObjCMethodDecl *setterMethod);
6982 
6983   ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
6984                                MutableArrayRef<ObjCDictionaryElement> Elements);
6985 
6986   ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
6987                                   TypeSourceInfo *EncodedTypeInfo,
6988                                   SourceLocation RParenLoc);
6989   ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
6990                                     CXXConversionDecl *Method,
6991                                     bool HadMultipleCandidates);
6992 
6993   ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
6994                                        SourceLocation EncodeLoc,
6995                                        SourceLocation LParenLoc,
6996                                        ParsedType Ty,
6997                                        SourceLocation RParenLoc);
6998 
6999   /// ParseObjCSelectorExpression - Build selector expression for \@selector
7000   ExprResult ParseObjCSelectorExpression(Selector Sel,
7001                                          SourceLocation AtLoc,
7002                                          SourceLocation SelLoc,
7003                                          SourceLocation LParenLoc,
7004                                          SourceLocation RParenLoc,
7005                                          bool WarnMultipleSelectors);
7006 
7007   /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
7008   ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
7009                                          SourceLocation AtLoc,
7010                                          SourceLocation ProtoLoc,
7011                                          SourceLocation LParenLoc,
7012                                          SourceLocation ProtoIdLoc,
7013                                          SourceLocation RParenLoc);
7014 
7015   //===--------------------------------------------------------------------===//
7016   // C++ Declarations
7017   //
7018   Decl *ActOnStartLinkageSpecification(Scope *S,
7019                                        SourceLocation ExternLoc,
7020                                        Expr *LangStr,
7021                                        SourceLocation LBraceLoc);
7022   Decl *ActOnFinishLinkageSpecification(Scope *S,
7023                                         Decl *LinkageSpec,
7024                                         SourceLocation RBraceLoc);
7025 
7026 
7027   //===--------------------------------------------------------------------===//
7028   // C++ Classes
7029   //
7030   CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS);
7031   bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
7032                           const CXXScopeSpec *SS = nullptr);
7033   bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
7034 
7035   bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
7036                             SourceLocation ColonLoc,
7037                             const ParsedAttributesView &Attrs);
7038 
7039   NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
7040                                  Declarator &D,
7041                                  MultiTemplateParamsArg TemplateParameterLists,
7042                                  Expr *BitfieldWidth, const VirtSpecifiers &VS,
7043                                  InClassInitStyle InitStyle);
7044 
7045   void ActOnStartCXXInClassMemberInitializer();
7046   void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
7047                                               SourceLocation EqualLoc,
7048                                               Expr *Init);
7049 
7050   MemInitResult ActOnMemInitializer(Decl *ConstructorD,
7051                                     Scope *S,
7052                                     CXXScopeSpec &SS,
7053                                     IdentifierInfo *MemberOrBase,
7054                                     ParsedType TemplateTypeTy,
7055                                     const DeclSpec &DS,
7056                                     SourceLocation IdLoc,
7057                                     SourceLocation LParenLoc,
7058                                     ArrayRef<Expr *> Args,
7059                                     SourceLocation RParenLoc,
7060                                     SourceLocation EllipsisLoc);
7061 
7062   MemInitResult ActOnMemInitializer(Decl *ConstructorD,
7063                                     Scope *S,
7064                                     CXXScopeSpec &SS,
7065                                     IdentifierInfo *MemberOrBase,
7066                                     ParsedType TemplateTypeTy,
7067                                     const DeclSpec &DS,
7068                                     SourceLocation IdLoc,
7069                                     Expr *InitList,
7070                                     SourceLocation EllipsisLoc);
7071 
7072   MemInitResult BuildMemInitializer(Decl *ConstructorD,
7073                                     Scope *S,
7074                                     CXXScopeSpec &SS,
7075                                     IdentifierInfo *MemberOrBase,
7076                                     ParsedType TemplateTypeTy,
7077                                     const DeclSpec &DS,
7078                                     SourceLocation IdLoc,
7079                                     Expr *Init,
7080                                     SourceLocation EllipsisLoc);
7081 
7082   MemInitResult BuildMemberInitializer(ValueDecl *Member,
7083                                        Expr *Init,
7084                                        SourceLocation IdLoc);
7085 
7086   MemInitResult BuildBaseInitializer(QualType BaseType,
7087                                      TypeSourceInfo *BaseTInfo,
7088                                      Expr *Init,
7089                                      CXXRecordDecl *ClassDecl,
7090                                      SourceLocation EllipsisLoc);
7091 
7092   MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
7093                                            Expr *Init,
7094                                            CXXRecordDecl *ClassDecl);
7095 
7096   bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
7097                                 CXXCtorInitializer *Initializer);
7098 
7099   bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
7100                            ArrayRef<CXXCtorInitializer *> Initializers = None);
7101 
7102   void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
7103 
7104 
7105   /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
7106   /// mark all the non-trivial destructors of its members and bases as
7107   /// referenced.
7108   void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
7109                                               CXXRecordDecl *Record);
7110 
7111   /// Mark destructors of virtual bases of this class referenced. In the Itanium
7112   /// C++ ABI, this is done when emitting a destructor for any non-abstract
7113   /// class. In the Microsoft C++ ABI, this is done any time a class's
7114   /// destructor is referenced.
7115   void MarkVirtualBaseDestructorsReferenced(
7116       SourceLocation Location, CXXRecordDecl *ClassDecl,
7117       llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases = nullptr);
7118 
7119   /// Do semantic checks to allow the complete destructor variant to be emitted
7120   /// when the destructor is defined in another translation unit. In the Itanium
7121   /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they
7122   /// can be emitted in separate TUs. To emit the complete variant, run a subset
7123   /// of the checks performed when emitting a regular destructor.
7124   void CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
7125                                       CXXDestructorDecl *Dtor);
7126 
7127   /// The list of classes whose vtables have been used within
7128   /// this translation unit, and the source locations at which the
7129   /// first use occurred.
7130   typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
7131 
7132   /// The list of vtables that are required but have not yet been
7133   /// materialized.
7134   SmallVector<VTableUse, 16> VTableUses;
7135 
7136   /// The set of classes whose vtables have been used within
7137   /// this translation unit, and a bit that will be true if the vtable is
7138   /// required to be emitted (otherwise, it should be emitted only if needed
7139   /// by code generation).
7140   llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
7141 
7142   /// Load any externally-stored vtable uses.
7143   void LoadExternalVTableUses();
7144 
7145   /// Note that the vtable for the given class was used at the
7146   /// given location.
7147   void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
7148                       bool DefinitionRequired = false);
7149 
7150   /// Mark the exception specifications of all virtual member functions
7151   /// in the given class as needed.
7152   void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
7153                                              const CXXRecordDecl *RD);
7154 
7155   /// MarkVirtualMembersReferenced - Will mark all members of the given
7156   /// CXXRecordDecl referenced.
7157   void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD,
7158                                     bool ConstexprOnly = false);
7159 
7160   /// Define all of the vtables that have been used in this
7161   /// translation unit and reference any virtual members used by those
7162   /// vtables.
7163   ///
7164   /// \returns true if any work was done, false otherwise.
7165   bool DefineUsedVTables();
7166 
7167   void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
7168 
7169   void ActOnMemInitializers(Decl *ConstructorDecl,
7170                             SourceLocation ColonLoc,
7171                             ArrayRef<CXXCtorInitializer*> MemInits,
7172                             bool AnyErrors);
7173 
7174   /// Check class-level dllimport/dllexport attribute. The caller must
7175   /// ensure that referenceDLLExportedClassMethods is called some point later
7176   /// when all outer classes of Class are complete.
7177   void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
7178   void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class);
7179 
7180   void referenceDLLExportedClassMethods();
7181 
7182   void propagateDLLAttrToBaseClassTemplate(
7183       CXXRecordDecl *Class, Attr *ClassAttr,
7184       ClassTemplateSpecializationDecl *BaseTemplateSpec,
7185       SourceLocation BaseLoc);
7186 
7187   /// Add gsl::Pointer attribute to std::container::iterator
7188   /// \param ND The declaration that introduces the name
7189   /// std::container::iterator. \param UnderlyingRecord The record named by ND.
7190   void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
7191 
7192   /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
7193   void inferGslOwnerPointerAttribute(CXXRecordDecl *Record);
7194 
7195   /// Add [[gsl::Pointer]] attributes for std:: types.
7196   void inferGslPointerAttribute(TypedefNameDecl *TD);
7197 
7198   void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record);
7199 
7200   /// Check that the C++ class annoated with "trivial_abi" satisfies all the
7201   /// conditions that are needed for the attribute to have an effect.
7202   void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
7203 
7204   void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc,
7205                                          Decl *TagDecl, SourceLocation LBrac,
7206                                          SourceLocation RBrac,
7207                                          const ParsedAttributesView &AttrList);
7208   void ActOnFinishCXXMemberDecls();
7209   void ActOnFinishCXXNonNestedClass();
7210 
7211   void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
7212   unsigned ActOnReenterTemplateScope(Decl *Template,
7213                                      llvm::function_ref<Scope *()> EnterScope);
7214   void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
7215   void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
7216   void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
7217   void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
7218   void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
7219   void ActOnFinishDelayedMemberInitializers(Decl *Record);
7220   void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
7221                                 CachedTokens &Toks);
7222   void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
7223   bool IsInsideALocalClassWithinATemplateFunction();
7224 
7225   Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
7226                                      Expr *AssertExpr,
7227                                      Expr *AssertMessageExpr,
7228                                      SourceLocation RParenLoc);
7229   Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
7230                                      Expr *AssertExpr,
7231                                      StringLiteral *AssertMessageExpr,
7232                                      SourceLocation RParenLoc,
7233                                      bool Failed);
7234 
7235   FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
7236                                   SourceLocation FriendLoc,
7237                                   TypeSourceInfo *TSInfo);
7238   Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
7239                             MultiTemplateParamsArg TemplateParams);
7240   NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
7241                                      MultiTemplateParamsArg TemplateParams);
7242 
7243   QualType CheckConstructorDeclarator(Declarator &D, QualType R,
7244                                       StorageClass& SC);
7245   void CheckConstructor(CXXConstructorDecl *Constructor);
7246   QualType CheckDestructorDeclarator(Declarator &D, QualType R,
7247                                      StorageClass& SC);
7248   bool CheckDestructor(CXXDestructorDecl *Destructor);
7249   void CheckConversionDeclarator(Declarator &D, QualType &R,
7250                                  StorageClass& SC);
7251   Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
7252   void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
7253                                      StorageClass &SC);
7254   void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
7255 
7256   void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD);
7257 
7258   bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7259                                              CXXSpecialMember CSM);
7260   void CheckDelayedMemberExceptionSpecs();
7261 
7262   bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD,
7263                                           DefaultedComparisonKind DCK);
7264   void DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
7265                                          FunctionDecl *Spaceship);
7266   void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD,
7267                                  DefaultedComparisonKind DCK);
7268 
7269   //===--------------------------------------------------------------------===//
7270   // C++ Derived Classes
7271   //
7272 
7273   /// ActOnBaseSpecifier - Parsed a base specifier
7274   CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
7275                                        SourceRange SpecifierRange,
7276                                        bool Virtual, AccessSpecifier Access,
7277                                        TypeSourceInfo *TInfo,
7278                                        SourceLocation EllipsisLoc);
7279 
7280   BaseResult ActOnBaseSpecifier(Decl *classdecl,
7281                                 SourceRange SpecifierRange,
7282                                 ParsedAttributes &Attrs,
7283                                 bool Virtual, AccessSpecifier Access,
7284                                 ParsedType basetype,
7285                                 SourceLocation BaseLoc,
7286                                 SourceLocation EllipsisLoc);
7287 
7288   bool AttachBaseSpecifiers(CXXRecordDecl *Class,
7289                             MutableArrayRef<CXXBaseSpecifier *> Bases);
7290   void ActOnBaseSpecifiers(Decl *ClassDecl,
7291                            MutableArrayRef<CXXBaseSpecifier *> Bases);
7292 
7293   bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
7294   bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
7295                      CXXBasePaths &Paths);
7296 
7297   // FIXME: I don't like this name.
7298   void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
7299 
7300   bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
7301                                     SourceLocation Loc, SourceRange Range,
7302                                     CXXCastPath *BasePath = nullptr,
7303                                     bool IgnoreAccess = false);
7304   bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
7305                                     unsigned InaccessibleBaseID,
7306                                     unsigned AmbiguousBaseConvID,
7307                                     SourceLocation Loc, SourceRange Range,
7308                                     DeclarationName Name,
7309                                     CXXCastPath *BasePath,
7310                                     bool IgnoreAccess = false);
7311 
7312   std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
7313 
7314   bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
7315                                          const CXXMethodDecl *Old);
7316 
7317   /// CheckOverridingFunctionReturnType - Checks whether the return types are
7318   /// covariant, according to C++ [class.virtual]p5.
7319   bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
7320                                          const CXXMethodDecl *Old);
7321 
7322   /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
7323   /// spec is a subset of base spec.
7324   bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
7325                                             const CXXMethodDecl *Old);
7326 
7327   bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
7328 
7329   /// CheckOverrideControl - Check C++11 override control semantics.
7330   void CheckOverrideControl(NamedDecl *D);
7331 
7332   /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
7333   /// not used in the declaration of an overriding method.
7334   void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent);
7335 
7336   /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
7337   /// overrides a virtual member function marked 'final', according to
7338   /// C++11 [class.virtual]p4.
7339   bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
7340                                               const CXXMethodDecl *Old);
7341 
7342 
7343   //===--------------------------------------------------------------------===//
7344   // C++ Access Control
7345   //
7346 
7347   enum AccessResult {
7348     AR_accessible,
7349     AR_inaccessible,
7350     AR_dependent,
7351     AR_delayed
7352   };
7353 
7354   bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
7355                                 NamedDecl *PrevMemberDecl,
7356                                 AccessSpecifier LexicalAS);
7357 
7358   AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
7359                                            DeclAccessPair FoundDecl);
7360   AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
7361                                            DeclAccessPair FoundDecl);
7362   AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
7363                                      SourceRange PlacementRange,
7364                                      CXXRecordDecl *NamingClass,
7365                                      DeclAccessPair FoundDecl,
7366                                      bool Diagnose = true);
7367   AccessResult CheckConstructorAccess(SourceLocation Loc,
7368                                       CXXConstructorDecl *D,
7369                                       DeclAccessPair FoundDecl,
7370                                       const InitializedEntity &Entity,
7371                                       bool IsCopyBindingRefToTemp = false);
7372   AccessResult CheckConstructorAccess(SourceLocation Loc,
7373                                       CXXConstructorDecl *D,
7374                                       DeclAccessPair FoundDecl,
7375                                       const InitializedEntity &Entity,
7376                                       const PartialDiagnostic &PDiag);
7377   AccessResult CheckDestructorAccess(SourceLocation Loc,
7378                                      CXXDestructorDecl *Dtor,
7379                                      const PartialDiagnostic &PDiag,
7380                                      QualType objectType = QualType());
7381   AccessResult CheckFriendAccess(NamedDecl *D);
7382   AccessResult CheckMemberAccess(SourceLocation UseLoc,
7383                                  CXXRecordDecl *NamingClass,
7384                                  DeclAccessPair Found);
7385   AccessResult
7386   CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
7387                                      CXXRecordDecl *DecomposedClass,
7388                                      DeclAccessPair Field);
7389   AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
7390                                          Expr *ObjectExpr,
7391                                          Expr *ArgExpr,
7392                                          DeclAccessPair FoundDecl);
7393   AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
7394                                           DeclAccessPair FoundDecl);
7395   AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
7396                                     QualType Base, QualType Derived,
7397                                     const CXXBasePath &Path,
7398                                     unsigned DiagID,
7399                                     bool ForceCheck = false,
7400                                     bool ForceUnprivileged = false);
7401   void CheckLookupAccess(const LookupResult &R);
7402   bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
7403                           QualType BaseType);
7404   bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
7405                                      DeclAccessPair Found, QualType ObjectType,
7406                                      SourceLocation Loc,
7407                                      const PartialDiagnostic &Diag);
isMemberAccessibleForDeletion(CXXRecordDecl * NamingClass,DeclAccessPair Found,QualType ObjectType)7408   bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
7409                                      DeclAccessPair Found,
7410                                      QualType ObjectType) {
7411     return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType,
7412                                          SourceLocation(), PDiag());
7413   }
7414 
7415   void HandleDependentAccessCheck(const DependentDiagnostic &DD,
7416                          const MultiLevelTemplateArgumentList &TemplateArgs);
7417   void PerformDependentDiagnostics(const DeclContext *Pattern,
7418                         const MultiLevelTemplateArgumentList &TemplateArgs);
7419 
7420   void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
7421 
7422   /// When true, access checking violations are treated as SFINAE
7423   /// failures rather than hard errors.
7424   bool AccessCheckingSFINAE;
7425 
7426   enum AbstractDiagSelID {
7427     AbstractNone = -1,
7428     AbstractReturnType,
7429     AbstractParamType,
7430     AbstractVariableType,
7431     AbstractFieldType,
7432     AbstractIvarType,
7433     AbstractSynthesizedIvarType,
7434     AbstractArrayType
7435   };
7436 
7437   bool isAbstractType(SourceLocation Loc, QualType T);
7438   bool RequireNonAbstractType(SourceLocation Loc, QualType T,
7439                               TypeDiagnoser &Diagnoser);
7440   template <typename... Ts>
RequireNonAbstractType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)7441   bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
7442                               const Ts &...Args) {
7443     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
7444     return RequireNonAbstractType(Loc, T, Diagnoser);
7445   }
7446 
7447   void DiagnoseAbstractType(const CXXRecordDecl *RD);
7448 
7449   //===--------------------------------------------------------------------===//
7450   // C++ Overloaded Operators [C++ 13.5]
7451   //
7452 
7453   bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
7454 
7455   bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
7456 
7457   //===--------------------------------------------------------------------===//
7458   // C++ Templates [C++ 14]
7459   //
7460   void FilterAcceptableTemplateNames(LookupResult &R,
7461                                      bool AllowFunctionTemplates = true,
7462                                      bool AllowDependent = true);
7463   bool hasAnyAcceptableTemplateNames(LookupResult &R,
7464                                      bool AllowFunctionTemplates = true,
7465                                      bool AllowDependent = true,
7466                                      bool AllowNonTemplateFunctions = false);
7467   /// Try to interpret the lookup result D as a template-name.
7468   ///
7469   /// \param D A declaration found by name lookup.
7470   /// \param AllowFunctionTemplates Whether function templates should be
7471   ///        considered valid results.
7472   /// \param AllowDependent Whether unresolved using declarations (that might
7473   ///        name templates) should be considered valid results.
7474   static NamedDecl *getAsTemplateNameDecl(NamedDecl *D,
7475                                           bool AllowFunctionTemplates = true,
7476                                           bool AllowDependent = true);
7477 
7478   enum TemplateNameIsRequiredTag { TemplateNameIsRequired };
7479   /// Whether and why a template name is required in this lookup.
7480   class RequiredTemplateKind {
7481   public:
7482     /// Template name is required if TemplateKWLoc is valid.
7483     RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation())
TemplateKW(TemplateKWLoc)7484         : TemplateKW(TemplateKWLoc) {}
7485     /// Template name is unconditionally required.
RequiredTemplateKind(TemplateNameIsRequiredTag)7486     RequiredTemplateKind(TemplateNameIsRequiredTag) : TemplateKW() {}
7487 
getTemplateKeywordLoc()7488     SourceLocation getTemplateKeywordLoc() const {
7489       return TemplateKW.getValueOr(SourceLocation());
7490     }
hasTemplateKeyword()7491     bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
isRequired()7492     bool isRequired() const { return TemplateKW != SourceLocation(); }
7493     explicit operator bool() const { return isRequired(); }
7494 
7495   private:
7496     llvm::Optional<SourceLocation> TemplateKW;
7497   };
7498 
7499   enum class AssumedTemplateKind {
7500     /// This is not assumed to be a template name.
7501     None,
7502     /// This is assumed to be a template name because lookup found nothing.
7503     FoundNothing,
7504     /// This is assumed to be a template name because lookup found one or more
7505     /// functions (but no function templates).
7506     FoundFunctions,
7507   };
7508   bool LookupTemplateName(
7509       LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType,
7510       bool EnteringContext, bool &MemberOfUnknownSpecialization,
7511       RequiredTemplateKind RequiredTemplate = SourceLocation(),
7512       AssumedTemplateKind *ATK = nullptr, bool AllowTypoCorrection = true);
7513 
7514   TemplateNameKind isTemplateName(Scope *S,
7515                                   CXXScopeSpec &SS,
7516                                   bool hasTemplateKeyword,
7517                                   const UnqualifiedId &Name,
7518                                   ParsedType ObjectType,
7519                                   bool EnteringContext,
7520                                   TemplateTy &Template,
7521                                   bool &MemberOfUnknownSpecialization,
7522                                   bool Disambiguation = false);
7523 
7524   /// Try to resolve an undeclared template name as a type template.
7525   ///
7526   /// Sets II to the identifier corresponding to the template name, and updates
7527   /// Name to a corresponding (typo-corrected) type template name and TNK to
7528   /// the corresponding kind, if possible.
7529   void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name,
7530                                        TemplateNameKind &TNK,
7531                                        SourceLocation NameLoc,
7532                                        IdentifierInfo *&II);
7533 
7534   bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
7535                                         SourceLocation NameLoc,
7536                                         bool Diagnose = true);
7537 
7538   /// Determine whether a particular identifier might be the name in a C++1z
7539   /// deduction-guide declaration.
7540   bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
7541                             SourceLocation NameLoc,
7542                             ParsedTemplateTy *Template = nullptr);
7543 
7544   bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
7545                                    SourceLocation IILoc,
7546                                    Scope *S,
7547                                    const CXXScopeSpec *SS,
7548                                    TemplateTy &SuggestedTemplate,
7549                                    TemplateNameKind &SuggestedKind);
7550 
7551   bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
7552                                       NamedDecl *Instantiation,
7553                                       bool InstantiatedFromMember,
7554                                       const NamedDecl *Pattern,
7555                                       const NamedDecl *PatternDef,
7556                                       TemplateSpecializationKind TSK,
7557                                       bool Complain = true);
7558 
7559   void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
7560   TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
7561 
7562   NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
7563                                 SourceLocation EllipsisLoc,
7564                                 SourceLocation KeyLoc,
7565                                 IdentifierInfo *ParamName,
7566                                 SourceLocation ParamNameLoc,
7567                                 unsigned Depth, unsigned Position,
7568                                 SourceLocation EqualLoc,
7569                                 ParsedType DefaultArg, bool HasTypeConstraint);
7570 
7571   bool ActOnTypeConstraint(const CXXScopeSpec &SS,
7572                            TemplateIdAnnotation *TypeConstraint,
7573                            TemplateTypeParmDecl *ConstrainedParameter,
7574                            SourceLocation EllipsisLoc);
7575   bool BuildTypeConstraint(const CXXScopeSpec &SS,
7576                            TemplateIdAnnotation *TypeConstraint,
7577                            TemplateTypeParmDecl *ConstrainedParameter,
7578                            SourceLocation EllipsisLoc,
7579                            bool AllowUnexpandedPack);
7580 
7581   bool AttachTypeConstraint(NestedNameSpecifierLoc NS,
7582                             DeclarationNameInfo NameInfo,
7583                             ConceptDecl *NamedConcept,
7584                             const TemplateArgumentListInfo *TemplateArgs,
7585                             TemplateTypeParmDecl *ConstrainedParameter,
7586                             SourceLocation EllipsisLoc);
7587 
7588   bool AttachTypeConstraint(AutoTypeLoc TL,
7589                             NonTypeTemplateParmDecl *ConstrainedParameter,
7590                             SourceLocation EllipsisLoc);
7591 
7592   bool RequireStructuralType(QualType T, SourceLocation Loc);
7593 
7594   QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
7595                                              SourceLocation Loc);
7596   QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
7597 
7598   NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
7599                                       unsigned Depth,
7600                                       unsigned Position,
7601                                       SourceLocation EqualLoc,
7602                                       Expr *DefaultArg);
7603   NamedDecl *ActOnTemplateTemplateParameter(Scope *S,
7604                                        SourceLocation TmpLoc,
7605                                        TemplateParameterList *Params,
7606                                        SourceLocation EllipsisLoc,
7607                                        IdentifierInfo *ParamName,
7608                                        SourceLocation ParamNameLoc,
7609                                        unsigned Depth,
7610                                        unsigned Position,
7611                                        SourceLocation EqualLoc,
7612                                        ParsedTemplateArgument DefaultArg);
7613 
7614   TemplateParameterList *
7615   ActOnTemplateParameterList(unsigned Depth,
7616                              SourceLocation ExportLoc,
7617                              SourceLocation TemplateLoc,
7618                              SourceLocation LAngleLoc,
7619                              ArrayRef<NamedDecl *> Params,
7620                              SourceLocation RAngleLoc,
7621                              Expr *RequiresClause);
7622 
7623   /// The context in which we are checking a template parameter list.
7624   enum TemplateParamListContext {
7625     TPC_ClassTemplate,
7626     TPC_VarTemplate,
7627     TPC_FunctionTemplate,
7628     TPC_ClassTemplateMember,
7629     TPC_FriendClassTemplate,
7630     TPC_FriendFunctionTemplate,
7631     TPC_FriendFunctionTemplateDefinition,
7632     TPC_TypeAliasTemplate
7633   };
7634 
7635   bool CheckTemplateParameterList(TemplateParameterList *NewParams,
7636                                   TemplateParameterList *OldParams,
7637                                   TemplateParamListContext TPC,
7638                                   SkipBodyInfo *SkipBody = nullptr);
7639   TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
7640       SourceLocation DeclStartLoc, SourceLocation DeclLoc,
7641       const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
7642       ArrayRef<TemplateParameterList *> ParamLists,
7643       bool IsFriend, bool &IsMemberSpecialization, bool &Invalid,
7644       bool SuppressDiagnostic = false);
7645 
7646   DeclResult CheckClassTemplate(
7647       Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7648       CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
7649       const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
7650       AccessSpecifier AS, SourceLocation ModulePrivateLoc,
7651       SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
7652       TemplateParameterList **OuterTemplateParamLists,
7653       SkipBodyInfo *SkipBody = nullptr);
7654 
7655   TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
7656                                                     QualType NTTPType,
7657                                                     SourceLocation Loc);
7658 
7659   /// Get a template argument mapping the given template parameter to itself,
7660   /// e.g. for X in \c template<int X>, this would return an expression template
7661   /// argument referencing X.
7662   TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param,
7663                                                      SourceLocation Location);
7664 
7665   void translateTemplateArguments(const ASTTemplateArgsPtr &In,
7666                                   TemplateArgumentListInfo &Out);
7667 
7668   ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
7669 
7670   void NoteAllFoundTemplates(TemplateName Name);
7671 
7672   QualType CheckTemplateIdType(TemplateName Template,
7673                                SourceLocation TemplateLoc,
7674                               TemplateArgumentListInfo &TemplateArgs);
7675 
7676   TypeResult
7677   ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
7678                       TemplateTy Template, IdentifierInfo *TemplateII,
7679                       SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
7680                       ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
7681                       bool IsCtorOrDtorName = false, bool IsClassName = false);
7682 
7683   /// Parsed an elaborated-type-specifier that refers to a template-id,
7684   /// such as \c class T::template apply<U>.
7685   TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
7686                                     TypeSpecifierType TagSpec,
7687                                     SourceLocation TagLoc,
7688                                     CXXScopeSpec &SS,
7689                                     SourceLocation TemplateKWLoc,
7690                                     TemplateTy TemplateD,
7691                                     SourceLocation TemplateLoc,
7692                                     SourceLocation LAngleLoc,
7693                                     ASTTemplateArgsPtr TemplateArgsIn,
7694                                     SourceLocation RAngleLoc);
7695 
7696   DeclResult ActOnVarTemplateSpecialization(
7697       Scope *S, Declarator &D, TypeSourceInfo *DI,
7698       SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
7699       StorageClass SC, bool IsPartialSpecialization);
7700 
7701   /// Get the specialization of the given variable template corresponding to
7702   /// the specified argument list, or a null-but-valid result if the arguments
7703   /// are dependent.
7704   DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
7705                                 SourceLocation TemplateLoc,
7706                                 SourceLocation TemplateNameLoc,
7707                                 const TemplateArgumentListInfo &TemplateArgs);
7708 
7709   /// Form a reference to the specialization of the given variable template
7710   /// corresponding to the specified argument list, or a null-but-valid result
7711   /// if the arguments are dependent.
7712   ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
7713                                 const DeclarationNameInfo &NameInfo,
7714                                 VarTemplateDecl *Template,
7715                                 SourceLocation TemplateLoc,
7716                                 const TemplateArgumentListInfo *TemplateArgs);
7717 
7718   ExprResult
7719   CheckConceptTemplateId(const CXXScopeSpec &SS,
7720                          SourceLocation TemplateKWLoc,
7721                          const DeclarationNameInfo &ConceptNameInfo,
7722                          NamedDecl *FoundDecl, ConceptDecl *NamedConcept,
7723                          const TemplateArgumentListInfo *TemplateArgs);
7724 
7725   void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc);
7726 
7727   ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
7728                                  SourceLocation TemplateKWLoc,
7729                                  LookupResult &R,
7730                                  bool RequiresADL,
7731                                const TemplateArgumentListInfo *TemplateArgs);
7732 
7733   ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
7734                                           SourceLocation TemplateKWLoc,
7735                                const DeclarationNameInfo &NameInfo,
7736                                const TemplateArgumentListInfo *TemplateArgs);
7737 
7738   TemplateNameKind ActOnTemplateName(
7739       Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
7740       const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
7741       TemplateTy &Template, bool AllowInjectedClassName = false);
7742 
7743   DeclResult ActOnClassTemplateSpecialization(
7744       Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7745       SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
7746       TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
7747       MultiTemplateParamsArg TemplateParameterLists,
7748       SkipBodyInfo *SkipBody = nullptr);
7749 
7750   bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
7751                                               TemplateDecl *PrimaryTemplate,
7752                                               unsigned NumExplicitArgs,
7753                                               ArrayRef<TemplateArgument> Args);
7754   void CheckTemplatePartialSpecialization(
7755       ClassTemplatePartialSpecializationDecl *Partial);
7756   void CheckTemplatePartialSpecialization(
7757       VarTemplatePartialSpecializationDecl *Partial);
7758 
7759   Decl *ActOnTemplateDeclarator(Scope *S,
7760                                 MultiTemplateParamsArg TemplateParameterLists,
7761                                 Declarator &D);
7762 
7763   bool
7764   CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
7765                                          TemplateSpecializationKind NewTSK,
7766                                          NamedDecl *PrevDecl,
7767                                          TemplateSpecializationKind PrevTSK,
7768                                          SourceLocation PrevPtOfInstantiation,
7769                                          bool &SuppressNew);
7770 
7771   bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
7772                     const TemplateArgumentListInfo &ExplicitTemplateArgs,
7773                                                     LookupResult &Previous);
7774 
7775   bool CheckFunctionTemplateSpecialization(
7776       FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
7777       LookupResult &Previous, bool QualifiedFriend = false);
7778   bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
7779   void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
7780 
7781   DeclResult ActOnExplicitInstantiation(
7782       Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
7783       unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
7784       TemplateTy Template, SourceLocation TemplateNameLoc,
7785       SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
7786       SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
7787 
7788   DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
7789                                         SourceLocation TemplateLoc,
7790                                         unsigned TagSpec, SourceLocation KWLoc,
7791                                         CXXScopeSpec &SS, IdentifierInfo *Name,
7792                                         SourceLocation NameLoc,
7793                                         const ParsedAttributesView &Attr);
7794 
7795   DeclResult ActOnExplicitInstantiation(Scope *S,
7796                                         SourceLocation ExternLoc,
7797                                         SourceLocation TemplateLoc,
7798                                         Declarator &D);
7799 
7800   TemplateArgumentLoc
7801   SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
7802                                           SourceLocation TemplateLoc,
7803                                           SourceLocation RAngleLoc,
7804                                           Decl *Param,
7805                                           SmallVectorImpl<TemplateArgument>
7806                                             &Converted,
7807                                           bool &HasDefaultArg);
7808 
7809   /// Specifies the context in which a particular template
7810   /// argument is being checked.
7811   enum CheckTemplateArgumentKind {
7812     /// The template argument was specified in the code or was
7813     /// instantiated with some deduced template arguments.
7814     CTAK_Specified,
7815 
7816     /// The template argument was deduced via template argument
7817     /// deduction.
7818     CTAK_Deduced,
7819 
7820     /// The template argument was deduced from an array bound
7821     /// via template argument deduction.
7822     CTAK_DeducedFromArrayBound
7823   };
7824 
7825   bool CheckTemplateArgument(NamedDecl *Param,
7826                              TemplateArgumentLoc &Arg,
7827                              NamedDecl *Template,
7828                              SourceLocation TemplateLoc,
7829                              SourceLocation RAngleLoc,
7830                              unsigned ArgumentPackIndex,
7831                            SmallVectorImpl<TemplateArgument> &Converted,
7832                              CheckTemplateArgumentKind CTAK = CTAK_Specified);
7833 
7834   /// Check that the given template arguments can be be provided to
7835   /// the given template, converting the arguments along the way.
7836   ///
7837   /// \param Template The template to which the template arguments are being
7838   /// provided.
7839   ///
7840   /// \param TemplateLoc The location of the template name in the source.
7841   ///
7842   /// \param TemplateArgs The list of template arguments. If the template is
7843   /// a template template parameter, this function may extend the set of
7844   /// template arguments to also include substituted, defaulted template
7845   /// arguments.
7846   ///
7847   /// \param PartialTemplateArgs True if the list of template arguments is
7848   /// intentionally partial, e.g., because we're checking just the initial
7849   /// set of template arguments.
7850   ///
7851   /// \param Converted Will receive the converted, canonicalized template
7852   /// arguments.
7853   ///
7854   /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
7855   /// contain the converted forms of the template arguments as written.
7856   /// Otherwise, \p TemplateArgs will not be modified.
7857   ///
7858   /// \param ConstraintsNotSatisfied If provided, and an error occured, will
7859   /// receive true if the cause for the error is the associated constraints of
7860   /// the template not being satisfied by the template arguments.
7861   ///
7862   /// \returns true if an error occurred, false otherwise.
7863   bool CheckTemplateArgumentList(TemplateDecl *Template,
7864                                  SourceLocation TemplateLoc,
7865                                  TemplateArgumentListInfo &TemplateArgs,
7866                                  bool PartialTemplateArgs,
7867                                  SmallVectorImpl<TemplateArgument> &Converted,
7868                                  bool UpdateArgsWithConversions = true,
7869                                  bool *ConstraintsNotSatisfied = nullptr);
7870 
7871   bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
7872                                  TemplateArgumentLoc &Arg,
7873                            SmallVectorImpl<TemplateArgument> &Converted);
7874 
7875   bool CheckTemplateArgument(TypeSourceInfo *Arg);
7876   ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
7877                                    QualType InstantiatedParamType, Expr *Arg,
7878                                    TemplateArgument &Converted,
7879                                CheckTemplateArgumentKind CTAK = CTAK_Specified);
7880   bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
7881                                      TemplateParameterList *Params,
7882                                      TemplateArgumentLoc &Arg);
7883 
7884   ExprResult
7885   BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
7886                                           QualType ParamType,
7887                                           SourceLocation Loc);
7888   ExprResult
7889   BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
7890                                               SourceLocation Loc);
7891 
7892   /// Enumeration describing how template parameter lists are compared
7893   /// for equality.
7894   enum TemplateParameterListEqualKind {
7895     /// We are matching the template parameter lists of two templates
7896     /// that might be redeclarations.
7897     ///
7898     /// \code
7899     /// template<typename T> struct X;
7900     /// template<typename T> struct X;
7901     /// \endcode
7902     TPL_TemplateMatch,
7903 
7904     /// We are matching the template parameter lists of two template
7905     /// template parameters as part of matching the template parameter lists
7906     /// of two templates that might be redeclarations.
7907     ///
7908     /// \code
7909     /// template<template<int I> class TT> struct X;
7910     /// template<template<int Value> class Other> struct X;
7911     /// \endcode
7912     TPL_TemplateTemplateParmMatch,
7913 
7914     /// We are matching the template parameter lists of a template
7915     /// template argument against the template parameter lists of a template
7916     /// template parameter.
7917     ///
7918     /// \code
7919     /// template<template<int Value> class Metafun> struct X;
7920     /// template<int Value> struct integer_c;
7921     /// X<integer_c> xic;
7922     /// \endcode
7923     TPL_TemplateTemplateArgumentMatch
7924   };
7925 
7926   bool TemplateParameterListsAreEqual(TemplateParameterList *New,
7927                                       TemplateParameterList *Old,
7928                                       bool Complain,
7929                                       TemplateParameterListEqualKind Kind,
7930                                       SourceLocation TemplateArgLoc
7931                                         = SourceLocation());
7932 
7933   bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
7934 
7935   /// Called when the parser has parsed a C++ typename
7936   /// specifier, e.g., "typename T::type".
7937   ///
7938   /// \param S The scope in which this typename type occurs.
7939   /// \param TypenameLoc the location of the 'typename' keyword
7940   /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
7941   /// \param II the identifier we're retrieving (e.g., 'type' in the example).
7942   /// \param IdLoc the location of the identifier.
7943   TypeResult
7944   ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
7945                     const CXXScopeSpec &SS, const IdentifierInfo &II,
7946                     SourceLocation IdLoc);
7947 
7948   /// Called when the parser has parsed a C++ typename
7949   /// specifier that ends in a template-id, e.g.,
7950   /// "typename MetaFun::template apply<T1, T2>".
7951   ///
7952   /// \param S The scope in which this typename type occurs.
7953   /// \param TypenameLoc the location of the 'typename' keyword
7954   /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
7955   /// \param TemplateLoc the location of the 'template' keyword, if any.
7956   /// \param TemplateName The template name.
7957   /// \param TemplateII The identifier used to name the template.
7958   /// \param TemplateIILoc The location of the template name.
7959   /// \param LAngleLoc The location of the opening angle bracket  ('<').
7960   /// \param TemplateArgs The template arguments.
7961   /// \param RAngleLoc The location of the closing angle bracket  ('>').
7962   TypeResult
7963   ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
7964                     const CXXScopeSpec &SS,
7965                     SourceLocation TemplateLoc,
7966                     TemplateTy TemplateName,
7967                     IdentifierInfo *TemplateII,
7968                     SourceLocation TemplateIILoc,
7969                     SourceLocation LAngleLoc,
7970                     ASTTemplateArgsPtr TemplateArgs,
7971                     SourceLocation RAngleLoc);
7972 
7973   QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
7974                              SourceLocation KeywordLoc,
7975                              NestedNameSpecifierLoc QualifierLoc,
7976                              const IdentifierInfo &II,
7977                              SourceLocation IILoc,
7978                              TypeSourceInfo **TSI,
7979                              bool DeducedTSTContext);
7980 
7981   QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
7982                              SourceLocation KeywordLoc,
7983                              NestedNameSpecifierLoc QualifierLoc,
7984                              const IdentifierInfo &II,
7985                              SourceLocation IILoc,
7986                              bool DeducedTSTContext = true);
7987 
7988 
7989   TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
7990                                                     SourceLocation Loc,
7991                                                     DeclarationName Name);
7992   bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
7993 
7994   ExprResult RebuildExprInCurrentInstantiation(Expr *E);
7995   bool RebuildTemplateParamsInCurrentInstantiation(
7996                                                 TemplateParameterList *Params);
7997 
7998   std::string
7999   getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8000                                   const TemplateArgumentList &Args);
8001 
8002   std::string
8003   getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8004                                   const TemplateArgument *Args,
8005                                   unsigned NumArgs);
8006 
8007   //===--------------------------------------------------------------------===//
8008   // C++ Concepts
8009   //===--------------------------------------------------------------------===//
8010   Decl *ActOnConceptDefinition(
8011       Scope *S, MultiTemplateParamsArg TemplateParameterLists,
8012       IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr);
8013 
8014   RequiresExprBodyDecl *
8015   ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
8016                          ArrayRef<ParmVarDecl *> LocalParameters,
8017                          Scope *BodyScope);
8018   void ActOnFinishRequiresExpr();
8019   concepts::Requirement *ActOnSimpleRequirement(Expr *E);
8020   concepts::Requirement *ActOnTypeRequirement(
8021       SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc,
8022       IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId);
8023   concepts::Requirement *ActOnCompoundRequirement(Expr *E,
8024                                                   SourceLocation NoexceptLoc);
8025   concepts::Requirement *
8026   ActOnCompoundRequirement(
8027       Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
8028       TemplateIdAnnotation *TypeConstraint, unsigned Depth);
8029   concepts::Requirement *ActOnNestedRequirement(Expr *Constraint);
8030   concepts::ExprRequirement *
8031   BuildExprRequirement(
8032       Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc,
8033       concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
8034   concepts::ExprRequirement *
8035   BuildExprRequirement(
8036       concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag,
8037       bool IsSatisfied, SourceLocation NoexceptLoc,
8038       concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
8039   concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type);
8040   concepts::TypeRequirement *
8041   BuildTypeRequirement(
8042       concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
8043   concepts::NestedRequirement *BuildNestedRequirement(Expr *E);
8044   concepts::NestedRequirement *
8045   BuildNestedRequirement(
8046       concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
8047   ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc,
8048                                RequiresExprBodyDecl *Body,
8049                                ArrayRef<ParmVarDecl *> LocalParameters,
8050                                ArrayRef<concepts::Requirement *> Requirements,
8051                                SourceLocation ClosingBraceLoc);
8052 
8053   //===--------------------------------------------------------------------===//
8054   // C++ Variadic Templates (C++0x [temp.variadic])
8055   //===--------------------------------------------------------------------===//
8056 
8057   /// Determine whether an unexpanded parameter pack might be permitted in this
8058   /// location. Useful for error recovery.
8059   bool isUnexpandedParameterPackPermitted();
8060 
8061   /// The context in which an unexpanded parameter pack is
8062   /// being diagnosed.
8063   ///
8064   /// Note that the values of this enumeration line up with the first
8065   /// argument to the \c err_unexpanded_parameter_pack diagnostic.
8066   enum UnexpandedParameterPackContext {
8067     /// An arbitrary expression.
8068     UPPC_Expression = 0,
8069 
8070     /// The base type of a class type.
8071     UPPC_BaseType,
8072 
8073     /// The type of an arbitrary declaration.
8074     UPPC_DeclarationType,
8075 
8076     /// The type of a data member.
8077     UPPC_DataMemberType,
8078 
8079     /// The size of a bit-field.
8080     UPPC_BitFieldWidth,
8081 
8082     /// The expression in a static assertion.
8083     UPPC_StaticAssertExpression,
8084 
8085     /// The fixed underlying type of an enumeration.
8086     UPPC_FixedUnderlyingType,
8087 
8088     /// The enumerator value.
8089     UPPC_EnumeratorValue,
8090 
8091     /// A using declaration.
8092     UPPC_UsingDeclaration,
8093 
8094     /// A friend declaration.
8095     UPPC_FriendDeclaration,
8096 
8097     /// A declaration qualifier.
8098     UPPC_DeclarationQualifier,
8099 
8100     /// An initializer.
8101     UPPC_Initializer,
8102 
8103     /// A default argument.
8104     UPPC_DefaultArgument,
8105 
8106     /// The type of a non-type template parameter.
8107     UPPC_NonTypeTemplateParameterType,
8108 
8109     /// The type of an exception.
8110     UPPC_ExceptionType,
8111 
8112     /// Partial specialization.
8113     UPPC_PartialSpecialization,
8114 
8115     /// Microsoft __if_exists.
8116     UPPC_IfExists,
8117 
8118     /// Microsoft __if_not_exists.
8119     UPPC_IfNotExists,
8120 
8121     /// Lambda expression.
8122     UPPC_Lambda,
8123 
8124     /// Block expression.
8125     UPPC_Block,
8126 
8127     /// A type constraint.
8128     UPPC_TypeConstraint,
8129 
8130     // A requirement in a requires-expression.
8131     UPPC_Requirement,
8132 
8133     // A requires-clause.
8134     UPPC_RequiresClause,
8135   };
8136 
8137   /// Diagnose unexpanded parameter packs.
8138   ///
8139   /// \param Loc The location at which we should emit the diagnostic.
8140   ///
8141   /// \param UPPC The context in which we are diagnosing unexpanded
8142   /// parameter packs.
8143   ///
8144   /// \param Unexpanded the set of unexpanded parameter packs.
8145   ///
8146   /// \returns true if an error occurred, false otherwise.
8147   bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
8148                                         UnexpandedParameterPackContext UPPC,
8149                                   ArrayRef<UnexpandedParameterPack> Unexpanded);
8150 
8151   /// If the given type contains an unexpanded parameter pack,
8152   /// diagnose the error.
8153   ///
8154   /// \param Loc The source location where a diagnostc should be emitted.
8155   ///
8156   /// \param T The type that is being checked for unexpanded parameter
8157   /// packs.
8158   ///
8159   /// \returns true if an error occurred, false otherwise.
8160   bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
8161                                        UnexpandedParameterPackContext UPPC);
8162 
8163   /// If the given expression contains an unexpanded parameter
8164   /// pack, diagnose the error.
8165   ///
8166   /// \param E The expression that is being checked for unexpanded
8167   /// parameter packs.
8168   ///
8169   /// \returns true if an error occurred, false otherwise.
8170   bool DiagnoseUnexpandedParameterPack(Expr *E,
8171                        UnexpandedParameterPackContext UPPC = UPPC_Expression);
8172 
8173   /// If the given requirees-expression contains an unexpanded reference to one
8174   /// of its own parameter packs, diagnose the error.
8175   ///
8176   /// \param RE The requiress-expression that is being checked for unexpanded
8177   /// parameter packs.
8178   ///
8179   /// \returns true if an error occurred, false otherwise.
8180   bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE);
8181 
8182   /// If the given nested-name-specifier contains an unexpanded
8183   /// parameter pack, diagnose the error.
8184   ///
8185   /// \param SS The nested-name-specifier that is being checked for
8186   /// unexpanded parameter packs.
8187   ///
8188   /// \returns true if an error occurred, false otherwise.
8189   bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
8190                                        UnexpandedParameterPackContext UPPC);
8191 
8192   /// If the given name contains an unexpanded parameter pack,
8193   /// diagnose the error.
8194   ///
8195   /// \param NameInfo The name (with source location information) that
8196   /// is being checked for unexpanded parameter packs.
8197   ///
8198   /// \returns true if an error occurred, false otherwise.
8199   bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
8200                                        UnexpandedParameterPackContext UPPC);
8201 
8202   /// If the given template name contains an unexpanded parameter pack,
8203   /// diagnose the error.
8204   ///
8205   /// \param Loc The location of the template name.
8206   ///
8207   /// \param Template The template name that is being checked for unexpanded
8208   /// parameter packs.
8209   ///
8210   /// \returns true if an error occurred, false otherwise.
8211   bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
8212                                        TemplateName Template,
8213                                        UnexpandedParameterPackContext UPPC);
8214 
8215   /// If the given template argument contains an unexpanded parameter
8216   /// pack, diagnose the error.
8217   ///
8218   /// \param Arg The template argument that is being checked for unexpanded
8219   /// parameter packs.
8220   ///
8221   /// \returns true if an error occurred, false otherwise.
8222   bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
8223                                        UnexpandedParameterPackContext UPPC);
8224 
8225   /// Collect the set of unexpanded parameter packs within the given
8226   /// template argument.
8227   ///
8228   /// \param Arg The template argument that will be traversed to find
8229   /// unexpanded parameter packs.
8230   void collectUnexpandedParameterPacks(TemplateArgument Arg,
8231                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8232 
8233   /// Collect the set of unexpanded parameter packs within the given
8234   /// template argument.
8235   ///
8236   /// \param Arg The template argument that will be traversed to find
8237   /// unexpanded parameter packs.
8238   void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
8239                     SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8240 
8241   /// Collect the set of unexpanded parameter packs within the given
8242   /// type.
8243   ///
8244   /// \param T The type that will be traversed to find
8245   /// unexpanded parameter packs.
8246   void collectUnexpandedParameterPacks(QualType T,
8247                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8248 
8249   /// Collect the set of unexpanded parameter packs within the given
8250   /// type.
8251   ///
8252   /// \param TL The type that will be traversed to find
8253   /// unexpanded parameter packs.
8254   void collectUnexpandedParameterPacks(TypeLoc TL,
8255                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8256 
8257   /// Collect the set of unexpanded parameter packs within the given
8258   /// nested-name-specifier.
8259   ///
8260   /// \param NNS The nested-name-specifier that will be traversed to find
8261   /// unexpanded parameter packs.
8262   void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
8263                          SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8264 
8265   /// Collect the set of unexpanded parameter packs within the given
8266   /// name.
8267   ///
8268   /// \param NameInfo The name that will be traversed to find
8269   /// unexpanded parameter packs.
8270   void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
8271                          SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8272 
8273   /// Invoked when parsing a template argument followed by an
8274   /// ellipsis, which creates a pack expansion.
8275   ///
8276   /// \param Arg The template argument preceding the ellipsis, which
8277   /// may already be invalid.
8278   ///
8279   /// \param EllipsisLoc The location of the ellipsis.
8280   ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
8281                                             SourceLocation EllipsisLoc);
8282 
8283   /// Invoked when parsing a type followed by an ellipsis, which
8284   /// creates a pack expansion.
8285   ///
8286   /// \param Type The type preceding the ellipsis, which will become
8287   /// the pattern of the pack expansion.
8288   ///
8289   /// \param EllipsisLoc The location of the ellipsis.
8290   TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
8291 
8292   /// Construct a pack expansion type from the pattern of the pack
8293   /// expansion.
8294   TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
8295                                      SourceLocation EllipsisLoc,
8296                                      Optional<unsigned> NumExpansions);
8297 
8298   /// Construct a pack expansion type from the pattern of the pack
8299   /// expansion.
8300   QualType CheckPackExpansion(QualType Pattern,
8301                               SourceRange PatternRange,
8302                               SourceLocation EllipsisLoc,
8303                               Optional<unsigned> NumExpansions);
8304 
8305   /// Invoked when parsing an expression followed by an ellipsis, which
8306   /// creates a pack expansion.
8307   ///
8308   /// \param Pattern The expression preceding the ellipsis, which will become
8309   /// the pattern of the pack expansion.
8310   ///
8311   /// \param EllipsisLoc The location of the ellipsis.
8312   ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
8313 
8314   /// Invoked when parsing an expression followed by an ellipsis, which
8315   /// creates a pack expansion.
8316   ///
8317   /// \param Pattern The expression preceding the ellipsis, which will become
8318   /// the pattern of the pack expansion.
8319   ///
8320   /// \param EllipsisLoc The location of the ellipsis.
8321   ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
8322                                 Optional<unsigned> NumExpansions);
8323 
8324   /// Determine whether we could expand a pack expansion with the
8325   /// given set of parameter packs into separate arguments by repeatedly
8326   /// transforming the pattern.
8327   ///
8328   /// \param EllipsisLoc The location of the ellipsis that identifies the
8329   /// pack expansion.
8330   ///
8331   /// \param PatternRange The source range that covers the entire pattern of
8332   /// the pack expansion.
8333   ///
8334   /// \param Unexpanded The set of unexpanded parameter packs within the
8335   /// pattern.
8336   ///
8337   /// \param ShouldExpand Will be set to \c true if the transformer should
8338   /// expand the corresponding pack expansions into separate arguments. When
8339   /// set, \c NumExpansions must also be set.
8340   ///
8341   /// \param RetainExpansion Whether the caller should add an unexpanded
8342   /// pack expansion after all of the expanded arguments. This is used
8343   /// when extending explicitly-specified template argument packs per
8344   /// C++0x [temp.arg.explicit]p9.
8345   ///
8346   /// \param NumExpansions The number of separate arguments that will be in
8347   /// the expanded form of the corresponding pack expansion. This is both an
8348   /// input and an output parameter, which can be set by the caller if the
8349   /// number of expansions is known a priori (e.g., due to a prior substitution)
8350   /// and will be set by the callee when the number of expansions is known.
8351   /// The callee must set this value when \c ShouldExpand is \c true; it may
8352   /// set this value in other cases.
8353   ///
8354   /// \returns true if an error occurred (e.g., because the parameter packs
8355   /// are to be instantiated with arguments of different lengths), false
8356   /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
8357   /// must be set.
8358   bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
8359                                        SourceRange PatternRange,
8360                              ArrayRef<UnexpandedParameterPack> Unexpanded,
8361                              const MultiLevelTemplateArgumentList &TemplateArgs,
8362                                        bool &ShouldExpand,
8363                                        bool &RetainExpansion,
8364                                        Optional<unsigned> &NumExpansions);
8365 
8366   /// Determine the number of arguments in the given pack expansion
8367   /// type.
8368   ///
8369   /// This routine assumes that the number of arguments in the expansion is
8370   /// consistent across all of the unexpanded parameter packs in its pattern.
8371   ///
8372   /// Returns an empty Optional if the type can't be expanded.
8373   Optional<unsigned> getNumArgumentsInExpansion(QualType T,
8374       const MultiLevelTemplateArgumentList &TemplateArgs);
8375 
8376   /// Determine whether the given declarator contains any unexpanded
8377   /// parameter packs.
8378   ///
8379   /// This routine is used by the parser to disambiguate function declarators
8380   /// with an ellipsis prior to the ')', e.g.,
8381   ///
8382   /// \code
8383   ///   void f(T...);
8384   /// \endcode
8385   ///
8386   /// To determine whether we have an (unnamed) function parameter pack or
8387   /// a variadic function.
8388   ///
8389   /// \returns true if the declarator contains any unexpanded parameter packs,
8390   /// false otherwise.
8391   bool containsUnexpandedParameterPacks(Declarator &D);
8392 
8393   /// Returns the pattern of the pack expansion for a template argument.
8394   ///
8395   /// \param OrigLoc The template argument to expand.
8396   ///
8397   /// \param Ellipsis Will be set to the location of the ellipsis.
8398   ///
8399   /// \param NumExpansions Will be set to the number of expansions that will
8400   /// be generated from this pack expansion, if known a priori.
8401   TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
8402       TemplateArgumentLoc OrigLoc,
8403       SourceLocation &Ellipsis,
8404       Optional<unsigned> &NumExpansions) const;
8405 
8406   /// Given a template argument that contains an unexpanded parameter pack, but
8407   /// which has already been substituted, attempt to determine the number of
8408   /// elements that will be produced once this argument is fully-expanded.
8409   ///
8410   /// This is intended for use when transforming 'sizeof...(Arg)' in order to
8411   /// avoid actually expanding the pack where possible.
8412   Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
8413 
8414   //===--------------------------------------------------------------------===//
8415   // C++ Template Argument Deduction (C++ [temp.deduct])
8416   //===--------------------------------------------------------------------===//
8417 
8418   /// Adjust the type \p ArgFunctionType to match the calling convention,
8419   /// noreturn, and optionally the exception specification of \p FunctionType.
8420   /// Deduction often wants to ignore these properties when matching function
8421   /// types.
8422   QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
8423                                bool AdjustExceptionSpec = false);
8424 
8425   /// Describes the result of template argument deduction.
8426   ///
8427   /// The TemplateDeductionResult enumeration describes the result of
8428   /// template argument deduction, as returned from
8429   /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
8430   /// structure provides additional information about the results of
8431   /// template argument deduction, e.g., the deduced template argument
8432   /// list (if successful) or the specific template parameters or
8433   /// deduced arguments that were involved in the failure.
8434   enum TemplateDeductionResult {
8435     /// Template argument deduction was successful.
8436     TDK_Success = 0,
8437     /// The declaration was invalid; do nothing.
8438     TDK_Invalid,
8439     /// Template argument deduction exceeded the maximum template
8440     /// instantiation depth (which has already been diagnosed).
8441     TDK_InstantiationDepth,
8442     /// Template argument deduction did not deduce a value
8443     /// for every template parameter.
8444     TDK_Incomplete,
8445     /// Template argument deduction did not deduce a value for every
8446     /// expansion of an expanded template parameter pack.
8447     TDK_IncompletePack,
8448     /// Template argument deduction produced inconsistent
8449     /// deduced values for the given template parameter.
8450     TDK_Inconsistent,
8451     /// Template argument deduction failed due to inconsistent
8452     /// cv-qualifiers on a template parameter type that would
8453     /// otherwise be deduced, e.g., we tried to deduce T in "const T"
8454     /// but were given a non-const "X".
8455     TDK_Underqualified,
8456     /// Substitution of the deduced template argument values
8457     /// resulted in an error.
8458     TDK_SubstitutionFailure,
8459     /// After substituting deduced template arguments, a dependent
8460     /// parameter type did not match the corresponding argument.
8461     TDK_DeducedMismatch,
8462     /// After substituting deduced template arguments, an element of
8463     /// a dependent parameter type did not match the corresponding element
8464     /// of the corresponding argument (when deducing from an initializer list).
8465     TDK_DeducedMismatchNested,
8466     /// A non-depnedent component of the parameter did not match the
8467     /// corresponding component of the argument.
8468     TDK_NonDeducedMismatch,
8469     /// When performing template argument deduction for a function
8470     /// template, there were too many call arguments.
8471     TDK_TooManyArguments,
8472     /// When performing template argument deduction for a function
8473     /// template, there were too few call arguments.
8474     TDK_TooFewArguments,
8475     /// The explicitly-specified template arguments were not valid
8476     /// template arguments for the given template.
8477     TDK_InvalidExplicitArguments,
8478     /// Checking non-dependent argument conversions failed.
8479     TDK_NonDependentConversionFailure,
8480     /// The deduced arguments did not satisfy the constraints associated
8481     /// with the template.
8482     TDK_ConstraintsNotSatisfied,
8483     /// Deduction failed; that's all we know.
8484     TDK_MiscellaneousDeductionFailure,
8485     /// CUDA Target attributes do not match.
8486     TDK_CUDATargetMismatch
8487   };
8488 
8489   TemplateDeductionResult
8490   DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
8491                           const TemplateArgumentList &TemplateArgs,
8492                           sema::TemplateDeductionInfo &Info);
8493 
8494   TemplateDeductionResult
8495   DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
8496                           const TemplateArgumentList &TemplateArgs,
8497                           sema::TemplateDeductionInfo &Info);
8498 
8499   TemplateDeductionResult SubstituteExplicitTemplateArguments(
8500       FunctionTemplateDecl *FunctionTemplate,
8501       TemplateArgumentListInfo &ExplicitTemplateArgs,
8502       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
8503       SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
8504       sema::TemplateDeductionInfo &Info);
8505 
8506   /// brief A function argument from which we performed template argument
8507   // deduction for a call.
8508   struct OriginalCallArg {
OriginalCallArgOriginalCallArg8509     OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
8510                     unsigned ArgIdx, QualType OriginalArgType)
8511         : OriginalParamType(OriginalParamType),
8512           DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
8513           OriginalArgType(OriginalArgType) {}
8514 
8515     QualType OriginalParamType;
8516     bool DecomposedParam;
8517     unsigned ArgIdx;
8518     QualType OriginalArgType;
8519   };
8520 
8521   TemplateDeductionResult FinishTemplateArgumentDeduction(
8522       FunctionTemplateDecl *FunctionTemplate,
8523       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
8524       unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
8525       sema::TemplateDeductionInfo &Info,
8526       SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
8527       bool PartialOverloading = false,
8528       llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
8529 
8530   TemplateDeductionResult DeduceTemplateArguments(
8531       FunctionTemplateDecl *FunctionTemplate,
8532       TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8533       FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
8534       bool PartialOverloading,
8535       llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
8536 
8537   TemplateDeductionResult
8538   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
8539                           TemplateArgumentListInfo *ExplicitTemplateArgs,
8540                           QualType ArgFunctionType,
8541                           FunctionDecl *&Specialization,
8542                           sema::TemplateDeductionInfo &Info,
8543                           bool IsAddressOfFunction = false);
8544 
8545   TemplateDeductionResult
8546   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
8547                           QualType ToType,
8548                           CXXConversionDecl *&Specialization,
8549                           sema::TemplateDeductionInfo &Info);
8550 
8551   TemplateDeductionResult
8552   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
8553                           TemplateArgumentListInfo *ExplicitTemplateArgs,
8554                           FunctionDecl *&Specialization,
8555                           sema::TemplateDeductionInfo &Info,
8556                           bool IsAddressOfFunction = false);
8557 
8558   /// Substitute Replacement for \p auto in \p TypeWithAuto
8559   QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
8560   /// Substitute Replacement for auto in TypeWithAuto
8561   TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
8562                                           QualType Replacement);
8563   /// Completely replace the \c auto in \p TypeWithAuto by
8564   /// \p Replacement. This does not retain any \c auto type sugar.
8565   QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
8566   TypeSourceInfo *ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
8567                                             QualType Replacement);
8568 
8569   /// Result type of DeduceAutoType.
8570   enum DeduceAutoResult {
8571     DAR_Succeeded,
8572     DAR_Failed,
8573     DAR_FailedAlreadyDiagnosed
8574   };
8575 
8576   DeduceAutoResult
8577   DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
8578                  Optional<unsigned> DependentDeductionDepth = None,
8579                  bool IgnoreConstraints = false);
8580   DeduceAutoResult
8581   DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
8582                  Optional<unsigned> DependentDeductionDepth = None,
8583                  bool IgnoreConstraints = false);
8584   void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
8585   bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
8586                         bool Diagnose = true);
8587 
8588   /// Declare implicit deduction guides for a class template if we've
8589   /// not already done so.
8590   void DeclareImplicitDeductionGuides(TemplateDecl *Template,
8591                                       SourceLocation Loc);
8592 
8593   QualType DeduceTemplateSpecializationFromInitializer(
8594       TypeSourceInfo *TInfo, const InitializedEntity &Entity,
8595       const InitializationKind &Kind, MultiExprArg Init);
8596 
8597   QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
8598                                         QualType Type, TypeSourceInfo *TSI,
8599                                         SourceRange Range, bool DirectInit,
8600                                         Expr *Init);
8601 
8602   TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
8603 
8604   bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
8605                                         SourceLocation ReturnLoc,
8606                                         Expr *&RetExpr, AutoType *AT);
8607 
8608   FunctionTemplateDecl *getMoreSpecializedTemplate(
8609       FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc,
8610       TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
8611       unsigned NumCallArguments2, bool Reversed = false);
8612   UnresolvedSetIterator
8613   getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
8614                      TemplateSpecCandidateSet &FailedCandidates,
8615                      SourceLocation Loc,
8616                      const PartialDiagnostic &NoneDiag,
8617                      const PartialDiagnostic &AmbigDiag,
8618                      const PartialDiagnostic &CandidateDiag,
8619                      bool Complain = true, QualType TargetType = QualType());
8620 
8621   ClassTemplatePartialSpecializationDecl *
8622   getMoreSpecializedPartialSpecialization(
8623                                   ClassTemplatePartialSpecializationDecl *PS1,
8624                                   ClassTemplatePartialSpecializationDecl *PS2,
8625                                   SourceLocation Loc);
8626 
8627   bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
8628                                     sema::TemplateDeductionInfo &Info);
8629 
8630   VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
8631       VarTemplatePartialSpecializationDecl *PS1,
8632       VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
8633 
8634   bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
8635                                     sema::TemplateDeductionInfo &Info);
8636 
8637   bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
8638       TemplateParameterList *PParam, TemplateDecl *AArg, SourceLocation Loc);
8639 
8640   void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
8641                                   unsigned Depth, llvm::SmallBitVector &Used);
8642 
8643   void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
8644                                   bool OnlyDeduced,
8645                                   unsigned Depth,
8646                                   llvm::SmallBitVector &Used);
MarkDeducedTemplateParameters(const FunctionTemplateDecl * FunctionTemplate,llvm::SmallBitVector & Deduced)8647   void MarkDeducedTemplateParameters(
8648                                   const FunctionTemplateDecl *FunctionTemplate,
8649                                   llvm::SmallBitVector &Deduced) {
8650     return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
8651   }
8652   static void MarkDeducedTemplateParameters(ASTContext &Ctx,
8653                                   const FunctionTemplateDecl *FunctionTemplate,
8654                                   llvm::SmallBitVector &Deduced);
8655 
8656   //===--------------------------------------------------------------------===//
8657   // C++ Template Instantiation
8658   //
8659 
8660   MultiLevelTemplateArgumentList
8661   getTemplateInstantiationArgs(NamedDecl *D,
8662                                const TemplateArgumentList *Innermost = nullptr,
8663                                bool RelativeToPrimary = false,
8664                                const FunctionDecl *Pattern = nullptr);
8665 
8666   /// A context in which code is being synthesized (where a source location
8667   /// alone is not sufficient to identify the context). This covers template
8668   /// instantiation and various forms of implicitly-generated functions.
8669   struct CodeSynthesisContext {
8670     /// The kind of template instantiation we are performing
8671     enum SynthesisKind {
8672       /// We are instantiating a template declaration. The entity is
8673       /// the declaration we're instantiating (e.g., a CXXRecordDecl).
8674       TemplateInstantiation,
8675 
8676       /// We are instantiating a default argument for a template
8677       /// parameter. The Entity is the template parameter whose argument is
8678       /// being instantiated, the Template is the template, and the
8679       /// TemplateArgs/NumTemplateArguments provide the template arguments as
8680       /// specified.
8681       DefaultTemplateArgumentInstantiation,
8682 
8683       /// We are instantiating a default argument for a function.
8684       /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
8685       /// provides the template arguments as specified.
8686       DefaultFunctionArgumentInstantiation,
8687 
8688       /// We are substituting explicit template arguments provided for
8689       /// a function template. The entity is a FunctionTemplateDecl.
8690       ExplicitTemplateArgumentSubstitution,
8691 
8692       /// We are substituting template argument determined as part of
8693       /// template argument deduction for either a class template
8694       /// partial specialization or a function template. The
8695       /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
8696       /// a TemplateDecl.
8697       DeducedTemplateArgumentSubstitution,
8698 
8699       /// We are substituting prior template arguments into a new
8700       /// template parameter. The template parameter itself is either a
8701       /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
8702       PriorTemplateArgumentSubstitution,
8703 
8704       /// We are checking the validity of a default template argument that
8705       /// has been used when naming a template-id.
8706       DefaultTemplateArgumentChecking,
8707 
8708       /// We are computing the exception specification for a defaulted special
8709       /// member function.
8710       ExceptionSpecEvaluation,
8711 
8712       /// We are instantiating the exception specification for a function
8713       /// template which was deferred until it was needed.
8714       ExceptionSpecInstantiation,
8715 
8716       /// We are instantiating a requirement of a requires expression.
8717       RequirementInstantiation,
8718 
8719       /// We are checking the satisfaction of a nested requirement of a requires
8720       /// expression.
8721       NestedRequirementConstraintsCheck,
8722 
8723       /// We are declaring an implicit special member function.
8724       DeclaringSpecialMember,
8725 
8726       /// We are declaring an implicit 'operator==' for a defaulted
8727       /// 'operator<=>'.
8728       DeclaringImplicitEqualityComparison,
8729 
8730       /// We are defining a synthesized function (such as a defaulted special
8731       /// member).
8732       DefiningSynthesizedFunction,
8733 
8734       // We are checking the constraints associated with a constrained entity or
8735       // the constraint expression of a concept. This includes the checks that
8736       // atomic constraints have the type 'bool' and that they can be constant
8737       // evaluated.
8738       ConstraintsCheck,
8739 
8740       // We are substituting template arguments into a constraint expression.
8741       ConstraintSubstitution,
8742 
8743       // We are normalizing a constraint expression.
8744       ConstraintNormalization,
8745 
8746       // We are substituting into the parameter mapping of an atomic constraint
8747       // during normalization.
8748       ParameterMappingSubstitution,
8749 
8750       /// We are rewriting a comparison operator in terms of an operator<=>.
8751       RewritingOperatorAsSpaceship,
8752 
8753       /// We are initializing a structured binding.
8754       InitializingStructuredBinding,
8755 
8756       /// We are marking a class as __dllexport.
8757       MarkingClassDllexported,
8758 
8759       /// Added for Template instantiation observation.
8760       /// Memoization means we are _not_ instantiating a template because
8761       /// it is already instantiated (but we entered a context where we
8762       /// would have had to if it was not already instantiated).
8763       Memoization
8764     } Kind;
8765 
8766     /// Was the enclosing context a non-instantiation SFINAE context?
8767     bool SavedInNonInstantiationSFINAEContext;
8768 
8769     /// The point of instantiation or synthesis within the source code.
8770     SourceLocation PointOfInstantiation;
8771 
8772     /// The entity that is being synthesized.
8773     Decl *Entity;
8774 
8775     /// The template (or partial specialization) in which we are
8776     /// performing the instantiation, for substitutions of prior template
8777     /// arguments.
8778     NamedDecl *Template;
8779 
8780     /// The list of template arguments we are substituting, if they
8781     /// are not part of the entity.
8782     const TemplateArgument *TemplateArgs;
8783 
8784     // FIXME: Wrap this union around more members, or perhaps store the
8785     // kind-specific members in the RAII object owning the context.
8786     union {
8787       /// The number of template arguments in TemplateArgs.
8788       unsigned NumTemplateArgs;
8789 
8790       /// The special member being declared or defined.
8791       CXXSpecialMember SpecialMember;
8792     };
8793 
template_argumentsCodeSynthesisContext8794     ArrayRef<TemplateArgument> template_arguments() const {
8795       assert(Kind != DeclaringSpecialMember);
8796       return {TemplateArgs, NumTemplateArgs};
8797     }
8798 
8799     /// The template deduction info object associated with the
8800     /// substitution or checking of explicit or deduced template arguments.
8801     sema::TemplateDeductionInfo *DeductionInfo;
8802 
8803     /// The source range that covers the construct that cause
8804     /// the instantiation, e.g., the template-id that causes a class
8805     /// template instantiation.
8806     SourceRange InstantiationRange;
8807 
CodeSynthesisContextCodeSynthesisContext8808     CodeSynthesisContext()
8809         : Kind(TemplateInstantiation),
8810           SavedInNonInstantiationSFINAEContext(false), Entity(nullptr),
8811           Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0),
8812           DeductionInfo(nullptr) {}
8813 
8814     /// Determines whether this template is an actual instantiation
8815     /// that should be counted toward the maximum instantiation depth.
8816     bool isInstantiationRecord() const;
8817   };
8818 
8819   /// List of active code synthesis contexts.
8820   ///
8821   /// This vector is treated as a stack. As synthesis of one entity requires
8822   /// synthesis of another, additional contexts are pushed onto the stack.
8823   SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
8824 
8825   /// Specializations whose definitions are currently being instantiated.
8826   llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
8827 
8828   /// Non-dependent types used in templates that have already been instantiated
8829   /// by some template instantiation.
8830   llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
8831 
8832   /// Extra modules inspected when performing a lookup during a template
8833   /// instantiation. Computed lazily.
8834   SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
8835 
8836   /// Cache of additional modules that should be used for name lookup
8837   /// within the current template instantiation. Computed lazily; use
8838   /// getLookupModules() to get a complete set.
8839   llvm::DenseSet<Module*> LookupModulesCache;
8840 
8841   /// Get the set of additional modules that should be checked during
8842   /// name lookup. A module and its imports become visible when instanting a
8843   /// template defined within it.
8844   llvm::DenseSet<Module*> &getLookupModules();
8845 
8846   /// Map from the most recent declaration of a namespace to the most
8847   /// recent visible declaration of that namespace.
8848   llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
8849 
8850   /// Whether we are in a SFINAE context that is not associated with
8851   /// template instantiation.
8852   ///
8853   /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
8854   /// of a template instantiation or template argument deduction.
8855   bool InNonInstantiationSFINAEContext;
8856 
8857   /// The number of \p CodeSynthesisContexts that are not template
8858   /// instantiations and, therefore, should not be counted as part of the
8859   /// instantiation depth.
8860   ///
8861   /// When the instantiation depth reaches the user-configurable limit
8862   /// \p LangOptions::InstantiationDepth we will abort instantiation.
8863   // FIXME: Should we have a similar limit for other forms of synthesis?
8864   unsigned NonInstantiationEntries;
8865 
8866   /// The depth of the context stack at the point when the most recent
8867   /// error or warning was produced.
8868   ///
8869   /// This value is used to suppress printing of redundant context stacks
8870   /// when there are multiple errors or warnings in the same instantiation.
8871   // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
8872   unsigned LastEmittedCodeSynthesisContextDepth = 0;
8873 
8874   /// The template instantiation callbacks to trace or track
8875   /// instantiations (objects can be chained).
8876   ///
8877   /// This callbacks is used to print, trace or track template
8878   /// instantiations as they are being constructed.
8879   std::vector<std::unique_ptr<TemplateInstantiationCallback>>
8880       TemplateInstCallbacks;
8881 
8882   /// The current index into pack expansion arguments that will be
8883   /// used for substitution of parameter packs.
8884   ///
8885   /// The pack expansion index will be -1 to indicate that parameter packs
8886   /// should be instantiated as themselves. Otherwise, the index specifies
8887   /// which argument within the parameter pack will be used for substitution.
8888   int ArgumentPackSubstitutionIndex;
8889 
8890   /// RAII object used to change the argument pack substitution index
8891   /// within a \c Sema object.
8892   ///
8893   /// See \c ArgumentPackSubstitutionIndex for more information.
8894   class ArgumentPackSubstitutionIndexRAII {
8895     Sema &Self;
8896     int OldSubstitutionIndex;
8897 
8898   public:
ArgumentPackSubstitutionIndexRAII(Sema & Self,int NewSubstitutionIndex)8899     ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
8900       : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
8901       Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
8902     }
8903 
~ArgumentPackSubstitutionIndexRAII()8904     ~ArgumentPackSubstitutionIndexRAII() {
8905       Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
8906     }
8907   };
8908 
8909   friend class ArgumentPackSubstitutionRAII;
8910 
8911   /// For each declaration that involved template argument deduction, the
8912   /// set of diagnostics that were suppressed during that template argument
8913   /// deduction.
8914   ///
8915   /// FIXME: Serialize this structure to the AST file.
8916   typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
8917     SuppressedDiagnosticsMap;
8918   SuppressedDiagnosticsMap SuppressedDiagnostics;
8919 
8920   /// A stack object to be created when performing template
8921   /// instantiation.
8922   ///
8923   /// Construction of an object of type \c InstantiatingTemplate
8924   /// pushes the current instantiation onto the stack of active
8925   /// instantiations. If the size of this stack exceeds the maximum
8926   /// number of recursive template instantiations, construction
8927   /// produces an error and evaluates true.
8928   ///
8929   /// Destruction of this object will pop the named instantiation off
8930   /// the stack.
8931   struct InstantiatingTemplate {
8932     /// Note that we are instantiating a class template,
8933     /// function template, variable template, alias template,
8934     /// or a member thereof.
8935     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8936                           Decl *Entity,
8937                           SourceRange InstantiationRange = SourceRange());
8938 
8939     struct ExceptionSpecification {};
8940     /// Note that we are instantiating an exception specification
8941     /// of a function template.
8942     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8943                           FunctionDecl *Entity, ExceptionSpecification,
8944                           SourceRange InstantiationRange = SourceRange());
8945 
8946     /// Note that we are instantiating a default argument in a
8947     /// template-id.
8948     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8949                           TemplateParameter Param, TemplateDecl *Template,
8950                           ArrayRef<TemplateArgument> TemplateArgs,
8951                           SourceRange InstantiationRange = SourceRange());
8952 
8953     /// Note that we are substituting either explicitly-specified or
8954     /// deduced template arguments during function template argument deduction.
8955     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8956                           FunctionTemplateDecl *FunctionTemplate,
8957                           ArrayRef<TemplateArgument> TemplateArgs,
8958                           CodeSynthesisContext::SynthesisKind Kind,
8959                           sema::TemplateDeductionInfo &DeductionInfo,
8960                           SourceRange InstantiationRange = SourceRange());
8961 
8962     /// Note that we are instantiating as part of template
8963     /// argument deduction for a class template declaration.
8964     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8965                           TemplateDecl *Template,
8966                           ArrayRef<TemplateArgument> TemplateArgs,
8967                           sema::TemplateDeductionInfo &DeductionInfo,
8968                           SourceRange InstantiationRange = SourceRange());
8969 
8970     /// Note that we are instantiating as part of template
8971     /// argument deduction for a class template partial
8972     /// specialization.
8973     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8974                           ClassTemplatePartialSpecializationDecl *PartialSpec,
8975                           ArrayRef<TemplateArgument> TemplateArgs,
8976                           sema::TemplateDeductionInfo &DeductionInfo,
8977                           SourceRange InstantiationRange = SourceRange());
8978 
8979     /// Note that we are instantiating as part of template
8980     /// argument deduction for a variable template partial
8981     /// specialization.
8982     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8983                           VarTemplatePartialSpecializationDecl *PartialSpec,
8984                           ArrayRef<TemplateArgument> TemplateArgs,
8985                           sema::TemplateDeductionInfo &DeductionInfo,
8986                           SourceRange InstantiationRange = SourceRange());
8987 
8988     /// Note that we are instantiating a default argument for a function
8989     /// parameter.
8990     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8991                           ParmVarDecl *Param,
8992                           ArrayRef<TemplateArgument> TemplateArgs,
8993                           SourceRange InstantiationRange = SourceRange());
8994 
8995     /// Note that we are substituting prior template arguments into a
8996     /// non-type parameter.
8997     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8998                           NamedDecl *Template,
8999                           NonTypeTemplateParmDecl *Param,
9000                           ArrayRef<TemplateArgument> TemplateArgs,
9001                           SourceRange InstantiationRange);
9002 
9003     /// Note that we are substituting prior template arguments into a
9004     /// template template parameter.
9005     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9006                           NamedDecl *Template,
9007                           TemplateTemplateParmDecl *Param,
9008                           ArrayRef<TemplateArgument> TemplateArgs,
9009                           SourceRange InstantiationRange);
9010 
9011     /// Note that we are checking the default template argument
9012     /// against the template parameter for a given template-id.
9013     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9014                           TemplateDecl *Template,
9015                           NamedDecl *Param,
9016                           ArrayRef<TemplateArgument> TemplateArgs,
9017                           SourceRange InstantiationRange);
9018 
9019     struct ConstraintsCheck {};
9020     /// \brief Note that we are checking the constraints associated with some
9021     /// constrained entity (a concept declaration or a template with associated
9022     /// constraints).
9023     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9024                           ConstraintsCheck, NamedDecl *Template,
9025                           ArrayRef<TemplateArgument> TemplateArgs,
9026                           SourceRange InstantiationRange);
9027 
9028     struct ConstraintSubstitution {};
9029     /// \brief Note that we are checking a constraint expression associated
9030     /// with a template declaration or as part of the satisfaction check of a
9031     /// concept.
9032     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9033                           ConstraintSubstitution, NamedDecl *Template,
9034                           sema::TemplateDeductionInfo &DeductionInfo,
9035                           SourceRange InstantiationRange);
9036 
9037     struct ConstraintNormalization {};
9038     /// \brief Note that we are normalizing a constraint expression.
9039     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9040                           ConstraintNormalization, NamedDecl *Template,
9041                           SourceRange InstantiationRange);
9042 
9043     struct ParameterMappingSubstitution {};
9044     /// \brief Note that we are subtituting into the parameter mapping of an
9045     /// atomic constraint during constraint normalization.
9046     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9047                           ParameterMappingSubstitution, NamedDecl *Template,
9048                           SourceRange InstantiationRange);
9049 
9050     /// \brief Note that we are substituting template arguments into a part of
9051     /// a requirement of a requires expression.
9052     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9053                           concepts::Requirement *Req,
9054                           sema::TemplateDeductionInfo &DeductionInfo,
9055                           SourceRange InstantiationRange = SourceRange());
9056 
9057     /// \brief Note that we are checking the satisfaction of the constraint
9058     /// expression inside of a nested requirement.
9059     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9060                           concepts::NestedRequirement *Req, ConstraintsCheck,
9061                           SourceRange InstantiationRange = SourceRange());
9062 
9063     /// Note that we have finished instantiating this template.
9064     void Clear();
9065 
~InstantiatingTemplateInstantiatingTemplate9066     ~InstantiatingTemplate() { Clear(); }
9067 
9068     /// Determines whether we have exceeded the maximum
9069     /// recursive template instantiations.
isInvalidInstantiatingTemplate9070     bool isInvalid() const { return Invalid; }
9071 
9072     /// Determine whether we are already instantiating this
9073     /// specialization in some surrounding active instantiation.
isAlreadyInstantiatingInstantiatingTemplate9074     bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
9075 
9076   private:
9077     Sema &SemaRef;
9078     bool Invalid;
9079     bool AlreadyInstantiating;
9080     bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
9081                                  SourceRange InstantiationRange);
9082 
9083     InstantiatingTemplate(
9084         Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
9085         SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
9086         Decl *Entity, NamedDecl *Template = nullptr,
9087         ArrayRef<TemplateArgument> TemplateArgs = None,
9088         sema::TemplateDeductionInfo *DeductionInfo = nullptr);
9089 
9090     InstantiatingTemplate(const InstantiatingTemplate&) = delete;
9091 
9092     InstantiatingTemplate&
9093     operator=(const InstantiatingTemplate&) = delete;
9094   };
9095 
9096   void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
9097   void popCodeSynthesisContext();
9098 
9099   /// Determine whether we are currently performing template instantiation.
inTemplateInstantiation()9100   bool inTemplateInstantiation() const {
9101     return CodeSynthesisContexts.size() > NonInstantiationEntries;
9102   }
9103 
PrintContextStack()9104   void PrintContextStack() {
9105     if (!CodeSynthesisContexts.empty() &&
9106         CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
9107       PrintInstantiationStack();
9108       LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
9109     }
9110     if (PragmaAttributeCurrentTargetDecl)
9111       PrintPragmaAttributeInstantiationPoint();
9112   }
9113   void PrintInstantiationStack();
9114 
9115   void PrintPragmaAttributeInstantiationPoint();
9116 
9117   /// Determines whether we are currently in a context where
9118   /// template argument substitution failures are not considered
9119   /// errors.
9120   ///
9121   /// \returns An empty \c Optional if we're not in a SFINAE context.
9122   /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
9123   /// template-deduction context object, which can be used to capture
9124   /// diagnostics that will be suppressed.
9125   Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
9126 
9127   /// Determines whether we are currently in a context that
9128   /// is not evaluated as per C++ [expr] p5.
isUnevaluatedContext()9129   bool isUnevaluatedContext() const {
9130     assert(!ExprEvalContexts.empty() &&
9131            "Must be in an expression evaluation context");
9132     return ExprEvalContexts.back().isUnevaluated();
9133   }
9134 
isImmediateFunctionContext()9135   bool isImmediateFunctionContext() const {
9136     assert(!ExprEvalContexts.empty() &&
9137            "Must be in an expression evaluation context");
9138     for (const ExpressionEvaluationContextRecord &context :
9139          llvm::reverse(ExprEvalContexts)) {
9140       if (context.isImmediateFunctionContext())
9141         return true;
9142       if (context.isUnevaluated())
9143         return false;
9144     }
9145     return false;
9146   }
9147 
9148   /// RAII class used to determine whether SFINAE has
9149   /// trapped any errors that occur during template argument
9150   /// deduction.
9151   class SFINAETrap {
9152     Sema &SemaRef;
9153     unsigned PrevSFINAEErrors;
9154     bool PrevInNonInstantiationSFINAEContext;
9155     bool PrevAccessCheckingSFINAE;
9156     bool PrevLastDiagnosticIgnored;
9157 
9158   public:
9159     explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
SemaRef(SemaRef)9160       : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
9161         PrevInNonInstantiationSFINAEContext(
9162                                       SemaRef.InNonInstantiationSFINAEContext),
9163         PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE),
9164         PrevLastDiagnosticIgnored(
9165             SemaRef.getDiagnostics().isLastDiagnosticIgnored())
9166     {
9167       if (!SemaRef.isSFINAEContext())
9168         SemaRef.InNonInstantiationSFINAEContext = true;
9169       SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
9170     }
9171 
~SFINAETrap()9172     ~SFINAETrap() {
9173       SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
9174       SemaRef.InNonInstantiationSFINAEContext
9175         = PrevInNonInstantiationSFINAEContext;
9176       SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
9177       SemaRef.getDiagnostics().setLastDiagnosticIgnored(
9178           PrevLastDiagnosticIgnored);
9179     }
9180 
9181     /// Determine whether any SFINAE errors have been trapped.
hasErrorOccurred()9182     bool hasErrorOccurred() const {
9183       return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
9184     }
9185   };
9186 
9187   /// RAII class used to indicate that we are performing provisional
9188   /// semantic analysis to determine the validity of a construct, so
9189   /// typo-correction and diagnostics in the immediate context (not within
9190   /// implicitly-instantiated templates) should be suppressed.
9191   class TentativeAnalysisScope {
9192     Sema &SemaRef;
9193     // FIXME: Using a SFINAETrap for this is a hack.
9194     SFINAETrap Trap;
9195     bool PrevDisableTypoCorrection;
9196   public:
TentativeAnalysisScope(Sema & SemaRef)9197     explicit TentativeAnalysisScope(Sema &SemaRef)
9198         : SemaRef(SemaRef), Trap(SemaRef, true),
9199           PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
9200       SemaRef.DisableTypoCorrection = true;
9201     }
~TentativeAnalysisScope()9202     ~TentativeAnalysisScope() {
9203       SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
9204     }
9205   };
9206 
9207   /// The current instantiation scope used to store local
9208   /// variables.
9209   LocalInstantiationScope *CurrentInstantiationScope;
9210 
9211   /// Tracks whether we are in a context where typo correction is
9212   /// disabled.
9213   bool DisableTypoCorrection;
9214 
9215   /// The number of typos corrected by CorrectTypo.
9216   unsigned TyposCorrected;
9217 
9218   typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
9219   typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
9220 
9221   /// A cache containing identifiers for which typo correction failed and
9222   /// their locations, so that repeated attempts to correct an identifier in a
9223   /// given location are ignored if typo correction already failed for it.
9224   IdentifierSourceLocations TypoCorrectionFailures;
9225 
9226   /// Worker object for performing CFG-based warnings.
9227   sema::AnalysisBasedWarnings AnalysisWarnings;
9228   threadSafety::BeforeSet *ThreadSafetyDeclCache;
9229 
9230   /// An entity for which implicit template instantiation is required.
9231   ///
9232   /// The source location associated with the declaration is the first place in
9233   /// the source code where the declaration was "used". It is not necessarily
9234   /// the point of instantiation (which will be either before or after the
9235   /// namespace-scope declaration that triggered this implicit instantiation),
9236   /// However, it is the location that diagnostics should generally refer to,
9237   /// because users will need to know what code triggered the instantiation.
9238   typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
9239 
9240   /// The queue of implicit template instantiations that are required
9241   /// but have not yet been performed.
9242   std::deque<PendingImplicitInstantiation> PendingInstantiations;
9243 
9244   /// Queue of implicit template instantiations that cannot be performed
9245   /// eagerly.
9246   SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations;
9247 
9248   class GlobalEagerInstantiationScope {
9249   public:
GlobalEagerInstantiationScope(Sema & S,bool Enabled)9250     GlobalEagerInstantiationScope(Sema &S, bool Enabled)
9251         : S(S), Enabled(Enabled) {
9252       if (!Enabled) return;
9253 
9254       SavedPendingInstantiations.swap(S.PendingInstantiations);
9255       SavedVTableUses.swap(S.VTableUses);
9256     }
9257 
perform()9258     void perform() {
9259       if (Enabled) {
9260         S.DefineUsedVTables();
9261         S.PerformPendingInstantiations();
9262       }
9263     }
9264 
~GlobalEagerInstantiationScope()9265     ~GlobalEagerInstantiationScope() {
9266       if (!Enabled) return;
9267 
9268       // Restore the set of pending vtables.
9269       assert(S.VTableUses.empty() &&
9270              "VTableUses should be empty before it is discarded.");
9271       S.VTableUses.swap(SavedVTableUses);
9272 
9273       // Restore the set of pending implicit instantiations.
9274       if (S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) {
9275         assert(S.PendingInstantiations.empty() &&
9276                "PendingInstantiations should be empty before it is discarded.");
9277         S.PendingInstantiations.swap(SavedPendingInstantiations);
9278       } else {
9279         // Template instantiations in the PCH may be delayed until the TU.
9280         S.PendingInstantiations.swap(SavedPendingInstantiations);
9281         S.PendingInstantiations.insert(S.PendingInstantiations.end(),
9282                                        SavedPendingInstantiations.begin(),
9283                                        SavedPendingInstantiations.end());
9284       }
9285     }
9286 
9287   private:
9288     Sema &S;
9289     SmallVector<VTableUse, 16> SavedVTableUses;
9290     std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
9291     bool Enabled;
9292   };
9293 
9294   /// The queue of implicit template instantiations that are required
9295   /// and must be performed within the current local scope.
9296   ///
9297   /// This queue is only used for member functions of local classes in
9298   /// templates, which must be instantiated in the same scope as their
9299   /// enclosing function, so that they can reference function-local
9300   /// types, static variables, enumerators, etc.
9301   std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
9302 
9303   class LocalEagerInstantiationScope {
9304   public:
LocalEagerInstantiationScope(Sema & S)9305     LocalEagerInstantiationScope(Sema &S) : S(S) {
9306       SavedPendingLocalImplicitInstantiations.swap(
9307           S.PendingLocalImplicitInstantiations);
9308     }
9309 
perform()9310     void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); }
9311 
~LocalEagerInstantiationScope()9312     ~LocalEagerInstantiationScope() {
9313       assert(S.PendingLocalImplicitInstantiations.empty() &&
9314              "there shouldn't be any pending local implicit instantiations");
9315       SavedPendingLocalImplicitInstantiations.swap(
9316           S.PendingLocalImplicitInstantiations);
9317     }
9318 
9319   private:
9320     Sema &S;
9321     std::deque<PendingImplicitInstantiation>
9322         SavedPendingLocalImplicitInstantiations;
9323   };
9324 
9325   /// A helper class for building up ExtParameterInfos.
9326   class ExtParameterInfoBuilder {
9327     SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
9328     bool HasInteresting = false;
9329 
9330   public:
9331     /// Set the ExtParameterInfo for the parameter at the given index,
9332     ///
set(unsigned index,FunctionProtoType::ExtParameterInfo info)9333     void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
9334       assert(Infos.size() <= index);
9335       Infos.resize(index);
9336       Infos.push_back(info);
9337 
9338       if (!HasInteresting)
9339         HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
9340     }
9341 
9342     /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
9343     /// ExtParameterInfo array we've built up.
9344     const FunctionProtoType::ExtParameterInfo *
getPointerOrNull(unsigned numParams)9345     getPointerOrNull(unsigned numParams) {
9346       if (!HasInteresting) return nullptr;
9347       Infos.resize(numParams);
9348       return Infos.data();
9349     }
9350   };
9351 
9352   void PerformPendingInstantiations(bool LocalOnly = false);
9353 
9354   TypeSourceInfo *SubstType(TypeSourceInfo *T,
9355                             const MultiLevelTemplateArgumentList &TemplateArgs,
9356                             SourceLocation Loc, DeclarationName Entity,
9357                             bool AllowDeducedTST = false);
9358 
9359   QualType SubstType(QualType T,
9360                      const MultiLevelTemplateArgumentList &TemplateArgs,
9361                      SourceLocation Loc, DeclarationName Entity);
9362 
9363   TypeSourceInfo *SubstType(TypeLoc TL,
9364                             const MultiLevelTemplateArgumentList &TemplateArgs,
9365                             SourceLocation Loc, DeclarationName Entity);
9366 
9367   TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
9368                             const MultiLevelTemplateArgumentList &TemplateArgs,
9369                                         SourceLocation Loc,
9370                                         DeclarationName Entity,
9371                                         CXXRecordDecl *ThisContext,
9372                                         Qualifiers ThisTypeQuals);
9373   void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
9374                           const MultiLevelTemplateArgumentList &Args);
9375   bool SubstExceptionSpec(SourceLocation Loc,
9376                           FunctionProtoType::ExceptionSpecInfo &ESI,
9377                           SmallVectorImpl<QualType> &ExceptionStorage,
9378                           const MultiLevelTemplateArgumentList &Args);
9379   ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
9380                             const MultiLevelTemplateArgumentList &TemplateArgs,
9381                                 int indexAdjustment,
9382                                 Optional<unsigned> NumExpansions,
9383                                 bool ExpectParameterPack);
9384   bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
9385                       const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
9386                       const MultiLevelTemplateArgumentList &TemplateArgs,
9387                       SmallVectorImpl<QualType> &ParamTypes,
9388                       SmallVectorImpl<ParmVarDecl *> *OutParams,
9389                       ExtParameterInfoBuilder &ParamInfos);
9390   ExprResult SubstExpr(Expr *E,
9391                        const MultiLevelTemplateArgumentList &TemplateArgs);
9392 
9393   /// Substitute the given template arguments into a list of
9394   /// expressions, expanding pack expansions if required.
9395   ///
9396   /// \param Exprs The list of expressions to substitute into.
9397   ///
9398   /// \param IsCall Whether this is some form of call, in which case
9399   /// default arguments will be dropped.
9400   ///
9401   /// \param TemplateArgs The set of template arguments to substitute.
9402   ///
9403   /// \param Outputs Will receive all of the substituted arguments.
9404   ///
9405   /// \returns true if an error occurred, false otherwise.
9406   bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
9407                   const MultiLevelTemplateArgumentList &TemplateArgs,
9408                   SmallVectorImpl<Expr *> &Outputs);
9409 
9410   StmtResult SubstStmt(Stmt *S,
9411                        const MultiLevelTemplateArgumentList &TemplateArgs);
9412 
9413   TemplateParameterList *
9414   SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
9415                       const MultiLevelTemplateArgumentList &TemplateArgs);
9416 
9417   bool
9418   SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
9419                          const MultiLevelTemplateArgumentList &TemplateArgs,
9420                          TemplateArgumentListInfo &Outputs);
9421 
9422 
9423   Decl *SubstDecl(Decl *D, DeclContext *Owner,
9424                   const MultiLevelTemplateArgumentList &TemplateArgs);
9425 
9426   /// Substitute the name and return type of a defaulted 'operator<=>' to form
9427   /// an implicit 'operator=='.
9428   FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
9429                                            FunctionDecl *Spaceship);
9430 
9431   ExprResult SubstInitializer(Expr *E,
9432                        const MultiLevelTemplateArgumentList &TemplateArgs,
9433                        bool CXXDirectInit);
9434 
9435   bool
9436   SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
9437                       CXXRecordDecl *Pattern,
9438                       const MultiLevelTemplateArgumentList &TemplateArgs);
9439 
9440   bool
9441   InstantiateClass(SourceLocation PointOfInstantiation,
9442                    CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
9443                    const MultiLevelTemplateArgumentList &TemplateArgs,
9444                    TemplateSpecializationKind TSK,
9445                    bool Complain = true);
9446 
9447   bool InstantiateEnum(SourceLocation PointOfInstantiation,
9448                        EnumDecl *Instantiation, EnumDecl *Pattern,
9449                        const MultiLevelTemplateArgumentList &TemplateArgs,
9450                        TemplateSpecializationKind TSK);
9451 
9452   bool InstantiateInClassInitializer(
9453       SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
9454       FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
9455 
9456   struct LateInstantiatedAttribute {
9457     const Attr *TmplAttr;
9458     LocalInstantiationScope *Scope;
9459     Decl *NewDecl;
9460 
LateInstantiatedAttributeLateInstantiatedAttribute9461     LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
9462                               Decl *D)
9463       : TmplAttr(A), Scope(S), NewDecl(D)
9464     { }
9465   };
9466   typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
9467 
9468   void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
9469                         const Decl *Pattern, Decl *Inst,
9470                         LateInstantiatedAttrVec *LateAttrs = nullptr,
9471                         LocalInstantiationScope *OuterMostScope = nullptr);
9472 
9473   void
9474   InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
9475                           const Decl *Pattern, Decl *Inst,
9476                           LateInstantiatedAttrVec *LateAttrs = nullptr,
9477                           LocalInstantiationScope *OuterMostScope = nullptr);
9478 
9479   void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor);
9480 
9481   bool usesPartialOrExplicitSpecialization(
9482       SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
9483 
9484   bool
9485   InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
9486                            ClassTemplateSpecializationDecl *ClassTemplateSpec,
9487                            TemplateSpecializationKind TSK,
9488                            bool Complain = true);
9489 
9490   void InstantiateClassMembers(SourceLocation PointOfInstantiation,
9491                                CXXRecordDecl *Instantiation,
9492                             const MultiLevelTemplateArgumentList &TemplateArgs,
9493                                TemplateSpecializationKind TSK);
9494 
9495   void InstantiateClassTemplateSpecializationMembers(
9496                                           SourceLocation PointOfInstantiation,
9497                            ClassTemplateSpecializationDecl *ClassTemplateSpec,
9498                                                 TemplateSpecializationKind TSK);
9499 
9500   NestedNameSpecifierLoc
9501   SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
9502                            const MultiLevelTemplateArgumentList &TemplateArgs);
9503 
9504   DeclarationNameInfo
9505   SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
9506                            const MultiLevelTemplateArgumentList &TemplateArgs);
9507   TemplateName
9508   SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
9509                     SourceLocation Loc,
9510                     const MultiLevelTemplateArgumentList &TemplateArgs);
9511 
9512   bool SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
9513                            const MultiLevelTemplateArgumentList &TemplateArgs);
9514 
9515   bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
9516                                   ParmVarDecl *Param);
9517   void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
9518                                 FunctionDecl *Function);
9519   bool CheckInstantiatedFunctionTemplateConstraints(
9520       SourceLocation PointOfInstantiation, FunctionDecl *Decl,
9521       ArrayRef<TemplateArgument> TemplateArgs,
9522       ConstraintSatisfaction &Satisfaction);
9523   FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
9524                                                const TemplateArgumentList *Args,
9525                                                SourceLocation Loc);
9526   void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
9527                                      FunctionDecl *Function,
9528                                      bool Recursive = false,
9529                                      bool DefinitionRequired = false,
9530                                      bool AtEndOfTU = false);
9531   VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
9532       VarTemplateDecl *VarTemplate, VarDecl *FromVar,
9533       const TemplateArgumentList &TemplateArgList,
9534       const TemplateArgumentListInfo &TemplateArgsInfo,
9535       SmallVectorImpl<TemplateArgument> &Converted,
9536       SourceLocation PointOfInstantiation,
9537       LateInstantiatedAttrVec *LateAttrs = nullptr,
9538       LocalInstantiationScope *StartingScope = nullptr);
9539   VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
9540       VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
9541       const MultiLevelTemplateArgumentList &TemplateArgs);
9542   void
9543   BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
9544                              const MultiLevelTemplateArgumentList &TemplateArgs,
9545                              LateInstantiatedAttrVec *LateAttrs,
9546                              DeclContext *Owner,
9547                              LocalInstantiationScope *StartingScope,
9548                              bool InstantiatingVarTemplate = false,
9549                              VarTemplateSpecializationDecl *PrevVTSD = nullptr);
9550 
9551   void InstantiateVariableInitializer(
9552       VarDecl *Var, VarDecl *OldVar,
9553       const MultiLevelTemplateArgumentList &TemplateArgs);
9554   void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
9555                                      VarDecl *Var, bool Recursive = false,
9556                                      bool DefinitionRequired = false,
9557                                      bool AtEndOfTU = false);
9558 
9559   void InstantiateMemInitializers(CXXConstructorDecl *New,
9560                                   const CXXConstructorDecl *Tmpl,
9561                             const MultiLevelTemplateArgumentList &TemplateArgs);
9562 
9563   NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
9564                           const MultiLevelTemplateArgumentList &TemplateArgs,
9565                           bool FindingInstantiatedContext = false);
9566   DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
9567                           const MultiLevelTemplateArgumentList &TemplateArgs);
9568 
9569   // Objective-C declarations.
9570   enum ObjCContainerKind {
9571     OCK_None = -1,
9572     OCK_Interface = 0,
9573     OCK_Protocol,
9574     OCK_Category,
9575     OCK_ClassExtension,
9576     OCK_Implementation,
9577     OCK_CategoryImplementation
9578   };
9579   ObjCContainerKind getObjCContainerKind() const;
9580 
9581   DeclResult actOnObjCTypeParam(Scope *S,
9582                                 ObjCTypeParamVariance variance,
9583                                 SourceLocation varianceLoc,
9584                                 unsigned index,
9585                                 IdentifierInfo *paramName,
9586                                 SourceLocation paramLoc,
9587                                 SourceLocation colonLoc,
9588                                 ParsedType typeBound);
9589 
9590   ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
9591                                             ArrayRef<Decl *> typeParams,
9592                                             SourceLocation rAngleLoc);
9593   void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
9594 
9595   Decl *ActOnStartClassInterface(
9596       Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
9597       SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
9598       IdentifierInfo *SuperName, SourceLocation SuperLoc,
9599       ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange,
9600       Decl *const *ProtoRefs, unsigned NumProtoRefs,
9601       const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
9602       const ParsedAttributesView &AttrList);
9603 
9604   void ActOnSuperClassOfClassInterface(Scope *S,
9605                                        SourceLocation AtInterfaceLoc,
9606                                        ObjCInterfaceDecl *IDecl,
9607                                        IdentifierInfo *ClassName,
9608                                        SourceLocation ClassLoc,
9609                                        IdentifierInfo *SuperName,
9610                                        SourceLocation SuperLoc,
9611                                        ArrayRef<ParsedType> SuperTypeArgs,
9612                                        SourceRange SuperTypeArgsRange);
9613 
9614   void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
9615                                SmallVectorImpl<SourceLocation> &ProtocolLocs,
9616                                IdentifierInfo *SuperName,
9617                                SourceLocation SuperLoc);
9618 
9619   Decl *ActOnCompatibilityAlias(
9620                     SourceLocation AtCompatibilityAliasLoc,
9621                     IdentifierInfo *AliasName,  SourceLocation AliasLocation,
9622                     IdentifierInfo *ClassName, SourceLocation ClassLocation);
9623 
9624   bool CheckForwardProtocolDeclarationForCircularDependency(
9625     IdentifierInfo *PName,
9626     SourceLocation &PLoc, SourceLocation PrevLoc,
9627     const ObjCList<ObjCProtocolDecl> &PList);
9628 
9629   Decl *ActOnStartProtocolInterface(
9630       SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
9631       SourceLocation ProtocolLoc, Decl *const *ProtoRefNames,
9632       unsigned NumProtoRefs, const SourceLocation *ProtoLocs,
9633       SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList);
9634 
9635   Decl *ActOnStartCategoryInterface(
9636       SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
9637       SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
9638       IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
9639       Decl *const *ProtoRefs, unsigned NumProtoRefs,
9640       const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
9641       const ParsedAttributesView &AttrList);
9642 
9643   Decl *ActOnStartClassImplementation(SourceLocation AtClassImplLoc,
9644                                       IdentifierInfo *ClassName,
9645                                       SourceLocation ClassLoc,
9646                                       IdentifierInfo *SuperClassname,
9647                                       SourceLocation SuperClassLoc,
9648                                       const ParsedAttributesView &AttrList);
9649 
9650   Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
9651                                          IdentifierInfo *ClassName,
9652                                          SourceLocation ClassLoc,
9653                                          IdentifierInfo *CatName,
9654                                          SourceLocation CatLoc,
9655                                          const ParsedAttributesView &AttrList);
9656 
9657   DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
9658                                                ArrayRef<Decl *> Decls);
9659 
9660   DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
9661                    IdentifierInfo **IdentList,
9662                    SourceLocation *IdentLocs,
9663                    ArrayRef<ObjCTypeParamList *> TypeParamLists,
9664                    unsigned NumElts);
9665 
9666   DeclGroupPtrTy
9667   ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
9668                                   ArrayRef<IdentifierLocPair> IdentList,
9669                                   const ParsedAttributesView &attrList);
9670 
9671   void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
9672                                ArrayRef<IdentifierLocPair> ProtocolId,
9673                                SmallVectorImpl<Decl *> &Protocols);
9674 
9675   void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
9676                                     SourceLocation ProtocolLoc,
9677                                     IdentifierInfo *TypeArgId,
9678                                     SourceLocation TypeArgLoc,
9679                                     bool SelectProtocolFirst = false);
9680 
9681   /// Given a list of identifiers (and their locations), resolve the
9682   /// names to either Objective-C protocol qualifiers or type
9683   /// arguments, as appropriate.
9684   void actOnObjCTypeArgsOrProtocolQualifiers(
9685          Scope *S,
9686          ParsedType baseType,
9687          SourceLocation lAngleLoc,
9688          ArrayRef<IdentifierInfo *> identifiers,
9689          ArrayRef<SourceLocation> identifierLocs,
9690          SourceLocation rAngleLoc,
9691          SourceLocation &typeArgsLAngleLoc,
9692          SmallVectorImpl<ParsedType> &typeArgs,
9693          SourceLocation &typeArgsRAngleLoc,
9694          SourceLocation &protocolLAngleLoc,
9695          SmallVectorImpl<Decl *> &protocols,
9696          SourceLocation &protocolRAngleLoc,
9697          bool warnOnIncompleteProtocols);
9698 
9699   /// Build a an Objective-C protocol-qualified 'id' type where no
9700   /// base type was specified.
9701   TypeResult actOnObjCProtocolQualifierType(
9702                SourceLocation lAngleLoc,
9703                ArrayRef<Decl *> protocols,
9704                ArrayRef<SourceLocation> protocolLocs,
9705                SourceLocation rAngleLoc);
9706 
9707   /// Build a specialized and/or protocol-qualified Objective-C type.
9708   TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
9709                Scope *S,
9710                SourceLocation Loc,
9711                ParsedType BaseType,
9712                SourceLocation TypeArgsLAngleLoc,
9713                ArrayRef<ParsedType> TypeArgs,
9714                SourceLocation TypeArgsRAngleLoc,
9715                SourceLocation ProtocolLAngleLoc,
9716                ArrayRef<Decl *> Protocols,
9717                ArrayRef<SourceLocation> ProtocolLocs,
9718                SourceLocation ProtocolRAngleLoc);
9719 
9720   /// Build an Objective-C type parameter type.
9721   QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
9722                                   SourceLocation ProtocolLAngleLoc,
9723                                   ArrayRef<ObjCProtocolDecl *> Protocols,
9724                                   ArrayRef<SourceLocation> ProtocolLocs,
9725                                   SourceLocation ProtocolRAngleLoc,
9726                                   bool FailOnError = false);
9727 
9728   /// Build an Objective-C object pointer type.
9729   QualType BuildObjCObjectType(QualType BaseType,
9730                                SourceLocation Loc,
9731                                SourceLocation TypeArgsLAngleLoc,
9732                                ArrayRef<TypeSourceInfo *> TypeArgs,
9733                                SourceLocation TypeArgsRAngleLoc,
9734                                SourceLocation ProtocolLAngleLoc,
9735                                ArrayRef<ObjCProtocolDecl *> Protocols,
9736                                ArrayRef<SourceLocation> ProtocolLocs,
9737                                SourceLocation ProtocolRAngleLoc,
9738                                bool FailOnError = false);
9739 
9740   /// Ensure attributes are consistent with type.
9741   /// \param [in, out] Attributes The attributes to check; they will
9742   /// be modified to be consistent with \p PropertyTy.
9743   void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
9744                                    SourceLocation Loc,
9745                                    unsigned &Attributes,
9746                                    bool propertyInPrimaryClass);
9747 
9748   /// Process the specified property declaration and create decls for the
9749   /// setters and getters as needed.
9750   /// \param property The property declaration being processed
9751   void ProcessPropertyDecl(ObjCPropertyDecl *property);
9752 
9753 
9754   void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
9755                                 ObjCPropertyDecl *SuperProperty,
9756                                 const IdentifierInfo *Name,
9757                                 bool OverridingProtocolProperty);
9758 
9759   void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
9760                                         ObjCInterfaceDecl *ID);
9761 
9762   Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
9763                    ArrayRef<Decl *> allMethods = None,
9764                    ArrayRef<DeclGroupPtrTy> allTUVars = None);
9765 
9766   Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
9767                       SourceLocation LParenLoc,
9768                       FieldDeclarator &FD, ObjCDeclSpec &ODS,
9769                       Selector GetterSel, Selector SetterSel,
9770                       tok::ObjCKeywordKind MethodImplKind,
9771                       DeclContext *lexicalDC = nullptr);
9772 
9773   Decl *ActOnPropertyImplDecl(Scope *S,
9774                               SourceLocation AtLoc,
9775                               SourceLocation PropertyLoc,
9776                               bool ImplKind,
9777                               IdentifierInfo *PropertyId,
9778                               IdentifierInfo *PropertyIvar,
9779                               SourceLocation PropertyIvarLoc,
9780                               ObjCPropertyQueryKind QueryKind);
9781 
9782   enum ObjCSpecialMethodKind {
9783     OSMK_None,
9784     OSMK_Alloc,
9785     OSMK_New,
9786     OSMK_Copy,
9787     OSMK_RetainingInit,
9788     OSMK_NonRetainingInit
9789   };
9790 
9791   struct ObjCArgInfo {
9792     IdentifierInfo *Name;
9793     SourceLocation NameLoc;
9794     // The Type is null if no type was specified, and the DeclSpec is invalid
9795     // in this case.
9796     ParsedType Type;
9797     ObjCDeclSpec DeclSpec;
9798 
9799     /// ArgAttrs - Attribute list for this argument.
9800     ParsedAttributesView ArgAttrs;
9801   };
9802 
9803   Decl *ActOnMethodDeclaration(
9804       Scope *S,
9805       SourceLocation BeginLoc, // location of the + or -.
9806       SourceLocation EndLoc,   // location of the ; or {.
9807       tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
9808       ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
9809       // optional arguments. The number of types/arguments is obtained
9810       // from the Sel.getNumArgs().
9811       ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
9812       unsigned CNumArgs, // c-style args
9813       const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind,
9814       bool isVariadic, bool MethodDefinition);
9815 
9816   ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
9817                                               const ObjCObjectPointerType *OPT,
9818                                               bool IsInstance);
9819   ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
9820                                            bool IsInstance);
9821 
9822   bool CheckARCMethodDecl(ObjCMethodDecl *method);
9823   bool inferObjCARCLifetime(ValueDecl *decl);
9824 
9825   void deduceOpenCLAddressSpace(ValueDecl *decl);
9826 
9827   ExprResult
9828   HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
9829                             Expr *BaseExpr,
9830                             SourceLocation OpLoc,
9831                             DeclarationName MemberName,
9832                             SourceLocation MemberLoc,
9833                             SourceLocation SuperLoc, QualType SuperType,
9834                             bool Super);
9835 
9836   ExprResult
9837   ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
9838                             IdentifierInfo &propertyName,
9839                             SourceLocation receiverNameLoc,
9840                             SourceLocation propertyNameLoc);
9841 
9842   ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
9843 
9844   /// Describes the kind of message expression indicated by a message
9845   /// send that starts with an identifier.
9846   enum ObjCMessageKind {
9847     /// The message is sent to 'super'.
9848     ObjCSuperMessage,
9849     /// The message is an instance message.
9850     ObjCInstanceMessage,
9851     /// The message is a class message, and the identifier is a type
9852     /// name.
9853     ObjCClassMessage
9854   };
9855 
9856   ObjCMessageKind getObjCMessageKind(Scope *S,
9857                                      IdentifierInfo *Name,
9858                                      SourceLocation NameLoc,
9859                                      bool IsSuper,
9860                                      bool HasTrailingDot,
9861                                      ParsedType &ReceiverType);
9862 
9863   ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
9864                                Selector Sel,
9865                                SourceLocation LBracLoc,
9866                                ArrayRef<SourceLocation> SelectorLocs,
9867                                SourceLocation RBracLoc,
9868                                MultiExprArg Args);
9869 
9870   ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
9871                                QualType ReceiverType,
9872                                SourceLocation SuperLoc,
9873                                Selector Sel,
9874                                ObjCMethodDecl *Method,
9875                                SourceLocation LBracLoc,
9876                                ArrayRef<SourceLocation> SelectorLocs,
9877                                SourceLocation RBracLoc,
9878                                MultiExprArg Args,
9879                                bool isImplicit = false);
9880 
9881   ExprResult BuildClassMessageImplicit(QualType ReceiverType,
9882                                        bool isSuperReceiver,
9883                                        SourceLocation Loc,
9884                                        Selector Sel,
9885                                        ObjCMethodDecl *Method,
9886                                        MultiExprArg Args);
9887 
9888   ExprResult ActOnClassMessage(Scope *S,
9889                                ParsedType Receiver,
9890                                Selector Sel,
9891                                SourceLocation LBracLoc,
9892                                ArrayRef<SourceLocation> SelectorLocs,
9893                                SourceLocation RBracLoc,
9894                                MultiExprArg Args);
9895 
9896   ExprResult BuildInstanceMessage(Expr *Receiver,
9897                                   QualType ReceiverType,
9898                                   SourceLocation SuperLoc,
9899                                   Selector Sel,
9900                                   ObjCMethodDecl *Method,
9901                                   SourceLocation LBracLoc,
9902                                   ArrayRef<SourceLocation> SelectorLocs,
9903                                   SourceLocation RBracLoc,
9904                                   MultiExprArg Args,
9905                                   bool isImplicit = false);
9906 
9907   ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
9908                                           QualType ReceiverType,
9909                                           SourceLocation Loc,
9910                                           Selector Sel,
9911                                           ObjCMethodDecl *Method,
9912                                           MultiExprArg Args);
9913 
9914   ExprResult ActOnInstanceMessage(Scope *S,
9915                                   Expr *Receiver,
9916                                   Selector Sel,
9917                                   SourceLocation LBracLoc,
9918                                   ArrayRef<SourceLocation> SelectorLocs,
9919                                   SourceLocation RBracLoc,
9920                                   MultiExprArg Args);
9921 
9922   ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
9923                                   ObjCBridgeCastKind Kind,
9924                                   SourceLocation BridgeKeywordLoc,
9925                                   TypeSourceInfo *TSInfo,
9926                                   Expr *SubExpr);
9927 
9928   ExprResult ActOnObjCBridgedCast(Scope *S,
9929                                   SourceLocation LParenLoc,
9930                                   ObjCBridgeCastKind Kind,
9931                                   SourceLocation BridgeKeywordLoc,
9932                                   ParsedType Type,
9933                                   SourceLocation RParenLoc,
9934                                   Expr *SubExpr);
9935 
9936   void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
9937 
9938   void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
9939 
9940   bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
9941                                      CastKind &Kind);
9942 
9943   bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
9944                                         QualType DestType, QualType SrcType,
9945                                         ObjCInterfaceDecl *&RelatedClass,
9946                                         ObjCMethodDecl *&ClassMethod,
9947                                         ObjCMethodDecl *&InstanceMethod,
9948                                         TypedefNameDecl *&TDNDecl,
9949                                         bool CfToNs, bool Diagnose = true);
9950 
9951   bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
9952                                          QualType DestType, QualType SrcType,
9953                                          Expr *&SrcExpr, bool Diagnose = true);
9954 
9955   bool CheckConversionToObjCLiteral(QualType DstType, Expr *&SrcExpr,
9956                                     bool Diagnose = true);
9957 
9958   bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
9959 
9960   /// Check whether the given new method is a valid override of the
9961   /// given overridden method, and set any properties that should be inherited.
9962   void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
9963                                const ObjCMethodDecl *Overridden);
9964 
9965   /// Describes the compatibility of a result type with its method.
9966   enum ResultTypeCompatibilityKind {
9967     RTC_Compatible,
9968     RTC_Incompatible,
9969     RTC_Unknown
9970   };
9971 
9972   void CheckObjCMethodDirectOverrides(ObjCMethodDecl *method,
9973                                       ObjCMethodDecl *overridden);
9974 
9975   void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
9976                                 ObjCInterfaceDecl *CurrentClass,
9977                                 ResultTypeCompatibilityKind RTC);
9978 
9979   enum PragmaOptionsAlignKind {
9980     POAK_Native,  // #pragma options align=native
9981     POAK_Natural, // #pragma options align=natural
9982     POAK_Packed,  // #pragma options align=packed
9983     POAK_Power,   // #pragma options align=power
9984     POAK_Mac68k,  // #pragma options align=mac68k
9985     POAK_Reset    // #pragma options align=reset
9986   };
9987 
9988   /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
9989   void ActOnPragmaClangSection(SourceLocation PragmaLoc,
9990                                PragmaClangSectionAction Action,
9991                                PragmaClangSectionKind SecKind, StringRef SecName);
9992 
9993   /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
9994   void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
9995                                SourceLocation PragmaLoc);
9996 
9997   /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
9998   void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
9999                        StringRef SlotLabel, Expr *Alignment);
10000 
10001   enum class PragmaAlignPackDiagnoseKind {
10002     NonDefaultStateAtInclude,
10003     ChangedStateAtExit
10004   };
10005 
10006   void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind,
10007                                          SourceLocation IncludeLoc);
10008   void DiagnoseUnterminatedPragmaAlignPack();
10009 
10010   /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
10011   void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
10012 
10013   /// ActOnPragmaMSComment - Called on well formed
10014   /// \#pragma comment(kind, "arg").
10015   void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
10016                             StringRef Arg);
10017 
10018   /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
10019   /// pointers_to_members(representation method[, general purpose
10020   /// representation]).
10021   void ActOnPragmaMSPointersToMembers(
10022       LangOptions::PragmaMSPointersToMembersKind Kind,
10023       SourceLocation PragmaLoc);
10024 
10025   /// Called on well formed \#pragma vtordisp().
10026   void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
10027                              SourceLocation PragmaLoc,
10028                              MSVtorDispMode Value);
10029 
10030   enum PragmaSectionKind {
10031     PSK_DataSeg,
10032     PSK_BSSSeg,
10033     PSK_ConstSeg,
10034     PSK_CodeSeg,
10035   };
10036 
10037   bool UnifySection(StringRef SectionName, int SectionFlags,
10038                     NamedDecl *TheDecl);
10039   bool UnifySection(StringRef SectionName,
10040                     int SectionFlags,
10041                     SourceLocation PragmaSectionLocation);
10042 
10043   /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
10044   void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
10045                         PragmaMsStackAction Action,
10046                         llvm::StringRef StackSlotLabel,
10047                         StringLiteral *SegmentName,
10048                         llvm::StringRef PragmaName);
10049 
10050   /// Called on well formed \#pragma section().
10051   void ActOnPragmaMSSection(SourceLocation PragmaLocation,
10052                             int SectionFlags, StringLiteral *SegmentName);
10053 
10054   /// Called on well-formed \#pragma init_seg().
10055   void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
10056                             StringLiteral *SegmentName);
10057 
10058   /// Called on #pragma clang __debug dump II
10059   void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
10060 
10061   /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
10062   void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
10063                                  StringRef Value);
10064 
10065   /// Are precise floating point semantics currently enabled?
isPreciseFPEnabled()10066   bool isPreciseFPEnabled() {
10067     return !CurFPFeatures.getAllowFPReassociate() &&
10068            !CurFPFeatures.getNoSignedZero() &&
10069            !CurFPFeatures.getAllowReciprocal() &&
10070            !CurFPFeatures.getAllowApproxFunc();
10071   }
10072 
10073   /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control
10074   void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action,
10075                                PragmaFloatControlKind Value);
10076 
10077   /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
10078   void ActOnPragmaUnused(const Token &Identifier,
10079                          Scope *curScope,
10080                          SourceLocation PragmaLoc);
10081 
10082   /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
10083   void ActOnPragmaVisibility(const IdentifierInfo* VisType,
10084                              SourceLocation PragmaLoc);
10085 
10086   NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
10087                                  SourceLocation Loc);
10088   void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
10089 
10090   /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
10091   void ActOnPragmaWeakID(IdentifierInfo* WeakName,
10092                          SourceLocation PragmaLoc,
10093                          SourceLocation WeakNameLoc);
10094 
10095   /// ActOnPragmaRedefineExtname - Called on well formed
10096   /// \#pragma redefine_extname oldname newname.
10097   void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
10098                                   IdentifierInfo* AliasName,
10099                                   SourceLocation PragmaLoc,
10100                                   SourceLocation WeakNameLoc,
10101                                   SourceLocation AliasNameLoc);
10102 
10103   /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
10104   void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
10105                             IdentifierInfo* AliasName,
10106                             SourceLocation PragmaLoc,
10107                             SourceLocation WeakNameLoc,
10108                             SourceLocation AliasNameLoc);
10109 
10110   /// ActOnPragmaFPContract - Called on well formed
10111   /// \#pragma {STDC,OPENCL} FP_CONTRACT and
10112   /// \#pragma clang fp contract
10113   void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC);
10114 
10115   /// Called on well formed
10116   /// \#pragma clang fp reassociate
10117   void ActOnPragmaFPReassociate(SourceLocation Loc, bool IsEnabled);
10118 
10119   /// ActOnPragmaFenvAccess - Called on well formed
10120   /// \#pragma STDC FENV_ACCESS
10121   void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled);
10122 
10123   /// Called on well formed '\#pragma clang fp' that has option 'exceptions'.
10124   void ActOnPragmaFPExceptions(SourceLocation Loc,
10125                                LangOptions::FPExceptionModeKind);
10126 
10127   /// Called to set constant rounding mode for floating point operations.
10128   void setRoundingMode(SourceLocation Loc, llvm::RoundingMode);
10129 
10130   /// Called to set exception behavior for floating point operations.
10131   void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind);
10132 
10133   /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
10134   /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
10135   void AddAlignmentAttributesForRecord(RecordDecl *RD);
10136 
10137   /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
10138   void AddMsStructLayoutForRecord(RecordDecl *RD);
10139 
10140   /// PushNamespaceVisibilityAttr - Note that we've entered a
10141   /// namespace with a visibility attribute.
10142   void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
10143                                    SourceLocation Loc);
10144 
10145   /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
10146   /// add an appropriate visibility attribute.
10147   void AddPushedVisibilityAttribute(Decl *RD);
10148 
10149   /// PopPragmaVisibility - Pop the top element of the visibility stack; used
10150   /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
10151   void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
10152 
10153   /// FreeVisContext - Deallocate and null out VisContext.
10154   void FreeVisContext();
10155 
10156   /// AddCFAuditedAttribute - Check whether we're currently within
10157   /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
10158   /// the appropriate attribute.
10159   void AddCFAuditedAttribute(Decl *D);
10160 
10161   void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute,
10162                                      SourceLocation PragmaLoc,
10163                                      attr::ParsedSubjectMatchRuleSet Rules);
10164   void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
10165                                      const IdentifierInfo *Namespace);
10166 
10167   /// Called on well-formed '\#pragma clang attribute pop'.
10168   void ActOnPragmaAttributePop(SourceLocation PragmaLoc,
10169                                const IdentifierInfo *Namespace);
10170 
10171   /// Adds the attributes that have been specified using the
10172   /// '\#pragma clang attribute push' directives to the given declaration.
10173   void AddPragmaAttributes(Scope *S, Decl *D);
10174 
10175   void DiagnoseUnterminatedPragmaAttribute();
10176 
10177   /// Called on well formed \#pragma clang optimize.
10178   void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
10179 
10180   /// Get the location for the currently active "\#pragma clang optimize
10181   /// off". If this location is invalid, then the state of the pragma is "on".
getOptimizeOffPragmaLocation()10182   SourceLocation getOptimizeOffPragmaLocation() const {
10183     return OptimizeOffPragmaLocation;
10184   }
10185 
10186   /// Only called on function definitions; if there is a pragma in scope
10187   /// with the effect of a range-based optnone, consider marking the function
10188   /// with attribute optnone.
10189   void AddRangeBasedOptnone(FunctionDecl *FD);
10190 
10191   /// Adds the 'optnone' attribute to the function declaration if there
10192   /// are no conflicts; Loc represents the location causing the 'optnone'
10193   /// attribute to be added (usually because of a pragma).
10194   void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
10195 
10196   /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
10197   void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
10198                       bool IsPackExpansion);
10199   void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T,
10200                       bool IsPackExpansion);
10201 
10202   /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
10203   /// declaration.
10204   void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
10205                             Expr *OE);
10206 
10207   /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
10208   /// declaration.
10209   void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
10210                          Expr *ParamExpr);
10211 
10212   /// AddAlignValueAttr - Adds an align_value attribute to a particular
10213   /// declaration.
10214   void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
10215 
10216   /// AddAnnotationAttr - Adds an annotation Annot with Args arguments to D.
10217   void AddAnnotationAttr(Decl *D, const AttributeCommonInfo &CI,
10218                          StringRef Annot, MutableArrayRef<Expr *> Args);
10219 
10220   /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
10221   /// declaration.
10222   void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
10223                            Expr *MaxThreads, Expr *MinBlocks);
10224 
10225   /// AddModeAttr - Adds a mode attribute to a particular declaration.
10226   void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name,
10227                    bool InInstantiation = false);
10228 
10229   void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI,
10230                            ParameterABI ABI);
10231 
10232   enum class RetainOwnershipKind {NS, CF, OS};
10233   void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI,
10234                         RetainOwnershipKind K, bool IsTemplateInstantiation);
10235 
10236   /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size
10237   /// attribute to a particular declaration.
10238   void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI,
10239                                       Expr *Min, Expr *Max);
10240 
10241   /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a
10242   /// particular declaration.
10243   void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI,
10244                                Expr *Min, Expr *Max);
10245 
10246   bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type);
10247 
10248   //===--------------------------------------------------------------------===//
10249   // C++ Coroutines TS
10250   //
10251   bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
10252                                StringRef Keyword);
10253   ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
10254   ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
10255   StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
10256 
10257   ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
10258                                       bool IsImplicit = false);
10259   ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
10260                                         UnresolvedLookupExpr* Lookup);
10261   ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
10262   StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
10263                                bool IsImplicit = false);
10264   StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
10265   bool buildCoroutineParameterMoves(SourceLocation Loc);
10266   VarDecl *buildCoroutinePromise(SourceLocation Loc);
10267   void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
10268   ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
10269                                            SourceLocation FuncLoc);
10270   /// Check that the expression co_await promise.final_suspend() shall not be
10271   /// potentially-throwing.
10272   bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend);
10273 
10274   //===--------------------------------------------------------------------===//
10275   // OpenMP directives and clauses.
10276   //
10277 private:
10278   void *VarDataSharingAttributesStack;
10279 
10280   struct DeclareTargetContextInfo {
10281     struct MapInfo {
10282       OMPDeclareTargetDeclAttr::MapTypeTy MT;
10283       SourceLocation Loc;
10284     };
10285     /// Explicitly listed variables and functions in a 'to' or 'link' clause.
10286     llvm::DenseMap<NamedDecl *, MapInfo> ExplicitlyMapped;
10287 
10288     /// The 'device_type' as parsed from the clause.
10289     OMPDeclareTargetDeclAttr::DevTypeTy DT = OMPDeclareTargetDeclAttr::DT_Any;
10290 
10291     /// The directive kind, `begin declare target` or `declare target`.
10292     OpenMPDirectiveKind Kind;
10293 
10294     /// The directive location.
10295     SourceLocation Loc;
10296 
DeclareTargetContextInfoDeclareTargetContextInfo10297     DeclareTargetContextInfo(OpenMPDirectiveKind Kind, SourceLocation Loc)
10298         : Kind(Kind), Loc(Loc) {}
10299   };
10300 
10301   /// Number of nested '#pragma omp declare target' directives.
10302   SmallVector<DeclareTargetContextInfo, 4> DeclareTargetNesting;
10303 
10304   /// Initialization of data-sharing attributes stack.
10305   void InitDataSharingAttributesStack();
10306   void DestroyDataSharingAttributesStack();
10307   ExprResult
10308   VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
10309                                         bool StrictlyPositive = true,
10310                                         bool SuppressExprDiags = false);
10311   /// Returns OpenMP nesting level for current directive.
10312   unsigned getOpenMPNestingLevel() const;
10313 
10314   /// Adjusts the function scopes index for the target-based regions.
10315   void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
10316                                     unsigned Level) const;
10317 
10318   /// Returns the number of scopes associated with the construct on the given
10319   /// OpenMP level.
10320   int getNumberOfConstructScopes(unsigned Level) const;
10321 
10322   /// Push new OpenMP function region for non-capturing function.
10323   void pushOpenMPFunctionRegion();
10324 
10325   /// Pop OpenMP function region for non-capturing function.
10326   void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI);
10327 
10328   /// Analyzes and checks a loop nest for use by a loop transformation.
10329   ///
10330   /// \param Kind          The loop transformation directive kind.
10331   /// \param NumLoops      How many nested loops the directive is expecting.
10332   /// \param AStmt         Associated statement of the transformation directive.
10333   /// \param LoopHelpers   [out] The loop analysis result.
10334   /// \param Body          [out] The body code nested in \p NumLoops loop.
10335   /// \param OriginalInits [out] Collection of statements and declarations that
10336   ///                      must have been executed/declared before entering the
10337   ///                      loop.
10338   ///
10339   /// \return Whether there was any error.
10340   bool checkTransformableLoopNest(
10341       OpenMPDirectiveKind Kind, Stmt *AStmt, int NumLoops,
10342       SmallVectorImpl<OMPLoopBasedDirective::HelperExprs> &LoopHelpers,
10343       Stmt *&Body,
10344       SmallVectorImpl<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>>
10345           &OriginalInits);
10346 
10347   /// Helper to keep information about the current `omp begin/end declare
10348   /// variant` nesting.
10349   struct OMPDeclareVariantScope {
10350     /// The associated OpenMP context selector.
10351     OMPTraitInfo *TI;
10352 
10353     /// The associated OpenMP context selector mangling.
10354     std::string NameSuffix;
10355 
10356     OMPDeclareVariantScope(OMPTraitInfo &TI);
10357   };
10358 
10359   /// Return the OMPTraitInfo for the surrounding scope, if any.
getOMPTraitInfoForSurroundingScope()10360   OMPTraitInfo *getOMPTraitInfoForSurroundingScope() {
10361     return OMPDeclareVariantScopes.empty() ? nullptr
10362                                            : OMPDeclareVariantScopes.back().TI;
10363   }
10364 
10365   /// The current `omp begin/end declare variant` scopes.
10366   SmallVector<OMPDeclareVariantScope, 4> OMPDeclareVariantScopes;
10367 
10368   /// The current `omp begin/end assumes` scopes.
10369   SmallVector<AssumptionAttr *, 4> OMPAssumeScoped;
10370 
10371   /// All `omp assumes` we encountered so far.
10372   SmallVector<AssumptionAttr *, 4> OMPAssumeGlobal;
10373 
10374 public:
10375   /// The declarator \p D defines a function in the scope \p S which is nested
10376   /// in an `omp begin/end declare variant` scope. In this method we create a
10377   /// declaration for \p D and rename \p D according to the OpenMP context
10378   /// selector of the surrounding scope. Return all base functions in \p Bases.
10379   void ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
10380       Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists,
10381       SmallVectorImpl<FunctionDecl *> &Bases);
10382 
10383   /// Register \p D as specialization of all base functions in \p Bases in the
10384   /// current `omp begin/end declare variant` scope.
10385   void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
10386       Decl *D, SmallVectorImpl<FunctionDecl *> &Bases);
10387 
10388   /// Act on \p D, a function definition inside of an `omp [begin/end] assumes`.
10389   void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D);
10390 
10391   /// Can we exit an OpenMP declare variant scope at the moment.
isInOpenMPDeclareVariantScope()10392   bool isInOpenMPDeclareVariantScope() const {
10393     return !OMPDeclareVariantScopes.empty();
10394   }
10395 
10396   /// Given the potential call expression \p Call, determine if there is a
10397   /// specialization via the OpenMP declare variant mechanism available. If
10398   /// there is, return the specialized call expression, otherwise return the
10399   /// original \p Call.
10400   ExprResult ActOnOpenMPCall(ExprResult Call, Scope *Scope,
10401                              SourceLocation LParenLoc, MultiExprArg ArgExprs,
10402                              SourceLocation RParenLoc, Expr *ExecConfig);
10403 
10404   /// Handle a `omp begin declare variant`.
10405   void ActOnOpenMPBeginDeclareVariant(SourceLocation Loc, OMPTraitInfo &TI);
10406 
10407   /// Handle a `omp end declare variant`.
10408   void ActOnOpenMPEndDeclareVariant();
10409 
10410   /// Checks if the variant/multiversion functions are compatible.
10411   bool areMultiversionVariantFunctionsCompatible(
10412       const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10413       const PartialDiagnostic &NoProtoDiagID,
10414       const PartialDiagnosticAt &NoteCausedDiagIDAt,
10415       const PartialDiagnosticAt &NoSupportDiagIDAt,
10416       const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10417       bool ConstexprSupported, bool CLinkageMayDiffer);
10418 
10419   /// Function tries to capture lambda's captured variables in the OpenMP region
10420   /// before the original lambda is captured.
10421   void tryCaptureOpenMPLambdas(ValueDecl *V);
10422 
10423   /// Return true if the provided declaration \a VD should be captured by
10424   /// reference.
10425   /// \param Level Relative level of nested OpenMP construct for that the check
10426   /// is performed.
10427   /// \param OpenMPCaptureLevel Capture level within an OpenMP construct.
10428   bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
10429                              unsigned OpenMPCaptureLevel) const;
10430 
10431   /// Check if the specified variable is used in one of the private
10432   /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
10433   /// constructs.
10434   VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false,
10435                                 unsigned StopAt = 0);
10436   ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
10437                                    ExprObjectKind OK, SourceLocation Loc);
10438 
10439   /// If the current region is a loop-based region, mark the start of the loop
10440   /// construct.
10441   void startOpenMPLoop();
10442 
10443   /// If the current region is a range loop-based region, mark the start of the
10444   /// loop construct.
10445   void startOpenMPCXXRangeFor();
10446 
10447   /// Check if the specified variable is used in 'private' clause.
10448   /// \param Level Relative level of nested OpenMP construct for that the check
10449   /// is performed.
10450   OpenMPClauseKind isOpenMPPrivateDecl(ValueDecl *D, unsigned Level,
10451                                        unsigned CapLevel) const;
10452 
10453   /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.)
10454   /// for \p FD based on DSA for the provided corresponding captured declaration
10455   /// \p D.
10456   void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level);
10457 
10458   /// Check if the specified variable is captured  by 'target' directive.
10459   /// \param Level Relative level of nested OpenMP construct for that the check
10460   /// is performed.
10461   bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level,
10462                                   unsigned CaptureLevel) const;
10463 
10464   /// Check if the specified global variable must be captured  by outer capture
10465   /// regions.
10466   /// \param Level Relative level of nested OpenMP construct for that
10467   /// the check is performed.
10468   bool isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level,
10469                                   unsigned CaptureLevel) const;
10470 
10471   ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
10472                                                     Expr *Op);
10473   /// Called on start of new data sharing attribute block.
10474   void StartOpenMPDSABlock(OpenMPDirectiveKind K,
10475                            const DeclarationNameInfo &DirName, Scope *CurScope,
10476                            SourceLocation Loc);
10477   /// Start analysis of clauses.
10478   void StartOpenMPClause(OpenMPClauseKind K);
10479   /// End analysis of clauses.
10480   void EndOpenMPClause();
10481   /// Called on end of data sharing attribute block.
10482   void EndOpenMPDSABlock(Stmt *CurDirective);
10483 
10484   /// Check if the current region is an OpenMP loop region and if it is,
10485   /// mark loop control variable, used in \p Init for loop initialization, as
10486   /// private by default.
10487   /// \param Init First part of the for loop.
10488   void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
10489 
10490   /// Called on well-formed '\#pragma omp metadirective' after parsing
10491   /// of the  associated statement.
10492   StmtResult ActOnOpenMPMetaDirective(ArrayRef<OMPClause *> Clauses,
10493                                       Stmt *AStmt, SourceLocation StartLoc,
10494                                       SourceLocation EndLoc);
10495 
10496   // OpenMP directives and clauses.
10497   /// Called on correct id-expression from the '#pragma omp
10498   /// threadprivate'.
10499   ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec,
10500                                      const DeclarationNameInfo &Id,
10501                                      OpenMPDirectiveKind Kind);
10502   /// Called on well-formed '#pragma omp threadprivate'.
10503   DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
10504                                      SourceLocation Loc,
10505                                      ArrayRef<Expr *> VarList);
10506   /// Builds a new OpenMPThreadPrivateDecl and checks its correctness.
10507   OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc,
10508                                                   ArrayRef<Expr *> VarList);
10509   /// Called on well-formed '#pragma omp allocate'.
10510   DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc,
10511                                               ArrayRef<Expr *> VarList,
10512                                               ArrayRef<OMPClause *> Clauses,
10513                                               DeclContext *Owner = nullptr);
10514 
10515   /// Called on well-formed '#pragma omp [begin] assume[s]'.
10516   void ActOnOpenMPAssumesDirective(SourceLocation Loc,
10517                                    OpenMPDirectiveKind DKind,
10518                                    ArrayRef<std::string> Assumptions,
10519                                    bool SkippedClauses);
10520 
10521   /// Check if there is an active global `omp begin assumes` directive.
isInOpenMPAssumeScope()10522   bool isInOpenMPAssumeScope() const { return !OMPAssumeScoped.empty(); }
10523 
10524   /// Check if there is an active global `omp assumes` directive.
hasGlobalOpenMPAssumes()10525   bool hasGlobalOpenMPAssumes() const { return !OMPAssumeGlobal.empty(); }
10526 
10527   /// Called on well-formed '#pragma omp end assumes'.
10528   void ActOnOpenMPEndAssumesDirective();
10529 
10530   /// Called on well-formed '#pragma omp requires'.
10531   DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc,
10532                                               ArrayRef<OMPClause *> ClauseList);
10533   /// Check restrictions on Requires directive
10534   OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc,
10535                                         ArrayRef<OMPClause *> Clauses);
10536   /// Check if the specified type is allowed to be used in 'omp declare
10537   /// reduction' construct.
10538   QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
10539                                            TypeResult ParsedType);
10540   /// Called on start of '#pragma omp declare reduction'.
10541   DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
10542       Scope *S, DeclContext *DC, DeclarationName Name,
10543       ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10544       AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
10545   /// Initialize declare reduction construct initializer.
10546   void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
10547   /// Finish current declare reduction construct initializer.
10548   void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
10549   /// Initialize declare reduction construct initializer.
10550   /// \return omp_priv variable.
10551   VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
10552   /// Finish current declare reduction construct initializer.
10553   void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
10554                                                  VarDecl *OmpPrivParm);
10555   /// Called at the end of '#pragma omp declare reduction'.
10556   DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
10557       Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
10558 
10559   /// Check variable declaration in 'omp declare mapper' construct.
10560   TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D);
10561   /// Check if the specified type is allowed to be used in 'omp declare
10562   /// mapper' construct.
10563   QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
10564                                         TypeResult ParsedType);
10565   /// Called on start of '#pragma omp declare mapper'.
10566   DeclGroupPtrTy ActOnOpenMPDeclareMapperDirective(
10567       Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
10568       SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
10569       Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses,
10570       Decl *PrevDeclInScope = nullptr);
10571   /// Build the mapper variable of '#pragma omp declare mapper'.
10572   ExprResult ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S,
10573                                                       QualType MapperType,
10574                                                       SourceLocation StartLoc,
10575                                                       DeclarationName VN);
10576   bool isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const;
10577   const ValueDecl *getOpenMPDeclareMapperVarName() const;
10578 
10579   /// Called on the start of target region i.e. '#pragma omp declare target'.
10580   bool ActOnStartOpenMPDeclareTargetContext(DeclareTargetContextInfo &DTCI);
10581 
10582   /// Called at the end of target region i.e. '#pragma omp end declare target'.
10583   const DeclareTargetContextInfo ActOnOpenMPEndDeclareTargetDirective();
10584 
10585   /// Called once a target context is completed, that can be when a
10586   /// '#pragma omp end declare target' was encountered or when a
10587   /// '#pragma omp declare target' without declaration-definition-seq was
10588   /// encountered.
10589   void ActOnFinishedOpenMPDeclareTargetContext(DeclareTargetContextInfo &DTCI);
10590 
10591   /// Searches for the provided declaration name for OpenMP declare target
10592   /// directive.
10593   NamedDecl *lookupOpenMPDeclareTargetName(Scope *CurScope,
10594                                            CXXScopeSpec &ScopeSpec,
10595                                            const DeclarationNameInfo &Id);
10596 
10597   /// Called on correct id-expression from the '#pragma omp declare target'.
10598   void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc,
10599                                     OMPDeclareTargetDeclAttr::MapTypeTy MT,
10600                                     OMPDeclareTargetDeclAttr::DevTypeTy DT);
10601 
10602   /// Check declaration inside target region.
10603   void
10604   checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
10605                                    SourceLocation IdLoc = SourceLocation());
10606   /// Finishes analysis of the deferred functions calls that may be declared as
10607   /// host/nohost during device/host compilation.
10608   void finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller,
10609                                      const FunctionDecl *Callee,
10610                                      SourceLocation Loc);
10611   /// Return true inside OpenMP declare target region.
isInOpenMPDeclareTargetContext()10612   bool isInOpenMPDeclareTargetContext() const {
10613     return !DeclareTargetNesting.empty();
10614   }
10615   /// Return true inside OpenMP target region.
10616   bool isInOpenMPTargetExecutionDirective() const;
10617 
10618   /// Return the number of captured regions created for an OpenMP directive.
10619   static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
10620 
10621   /// Initialization of captured region for OpenMP region.
10622   void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
10623 
10624   /// Called for syntactical loops (ForStmt or CXXForRangeStmt) associated to
10625   /// an OpenMP loop directive.
10626   StmtResult ActOnOpenMPCanonicalLoop(Stmt *AStmt);
10627 
10628   /// Process a canonical OpenMP loop nest that can either be a canonical
10629   /// literal loop (ForStmt or CXXForRangeStmt), or the generated loop of an
10630   /// OpenMP loop transformation construct.
10631   StmtResult ActOnOpenMPLoopnest(Stmt *AStmt);
10632 
10633   /// End of OpenMP region.
10634   ///
10635   /// \param S Statement associated with the current OpenMP region.
10636   /// \param Clauses List of clauses for the current OpenMP region.
10637   ///
10638   /// \returns Statement for finished OpenMP region.
10639   StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
10640   StmtResult ActOnOpenMPExecutableDirective(
10641       OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
10642       OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
10643       Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
10644   /// Called on well-formed '\#pragma omp parallel' after parsing
10645   /// of the  associated statement.
10646   StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
10647                                           Stmt *AStmt,
10648                                           SourceLocation StartLoc,
10649                                           SourceLocation EndLoc);
10650   using VarsWithInheritedDSAType =
10651       llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>;
10652   /// Called on well-formed '\#pragma omp simd' after parsing
10653   /// of the associated statement.
10654   StmtResult
10655   ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10656                            SourceLocation StartLoc, SourceLocation EndLoc,
10657                            VarsWithInheritedDSAType &VarsWithImplicitDSA);
10658   /// Called on well-formed '#pragma omp tile' after parsing of its clauses and
10659   /// the associated statement.
10660   StmtResult ActOnOpenMPTileDirective(ArrayRef<OMPClause *> Clauses,
10661                                       Stmt *AStmt, SourceLocation StartLoc,
10662                                       SourceLocation EndLoc);
10663   /// Called on well-formed '#pragma omp unroll' after parsing of its clauses
10664   /// and the associated statement.
10665   StmtResult ActOnOpenMPUnrollDirective(ArrayRef<OMPClause *> Clauses,
10666                                         Stmt *AStmt, SourceLocation StartLoc,
10667                                         SourceLocation EndLoc);
10668   /// Called on well-formed '\#pragma omp for' after parsing
10669   /// of the associated statement.
10670   StmtResult
10671   ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10672                           SourceLocation StartLoc, SourceLocation EndLoc,
10673                           VarsWithInheritedDSAType &VarsWithImplicitDSA);
10674   /// Called on well-formed '\#pragma omp for simd' after parsing
10675   /// of the associated statement.
10676   StmtResult
10677   ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10678                               SourceLocation StartLoc, SourceLocation EndLoc,
10679                               VarsWithInheritedDSAType &VarsWithImplicitDSA);
10680   /// Called on well-formed '\#pragma omp sections' after parsing
10681   /// of the associated statement.
10682   StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
10683                                           Stmt *AStmt, SourceLocation StartLoc,
10684                                           SourceLocation EndLoc);
10685   /// Called on well-formed '\#pragma omp section' after parsing of the
10686   /// associated statement.
10687   StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
10688                                          SourceLocation EndLoc);
10689   /// Called on well-formed '\#pragma omp single' after parsing of the
10690   /// associated statement.
10691   StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
10692                                         Stmt *AStmt, SourceLocation StartLoc,
10693                                         SourceLocation EndLoc);
10694   /// Called on well-formed '\#pragma omp master' after parsing of the
10695   /// associated statement.
10696   StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
10697                                         SourceLocation EndLoc);
10698   /// Called on well-formed '\#pragma omp critical' after parsing of the
10699   /// associated statement.
10700   StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
10701                                           ArrayRef<OMPClause *> Clauses,
10702                                           Stmt *AStmt, SourceLocation StartLoc,
10703                                           SourceLocation EndLoc);
10704   /// Called on well-formed '\#pragma omp parallel for' after parsing
10705   /// of the  associated statement.
10706   StmtResult ActOnOpenMPParallelForDirective(
10707       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10708       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10709   /// Called on well-formed '\#pragma omp parallel for simd' after
10710   /// parsing of the  associated statement.
10711   StmtResult ActOnOpenMPParallelForSimdDirective(
10712       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10713       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10714   /// Called on well-formed '\#pragma omp parallel master' after
10715   /// parsing of the  associated statement.
10716   StmtResult ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
10717                                                 Stmt *AStmt,
10718                                                 SourceLocation StartLoc,
10719                                                 SourceLocation EndLoc);
10720   /// Called on well-formed '\#pragma omp parallel sections' after
10721   /// parsing of the  associated statement.
10722   StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
10723                                                   Stmt *AStmt,
10724                                                   SourceLocation StartLoc,
10725                                                   SourceLocation EndLoc);
10726   /// Called on well-formed '\#pragma omp task' after parsing of the
10727   /// associated statement.
10728   StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
10729                                       Stmt *AStmt, SourceLocation StartLoc,
10730                                       SourceLocation EndLoc);
10731   /// Called on well-formed '\#pragma omp taskyield'.
10732   StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
10733                                            SourceLocation EndLoc);
10734   /// Called on well-formed '\#pragma omp barrier'.
10735   StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
10736                                          SourceLocation EndLoc);
10737   /// Called on well-formed '\#pragma omp taskwait'.
10738   StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
10739                                           SourceLocation EndLoc);
10740   /// Called on well-formed '\#pragma omp taskgroup'.
10741   StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
10742                                            Stmt *AStmt, SourceLocation StartLoc,
10743                                            SourceLocation EndLoc);
10744   /// Called on well-formed '\#pragma omp flush'.
10745   StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
10746                                        SourceLocation StartLoc,
10747                                        SourceLocation EndLoc);
10748   /// Called on well-formed '\#pragma omp depobj'.
10749   StmtResult ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses,
10750                                         SourceLocation StartLoc,
10751                                         SourceLocation EndLoc);
10752   /// Called on well-formed '\#pragma omp scan'.
10753   StmtResult ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses,
10754                                       SourceLocation StartLoc,
10755                                       SourceLocation EndLoc);
10756   /// Called on well-formed '\#pragma omp ordered' after parsing of the
10757   /// associated statement.
10758   StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
10759                                          Stmt *AStmt, SourceLocation StartLoc,
10760                                          SourceLocation EndLoc);
10761   /// Called on well-formed '\#pragma omp atomic' after parsing of the
10762   /// associated statement.
10763   StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
10764                                         Stmt *AStmt, SourceLocation StartLoc,
10765                                         SourceLocation EndLoc);
10766   /// Called on well-formed '\#pragma omp target' after parsing of the
10767   /// associated statement.
10768   StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
10769                                         Stmt *AStmt, SourceLocation StartLoc,
10770                                         SourceLocation EndLoc);
10771   /// Called on well-formed '\#pragma omp target data' after parsing of
10772   /// the associated statement.
10773   StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
10774                                             Stmt *AStmt, SourceLocation StartLoc,
10775                                             SourceLocation EndLoc);
10776   /// Called on well-formed '\#pragma omp target enter data' after
10777   /// parsing of the associated statement.
10778   StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
10779                                                  SourceLocation StartLoc,
10780                                                  SourceLocation EndLoc,
10781                                                  Stmt *AStmt);
10782   /// Called on well-formed '\#pragma omp target exit data' after
10783   /// parsing of the associated statement.
10784   StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
10785                                                 SourceLocation StartLoc,
10786                                                 SourceLocation EndLoc,
10787                                                 Stmt *AStmt);
10788   /// Called on well-formed '\#pragma omp target parallel' after
10789   /// parsing of the associated statement.
10790   StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
10791                                                 Stmt *AStmt,
10792                                                 SourceLocation StartLoc,
10793                                                 SourceLocation EndLoc);
10794   /// Called on well-formed '\#pragma omp target parallel for' after
10795   /// parsing of the  associated statement.
10796   StmtResult ActOnOpenMPTargetParallelForDirective(
10797       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10798       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10799   /// Called on well-formed '\#pragma omp teams' after parsing of the
10800   /// associated statement.
10801   StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
10802                                        Stmt *AStmt, SourceLocation StartLoc,
10803                                        SourceLocation EndLoc);
10804   /// Called on well-formed '\#pragma omp cancellation point'.
10805   StmtResult
10806   ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
10807                                         SourceLocation EndLoc,
10808                                         OpenMPDirectiveKind CancelRegion);
10809   /// Called on well-formed '\#pragma omp cancel'.
10810   StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
10811                                         SourceLocation StartLoc,
10812                                         SourceLocation EndLoc,
10813                                         OpenMPDirectiveKind CancelRegion);
10814   /// Called on well-formed '\#pragma omp taskloop' after parsing of the
10815   /// associated statement.
10816   StmtResult
10817   ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10818                                SourceLocation StartLoc, SourceLocation EndLoc,
10819                                VarsWithInheritedDSAType &VarsWithImplicitDSA);
10820   /// Called on well-formed '\#pragma omp taskloop simd' after parsing of
10821   /// the associated statement.
10822   StmtResult ActOnOpenMPTaskLoopSimdDirective(
10823       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10824       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10825   /// Called on well-formed '\#pragma omp master taskloop' after parsing of the
10826   /// associated statement.
10827   StmtResult ActOnOpenMPMasterTaskLoopDirective(
10828       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10829       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10830   /// Called on well-formed '\#pragma omp master taskloop simd' after parsing of
10831   /// the associated statement.
10832   StmtResult ActOnOpenMPMasterTaskLoopSimdDirective(
10833       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10834       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10835   /// Called on well-formed '\#pragma omp parallel master taskloop' after
10836   /// parsing of the associated statement.
10837   StmtResult ActOnOpenMPParallelMasterTaskLoopDirective(
10838       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10839       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10840   /// Called on well-formed '\#pragma omp parallel master taskloop simd' after
10841   /// parsing of the associated statement.
10842   StmtResult ActOnOpenMPParallelMasterTaskLoopSimdDirective(
10843       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10844       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10845   /// Called on well-formed '\#pragma omp distribute' after parsing
10846   /// of the associated statement.
10847   StmtResult
10848   ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10849                                  SourceLocation StartLoc, SourceLocation EndLoc,
10850                                  VarsWithInheritedDSAType &VarsWithImplicitDSA);
10851   /// Called on well-formed '\#pragma omp target update'.
10852   StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
10853                                               SourceLocation StartLoc,
10854                                               SourceLocation EndLoc,
10855                                               Stmt *AStmt);
10856   /// Called on well-formed '\#pragma omp distribute parallel for' after
10857   /// parsing of the associated statement.
10858   StmtResult ActOnOpenMPDistributeParallelForDirective(
10859       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10860       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10861   /// Called on well-formed '\#pragma omp distribute parallel for simd'
10862   /// after parsing of the associated statement.
10863   StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
10864       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10865       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10866   /// Called on well-formed '\#pragma omp distribute simd' after
10867   /// parsing of the associated statement.
10868   StmtResult ActOnOpenMPDistributeSimdDirective(
10869       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10870       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10871   /// Called on well-formed '\#pragma omp target parallel for simd' after
10872   /// parsing of the associated statement.
10873   StmtResult ActOnOpenMPTargetParallelForSimdDirective(
10874       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10875       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10876   /// Called on well-formed '\#pragma omp target simd' after parsing of
10877   /// the associated statement.
10878   StmtResult
10879   ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10880                                  SourceLocation StartLoc, SourceLocation EndLoc,
10881                                  VarsWithInheritedDSAType &VarsWithImplicitDSA);
10882   /// Called on well-formed '\#pragma omp teams distribute' after parsing of
10883   /// the associated statement.
10884   StmtResult ActOnOpenMPTeamsDistributeDirective(
10885       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10886       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10887   /// Called on well-formed '\#pragma omp teams distribute simd' after parsing
10888   /// of the associated statement.
10889   StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
10890       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10891       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10892   /// Called on well-formed '\#pragma omp teams distribute parallel for simd'
10893   /// after parsing of the associated statement.
10894   StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
10895       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10896       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10897   /// Called on well-formed '\#pragma omp teams distribute parallel for'
10898   /// after parsing of the associated statement.
10899   StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
10900       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10901       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10902   /// Called on well-formed '\#pragma omp target teams' after parsing of the
10903   /// associated statement.
10904   StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
10905                                              Stmt *AStmt,
10906                                              SourceLocation StartLoc,
10907                                              SourceLocation EndLoc);
10908   /// Called on well-formed '\#pragma omp target teams distribute' after parsing
10909   /// of the associated statement.
10910   StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
10911       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10912       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10913   /// Called on well-formed '\#pragma omp target teams distribute parallel for'
10914   /// after parsing of the associated statement.
10915   StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
10916       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10917       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10918   /// Called on well-formed '\#pragma omp target teams distribute parallel for
10919   /// simd' after parsing of the associated statement.
10920   StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
10921       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10922       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10923   /// Called on well-formed '\#pragma omp target teams distribute simd' after
10924   /// parsing of the associated statement.
10925   StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
10926       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10927       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10928   /// Called on well-formed '\#pragma omp interop'.
10929   StmtResult ActOnOpenMPInteropDirective(ArrayRef<OMPClause *> Clauses,
10930                                          SourceLocation StartLoc,
10931                                          SourceLocation EndLoc);
10932   /// Called on well-formed '\#pragma omp dispatch' after parsing of the
10933   // /associated statement.
10934   StmtResult ActOnOpenMPDispatchDirective(ArrayRef<OMPClause *> Clauses,
10935                                           Stmt *AStmt, SourceLocation StartLoc,
10936                                           SourceLocation EndLoc);
10937   /// Called on well-formed '\#pragma omp masked' after parsing of the
10938   // /associated statement.
10939   StmtResult ActOnOpenMPMaskedDirective(ArrayRef<OMPClause *> Clauses,
10940                                         Stmt *AStmt, SourceLocation StartLoc,
10941                                         SourceLocation EndLoc);
10942 
10943   /// Checks correctness of linear modifiers.
10944   bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
10945                                  SourceLocation LinLoc);
10946   /// Checks that the specified declaration matches requirements for the linear
10947   /// decls.
10948   bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
10949                              OpenMPLinearClauseKind LinKind, QualType Type,
10950                              bool IsDeclareSimd = false);
10951 
10952   /// Called on well-formed '\#pragma omp declare simd' after parsing of
10953   /// the associated method/function.
10954   DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
10955       DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
10956       Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
10957       ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
10958       ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
10959 
10960   /// Checks '\#pragma omp declare variant' variant function and original
10961   /// functions after parsing of the associated method/function.
10962   /// \param DG Function declaration to which declare variant directive is
10963   /// applied to.
10964   /// \param VariantRef Expression that references the variant function, which
10965   /// must be used instead of the original one, specified in \p DG.
10966   /// \param TI The trait info object representing the match clause.
10967   /// \returns None, if the function/variant function are not compatible with
10968   /// the pragma, pair of original function/variant ref expression otherwise.
10969   Optional<std::pair<FunctionDecl *, Expr *>>
10970   checkOpenMPDeclareVariantFunction(DeclGroupPtrTy DG, Expr *VariantRef,
10971                                     OMPTraitInfo &TI, SourceRange SR);
10972 
10973   /// Called on well-formed '\#pragma omp declare variant' after parsing of
10974   /// the associated method/function.
10975   /// \param FD Function declaration to which declare variant directive is
10976   /// applied to.
10977   /// \param VariantRef Expression that references the variant function, which
10978   /// must be used instead of the original one, specified in \p DG.
10979   /// \param TI The context traits associated with the function variant.
10980   void ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD, Expr *VariantRef,
10981                                           OMPTraitInfo &TI, SourceRange SR);
10982 
10983   OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
10984                                          Expr *Expr,
10985                                          SourceLocation StartLoc,
10986                                          SourceLocation LParenLoc,
10987                                          SourceLocation EndLoc);
10988   /// Called on well-formed 'allocator' clause.
10989   OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator,
10990                                         SourceLocation StartLoc,
10991                                         SourceLocation LParenLoc,
10992                                         SourceLocation EndLoc);
10993   /// Called on well-formed 'if' clause.
10994   OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
10995                                  Expr *Condition, SourceLocation StartLoc,
10996                                  SourceLocation LParenLoc,
10997                                  SourceLocation NameModifierLoc,
10998                                  SourceLocation ColonLoc,
10999                                  SourceLocation EndLoc);
11000   /// Called on well-formed 'final' clause.
11001   OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
11002                                     SourceLocation LParenLoc,
11003                                     SourceLocation EndLoc);
11004   /// Called on well-formed 'num_threads' clause.
11005   OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
11006                                          SourceLocation StartLoc,
11007                                          SourceLocation LParenLoc,
11008                                          SourceLocation EndLoc);
11009   /// Called on well-formed 'safelen' clause.
11010   OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
11011                                       SourceLocation StartLoc,
11012                                       SourceLocation LParenLoc,
11013                                       SourceLocation EndLoc);
11014   /// Called on well-formed 'simdlen' clause.
11015   OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
11016                                       SourceLocation LParenLoc,
11017                                       SourceLocation EndLoc);
11018   /// Called on well-form 'sizes' clause.
11019   OMPClause *ActOnOpenMPSizesClause(ArrayRef<Expr *> SizeExprs,
11020                                     SourceLocation StartLoc,
11021                                     SourceLocation LParenLoc,
11022                                     SourceLocation EndLoc);
11023   /// Called on well-form 'full' clauses.
11024   OMPClause *ActOnOpenMPFullClause(SourceLocation StartLoc,
11025                                    SourceLocation EndLoc);
11026   /// Called on well-form 'partial' clauses.
11027   OMPClause *ActOnOpenMPPartialClause(Expr *FactorExpr, SourceLocation StartLoc,
11028                                       SourceLocation LParenLoc,
11029                                       SourceLocation EndLoc);
11030   /// Called on well-formed 'collapse' clause.
11031   OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
11032                                        SourceLocation StartLoc,
11033                                        SourceLocation LParenLoc,
11034                                        SourceLocation EndLoc);
11035   /// Called on well-formed 'ordered' clause.
11036   OMPClause *
11037   ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
11038                            SourceLocation LParenLoc = SourceLocation(),
11039                            Expr *NumForLoops = nullptr);
11040   /// Called on well-formed 'grainsize' clause.
11041   OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
11042                                         SourceLocation LParenLoc,
11043                                         SourceLocation EndLoc);
11044   /// Called on well-formed 'num_tasks' clause.
11045   OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
11046                                        SourceLocation LParenLoc,
11047                                        SourceLocation EndLoc);
11048   /// Called on well-formed 'hint' clause.
11049   OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
11050                                    SourceLocation LParenLoc,
11051                                    SourceLocation EndLoc);
11052   /// Called on well-formed 'detach' clause.
11053   OMPClause *ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc,
11054                                      SourceLocation LParenLoc,
11055                                      SourceLocation EndLoc);
11056 
11057   OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
11058                                      unsigned Argument,
11059                                      SourceLocation ArgumentLoc,
11060                                      SourceLocation StartLoc,
11061                                      SourceLocation LParenLoc,
11062                                      SourceLocation EndLoc);
11063   /// Called on well-formed 'when' clause.
11064   OMPClause *ActOnOpenMPWhenClause(OMPTraitInfo &TI, SourceLocation StartLoc,
11065                                    SourceLocation LParenLoc,
11066                                    SourceLocation EndLoc);
11067   /// Called on well-formed 'default' clause.
11068   OMPClause *ActOnOpenMPDefaultClause(llvm::omp::DefaultKind Kind,
11069                                       SourceLocation KindLoc,
11070                                       SourceLocation StartLoc,
11071                                       SourceLocation LParenLoc,
11072                                       SourceLocation EndLoc);
11073   /// Called on well-formed 'proc_bind' clause.
11074   OMPClause *ActOnOpenMPProcBindClause(llvm::omp::ProcBindKind Kind,
11075                                        SourceLocation KindLoc,
11076                                        SourceLocation StartLoc,
11077                                        SourceLocation LParenLoc,
11078                                        SourceLocation EndLoc);
11079   /// Called on well-formed 'order' clause.
11080   OMPClause *ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind,
11081                                     SourceLocation KindLoc,
11082                                     SourceLocation StartLoc,
11083                                     SourceLocation LParenLoc,
11084                                     SourceLocation EndLoc);
11085   /// Called on well-formed 'update' clause.
11086   OMPClause *ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind,
11087                                      SourceLocation KindLoc,
11088                                      SourceLocation StartLoc,
11089                                      SourceLocation LParenLoc,
11090                                      SourceLocation EndLoc);
11091 
11092   OMPClause *ActOnOpenMPSingleExprWithArgClause(
11093       OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
11094       SourceLocation StartLoc, SourceLocation LParenLoc,
11095       ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
11096       SourceLocation EndLoc);
11097   /// Called on well-formed 'schedule' clause.
11098   OMPClause *ActOnOpenMPScheduleClause(
11099       OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
11100       OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
11101       SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
11102       SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
11103 
11104   OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
11105                                SourceLocation EndLoc);
11106   /// Called on well-formed 'nowait' clause.
11107   OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
11108                                      SourceLocation EndLoc);
11109   /// Called on well-formed 'untied' clause.
11110   OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
11111                                      SourceLocation EndLoc);
11112   /// Called on well-formed 'mergeable' clause.
11113   OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
11114                                         SourceLocation EndLoc);
11115   /// Called on well-formed 'read' clause.
11116   OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
11117                                    SourceLocation EndLoc);
11118   /// Called on well-formed 'write' clause.
11119   OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
11120                                     SourceLocation EndLoc);
11121   /// Called on well-formed 'update' clause.
11122   OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
11123                                      SourceLocation EndLoc);
11124   /// Called on well-formed 'capture' clause.
11125   OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
11126                                       SourceLocation EndLoc);
11127   /// Called on well-formed 'seq_cst' clause.
11128   OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
11129                                      SourceLocation EndLoc);
11130   /// Called on well-formed 'acq_rel' clause.
11131   OMPClause *ActOnOpenMPAcqRelClause(SourceLocation StartLoc,
11132                                      SourceLocation EndLoc);
11133   /// Called on well-formed 'acquire' clause.
11134   OMPClause *ActOnOpenMPAcquireClause(SourceLocation StartLoc,
11135                                       SourceLocation EndLoc);
11136   /// Called on well-formed 'release' clause.
11137   OMPClause *ActOnOpenMPReleaseClause(SourceLocation StartLoc,
11138                                       SourceLocation EndLoc);
11139   /// Called on well-formed 'relaxed' clause.
11140   OMPClause *ActOnOpenMPRelaxedClause(SourceLocation StartLoc,
11141                                       SourceLocation EndLoc);
11142 
11143   /// Called on well-formed 'init' clause.
11144   OMPClause *ActOnOpenMPInitClause(Expr *InteropVar, ArrayRef<Expr *> PrefExprs,
11145                                    bool IsTarget, bool IsTargetSync,
11146                                    SourceLocation StartLoc,
11147                                    SourceLocation LParenLoc,
11148                                    SourceLocation VarLoc,
11149                                    SourceLocation EndLoc);
11150 
11151   /// Called on well-formed 'use' clause.
11152   OMPClause *ActOnOpenMPUseClause(Expr *InteropVar, SourceLocation StartLoc,
11153                                   SourceLocation LParenLoc,
11154                                   SourceLocation VarLoc, SourceLocation EndLoc);
11155 
11156   /// Called on well-formed 'destroy' clause.
11157   OMPClause *ActOnOpenMPDestroyClause(Expr *InteropVar, SourceLocation StartLoc,
11158                                       SourceLocation LParenLoc,
11159                                       SourceLocation VarLoc,
11160                                       SourceLocation EndLoc);
11161   /// Called on well-formed 'novariants' clause.
11162   OMPClause *ActOnOpenMPNovariantsClause(Expr *Condition,
11163                                          SourceLocation StartLoc,
11164                                          SourceLocation LParenLoc,
11165                                          SourceLocation EndLoc);
11166   /// Called on well-formed 'nocontext' clause.
11167   OMPClause *ActOnOpenMPNocontextClause(Expr *Condition,
11168                                         SourceLocation StartLoc,
11169                                         SourceLocation LParenLoc,
11170                                         SourceLocation EndLoc);
11171   /// Called on well-formed 'filter' clause.
11172   OMPClause *ActOnOpenMPFilterClause(Expr *ThreadID, SourceLocation StartLoc,
11173                                      SourceLocation LParenLoc,
11174                                      SourceLocation EndLoc);
11175   /// Called on well-formed 'threads' clause.
11176   OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
11177                                       SourceLocation EndLoc);
11178   /// Called on well-formed 'simd' clause.
11179   OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
11180                                    SourceLocation EndLoc);
11181   /// Called on well-formed 'nogroup' clause.
11182   OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
11183                                       SourceLocation EndLoc);
11184   /// Called on well-formed 'unified_address' clause.
11185   OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
11186                                              SourceLocation EndLoc);
11187 
11188   /// Called on well-formed 'unified_address' clause.
11189   OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
11190                                                   SourceLocation EndLoc);
11191 
11192   /// Called on well-formed 'reverse_offload' clause.
11193   OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
11194                                              SourceLocation EndLoc);
11195 
11196   /// Called on well-formed 'dynamic_allocators' clause.
11197   OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
11198                                                 SourceLocation EndLoc);
11199 
11200   /// Called on well-formed 'atomic_default_mem_order' clause.
11201   OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause(
11202       OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc,
11203       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
11204 
11205   OMPClause *ActOnOpenMPVarListClause(
11206       OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *DepModOrTailExpr,
11207       const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
11208       CXXScopeSpec &ReductionOrMapperIdScopeSpec,
11209       DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier,
11210       ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
11211       ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit,
11212       SourceLocation ExtraModifierLoc,
11213       ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
11214       ArrayRef<SourceLocation> MotionModifiersLoc);
11215   /// Called on well-formed 'inclusive' clause.
11216   OMPClause *ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList,
11217                                         SourceLocation StartLoc,
11218                                         SourceLocation LParenLoc,
11219                                         SourceLocation EndLoc);
11220   /// Called on well-formed 'exclusive' clause.
11221   OMPClause *ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList,
11222                                         SourceLocation StartLoc,
11223                                         SourceLocation LParenLoc,
11224                                         SourceLocation EndLoc);
11225   /// Called on well-formed 'allocate' clause.
11226   OMPClause *
11227   ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList,
11228                             SourceLocation StartLoc, SourceLocation ColonLoc,
11229                             SourceLocation LParenLoc, SourceLocation EndLoc);
11230   /// Called on well-formed 'private' clause.
11231   OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
11232                                       SourceLocation StartLoc,
11233                                       SourceLocation LParenLoc,
11234                                       SourceLocation EndLoc);
11235   /// Called on well-formed 'firstprivate' clause.
11236   OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
11237                                            SourceLocation StartLoc,
11238                                            SourceLocation LParenLoc,
11239                                            SourceLocation EndLoc);
11240   /// Called on well-formed 'lastprivate' clause.
11241   OMPClause *ActOnOpenMPLastprivateClause(
11242       ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
11243       SourceLocation LPKindLoc, SourceLocation ColonLoc,
11244       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
11245   /// Called on well-formed 'shared' clause.
11246   OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
11247                                      SourceLocation StartLoc,
11248                                      SourceLocation LParenLoc,
11249                                      SourceLocation EndLoc);
11250   /// Called on well-formed 'reduction' clause.
11251   OMPClause *ActOnOpenMPReductionClause(
11252       ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
11253       SourceLocation StartLoc, SourceLocation LParenLoc,
11254       SourceLocation ModifierLoc, SourceLocation ColonLoc,
11255       SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
11256       const DeclarationNameInfo &ReductionId,
11257       ArrayRef<Expr *> UnresolvedReductions = llvm::None);
11258   /// Called on well-formed 'task_reduction' clause.
11259   OMPClause *ActOnOpenMPTaskReductionClause(
11260       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11261       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
11262       CXXScopeSpec &ReductionIdScopeSpec,
11263       const DeclarationNameInfo &ReductionId,
11264       ArrayRef<Expr *> UnresolvedReductions = llvm::None);
11265   /// Called on well-formed 'in_reduction' clause.
11266   OMPClause *ActOnOpenMPInReductionClause(
11267       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11268       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
11269       CXXScopeSpec &ReductionIdScopeSpec,
11270       const DeclarationNameInfo &ReductionId,
11271       ArrayRef<Expr *> UnresolvedReductions = llvm::None);
11272   /// Called on well-formed 'linear' clause.
11273   OMPClause *
11274   ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
11275                           SourceLocation StartLoc, SourceLocation LParenLoc,
11276                           OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
11277                           SourceLocation ColonLoc, SourceLocation EndLoc);
11278   /// Called on well-formed 'aligned' clause.
11279   OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
11280                                       Expr *Alignment,
11281                                       SourceLocation StartLoc,
11282                                       SourceLocation LParenLoc,
11283                                       SourceLocation ColonLoc,
11284                                       SourceLocation EndLoc);
11285   /// Called on well-formed 'copyin' clause.
11286   OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
11287                                      SourceLocation StartLoc,
11288                                      SourceLocation LParenLoc,
11289                                      SourceLocation EndLoc);
11290   /// Called on well-formed 'copyprivate' clause.
11291   OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
11292                                           SourceLocation StartLoc,
11293                                           SourceLocation LParenLoc,
11294                                           SourceLocation EndLoc);
11295   /// Called on well-formed 'flush' pseudo clause.
11296   OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
11297                                     SourceLocation StartLoc,
11298                                     SourceLocation LParenLoc,
11299                                     SourceLocation EndLoc);
11300   /// Called on well-formed 'depobj' pseudo clause.
11301   OMPClause *ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
11302                                      SourceLocation LParenLoc,
11303                                      SourceLocation EndLoc);
11304   /// Called on well-formed 'depend' clause.
11305   OMPClause *
11306   ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind,
11307                           SourceLocation DepLoc, SourceLocation ColonLoc,
11308                           ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11309                           SourceLocation LParenLoc, SourceLocation EndLoc);
11310   /// Called on well-formed 'device' clause.
11311   OMPClause *ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
11312                                      Expr *Device, SourceLocation StartLoc,
11313                                      SourceLocation LParenLoc,
11314                                      SourceLocation ModifierLoc,
11315                                      SourceLocation EndLoc);
11316   /// Called on well-formed 'map' clause.
11317   OMPClause *ActOnOpenMPMapClause(
11318       ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
11319       ArrayRef<SourceLocation> MapTypeModifiersLoc,
11320       CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
11321       OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
11322       SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
11323       const OMPVarListLocTy &Locs, bool NoDiagnose = false,
11324       ArrayRef<Expr *> UnresolvedMappers = llvm::None);
11325   /// Called on well-formed 'num_teams' clause.
11326   OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
11327                                        SourceLocation LParenLoc,
11328                                        SourceLocation EndLoc);
11329   /// Called on well-formed 'thread_limit' clause.
11330   OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
11331                                           SourceLocation StartLoc,
11332                                           SourceLocation LParenLoc,
11333                                           SourceLocation EndLoc);
11334   /// Called on well-formed 'priority' clause.
11335   OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
11336                                        SourceLocation LParenLoc,
11337                                        SourceLocation EndLoc);
11338   /// Called on well-formed 'dist_schedule' clause.
11339   OMPClause *ActOnOpenMPDistScheduleClause(
11340       OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
11341       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
11342       SourceLocation CommaLoc, SourceLocation EndLoc);
11343   /// Called on well-formed 'defaultmap' clause.
11344   OMPClause *ActOnOpenMPDefaultmapClause(
11345       OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
11346       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
11347       SourceLocation KindLoc, SourceLocation EndLoc);
11348   /// Called on well-formed 'to' clause.
11349   OMPClause *
11350   ActOnOpenMPToClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
11351                       ArrayRef<SourceLocation> MotionModifiersLoc,
11352                       CXXScopeSpec &MapperIdScopeSpec,
11353                       DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
11354                       ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
11355                       ArrayRef<Expr *> UnresolvedMappers = llvm::None);
11356   /// Called on well-formed 'from' clause.
11357   OMPClause *
11358   ActOnOpenMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
11359                         ArrayRef<SourceLocation> MotionModifiersLoc,
11360                         CXXScopeSpec &MapperIdScopeSpec,
11361                         DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
11362                         ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
11363                         ArrayRef<Expr *> UnresolvedMappers = llvm::None);
11364   /// Called on well-formed 'use_device_ptr' clause.
11365   OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
11366                                            const OMPVarListLocTy &Locs);
11367   /// Called on well-formed 'use_device_addr' clause.
11368   OMPClause *ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
11369                                             const OMPVarListLocTy &Locs);
11370   /// Called on well-formed 'is_device_ptr' clause.
11371   OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
11372                                           const OMPVarListLocTy &Locs);
11373   /// Called on well-formed 'nontemporal' clause.
11374   OMPClause *ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
11375                                           SourceLocation StartLoc,
11376                                           SourceLocation LParenLoc,
11377                                           SourceLocation EndLoc);
11378 
11379   /// Data for list of allocators.
11380   struct UsesAllocatorsData {
11381     /// Allocator.
11382     Expr *Allocator = nullptr;
11383     /// Allocator traits.
11384     Expr *AllocatorTraits = nullptr;
11385     /// Locations of '(' and ')' symbols.
11386     SourceLocation LParenLoc, RParenLoc;
11387   };
11388   /// Called on well-formed 'uses_allocators' clause.
11389   OMPClause *ActOnOpenMPUsesAllocatorClause(SourceLocation StartLoc,
11390                                             SourceLocation LParenLoc,
11391                                             SourceLocation EndLoc,
11392                                             ArrayRef<UsesAllocatorsData> Data);
11393   /// Called on well-formed 'affinity' clause.
11394   OMPClause *ActOnOpenMPAffinityClause(SourceLocation StartLoc,
11395                                        SourceLocation LParenLoc,
11396                                        SourceLocation ColonLoc,
11397                                        SourceLocation EndLoc, Expr *Modifier,
11398                                        ArrayRef<Expr *> Locators);
11399 
11400   /// The kind of conversion being performed.
11401   enum CheckedConversionKind {
11402     /// An implicit conversion.
11403     CCK_ImplicitConversion,
11404     /// A C-style cast.
11405     CCK_CStyleCast,
11406     /// A functional-style cast.
11407     CCK_FunctionalCast,
11408     /// A cast other than a C-style cast.
11409     CCK_OtherCast,
11410     /// A conversion for an operand of a builtin overloaded operator.
11411     CCK_ForBuiltinOverloadedOp
11412   };
11413 
isCast(CheckedConversionKind CCK)11414   static bool isCast(CheckedConversionKind CCK) {
11415     return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast ||
11416            CCK == CCK_OtherCast;
11417   }
11418 
11419   /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
11420   /// cast.  If there is already an implicit cast, merge into the existing one.
11421   /// If isLvalue, the result of the cast is an lvalue.
11422   ExprResult
11423   ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
11424                     ExprValueKind VK = VK_PRValue,
11425                     const CXXCastPath *BasePath = nullptr,
11426                     CheckedConversionKind CCK = CCK_ImplicitConversion);
11427 
11428   /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
11429   /// to the conversion from scalar type ScalarTy to the Boolean type.
11430   static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
11431 
11432   /// IgnoredValueConversions - Given that an expression's result is
11433   /// syntactically ignored, perform any conversions that are
11434   /// required.
11435   ExprResult IgnoredValueConversions(Expr *E);
11436 
11437   // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
11438   // functions and arrays to their respective pointers (C99 6.3.2.1).
11439   ExprResult UsualUnaryConversions(Expr *E);
11440 
11441   /// CallExprUnaryConversions - a special case of an unary conversion
11442   /// performed on a function designator of a call expression.
11443   ExprResult CallExprUnaryConversions(Expr *E);
11444 
11445   // DefaultFunctionArrayConversion - converts functions and arrays
11446   // to their respective pointers (C99 6.3.2.1).
11447   ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
11448 
11449   // DefaultFunctionArrayLvalueConversion - converts functions and
11450   // arrays to their respective pointers and performs the
11451   // lvalue-to-rvalue conversion.
11452   ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
11453                                                   bool Diagnose = true);
11454 
11455   // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
11456   // the operand. This function is a no-op if the operand has a function type
11457   // or an array type.
11458   ExprResult DefaultLvalueConversion(Expr *E);
11459 
11460   // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
11461   // do not have a prototype. Integer promotions are performed on each
11462   // argument, and arguments that have type float are promoted to double.
11463   ExprResult DefaultArgumentPromotion(Expr *E);
11464 
11465   /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
11466   /// it as an xvalue. In C++98, the result will still be a prvalue, because
11467   /// we don't have xvalues there.
11468   ExprResult TemporaryMaterializationConversion(Expr *E);
11469 
11470   // Used for emitting the right warning by DefaultVariadicArgumentPromotion
11471   enum VariadicCallType {
11472     VariadicFunction,
11473     VariadicBlock,
11474     VariadicMethod,
11475     VariadicConstructor,
11476     VariadicDoesNotApply
11477   };
11478 
11479   VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
11480                                        const FunctionProtoType *Proto,
11481                                        Expr *Fn);
11482 
11483   // Used for determining in which context a type is allowed to be passed to a
11484   // vararg function.
11485   enum VarArgKind {
11486     VAK_Valid,
11487     VAK_ValidInCXX11,
11488     VAK_Undefined,
11489     VAK_MSVCUndefined,
11490     VAK_Invalid
11491   };
11492 
11493   // Determines which VarArgKind fits an expression.
11494   VarArgKind isValidVarArgType(const QualType &Ty);
11495 
11496   /// Check to see if the given expression is a valid argument to a variadic
11497   /// function, issuing a diagnostic if not.
11498   void checkVariadicArgument(const Expr *E, VariadicCallType CT);
11499 
11500   /// Check whether the given statement can have musttail applied to it,
11501   /// issuing a diagnostic and returning false if not. In the success case,
11502   /// the statement is rewritten to remove implicit nodes from the return
11503   /// value.
11504   bool checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA);
11505 
11506 private:
11507   /// Check whether the given statement can have musttail applied to it,
11508   /// issuing a diagnostic and returning false if not.
11509   bool checkMustTailAttr(const Stmt *St, const Attr &MTA);
11510 
11511 public:
11512   /// Check to see if a given expression could have '.c_str()' called on it.
11513   bool hasCStrMethod(const Expr *E);
11514 
11515   /// GatherArgumentsForCall - Collector argument expressions for various
11516   /// form of call prototypes.
11517   bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
11518                               const FunctionProtoType *Proto,
11519                               unsigned FirstParam, ArrayRef<Expr *> Args,
11520                               SmallVectorImpl<Expr *> &AllArgs,
11521                               VariadicCallType CallType = VariadicDoesNotApply,
11522                               bool AllowExplicit = false,
11523                               bool IsListInitialization = false);
11524 
11525   // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
11526   // will create a runtime trap if the resulting type is not a POD type.
11527   ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
11528                                               FunctionDecl *FDecl);
11529 
11530   /// Context in which we're performing a usual arithmetic conversion.
11531   enum ArithConvKind {
11532     /// An arithmetic operation.
11533     ACK_Arithmetic,
11534     /// A bitwise operation.
11535     ACK_BitwiseOp,
11536     /// A comparison.
11537     ACK_Comparison,
11538     /// A conditional (?:) operator.
11539     ACK_Conditional,
11540     /// A compound assignment expression.
11541     ACK_CompAssign,
11542   };
11543 
11544   // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
11545   // operands and then handles various conversions that are common to binary
11546   // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
11547   // routine returns the first non-arithmetic type found. The client is
11548   // responsible for emitting appropriate error diagnostics.
11549   QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
11550                                       SourceLocation Loc, ArithConvKind ACK);
11551 
11552   /// AssignConvertType - All of the 'assignment' semantic checks return this
11553   /// enum to indicate whether the assignment was allowed.  These checks are
11554   /// done for simple assignments, as well as initialization, return from
11555   /// function, argument passing, etc.  The query is phrased in terms of a
11556   /// source and destination type.
11557   enum AssignConvertType {
11558     /// Compatible - the types are compatible according to the standard.
11559     Compatible,
11560 
11561     /// PointerToInt - The assignment converts a pointer to an int, which we
11562     /// accept as an extension.
11563     PointerToInt,
11564 
11565     /// IntToPointer - The assignment converts an int to a pointer, which we
11566     /// accept as an extension.
11567     IntToPointer,
11568 
11569     /// FunctionVoidPointer - The assignment is between a function pointer and
11570     /// void*, which the standard doesn't allow, but we accept as an extension.
11571     FunctionVoidPointer,
11572 
11573     /// IncompatiblePointer - The assignment is between two pointers types that
11574     /// are not compatible, but we accept them as an extension.
11575     IncompatiblePointer,
11576 
11577     /// IncompatibleFunctionPointer - The assignment is between two function
11578     /// pointers types that are not compatible, but we accept them as an
11579     /// extension.
11580     IncompatibleFunctionPointer,
11581 
11582     /// IncompatiblePointerSign - The assignment is between two pointers types
11583     /// which point to integers which have a different sign, but are otherwise
11584     /// identical. This is a subset of the above, but broken out because it's by
11585     /// far the most common case of incompatible pointers.
11586     IncompatiblePointerSign,
11587 
11588     /// CompatiblePointerDiscardsQualifiers - The assignment discards
11589     /// c/v/r qualifiers, which we accept as an extension.
11590     CompatiblePointerDiscardsQualifiers,
11591 
11592     /// IncompatiblePointerDiscardsQualifiers - The assignment
11593     /// discards qualifiers that we don't permit to be discarded,
11594     /// like address spaces.
11595     IncompatiblePointerDiscardsQualifiers,
11596 
11597     /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment
11598     /// changes address spaces in nested pointer types which is not allowed.
11599     /// For instance, converting __private int ** to __generic int ** is
11600     /// illegal even though __private could be converted to __generic.
11601     IncompatibleNestedPointerAddressSpaceMismatch,
11602 
11603     /// IncompatibleNestedPointerQualifiers - The assignment is between two
11604     /// nested pointer types, and the qualifiers other than the first two
11605     /// levels differ e.g. char ** -> const char **, but we accept them as an
11606     /// extension.
11607     IncompatibleNestedPointerQualifiers,
11608 
11609     /// IncompatibleVectors - The assignment is between two vector types that
11610     /// have the same size, which we accept as an extension.
11611     IncompatibleVectors,
11612 
11613     /// IntToBlockPointer - The assignment converts an int to a block
11614     /// pointer. We disallow this.
11615     IntToBlockPointer,
11616 
11617     /// IncompatibleBlockPointer - The assignment is between two block
11618     /// pointers types that are not compatible.
11619     IncompatibleBlockPointer,
11620 
11621     /// IncompatibleObjCQualifiedId - The assignment is between a qualified
11622     /// id type and something else (that is incompatible with it). For example,
11623     /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
11624     IncompatibleObjCQualifiedId,
11625 
11626     /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
11627     /// object with __weak qualifier.
11628     IncompatibleObjCWeakRef,
11629 
11630     /// Incompatible - We reject this conversion outright, it is invalid to
11631     /// represent it in the AST.
11632     Incompatible
11633   };
11634 
11635   /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
11636   /// assignment conversion type specified by ConvTy.  This returns true if the
11637   /// conversion was invalid or false if the conversion was accepted.
11638   bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
11639                                 SourceLocation Loc,
11640                                 QualType DstType, QualType SrcType,
11641                                 Expr *SrcExpr, AssignmentAction Action,
11642                                 bool *Complained = nullptr);
11643 
11644   /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
11645   /// enum. If AllowMask is true, then we also allow the complement of a valid
11646   /// value, to be used as a mask.
11647   bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
11648                          bool AllowMask) const;
11649 
11650   /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
11651   /// integer not in the range of enum values.
11652   void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
11653                               Expr *SrcExpr);
11654 
11655   /// CheckAssignmentConstraints - Perform type checking for assignment,
11656   /// argument passing, variable initialization, and function return values.
11657   /// C99 6.5.16.
11658   AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
11659                                                QualType LHSType,
11660                                                QualType RHSType);
11661 
11662   /// Check assignment constraints and optionally prepare for a conversion of
11663   /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
11664   /// is true.
11665   AssignConvertType CheckAssignmentConstraints(QualType LHSType,
11666                                                ExprResult &RHS,
11667                                                CastKind &Kind,
11668                                                bool ConvertRHS = true);
11669 
11670   /// Check assignment constraints for an assignment of RHS to LHSType.
11671   ///
11672   /// \param LHSType The destination type for the assignment.
11673   /// \param RHS The source expression for the assignment.
11674   /// \param Diagnose If \c true, diagnostics may be produced when checking
11675   ///        for assignability. If a diagnostic is produced, \p RHS will be
11676   ///        set to ExprError(). Note that this function may still return
11677   ///        without producing a diagnostic, even for an invalid assignment.
11678   /// \param DiagnoseCFAudited If \c true, the target is a function parameter
11679   ///        in an audited Core Foundation API and does not need to be checked
11680   ///        for ARC retain issues.
11681   /// \param ConvertRHS If \c true, \p RHS will be updated to model the
11682   ///        conversions necessary to perform the assignment. If \c false,
11683   ///        \p Diagnose must also be \c false.
11684   AssignConvertType CheckSingleAssignmentConstraints(
11685       QualType LHSType, ExprResult &RHS, bool Diagnose = true,
11686       bool DiagnoseCFAudited = false, bool ConvertRHS = true);
11687 
11688   // If the lhs type is a transparent union, check whether we
11689   // can initialize the transparent union with the given expression.
11690   AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
11691                                                              ExprResult &RHS);
11692 
11693   bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
11694 
11695   bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
11696 
11697   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
11698                                        AssignmentAction Action,
11699                                        bool AllowExplicit = false);
11700   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
11701                                        const ImplicitConversionSequence& ICS,
11702                                        AssignmentAction Action,
11703                                        CheckedConversionKind CCK
11704                                           = CCK_ImplicitConversion);
11705   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
11706                                        const StandardConversionSequence& SCS,
11707                                        AssignmentAction Action,
11708                                        CheckedConversionKind CCK);
11709 
11710   ExprResult PerformQualificationConversion(
11711       Expr *E, QualType Ty, ExprValueKind VK = VK_PRValue,
11712       CheckedConversionKind CCK = CCK_ImplicitConversion);
11713 
11714   /// the following "Check" methods will return a valid/converted QualType
11715   /// or a null QualType (indicating an error diagnostic was issued).
11716 
11717   /// type checking binary operators (subroutines of CreateBuiltinBinOp).
11718   QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
11719                            ExprResult &RHS);
11720   QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
11721                                  ExprResult &RHS);
11722   QualType CheckPointerToMemberOperands( // C++ 5.5
11723     ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
11724     SourceLocation OpLoc, bool isIndirect);
11725   QualType CheckMultiplyDivideOperands( // C99 6.5.5
11726     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
11727     bool IsDivide);
11728   QualType CheckRemainderOperands( // C99 6.5.5
11729     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11730     bool IsCompAssign = false);
11731   QualType CheckAdditionOperands( // C99 6.5.6
11732     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11733     BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
11734   QualType CheckSubtractionOperands( // C99 6.5.6
11735     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11736     QualType* CompLHSTy = nullptr);
11737   QualType CheckShiftOperands( // C99 6.5.7
11738     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11739     BinaryOperatorKind Opc, bool IsCompAssign = false);
11740   void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE);
11741   QualType CheckCompareOperands( // C99 6.5.8/9
11742       ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11743       BinaryOperatorKind Opc);
11744   QualType CheckBitwiseOperands( // C99 6.5.[10...12]
11745       ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11746       BinaryOperatorKind Opc);
11747   QualType CheckLogicalOperands( // C99 6.5.[13,14]
11748     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11749     BinaryOperatorKind Opc);
11750   // CheckAssignmentOperands is used for both simple and compound assignment.
11751   // For simple assignment, pass both expressions and a null converted type.
11752   // For compound assignment, pass both expressions and the converted type.
11753   QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
11754     Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
11755 
11756   ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
11757                                      UnaryOperatorKind Opcode, Expr *Op);
11758   ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
11759                                          BinaryOperatorKind Opcode,
11760                                          Expr *LHS, Expr *RHS);
11761   ExprResult checkPseudoObjectRValue(Expr *E);
11762   Expr *recreateSyntacticForm(PseudoObjectExpr *E);
11763 
11764   QualType CheckConditionalOperands( // C99 6.5.15
11765     ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
11766     ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
11767   QualType CXXCheckConditionalOperands( // C++ 5.16
11768     ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
11769     ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
11770   QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
11771                                        ExprResult &RHS,
11772                                        SourceLocation QuestionLoc);
11773   QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
11774                                     bool ConvertArgs = true);
11775   QualType FindCompositePointerType(SourceLocation Loc,
11776                                     ExprResult &E1, ExprResult &E2,
11777                                     bool ConvertArgs = true) {
11778     Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
11779     QualType Composite =
11780         FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
11781     E1 = E1Tmp;
11782     E2 = E2Tmp;
11783     return Composite;
11784   }
11785 
11786   QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
11787                                         SourceLocation QuestionLoc);
11788 
11789   bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
11790                                   SourceLocation QuestionLoc);
11791 
11792   void DiagnoseAlwaysNonNullPointer(Expr *E,
11793                                     Expr::NullPointerConstantKind NullType,
11794                                     bool IsEqual, SourceRange Range);
11795 
11796   /// type checking for vector binary operators.
11797   QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
11798                                SourceLocation Loc, bool IsCompAssign,
11799                                bool AllowBothBool, bool AllowBoolConversion);
11800   QualType GetSignedVectorType(QualType V);
11801   QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
11802                                       SourceLocation Loc,
11803                                       BinaryOperatorKind Opc);
11804   QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11805                                       SourceLocation Loc);
11806 
11807   /// Type checking for matrix binary operators.
11808   QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
11809                                           SourceLocation Loc,
11810                                           bool IsCompAssign);
11811   QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
11812                                        SourceLocation Loc, bool IsCompAssign);
11813 
11814   bool isValidSveBitcast(QualType srcType, QualType destType);
11815 
11816   bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy);
11817 
11818   bool areVectorTypesSameSize(QualType srcType, QualType destType);
11819   bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
11820   bool isLaxVectorConversion(QualType srcType, QualType destType);
11821 
11822   /// type checking declaration initializers (C99 6.7.8)
11823   bool CheckForConstantInitializer(Expr *e, QualType t);
11824 
11825   // type checking C++ declaration initializers (C++ [dcl.init]).
11826 
11827   /// ReferenceCompareResult - Expresses the result of comparing two
11828   /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
11829   /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
11830   enum ReferenceCompareResult {
11831     /// Ref_Incompatible - The two types are incompatible, so direct
11832     /// reference binding is not possible.
11833     Ref_Incompatible = 0,
11834     /// Ref_Related - The two types are reference-related, which means
11835     /// that their unqualified forms (T1 and T2) are either the same
11836     /// or T1 is a base class of T2.
11837     Ref_Related,
11838     /// Ref_Compatible - The two types are reference-compatible.
11839     Ref_Compatible
11840   };
11841 
11842   // Fake up a scoped enumeration that still contextually converts to bool.
11843   struct ReferenceConversionsScope {
11844     /// The conversions that would be performed on an lvalue of type T2 when
11845     /// binding a reference of type T1 to it, as determined when evaluating
11846     /// whether T1 is reference-compatible with T2.
11847     enum ReferenceConversions {
11848       Qualification = 0x1,
11849       NestedQualification = 0x2,
11850       Function = 0x4,
11851       DerivedToBase = 0x8,
11852       ObjC = 0x10,
11853       ObjCLifetime = 0x20,
11854 
11855       LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime)
11856     };
11857   };
11858   using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions;
11859 
11860   ReferenceCompareResult
11861   CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2,
11862                                ReferenceConversions *Conv = nullptr);
11863 
11864   ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11865                                  Expr *CastExpr, CastKind &CastKind,
11866                                  ExprValueKind &VK, CXXCastPath &Path);
11867 
11868   /// Force an expression with unknown-type to an expression of the
11869   /// given type.
11870   ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
11871 
11872   /// Type-check an expression that's being passed to an
11873   /// __unknown_anytype parameter.
11874   ExprResult checkUnknownAnyArg(SourceLocation callLoc,
11875                                 Expr *result, QualType &paramType);
11876 
11877   // CheckMatrixCast - Check type constraints for matrix casts.
11878   // We allow casting between matrixes of the same dimensions i.e. when they
11879   // have the same number of rows and column. Returns true if the cast is
11880   // invalid.
11881   bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
11882                        CastKind &Kind);
11883 
11884   // CheckVectorCast - check type constraints for vectors.
11885   // Since vectors are an extension, there are no C standard reference for this.
11886   // We allow casting between vectors and integer datatypes of the same size.
11887   // returns true if the cast is invalid
11888   bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
11889                        CastKind &Kind);
11890 
11891   /// Prepare `SplattedExpr` for a vector splat operation, adding
11892   /// implicit casts if necessary.
11893   ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
11894 
11895   // CheckExtVectorCast - check type constraints for extended vectors.
11896   // Since vectors are an extension, there are no C standard reference for this.
11897   // We allow casting between vectors and integer datatypes of the same size,
11898   // or vectors and the element type of that vector.
11899   // returns the cast expr
11900   ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
11901                                 CastKind &Kind);
11902 
11903   ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
11904                                         SourceLocation LParenLoc,
11905                                         Expr *CastExpr,
11906                                         SourceLocation RParenLoc);
11907 
11908   enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
11909 
11910   /// Checks for invalid conversions and casts between
11911   /// retainable pointers and other pointer kinds for ARC and Weak.
11912   ARCConversionResult CheckObjCConversion(SourceRange castRange,
11913                                           QualType castType, Expr *&op,
11914                                           CheckedConversionKind CCK,
11915                                           bool Diagnose = true,
11916                                           bool DiagnoseCFAudited = false,
11917                                           BinaryOperatorKind Opc = BO_PtrMemD
11918                                           );
11919 
11920   Expr *stripARCUnbridgedCast(Expr *e);
11921   void diagnoseARCUnbridgedCast(Expr *e);
11922 
11923   bool CheckObjCARCUnavailableWeakConversion(QualType castType,
11924                                              QualType ExprType);
11925 
11926   /// checkRetainCycles - Check whether an Objective-C message send
11927   /// might create an obvious retain cycle.
11928   void checkRetainCycles(ObjCMessageExpr *msg);
11929   void checkRetainCycles(Expr *receiver, Expr *argument);
11930   void checkRetainCycles(VarDecl *Var, Expr *Init);
11931 
11932   /// checkUnsafeAssigns - Check whether +1 expr is being assigned
11933   /// to weak/__unsafe_unretained type.
11934   bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
11935 
11936   /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
11937   /// to weak/__unsafe_unretained expression.
11938   void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
11939 
11940   /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
11941   /// \param Method - May be null.
11942   /// \param [out] ReturnType - The return type of the send.
11943   /// \return true iff there were any incompatible types.
11944   bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType,
11945                                  MultiExprArg Args, Selector Sel,
11946                                  ArrayRef<SourceLocation> SelectorLocs,
11947                                  ObjCMethodDecl *Method, bool isClassMessage,
11948                                  bool isSuperMessage, SourceLocation lbrac,
11949                                  SourceLocation rbrac, SourceRange RecRange,
11950                                  QualType &ReturnType, ExprValueKind &VK);
11951 
11952   /// Determine the result of a message send expression based on
11953   /// the type of the receiver, the method expected to receive the message,
11954   /// and the form of the message send.
11955   QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType,
11956                                     ObjCMethodDecl *Method, bool isClassMessage,
11957                                     bool isSuperMessage);
11958 
11959   /// If the given expression involves a message send to a method
11960   /// with a related result type, emit a note describing what happened.
11961   void EmitRelatedResultTypeNote(const Expr *E);
11962 
11963   /// Given that we had incompatible pointer types in a return
11964   /// statement, check whether we're in a method with a related result
11965   /// type, and if so, emit a note describing what happened.
11966   void EmitRelatedResultTypeNoteForReturn(QualType destType);
11967 
11968   class ConditionResult {
11969     Decl *ConditionVar;
11970     FullExprArg Condition;
11971     bool Invalid;
11972     bool HasKnownValue;
11973     bool KnownValue;
11974 
11975     friend class Sema;
ConditionResult(Sema & S,Decl * ConditionVar,FullExprArg Condition,bool IsConstexpr)11976     ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
11977                     bool IsConstexpr)
11978         : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
11979           HasKnownValue(IsConstexpr && Condition.get() &&
11980                         !Condition.get()->isValueDependent()),
11981           KnownValue(HasKnownValue &&
11982                      !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
ConditionResult(bool Invalid)11983     explicit ConditionResult(bool Invalid)
11984         : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
11985           HasKnownValue(false), KnownValue(false) {}
11986 
11987   public:
ConditionResult()11988     ConditionResult() : ConditionResult(false) {}
isInvalid()11989     bool isInvalid() const { return Invalid; }
get()11990     std::pair<VarDecl *, Expr *> get() const {
11991       return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
11992                             Condition.get());
11993     }
getKnownValue()11994     llvm::Optional<bool> getKnownValue() const {
11995       if (!HasKnownValue)
11996         return None;
11997       return KnownValue;
11998     }
11999   };
ConditionError()12000   static ConditionResult ConditionError() { return ConditionResult(true); }
12001 
12002   enum class ConditionKind {
12003     Boolean,     ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
12004     ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
12005     Switch       ///< An integral condition for a 'switch' statement.
12006   };
12007 
12008   ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
12009                                  Expr *SubExpr, ConditionKind CK);
12010 
12011   ConditionResult ActOnConditionVariable(Decl *ConditionVar,
12012                                          SourceLocation StmtLoc,
12013                                          ConditionKind CK);
12014 
12015   DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
12016 
12017   ExprResult CheckConditionVariable(VarDecl *ConditionVar,
12018                                     SourceLocation StmtLoc,
12019                                     ConditionKind CK);
12020   ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
12021 
12022   /// CheckBooleanCondition - Diagnose problems involving the use of
12023   /// the given expression as a boolean condition (e.g. in an if
12024   /// statement).  Also performs the standard function and array
12025   /// decays, possibly changing the input variable.
12026   ///
12027   /// \param Loc - A location associated with the condition, e.g. the
12028   /// 'if' keyword.
12029   /// \return true iff there were any errors
12030   ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
12031                                    bool IsConstexpr = false);
12032 
12033   /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression
12034   /// found in an explicit(bool) specifier.
12035   ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E);
12036 
12037   /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
12038   /// Returns true if the explicit specifier is now resolved.
12039   bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec);
12040 
12041   /// DiagnoseAssignmentAsCondition - Given that an expression is
12042   /// being used as a boolean condition, warn if it's an assignment.
12043   void DiagnoseAssignmentAsCondition(Expr *E);
12044 
12045   /// Redundant parentheses over an equality comparison can indicate
12046   /// that the user intended an assignment used as condition.
12047   void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
12048 
12049   /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
12050   ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
12051 
12052   /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
12053   /// the specified width and sign.  If an overflow occurs, detect it and emit
12054   /// the specified diagnostic.
12055   void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
12056                                           unsigned NewWidth, bool NewSign,
12057                                           SourceLocation Loc, unsigned DiagID);
12058 
12059   /// Checks that the Objective-C declaration is declared in the global scope.
12060   /// Emits an error and marks the declaration as invalid if it's not declared
12061   /// in the global scope.
12062   bool CheckObjCDeclScope(Decl *D);
12063 
12064   /// Abstract base class used for diagnosing integer constant
12065   /// expression violations.
12066   class VerifyICEDiagnoser {
12067   public:
12068     bool Suppress;
12069 
Suppress(Suppress)12070     VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
12071 
12072     virtual SemaDiagnosticBuilder
12073     diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T);
12074     virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
12075                                                  SourceLocation Loc) = 0;
12076     virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc);
~VerifyICEDiagnoser()12077     virtual ~VerifyICEDiagnoser() {}
12078   };
12079 
12080   enum AllowFoldKind {
12081     NoFold,
12082     AllowFold,
12083   };
12084 
12085   /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
12086   /// and reports the appropriate diagnostics. Returns false on success.
12087   /// Can optionally return the value of the expression.
12088   ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12089                                              VerifyICEDiagnoser &Diagnoser,
12090                                              AllowFoldKind CanFold = NoFold);
12091   ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12092                                              unsigned DiagID,
12093                                              AllowFoldKind CanFold = NoFold);
12094   ExprResult VerifyIntegerConstantExpression(Expr *E,
12095                                              llvm::APSInt *Result = nullptr,
12096                                              AllowFoldKind CanFold = NoFold);
12097   ExprResult VerifyIntegerConstantExpression(Expr *E,
12098                                              AllowFoldKind CanFold = NoFold) {
12099     return VerifyIntegerConstantExpression(E, nullptr, CanFold);
12100   }
12101 
12102   /// VerifyBitField - verifies that a bit field expression is an ICE and has
12103   /// the correct width, and that the field type is valid.
12104   /// Returns false on success.
12105   /// Can optionally return whether the bit-field is of width 0
12106   ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
12107                             QualType FieldTy, bool IsMsStruct,
12108                             Expr *BitWidth, bool *ZeroWidth = nullptr);
12109 
12110 private:
12111   unsigned ForceCUDAHostDeviceDepth = 0;
12112 
12113 public:
12114   /// Increments our count of the number of times we've seen a pragma forcing
12115   /// functions to be __host__ __device__.  So long as this count is greater
12116   /// than zero, all functions encountered will be __host__ __device__.
12117   void PushForceCUDAHostDevice();
12118 
12119   /// Decrements our count of the number of times we've seen a pragma forcing
12120   /// functions to be __host__ __device__.  Returns false if the count is 0
12121   /// before incrementing, so you can emit an error.
12122   bool PopForceCUDAHostDevice();
12123 
12124   /// Diagnostics that are emitted only if we discover that the given function
12125   /// must be codegen'ed.  Because handling these correctly adds overhead to
12126   /// compilation, this is currently only enabled for CUDA compilations.
12127   llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
12128                  std::vector<PartialDiagnosticAt>>
12129       DeviceDeferredDiags;
12130 
12131   /// A pair of a canonical FunctionDecl and a SourceLocation.  When used as the
12132   /// key in a hashtable, both the FD and location are hashed.
12133   struct FunctionDeclAndLoc {
12134     CanonicalDeclPtr<FunctionDecl> FD;
12135     SourceLocation Loc;
12136   };
12137 
12138   /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
12139   /// (maybe deferred) "bad call" diagnostic.  We use this to avoid emitting the
12140   /// same deferred diag twice.
12141   llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
12142 
12143   /// An inverse call graph, mapping known-emitted functions to one of their
12144   /// known-emitted callers (plus the location of the call).
12145   ///
12146   /// Functions that we can tell a priori must be emitted aren't added to this
12147   /// map.
12148   llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
12149                  /* Caller = */ FunctionDeclAndLoc>
12150       DeviceKnownEmittedFns;
12151 
12152   /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
12153   /// context is "used as device code".
12154   ///
12155   /// - If CurContext is a __host__ function, does not emit any diagnostics
12156   ///   unless \p EmitOnBothSides is true.
12157   /// - If CurContext is a __device__ or __global__ function, emits the
12158   ///   diagnostics immediately.
12159   /// - If CurContext is a __host__ __device__ function and we are compiling for
12160   ///   the device, creates a diagnostic which is emitted if and when we realize
12161   ///   that the function will be codegen'ed.
12162   ///
12163   /// Example usage:
12164   ///
12165   ///  // Variable-length arrays are not allowed in CUDA device code.
12166   ///  if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
12167   ///    return ExprError();
12168   ///  // Otherwise, continue parsing as normal.
12169   SemaDiagnosticBuilder CUDADiagIfDeviceCode(SourceLocation Loc,
12170                                              unsigned DiagID);
12171 
12172   /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
12173   /// context is "used as host code".
12174   ///
12175   /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
12176   SemaDiagnosticBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
12177 
12178   /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
12179   /// context is "used as device code".
12180   ///
12181   /// - If CurContext is a `declare target` function or it is known that the
12182   /// function is emitted for the device, emits the diagnostics immediately.
12183   /// - If CurContext is a non-`declare target` function and we are compiling
12184   ///   for the device, creates a diagnostic which is emitted if and when we
12185   ///   realize that the function will be codegen'ed.
12186   ///
12187   /// Example usage:
12188   ///
12189   ///  // Variable-length arrays are not allowed in NVPTX device code.
12190   ///  if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported))
12191   ///    return ExprError();
12192   ///  // Otherwise, continue parsing as normal.
12193   SemaDiagnosticBuilder
12194   diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID, FunctionDecl *FD);
12195 
12196   /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
12197   /// context is "used as host code".
12198   ///
12199   /// - If CurContext is a `declare target` function or it is known that the
12200   /// function is emitted for the host, emits the diagnostics immediately.
12201   /// - If CurContext is a non-host function, just ignore it.
12202   ///
12203   /// Example usage:
12204   ///
12205   ///  // Variable-length arrays are not allowed in NVPTX device code.
12206   ///  if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported))
12207   ///    return ExprError();
12208   ///  // Otherwise, continue parsing as normal.
12209   SemaDiagnosticBuilder diagIfOpenMPHostCode(SourceLocation Loc,
12210                                              unsigned DiagID, FunctionDecl *FD);
12211 
12212   SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID,
12213                                    FunctionDecl *FD = nullptr);
12214   SemaDiagnosticBuilder targetDiag(SourceLocation Loc,
12215                                    const PartialDiagnostic &PD,
12216                                    FunctionDecl *FD = nullptr) {
12217     return targetDiag(Loc, PD.getDiagID(), FD) << PD;
12218   }
12219 
12220   /// Check if the expression is allowed to be used in expressions for the
12221   /// offloading devices.
12222   void checkDeviceDecl(ValueDecl *D, SourceLocation Loc);
12223 
12224   enum CUDAFunctionTarget {
12225     CFT_Device,
12226     CFT_Global,
12227     CFT_Host,
12228     CFT_HostDevice,
12229     CFT_InvalidTarget
12230   };
12231 
12232   /// Determines whether the given function is a CUDA device/host/kernel/etc.
12233   /// function.
12234   ///
12235   /// Use this rather than examining the function's attributes yourself -- you
12236   /// will get it wrong.  Returns CFT_Host if D is null.
12237   CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
12238                                         bool IgnoreImplicitHDAttr = false);
12239   CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs);
12240 
12241   enum CUDAVariableTarget {
12242     CVT_Device,  /// Emitted on device side with a shadow variable on host side
12243     CVT_Host,    /// Emitted on host side only
12244     CVT_Both,    /// Emitted on both sides with different addresses
12245     CVT_Unified, /// Emitted as a unified address, e.g. managed variables
12246   };
12247   /// Determines whether the given variable is emitted on host or device side.
12248   CUDAVariableTarget IdentifyCUDATarget(const VarDecl *D);
12249 
12250   /// Gets the CUDA target for the current context.
CurrentCUDATarget()12251   CUDAFunctionTarget CurrentCUDATarget() {
12252     return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
12253   }
12254 
12255   static bool isCUDAImplicitHostDeviceFunction(const FunctionDecl *D);
12256 
12257   // CUDA function call preference. Must be ordered numerically from
12258   // worst to best.
12259   enum CUDAFunctionPreference {
12260     CFP_Never,      // Invalid caller/callee combination.
12261     CFP_WrongSide,  // Calls from host-device to host or device
12262                     // function that do not match current compilation
12263                     // mode.
12264     CFP_HostDevice, // Any calls to host/device functions.
12265     CFP_SameSide,   // Calls from host-device to host or device
12266                     // function matching current compilation mode.
12267     CFP_Native,     // host-to-host or device-to-device calls.
12268   };
12269 
12270   /// Identifies relative preference of a given Caller/Callee
12271   /// combination, based on their host/device attributes.
12272   /// \param Caller function which needs address of \p Callee.
12273   ///               nullptr in case of global context.
12274   /// \param Callee target function
12275   ///
12276   /// \returns preference value for particular Caller/Callee combination.
12277   CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
12278                                                 const FunctionDecl *Callee);
12279 
12280   /// Determines whether Caller may invoke Callee, based on their CUDA
12281   /// host/device attributes.  Returns false if the call is not allowed.
12282   ///
12283   /// Note: Will return true for CFP_WrongSide calls.  These may appear in
12284   /// semantically correct CUDA programs, but only if they're never codegen'ed.
IsAllowedCUDACall(const FunctionDecl * Caller,const FunctionDecl * Callee)12285   bool IsAllowedCUDACall(const FunctionDecl *Caller,
12286                          const FunctionDecl *Callee) {
12287     return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
12288   }
12289 
12290   /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
12291   /// depending on FD and the current compilation settings.
12292   void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
12293                                    const LookupResult &Previous);
12294 
12295   /// May add implicit CUDAConstantAttr attribute to VD, depending on VD
12296   /// and current compilation settings.
12297   void MaybeAddCUDAConstantAttr(VarDecl *VD);
12298 
12299 public:
12300   /// Check whether we're allowed to call Callee from the current context.
12301   ///
12302   /// - If the call is never allowed in a semantically-correct program
12303   ///   (CFP_Never), emits an error and returns false.
12304   ///
12305   /// - If the call is allowed in semantically-correct programs, but only if
12306   ///   it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
12307   ///   be emitted if and when the caller is codegen'ed, and returns true.
12308   ///
12309   ///   Will only create deferred diagnostics for a given SourceLocation once,
12310   ///   so you can safely call this multiple times without generating duplicate
12311   ///   deferred errors.
12312   ///
12313   /// - Otherwise, returns true without emitting any diagnostics.
12314   bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
12315 
12316   void CUDACheckLambdaCapture(CXXMethodDecl *D, const sema::Capture &Capture);
12317 
12318   /// Set __device__ or __host__ __device__ attributes on the given lambda
12319   /// operator() method.
12320   ///
12321   /// CUDA lambdas by default is host device function unless it has explicit
12322   /// host or device attribute.
12323   void CUDASetLambdaAttrs(CXXMethodDecl *Method);
12324 
12325   /// Finds a function in \p Matches with highest calling priority
12326   /// from \p Caller context and erases all functions with lower
12327   /// calling priority.
12328   void EraseUnwantedCUDAMatches(
12329       const FunctionDecl *Caller,
12330       SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
12331 
12332   /// Given a implicit special member, infer its CUDA target from the
12333   /// calls it needs to make to underlying base/field special members.
12334   /// \param ClassDecl the class for which the member is being created.
12335   /// \param CSM the kind of special member.
12336   /// \param MemberDecl the special member itself.
12337   /// \param ConstRHS true if this is a copy operation with a const object on
12338   ///        its RHS.
12339   /// \param Diagnose true if this call should emit diagnostics.
12340   /// \return true if there was an error inferring.
12341   /// The result of this call is implicit CUDA target attribute(s) attached to
12342   /// the member declaration.
12343   bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
12344                                                CXXSpecialMember CSM,
12345                                                CXXMethodDecl *MemberDecl,
12346                                                bool ConstRHS,
12347                                                bool Diagnose);
12348 
12349   /// \return true if \p CD can be considered empty according to CUDA
12350   /// (E.2.3.1 in CUDA 7.5 Programming guide).
12351   bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
12352   bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
12353 
12354   // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In
12355   // case of error emits appropriate diagnostic and invalidates \p Var.
12356   //
12357   // \details CUDA allows only empty constructors as initializers for global
12358   // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all
12359   // __shared__ variables whether they are local or not (they all are implicitly
12360   // static in CUDA). One exception is that CUDA allows constant initializers
12361   // for __constant__ and __device__ variables.
12362   void checkAllowedCUDAInitializer(VarDecl *VD);
12363 
12364   /// Check whether NewFD is a valid overload for CUDA. Emits
12365   /// diagnostics and invalidates NewFD if not.
12366   void checkCUDATargetOverload(FunctionDecl *NewFD,
12367                                const LookupResult &Previous);
12368   /// Copies target attributes from the template TD to the function FD.
12369   void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
12370 
12371   /// Returns the name of the launch configuration function.  This is the name
12372   /// of the function that will be called to configure kernel call, with the
12373   /// parameters specified via <<<>>>.
12374   std::string getCudaConfigureFuncName() const;
12375 
12376   /// \name Code completion
12377   //@{
12378   /// Describes the context in which code completion occurs.
12379   enum ParserCompletionContext {
12380     /// Code completion occurs at top-level or namespace context.
12381     PCC_Namespace,
12382     /// Code completion occurs within a class, struct, or union.
12383     PCC_Class,
12384     /// Code completion occurs within an Objective-C interface, protocol,
12385     /// or category.
12386     PCC_ObjCInterface,
12387     /// Code completion occurs within an Objective-C implementation or
12388     /// category implementation
12389     PCC_ObjCImplementation,
12390     /// Code completion occurs within the list of instance variables
12391     /// in an Objective-C interface, protocol, category, or implementation.
12392     PCC_ObjCInstanceVariableList,
12393     /// Code completion occurs following one or more template
12394     /// headers.
12395     PCC_Template,
12396     /// Code completion occurs following one or more template
12397     /// headers within a class.
12398     PCC_MemberTemplate,
12399     /// Code completion occurs within an expression.
12400     PCC_Expression,
12401     /// Code completion occurs within a statement, which may
12402     /// also be an expression or a declaration.
12403     PCC_Statement,
12404     /// Code completion occurs at the beginning of the
12405     /// initialization statement (or expression) in a for loop.
12406     PCC_ForInit,
12407     /// Code completion occurs within the condition of an if,
12408     /// while, switch, or for statement.
12409     PCC_Condition,
12410     /// Code completion occurs within the body of a function on a
12411     /// recovery path, where we do not have a specific handle on our position
12412     /// in the grammar.
12413     PCC_RecoveryInFunction,
12414     /// Code completion occurs where only a type is permitted.
12415     PCC_Type,
12416     /// Code completion occurs in a parenthesized expression, which
12417     /// might also be a type cast.
12418     PCC_ParenthesizedExpression,
12419     /// Code completion occurs within a sequence of declaration
12420     /// specifiers within a function, method, or block.
12421     PCC_LocalDeclarationSpecifiers
12422   };
12423 
12424   void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
12425   void CodeCompleteOrdinaryName(Scope *S,
12426                                 ParserCompletionContext CompletionContext);
12427   void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
12428                             bool AllowNonIdentifiers,
12429                             bool AllowNestedNameSpecifiers);
12430 
12431   struct CodeCompleteExpressionData;
12432   void CodeCompleteExpression(Scope *S,
12433                               const CodeCompleteExpressionData &Data);
12434   void CodeCompleteExpression(Scope *S, QualType PreferredType,
12435                               bool IsParenthesized = false);
12436   void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase,
12437                                        SourceLocation OpLoc, bool IsArrow,
12438                                        bool IsBaseExprStatement,
12439                                        QualType PreferredType);
12440   void CodeCompletePostfixExpression(Scope *S, ExprResult LHS,
12441                                      QualType PreferredType);
12442   void CodeCompleteTag(Scope *S, unsigned TagSpec);
12443   void CodeCompleteTypeQualifiers(DeclSpec &DS);
12444   void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
12445                                       const VirtSpecifiers *VS = nullptr);
12446   void CodeCompleteBracketDeclarator(Scope *S);
12447   void CodeCompleteCase(Scope *S);
12448   enum class AttributeCompletion {
12449     Attribute,
12450     Scope,
12451     None,
12452   };
12453   void CodeCompleteAttribute(
12454       AttributeCommonInfo::Syntax Syntax,
12455       AttributeCompletion Completion = AttributeCompletion::Attribute,
12456       const IdentifierInfo *Scope = nullptr);
12457   /// Determines the preferred type of the current function argument, by
12458   /// examining the signatures of all possible overloads.
12459   /// Returns null if unknown or ambiguous, or if code completion is off.
12460   ///
12461   /// If the code completion point has been reached, also reports the function
12462   /// signatures that were considered.
12463   ///
12464   /// FIXME: rename to GuessCallArgumentType to reduce confusion.
12465   QualType ProduceCallSignatureHelp(Scope *S, Expr *Fn, ArrayRef<Expr *> Args,
12466                                     SourceLocation OpenParLoc);
12467   QualType ProduceConstructorSignatureHelp(Scope *S, QualType Type,
12468                                            SourceLocation Loc,
12469                                            ArrayRef<Expr *> Args,
12470                                            SourceLocation OpenParLoc);
12471   QualType ProduceCtorInitMemberSignatureHelp(Scope *S, Decl *ConstructorDecl,
12472                                               CXXScopeSpec SS,
12473                                               ParsedType TemplateTypeTy,
12474                                               ArrayRef<Expr *> ArgExprs,
12475                                               IdentifierInfo *II,
12476                                               SourceLocation OpenParLoc);
12477   void CodeCompleteInitializer(Scope *S, Decl *D);
12478   /// Trigger code completion for a record of \p BaseType. \p InitExprs are
12479   /// expressions in the initializer list seen so far and \p D is the current
12480   /// Designation being parsed.
12481   void CodeCompleteDesignator(const QualType BaseType,
12482                               llvm::ArrayRef<Expr *> InitExprs,
12483                               const Designation &D);
12484   void CodeCompleteAfterIf(Scope *S, bool IsBracedThen);
12485 
12486   void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext,
12487                                bool IsUsingDeclaration, QualType BaseType,
12488                                QualType PreferredType);
12489   void CodeCompleteUsing(Scope *S);
12490   void CodeCompleteUsingDirective(Scope *S);
12491   void CodeCompleteNamespaceDecl(Scope *S);
12492   void CodeCompleteNamespaceAliasDecl(Scope *S);
12493   void CodeCompleteOperatorName(Scope *S);
12494   void CodeCompleteConstructorInitializer(
12495                                 Decl *Constructor,
12496                                 ArrayRef<CXXCtorInitializer *> Initializers);
12497 
12498   void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
12499                                     bool AfterAmpersand);
12500   void CodeCompleteAfterFunctionEquals(Declarator &D);
12501 
12502   void CodeCompleteObjCAtDirective(Scope *S);
12503   void CodeCompleteObjCAtVisibility(Scope *S);
12504   void CodeCompleteObjCAtStatement(Scope *S);
12505   void CodeCompleteObjCAtExpression(Scope *S);
12506   void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
12507   void CodeCompleteObjCPropertyGetter(Scope *S);
12508   void CodeCompleteObjCPropertySetter(Scope *S);
12509   void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
12510                                    bool IsParameter);
12511   void CodeCompleteObjCMessageReceiver(Scope *S);
12512   void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
12513                                     ArrayRef<IdentifierInfo *> SelIdents,
12514                                     bool AtArgumentExpression);
12515   void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
12516                                     ArrayRef<IdentifierInfo *> SelIdents,
12517                                     bool AtArgumentExpression,
12518                                     bool IsSuper = false);
12519   void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
12520                                        ArrayRef<IdentifierInfo *> SelIdents,
12521                                        bool AtArgumentExpression,
12522                                        ObjCInterfaceDecl *Super = nullptr);
12523   void CodeCompleteObjCForCollection(Scope *S,
12524                                      DeclGroupPtrTy IterationVar);
12525   void CodeCompleteObjCSelector(Scope *S,
12526                                 ArrayRef<IdentifierInfo *> SelIdents);
12527   void CodeCompleteObjCProtocolReferences(
12528                                          ArrayRef<IdentifierLocPair> Protocols);
12529   void CodeCompleteObjCProtocolDecl(Scope *S);
12530   void CodeCompleteObjCInterfaceDecl(Scope *S);
12531   void CodeCompleteObjCSuperclass(Scope *S,
12532                                   IdentifierInfo *ClassName,
12533                                   SourceLocation ClassNameLoc);
12534   void CodeCompleteObjCImplementationDecl(Scope *S);
12535   void CodeCompleteObjCInterfaceCategory(Scope *S,
12536                                          IdentifierInfo *ClassName,
12537                                          SourceLocation ClassNameLoc);
12538   void CodeCompleteObjCImplementationCategory(Scope *S,
12539                                               IdentifierInfo *ClassName,
12540                                               SourceLocation ClassNameLoc);
12541   void CodeCompleteObjCPropertyDefinition(Scope *S);
12542   void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
12543                                               IdentifierInfo *PropertyName);
12544   void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod,
12545                                   ParsedType ReturnType);
12546   void CodeCompleteObjCMethodDeclSelector(Scope *S,
12547                                           bool IsInstanceMethod,
12548                                           bool AtParameterName,
12549                                           ParsedType ReturnType,
12550                                           ArrayRef<IdentifierInfo *> SelIdents);
12551   void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
12552                                             SourceLocation ClassNameLoc,
12553                                             bool IsBaseExprStatement);
12554   void CodeCompletePreprocessorDirective(bool InConditional);
12555   void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
12556   void CodeCompletePreprocessorMacroName(bool IsDefinition);
12557   void CodeCompletePreprocessorExpression();
12558   void CodeCompletePreprocessorMacroArgument(Scope *S,
12559                                              IdentifierInfo *Macro,
12560                                              MacroInfo *MacroInfo,
12561                                              unsigned Argument);
12562   void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled);
12563   void CodeCompleteNaturalLanguage();
12564   void CodeCompleteAvailabilityPlatformName();
12565   void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
12566                                    CodeCompletionTUInfo &CCTUInfo,
12567                   SmallVectorImpl<CodeCompletionResult> &Results);
12568   //@}
12569 
12570   //===--------------------------------------------------------------------===//
12571   // Extra semantic analysis beyond the C type system
12572 
12573 public:
12574   SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
12575                                                 unsigned ByteNo) const;
12576 
12577 private:
12578   void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
12579                         const ArraySubscriptExpr *ASE=nullptr,
12580                         bool AllowOnePastEnd=true, bool IndexNegated=false);
12581   void CheckArrayAccess(const Expr *E);
12582   // Used to grab the relevant information from a FormatAttr and a
12583   // FunctionDeclaration.
12584   struct FormatStringInfo {
12585     unsigned FormatIdx;
12586     unsigned FirstDataArg;
12587     bool HasVAListArg;
12588   };
12589 
12590   static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
12591                                   FormatStringInfo *FSI);
12592   bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
12593                          const FunctionProtoType *Proto);
12594   bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
12595                            ArrayRef<const Expr *> Args);
12596   bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
12597                         const FunctionProtoType *Proto);
12598   bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
12599   void CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
12600                             ArrayRef<const Expr *> Args,
12601                             const FunctionProtoType *Proto, SourceLocation Loc);
12602 
12603   void CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
12604                          StringRef ParamName, QualType ArgTy, QualType ParamTy);
12605 
12606   void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
12607                  const Expr *ThisArg, ArrayRef<const Expr *> Args,
12608                  bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
12609                  VariadicCallType CallType);
12610 
12611   bool CheckObjCString(Expr *Arg);
12612   ExprResult CheckOSLogFormatStringArg(Expr *Arg);
12613 
12614   ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
12615                                       unsigned BuiltinID, CallExpr *TheCall);
12616 
12617   bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12618                                   CallExpr *TheCall);
12619 
12620   void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
12621 
12622   bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
12623                                     unsigned MaxWidth);
12624   bool CheckNeonBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12625                                     CallExpr *TheCall);
12626   bool CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12627   bool CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12628   bool CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12629                                    CallExpr *TheCall);
12630   bool CheckARMCoprocessorImmediate(const TargetInfo &TI, const Expr *CoprocArg,
12631                                     bool WantCDE);
12632   bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12633                                    CallExpr *TheCall);
12634 
12635   bool CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12636                                        CallExpr *TheCall);
12637   bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12638   bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12639   bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
12640   bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12641                                     CallExpr *TheCall);
12642   bool CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
12643                            CallExpr *TheCall);
12644   bool CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
12645   bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12646   bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
12647   bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
12648   bool CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall);
12649   bool CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
12650                                          ArrayRef<int> ArgNums);
12651   bool CheckX86BuiltinTileDuplicate(CallExpr *TheCall, ArrayRef<int> ArgNums);
12652   bool CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
12653                                             ArrayRef<int> ArgNums);
12654   bool CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12655                                    CallExpr *TheCall);
12656   bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12657                                    CallExpr *TheCall);
12658   bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12659   bool CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum);
12660   bool CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12661                                      CallExpr *TheCall);
12662 
12663   bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
12664   bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call);
12665   bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
12666   bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
12667   bool SemaBuiltinComplex(CallExpr *TheCall);
12668   bool SemaBuiltinVSX(CallExpr *TheCall);
12669   bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
12670   bool SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum);
12671 
12672 public:
12673   // Used by C++ template instantiation.
12674   ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
12675   ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
12676                                    SourceLocation BuiltinLoc,
12677                                    SourceLocation RParenLoc);
12678 
12679 private:
12680   bool SemaBuiltinPrefetch(CallExpr *TheCall);
12681   bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
12682   bool SemaBuiltinArithmeticFence(CallExpr *TheCall);
12683   bool SemaBuiltinAssume(CallExpr *TheCall);
12684   bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
12685   bool SemaBuiltinLongjmp(CallExpr *TheCall);
12686   bool SemaBuiltinSetjmp(CallExpr *TheCall);
12687   ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
12688   ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
12689   ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
12690                                      AtomicExpr::AtomicOp Op);
12691   ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
12692                                                     bool IsDelete);
12693   bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
12694                               llvm::APSInt &Result);
12695   bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low,
12696                                    int High, bool RangeIsError = true);
12697   bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
12698                                       unsigned Multiple);
12699   bool SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum);
12700   bool SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
12701                                          unsigned ArgBits);
12702   bool SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum,
12703                                                unsigned ArgBits);
12704   bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
12705                                 int ArgNum, unsigned ExpectedFieldNum,
12706                                 bool AllowName);
12707   bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall);
12708   bool SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID,
12709                              const char *TypeDesc);
12710 
12711   bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc);
12712 
12713   // Matrix builtin handling.
12714   ExprResult SemaBuiltinMatrixTranspose(CallExpr *TheCall,
12715                                         ExprResult CallResult);
12716   ExprResult SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
12717                                               ExprResult CallResult);
12718   ExprResult SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
12719                                                ExprResult CallResult);
12720 
12721 public:
12722   enum FormatStringType {
12723     FST_Scanf,
12724     FST_Printf,
12725     FST_NSString,
12726     FST_Strftime,
12727     FST_Strfmon,
12728     FST_Kprintf,
12729     FST_FreeBSDKPrintf,
12730     FST_OSTrace,
12731     FST_OSLog,
12732     FST_Unknown
12733   };
12734   static FormatStringType GetFormatStringType(const FormatAttr *Format);
12735 
12736   bool FormatStringHasSArg(const StringLiteral *FExpr);
12737 
12738   static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
12739 
12740 private:
12741   bool CheckFormatArguments(const FormatAttr *Format,
12742                             ArrayRef<const Expr *> Args,
12743                             bool IsCXXMember,
12744                             VariadicCallType CallType,
12745                             SourceLocation Loc, SourceRange Range,
12746                             llvm::SmallBitVector &CheckedVarArgs);
12747   bool CheckFormatArguments(ArrayRef<const Expr *> Args,
12748                             bool HasVAListArg, unsigned format_idx,
12749                             unsigned firstDataArg, FormatStringType Type,
12750                             VariadicCallType CallType,
12751                             SourceLocation Loc, SourceRange range,
12752                             llvm::SmallBitVector &CheckedVarArgs);
12753 
12754   void CheckAbsoluteValueFunction(const CallExpr *Call,
12755                                   const FunctionDecl *FDecl);
12756 
12757   void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
12758 
12759   void CheckMemaccessArguments(const CallExpr *Call,
12760                                unsigned BId,
12761                                IdentifierInfo *FnName);
12762 
12763   void CheckStrlcpycatArguments(const CallExpr *Call,
12764                                 IdentifierInfo *FnName);
12765 
12766   void CheckStrncatArguments(const CallExpr *Call,
12767                              IdentifierInfo *FnName);
12768 
12769   void CheckFreeArguments(const CallExpr *E);
12770 
12771   void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
12772                           SourceLocation ReturnLoc,
12773                           bool isObjCMethod = false,
12774                           const AttrVec *Attrs = nullptr,
12775                           const FunctionDecl *FD = nullptr);
12776 
12777 public:
12778   void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS);
12779 
12780 private:
12781   void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
12782   void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
12783   void CheckForIntOverflow(Expr *E);
12784   void CheckUnsequencedOperations(const Expr *E);
12785 
12786   /// Perform semantic checks on a completed expression. This will either
12787   /// be a full-expression or a default argument expression.
12788   void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
12789                           bool IsConstexpr = false);
12790 
12791   void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
12792                                    Expr *Init);
12793 
12794   /// Check if there is a field shadowing.
12795   void CheckShadowInheritedFields(const SourceLocation &Loc,
12796                                   DeclarationName FieldName,
12797                                   const CXXRecordDecl *RD,
12798                                   bool DeclIsField = true);
12799 
12800   /// Check if the given expression contains 'break' or 'continue'
12801   /// statement that produces control flow different from GCC.
12802   void CheckBreakContinueBinding(Expr *E);
12803 
12804   /// Check whether receiver is mutable ObjC container which
12805   /// attempts to add itself into the container
12806   void CheckObjCCircularContainer(ObjCMessageExpr *Message);
12807 
12808   void CheckTCBEnforcement(const CallExpr *TheCall, const FunctionDecl *Callee);
12809 
12810   void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
12811   void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
12812                                  bool DeleteWasArrayForm);
12813 public:
12814   /// Register a magic integral constant to be used as a type tag.
12815   void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12816                                   uint64_t MagicValue, QualType Type,
12817                                   bool LayoutCompatible, bool MustBeNull);
12818 
12819   struct TypeTagData {
TypeTagDataTypeTagData12820     TypeTagData() {}
12821 
TypeTagDataTypeTagData12822     TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
12823         Type(Type), LayoutCompatible(LayoutCompatible),
12824         MustBeNull(MustBeNull)
12825     {}
12826 
12827     QualType Type;
12828 
12829     /// If true, \c Type should be compared with other expression's types for
12830     /// layout-compatibility.
12831     unsigned LayoutCompatible : 1;
12832     unsigned MustBeNull : 1;
12833   };
12834 
12835   /// A pair of ArgumentKind identifier and magic value.  This uniquely
12836   /// identifies the magic value.
12837   typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
12838 
12839 private:
12840   /// A map from magic value to type information.
12841   std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
12842       TypeTagForDatatypeMagicValues;
12843 
12844   /// Peform checks on a call of a function with argument_with_type_tag
12845   /// or pointer_with_type_tag attributes.
12846   void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
12847                                 const ArrayRef<const Expr *> ExprArgs,
12848                                 SourceLocation CallSiteLoc);
12849 
12850   /// Check if we are taking the address of a packed field
12851   /// as this may be a problem if the pointer value is dereferenced.
12852   void CheckAddressOfPackedMember(Expr *rhs);
12853 
12854   /// The parser's current scope.
12855   ///
12856   /// The parser maintains this state here.
12857   Scope *CurScope;
12858 
12859   mutable IdentifierInfo *Ident_super;
12860   mutable IdentifierInfo *Ident___float128;
12861 
12862   /// Nullability type specifiers.
12863   IdentifierInfo *Ident__Nonnull = nullptr;
12864   IdentifierInfo *Ident__Nullable = nullptr;
12865   IdentifierInfo *Ident__Nullable_result = nullptr;
12866   IdentifierInfo *Ident__Null_unspecified = nullptr;
12867 
12868   IdentifierInfo *Ident_NSError = nullptr;
12869 
12870   /// The handler for the FileChanged preprocessor events.
12871   ///
12872   /// Used for diagnostics that implement custom semantic analysis for #include
12873   /// directives, like -Wpragma-pack.
12874   sema::SemaPPCallbacks *SemaPPCallbackHandler;
12875 
12876 protected:
12877   friend class Parser;
12878   friend class InitializationSequence;
12879   friend class ASTReader;
12880   friend class ASTDeclReader;
12881   friend class ASTWriter;
12882 
12883 public:
12884   /// Retrieve the keyword associated
12885   IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
12886 
12887   /// The struct behind the CFErrorRef pointer.
12888   RecordDecl *CFError = nullptr;
12889   bool isCFError(RecordDecl *D);
12890 
12891   /// Retrieve the identifier "NSError".
12892   IdentifierInfo *getNSErrorIdent();
12893 
12894   /// Retrieve the parser's current scope.
12895   ///
12896   /// This routine must only be used when it is certain that semantic analysis
12897   /// and the parser are in precisely the same context, which is not the case
12898   /// when, e.g., we are performing any kind of template instantiation.
12899   /// Therefore, the only safe places to use this scope are in the parser
12900   /// itself and in routines directly invoked from the parser and *never* from
12901   /// template substitution or instantiation.
getCurScope()12902   Scope *getCurScope() const { return CurScope; }
12903 
incrementMSManglingNumber()12904   void incrementMSManglingNumber() const {
12905     return CurScope->incrementMSManglingNumber();
12906   }
12907 
12908   IdentifierInfo *getSuperIdentifier() const;
12909   IdentifierInfo *getFloat128Identifier() const;
12910 
12911   Decl *getObjCDeclContext() const;
12912 
getCurLexicalContext()12913   DeclContext *getCurLexicalContext() const {
12914     return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
12915   }
12916 
getCurObjCLexicalContext()12917   const DeclContext *getCurObjCLexicalContext() const {
12918     const DeclContext *DC = getCurLexicalContext();
12919     // A category implicitly has the attribute of the interface.
12920     if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
12921       DC = CatD->getClassInterface();
12922     return DC;
12923   }
12924 
12925   /// Determine the number of levels of enclosing template parameters. This is
12926   /// only usable while parsing. Note that this does not include dependent
12927   /// contexts in which no template parameters have yet been declared, such as
12928   /// in a terse function template or generic lambda before the first 'auto' is
12929   /// encountered.
12930   unsigned getTemplateDepth(Scope *S) const;
12931 
12932   /// To be used for checking whether the arguments being passed to
12933   /// function exceeds the number of parameters expected for it.
12934   static bool TooManyArguments(size_t NumParams, size_t NumArgs,
12935                                bool PartialOverloading = false) {
12936     // We check whether we're just after a comma in code-completion.
12937     if (NumArgs > 0 && PartialOverloading)
12938       return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
12939     return NumArgs > NumParams;
12940   }
12941 
12942   // Emitting members of dllexported classes is delayed until the class
12943   // (including field initializers) is fully parsed.
12944   SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
12945   SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions;
12946 
12947 private:
12948   int ParsingClassDepth = 0;
12949 
12950   class SavePendingParsedClassStateRAII {
12951   public:
SavePendingParsedClassStateRAII(Sema & S)12952     SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
12953 
~SavePendingParsedClassStateRAII()12954     ~SavePendingParsedClassStateRAII() {
12955       assert(S.DelayedOverridingExceptionSpecChecks.empty() &&
12956              "there shouldn't be any pending delayed exception spec checks");
12957       assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&
12958              "there shouldn't be any pending delayed exception spec checks");
12959       swapSavedState();
12960     }
12961 
12962   private:
12963     Sema &S;
12964     decltype(DelayedOverridingExceptionSpecChecks)
12965         SavedOverridingExceptionSpecChecks;
12966     decltype(DelayedEquivalentExceptionSpecChecks)
12967         SavedEquivalentExceptionSpecChecks;
12968 
swapSavedState()12969     void swapSavedState() {
12970       SavedOverridingExceptionSpecChecks.swap(
12971           S.DelayedOverridingExceptionSpecChecks);
12972       SavedEquivalentExceptionSpecChecks.swap(
12973           S.DelayedEquivalentExceptionSpecChecks);
12974     }
12975   };
12976 
12977   /// Helper class that collects misaligned member designations and
12978   /// their location info for delayed diagnostics.
12979   struct MisalignedMember {
12980     Expr *E;
12981     RecordDecl *RD;
12982     ValueDecl *MD;
12983     CharUnits Alignment;
12984 
MisalignedMemberMisalignedMember12985     MisalignedMember() : E(), RD(), MD(), Alignment() {}
MisalignedMemberMisalignedMember12986     MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
12987                      CharUnits Alignment)
12988         : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
MisalignedMemberMisalignedMember12989     explicit MisalignedMember(Expr *E)
12990         : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
12991 
12992     bool operator==(const MisalignedMember &m) { return this->E == m.E; }
12993   };
12994   /// Small set of gathered accesses to potentially misaligned members
12995   /// due to the packed attribute.
12996   SmallVector<MisalignedMember, 4> MisalignedMembers;
12997 
12998   /// Adds an expression to the set of gathered misaligned members.
12999   void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
13000                                      CharUnits Alignment);
13001 
13002 public:
13003   /// Diagnoses the current set of gathered accesses. This typically
13004   /// happens at full expression level. The set is cleared after emitting the
13005   /// diagnostics.
13006   void DiagnoseMisalignedMembers();
13007 
13008   /// This function checks if the expression is in the sef of potentially
13009   /// misaligned members and it is converted to some pointer type T with lower
13010   /// or equal alignment requirements. If so it removes it. This is used when
13011   /// we do not want to diagnose such misaligned access (e.g. in conversions to
13012   /// void*).
13013   void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
13014 
13015   /// This function calls Action when it determines that E designates a
13016   /// misaligned member due to the packed attribute. This is used to emit
13017   /// local diagnostics like in reference binding.
13018   void RefersToMemberWithReducedAlignment(
13019       Expr *E,
13020       llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
13021           Action);
13022 
13023   /// Describes the reason a calling convention specification was ignored, used
13024   /// for diagnostics.
13025   enum class CallingConventionIgnoredReason {
13026     ForThisTarget = 0,
13027     VariadicFunction,
13028     ConstructorDestructor,
13029     BuiltinFunction
13030   };
13031   /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
13032   /// context is "used as device code".
13033   ///
13034   /// - If CurLexicalContext is a kernel function or it is known that the
13035   ///   function will be emitted for the device, emits the diagnostics
13036   ///   immediately.
13037   /// - If CurLexicalContext is a function and we are compiling
13038   ///   for the device, but we don't know that this function will be codegen'ed
13039   ///   for devive yet, creates a diagnostic which is emitted if and when we
13040   ///   realize that the function will be codegen'ed.
13041   ///
13042   /// Example usage:
13043   ///
13044   /// Diagnose __float128 type usage only from SYCL device code if the current
13045   /// target doesn't support it
13046   /// if (!S.Context.getTargetInfo().hasFloat128Type() &&
13047   ///     S.getLangOpts().SYCLIsDevice)
13048   ///   SYCLDiagIfDeviceCode(Loc, diag::err_type_unsupported) << "__float128";
13049   SemaDiagnosticBuilder SYCLDiagIfDeviceCode(SourceLocation Loc,
13050                                              unsigned DiagID);
13051 
13052   /// Check whether we're allowed to call Callee from the current context.
13053   ///
13054   /// - If the call is never allowed in a semantically-correct program
13055   ///   emits an error and returns false.
13056   ///
13057   /// - If the call is allowed in semantically-correct programs, but only if
13058   ///   it's never codegen'ed, creates a deferred diagnostic to be emitted if
13059   ///   and when the caller is codegen'ed, and returns true.
13060   ///
13061   /// - Otherwise, returns true without emitting any diagnostics.
13062   ///
13063   /// Adds Callee to DeviceCallGraph if we don't know if its caller will be
13064   /// codegen'ed yet.
13065   bool checkSYCLDeviceFunction(SourceLocation Loc, FunctionDecl *Callee);
13066 };
13067 
13068 /// RAII object that enters a new expression evaluation context.
13069 class EnterExpressionEvaluationContext {
13070   Sema &Actions;
13071   bool Entered = true;
13072 
13073 public:
13074   EnterExpressionEvaluationContext(
13075       Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
13076       Decl *LambdaContextDecl = nullptr,
13077       Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
13078           Sema::ExpressionEvaluationContextRecord::EK_Other,
13079       bool ShouldEnter = true)
Actions(Actions)13080       : Actions(Actions), Entered(ShouldEnter) {
13081     if (Entered)
13082       Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
13083                                               ExprContext);
13084   }
13085   EnterExpressionEvaluationContext(
13086       Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
13087       Sema::ReuseLambdaContextDecl_t,
13088       Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
13089           Sema::ExpressionEvaluationContextRecord::EK_Other)
Actions(Actions)13090       : Actions(Actions) {
13091     Actions.PushExpressionEvaluationContext(
13092         NewContext, Sema::ReuseLambdaContextDecl, ExprContext);
13093   }
13094 
13095   enum InitListTag { InitList };
13096   EnterExpressionEvaluationContext(Sema &Actions, InitListTag,
13097                                    bool ShouldEnter = true)
Actions(Actions)13098       : Actions(Actions), Entered(false) {
13099     // In C++11 onwards, narrowing checks are performed on the contents of
13100     // braced-init-lists, even when they occur within unevaluated operands.
13101     // Therefore we still need to instantiate constexpr functions used in such
13102     // a context.
13103     if (ShouldEnter && Actions.isUnevaluatedContext() &&
13104         Actions.getLangOpts().CPlusPlus11) {
13105       Actions.PushExpressionEvaluationContext(
13106           Sema::ExpressionEvaluationContext::UnevaluatedList);
13107       Entered = true;
13108     }
13109   }
13110 
~EnterExpressionEvaluationContext()13111   ~EnterExpressionEvaluationContext() {
13112     if (Entered)
13113       Actions.PopExpressionEvaluationContext();
13114   }
13115 };
13116 
13117 DeductionFailureInfo
13118 MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
13119                          sema::TemplateDeductionInfo &Info);
13120 
13121 /// Contains a late templated function.
13122 /// Will be parsed at the end of the translation unit, used by Sema & Parser.
13123 struct LateParsedTemplate {
13124   CachedTokens Toks;
13125   /// The template function declaration to be late parsed.
13126   Decl *D;
13127 };
13128 
13129 template <>
13130 void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation,
13131                                                  PragmaMsStackAction Action,
13132                                                  llvm::StringRef StackSlotLabel,
13133                                                  AlignPackInfo Value);
13134 
13135 } // end namespace clang
13136 
13137 namespace llvm {
13138 // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
13139 // SourceLocation.
13140 template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
13141   using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
13142   using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
13143 
13144   static FunctionDeclAndLoc getEmptyKey() {
13145     return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
13146   }
13147 
13148   static FunctionDeclAndLoc getTombstoneKey() {
13149     return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
13150   }
13151 
13152   static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
13153     return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
13154                         FDL.Loc.getHashValue());
13155   }
13156 
13157   static bool isEqual(const FunctionDeclAndLoc &LHS,
13158                       const FunctionDeclAndLoc &RHS) {
13159     return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
13160   }
13161 };
13162 } // namespace llvm
13163 
13164 #endif
13165