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/TypeLoc.h"
36 #include "clang/AST/TypeOrdering.h"
37 #include "clang/Basic/BitmaskEnum.h"
38 #include "clang/Basic/ExpressionTraits.h"
39 #include "clang/Basic/Module.h"
40 #include "clang/Basic/OpenCLOptions.h"
41 #include "clang/Basic/OpenMPKinds.h"
42 #include "clang/Basic/PragmaKinds.h"
43 #include "clang/Basic/Specifiers.h"
44 #include "clang/Basic/TemplateKinds.h"
45 #include "clang/Basic/TypeTraits.h"
46 #include "clang/Sema/AnalysisBasedWarnings.h"
47 #include "clang/Sema/CleanupInfo.h"
48 #include "clang/Sema/DeclSpec.h"
49 #include "clang/Sema/ExternalSemaSource.h"
50 #include "clang/Sema/IdentifierResolver.h"
51 #include "clang/Sema/ObjCMethodList.h"
52 #include "clang/Sema/Ownership.h"
53 #include "clang/Sema/Scope.h"
54 #include "clang/Sema/SemaConcept.h"
55 #include "clang/Sema/TypoCorrection.h"
56 #include "clang/Sema/Weak.h"
57 #include "llvm/ADT/ArrayRef.h"
58 #include "llvm/ADT/Optional.h"
59 #include "llvm/ADT/SetVector.h"
60 #include "llvm/ADT/SmallBitVector.h"
61 #include "llvm/ADT/SmallSet.h"
62 #include "llvm/ADT/SmallPtrSet.h"
63 #include "llvm/ADT/SmallVector.h"
64 #include "llvm/ADT/TinyPtrVector.h"
65 #include "llvm/Frontend/OpenMP/OMPConstants.h"
66 #include <deque>
67 #include <memory>
68 #include <string>
69 #include <tuple>
70 #include <vector>
71 
72 namespace llvm {
73   class APSInt;
74   template <typename ValueT> struct DenseMapInfo;
75   template <typename ValueT, typename ValueInfoT> class DenseSet;
76   class SmallBitVector;
77   struct InlineAsmIdentifierInfo;
78 }
79 
80 namespace clang {
81   class ADLResult;
82   class ASTConsumer;
83   class ASTContext;
84   class ASTMutationListener;
85   class ASTReader;
86   class ASTWriter;
87   class ArrayType;
88   class ParsedAttr;
89   class BindingDecl;
90   class BlockDecl;
91   class CapturedDecl;
92   class CXXBasePath;
93   class CXXBasePaths;
94   class CXXBindTemporaryExpr;
95   typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
96   class CXXConstructorDecl;
97   class CXXConversionDecl;
98   class CXXDeleteExpr;
99   class CXXDestructorDecl;
100   class CXXFieldCollector;
101   class CXXMemberCallExpr;
102   class CXXMethodDecl;
103   class CXXScopeSpec;
104   class CXXTemporary;
105   class CXXTryStmt;
106   class CallExpr;
107   class ClassTemplateDecl;
108   class ClassTemplatePartialSpecializationDecl;
109   class ClassTemplateSpecializationDecl;
110   class VarTemplatePartialSpecializationDecl;
111   class CodeCompleteConsumer;
112   class CodeCompletionAllocator;
113   class CodeCompletionTUInfo;
114   class CodeCompletionResult;
115   class CoroutineBodyStmt;
116   class Decl;
117   class DeclAccessPair;
118   class DeclContext;
119   class DeclRefExpr;
120   class DeclaratorDecl;
121   class DeducedTemplateArgument;
122   class DependentDiagnostic;
123   class DesignatedInitExpr;
124   class Designation;
125   class EnableIfAttr;
126   class EnumConstantDecl;
127   class Expr;
128   class ExtVectorType;
129   class FormatAttr;
130   class FriendDecl;
131   class FunctionDecl;
132   class FunctionProtoType;
133   class FunctionTemplateDecl;
134   class ImplicitConversionSequence;
135   typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
136   class InitListExpr;
137   class InitializationKind;
138   class InitializationSequence;
139   class InitializedEntity;
140   class IntegerLiteral;
141   class LabelStmt;
142   class LambdaExpr;
143   class LangOptions;
144   class LocalInstantiationScope;
145   class LookupResult;
146   class MacroInfo;
147   typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
148   class ModuleLoader;
149   class MultiLevelTemplateArgumentList;
150   class NamedDecl;
151   class ObjCCategoryDecl;
152   class ObjCCategoryImplDecl;
153   class ObjCCompatibleAliasDecl;
154   class ObjCContainerDecl;
155   class ObjCImplDecl;
156   class ObjCImplementationDecl;
157   class ObjCInterfaceDecl;
158   class ObjCIvarDecl;
159   template <class T> class ObjCList;
160   class ObjCMessageExpr;
161   class ObjCMethodDecl;
162   class ObjCPropertyDecl;
163   class ObjCProtocolDecl;
164   class OMPThreadPrivateDecl;
165   class OMPRequiresDecl;
166   class OMPDeclareReductionDecl;
167   class OMPDeclareSimdDecl;
168   class OMPClause;
169   struct OMPVarListLocTy;
170   struct OverloadCandidate;
171   enum class OverloadCandidateParamOrder : char;
172   enum OverloadCandidateRewriteKind : unsigned;
173   class OverloadCandidateSet;
174   class OverloadExpr;
175   class ParenListExpr;
176   class ParmVarDecl;
177   class Preprocessor;
178   class PseudoDestructorTypeStorage;
179   class PseudoObjectExpr;
180   class QualType;
181   class StandardConversionSequence;
182   class Stmt;
183   class StringLiteral;
184   class SwitchStmt;
185   class TemplateArgument;
186   class TemplateArgumentList;
187   class TemplateArgumentLoc;
188   class TemplateDecl;
189   class TemplateInstantiationCallback;
190   class TemplateParameterList;
191   class TemplatePartialOrderingContext;
192   class TemplateTemplateParmDecl;
193   class Token;
194   class TypeAliasDecl;
195   class TypedefDecl;
196   class TypedefNameDecl;
197   class TypeLoc;
198   class TypoCorrectionConsumer;
199   class UnqualifiedId;
200   class UnresolvedLookupExpr;
201   class UnresolvedMemberExpr;
202   class UnresolvedSetImpl;
203   class UnresolvedSetIterator;
204   class UsingDecl;
205   class UsingShadowDecl;
206   class ValueDecl;
207   class VarDecl;
208   class VarTemplateSpecializationDecl;
209   class VisibilityAttr;
210   class VisibleDeclConsumer;
211   class IndirectFieldDecl;
212   struct DeductionFailureInfo;
213   class TemplateSpecCandidateSet;
214 
215 namespace sema {
216   class AccessedEntity;
217   class BlockScopeInfo;
218   class Capture;
219   class CapturedRegionScopeInfo;
220   class CapturingScopeInfo;
221   class CompoundScopeInfo;
222   class DelayedDiagnostic;
223   class DelayedDiagnosticPool;
224   class FunctionScopeInfo;
225   class LambdaScopeInfo;
226   class PossiblyUnreachableDiag;
227   class SemaPPCallbacks;
228   class TemplateDeductionInfo;
229 }
230 
231 namespace threadSafety {
232   class BeforeSet;
233   void threadSafetyCleanup(BeforeSet* Cache);
234 }
235 
236 // FIXME: No way to easily map from TemplateTypeParmTypes to
237 // TemplateTypeParmDecls, so we have this horrible PointerUnion.
238 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
239                   SourceLocation> UnexpandedParameterPack;
240 
241 /// Describes whether we've seen any nullability information for the given
242 /// file.
243 struct FileNullability {
244   /// The first pointer declarator (of any pointer kind) in the file that does
245   /// not have a corresponding nullability annotation.
246   SourceLocation PointerLoc;
247 
248   /// The end location for the first pointer declarator in the file. Used for
249   /// placing fix-its.
250   SourceLocation PointerEndLoc;
251 
252   /// Which kind of pointer declarator we saw.
253   uint8_t PointerKind;
254 
255   /// Whether we saw any type nullability annotations in the given file.
256   bool SawTypeNullability = false;
257 };
258 
259 /// A mapping from file IDs to a record of whether we've seen nullability
260 /// information in that file.
261 class FileNullabilityMap {
262   /// A mapping from file IDs to the nullability information for each file ID.
263   llvm::DenseMap<FileID, FileNullability> Map;
264 
265   /// A single-element cache based on the file ID.
266   struct {
267     FileID File;
268     FileNullability Nullability;
269   } Cache;
270 
271 public:
272   FileNullability &operator[](FileID file) {
273     // Check the single-element cache.
274     if (file == Cache.File)
275       return Cache.Nullability;
276 
277     // It's not in the single-element cache; flush the cache if we have one.
278     if (!Cache.File.isInvalid()) {
279       Map[Cache.File] = Cache.Nullability;
280     }
281 
282     // Pull this entry into the cache.
283     Cache.File = file;
284     Cache.Nullability = Map[file];
285     return Cache.Nullability;
286   }
287 };
288 
289 /// Keeps track of expected type during expression parsing. The type is tied to
290 /// a particular token, all functions that update or consume the type take a
291 /// start location of the token they are looking at as a parameter. This allows
292 /// to avoid updating the type on hot paths in the parser.
293 class PreferredTypeBuilder {
294 public:
295   PreferredTypeBuilder() = default;
PreferredTypeBuilder(QualType Type)296   explicit PreferredTypeBuilder(QualType Type) : Type(Type) {}
297 
298   void enterCondition(Sema &S, SourceLocation Tok);
299   void enterReturn(Sema &S, SourceLocation Tok);
300   void enterVariableInit(SourceLocation Tok, Decl *D);
301   /// Computing a type for the function argument may require running
302   /// overloading, so we postpone its computation until it is actually needed.
303   ///
304   /// Clients should be very careful when using this funciton, as it stores a
305   /// function_ref, clients should make sure all calls to get() with the same
306   /// location happen while function_ref is alive.
307   void enterFunctionArgument(SourceLocation Tok,
308                              llvm::function_ref<QualType()> ComputeType);
309 
310   void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
311   void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
312                   SourceLocation OpLoc);
313   void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
314   void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
315   void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
316   /// Handles all type casts, including C-style cast, C++ casts, etc.
317   void enterTypeCast(SourceLocation Tok, QualType CastType);
318 
get(SourceLocation Tok)319   QualType get(SourceLocation Tok) const {
320     if (Tok != ExpectedLoc)
321       return QualType();
322     if (!Type.isNull())
323       return Type;
324     if (ComputeType)
325       return ComputeType();
326     return QualType();
327   }
328 
329 private:
330   /// Start position of a token for which we store expected type.
331   SourceLocation ExpectedLoc;
332   /// Expected type for a token starting at ExpectedLoc.
333   QualType Type;
334   /// A function to compute expected type at ExpectedLoc. It is only considered
335   /// if Type is null.
336   llvm::function_ref<QualType()> ComputeType;
337 };
338 
339 /// Sema - This implements semantic analysis and AST building for C.
340 class Sema final {
341   Sema(const Sema &) = delete;
342   void operator=(const Sema &) = delete;
343 
344   /// A key method to reduce duplicate debug info from Sema.
345   virtual void anchor();
346 
347   ///Source of additional semantic information.
348   ExternalSemaSource *ExternalSource;
349 
350   ///Whether Sema has generated a multiplexer and has to delete it.
351   bool isMultiplexExternalSource;
352 
353   static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
354 
355   bool isVisibleSlow(const NamedDecl *D);
356 
357   /// Determine whether two declarations should be linked together, given that
358   /// the old declaration might not be visible and the new declaration might
359   /// not have external linkage.
shouldLinkPossiblyHiddenDecl(const NamedDecl * Old,const NamedDecl * New)360   bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
361                                     const NamedDecl *New) {
362     if (isVisible(Old))
363      return true;
364     // See comment in below overload for why it's safe to compute the linkage
365     // of the new declaration here.
366     if (New->isExternallyDeclarable()) {
367       assert(Old->isExternallyDeclarable() &&
368              "should not have found a non-externally-declarable previous decl");
369       return true;
370     }
371     return false;
372   }
373   bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
374 
375   void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
376                                       QualType ResultTy,
377                                       ArrayRef<QualType> Args);
378 
379 public:
380   /// The maximum alignment, same as in llvm::Value. We duplicate them here
381   /// because that allows us not to duplicate the constants in clang code,
382   /// which we must to since we can't directly use the llvm constants.
383   /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
384   ///
385   /// This is the greatest alignment value supported by load, store, and alloca
386   /// instructions, and global values.
387   static const unsigned MaxAlignmentExponent = 29;
388   static const unsigned MaximumAlignment = 1u << MaxAlignmentExponent;
389 
390   typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
391   typedef OpaquePtr<TemplateName> TemplateTy;
392   typedef OpaquePtr<QualType> TypeTy;
393 
394   OpenCLOptions OpenCLFeatures;
395   FPOptions CurFPFeatures;
396 
397   const LangOptions &LangOpts;
398   Preprocessor &PP;
399   ASTContext &Context;
400   ASTConsumer &Consumer;
401   DiagnosticsEngine &Diags;
402   SourceManager &SourceMgr;
403 
404   /// Flag indicating whether or not to collect detailed statistics.
405   bool CollectStats;
406 
407   /// Code-completion consumer.
408   CodeCompleteConsumer *CodeCompleter;
409 
410   /// CurContext - This is the current declaration context of parsing.
411   DeclContext *CurContext;
412 
413   /// Generally null except when we temporarily switch decl contexts,
414   /// like in \see ActOnObjCTemporaryExitContainerContext.
415   DeclContext *OriginalLexicalContext;
416 
417   /// VAListTagName - The declaration name corresponding to __va_list_tag.
418   /// This is used as part of a hack to omit that class from ADL results.
419   DeclarationName VAListTagName;
420 
421   bool MSStructPragmaOn; // True when \#pragma ms_struct on
422 
423   /// Controls member pointer representation format under the MS ABI.
424   LangOptions::PragmaMSPointersToMembersKind
425       MSPointerToMemberRepresentationMethod;
426 
427   /// Stack of active SEH __finally scopes.  Can be empty.
428   SmallVector<Scope*, 2> CurrentSEHFinally;
429 
430   /// Source location for newly created implicit MSInheritanceAttrs
431   SourceLocation ImplicitMSInheritanceAttrLoc;
432 
433   /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
434   /// `TransformTypos` in order to keep track of any TypoExprs that are created
435   /// recursively during typo correction and wipe them away if the correction
436   /// fails.
437   llvm::SmallVector<TypoExpr *, 2> TypoExprs;
438 
439   /// pragma clang section kind
440   enum PragmaClangSectionKind {
441     PCSK_Invalid      = 0,
442     PCSK_BSS          = 1,
443     PCSK_Data         = 2,
444     PCSK_Rodata       = 3,
445     PCSK_Text         = 4,
446     PCSK_Relro        = 5
447    };
448 
449   enum PragmaClangSectionAction {
450     PCSA_Set     = 0,
451     PCSA_Clear   = 1
452   };
453 
454   struct PragmaClangSection {
455     std::string SectionName;
456     bool Valid = false;
457     SourceLocation PragmaLocation;
458 
459     void Act(SourceLocation PragmaLocation,
460              PragmaClangSectionAction Action,
461              StringLiteral* Name);
462    };
463 
464    PragmaClangSection PragmaClangBSSSection;
465    PragmaClangSection PragmaClangDataSection;
466    PragmaClangSection PragmaClangRodataSection;
467    PragmaClangSection PragmaClangRelroSection;
468    PragmaClangSection PragmaClangTextSection;
469 
470   enum PragmaMsStackAction {
471     PSK_Reset     = 0x0,                // #pragma ()
472     PSK_Set       = 0x1,                // #pragma (value)
473     PSK_Push      = 0x2,                // #pragma (push[, id])
474     PSK_Pop       = 0x4,                // #pragma (pop[, id])
475     PSK_Show      = 0x8,                // #pragma (show) -- only for "pack"!
476     PSK_Push_Set  = PSK_Push | PSK_Set, // #pragma (push[, id], value)
477     PSK_Pop_Set   = PSK_Pop | PSK_Set,  // #pragma (pop[, id], value)
478   };
479 
480   template<typename ValueType>
481   struct PragmaStack {
482     struct Slot {
483       llvm::StringRef StackSlotLabel;
484       ValueType Value;
485       SourceLocation PragmaLocation;
486       SourceLocation PragmaPushLocation;
SlotPragmaStack::Slot487       Slot(llvm::StringRef StackSlotLabel, ValueType Value,
488            SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
489           : StackSlotLabel(StackSlotLabel), Value(Value),
490             PragmaLocation(PragmaLocation),
491             PragmaPushLocation(PragmaPushLocation) {}
492     };
493 
ActPragmaStack494     void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
495              llvm::StringRef StackSlotLabel, ValueType Value) {
496       if (Action == PSK_Reset) {
497         CurrentValue = DefaultValue;
498         CurrentPragmaLocation = PragmaLocation;
499         return;
500       }
501       if (Action & PSK_Push)
502         Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
503                            PragmaLocation);
504       else if (Action & PSK_Pop) {
505         if (!StackSlotLabel.empty()) {
506           // If we've got a label, try to find it and jump there.
507           auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
508             return x.StackSlotLabel == StackSlotLabel;
509           });
510           // If we found the label so pop from there.
511           if (I != Stack.rend()) {
512             CurrentValue = I->Value;
513             CurrentPragmaLocation = I->PragmaLocation;
514             Stack.erase(std::prev(I.base()), Stack.end());
515           }
516         } else if (!Stack.empty()) {
517           // We do not have a label, just pop the last entry.
518           CurrentValue = Stack.back().Value;
519           CurrentPragmaLocation = Stack.back().PragmaLocation;
520           Stack.pop_back();
521         }
522       }
523       if (Action & PSK_Set) {
524         CurrentValue = Value;
525         CurrentPragmaLocation = PragmaLocation;
526       }
527     }
528 
529     // MSVC seems to add artificial slots to #pragma stacks on entering a C++
530     // method body to restore the stacks on exit, so it works like this:
531     //
532     //   struct S {
533     //     #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
534     //     void Method {}
535     //     #pragma <name>(pop, InternalPragmaSlot)
536     //   };
537     //
538     // It works even with #pragma vtordisp, although MSVC doesn't support
539     //   #pragma vtordisp(push [, id], n)
540     // syntax.
541     //
542     // Push / pop a named sentinel slot.
SentinelActionPragmaStack543     void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
544       assert((Action == PSK_Push || Action == PSK_Pop) &&
545              "Can only push / pop #pragma stack sentinels!");
546       Act(CurrentPragmaLocation, Action, Label, CurrentValue);
547     }
548 
549     // Constructors.
PragmaStackPragmaStack550     explicit PragmaStack(const ValueType &Default)
551         : DefaultValue(Default), CurrentValue(Default) {}
552 
hasValuePragmaStack553     bool hasValue() const { return CurrentValue != DefaultValue; }
554 
555     SmallVector<Slot, 2> Stack;
556     ValueType DefaultValue; // Value used for PSK_Reset action.
557     ValueType CurrentValue;
558     SourceLocation CurrentPragmaLocation;
559   };
560   // FIXME: We should serialize / deserialize these if they occur in a PCH (but
561   // we shouldn't do so if they're in a module).
562 
563   /// Whether to insert vtordisps prior to virtual bases in the Microsoft
564   /// C++ ABI.  Possible values are 0, 1, and 2, which mean:
565   ///
566   /// 0: Suppress all vtordisps
567   /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
568   ///    structors
569   /// 2: Always insert vtordisps to support RTTI on partially constructed
570   ///    objects
571   PragmaStack<MSVtorDispMode> VtorDispStack;
572   // #pragma pack.
573   // Sentinel to represent when the stack is set to mac68k alignment.
574   static const unsigned kMac68kAlignmentSentinel = ~0U;
575   PragmaStack<unsigned> PackStack;
576   // The current #pragma pack values and locations at each #include.
577   struct PackIncludeState {
578     unsigned CurrentValue;
579     SourceLocation CurrentPragmaLocation;
580     bool HasNonDefaultValue, ShouldWarnOnInclude;
581   };
582   SmallVector<PackIncludeState, 8> PackIncludeStack;
583   // Segment #pragmas.
584   PragmaStack<StringLiteral *> DataSegStack;
585   PragmaStack<StringLiteral *> BSSSegStack;
586   PragmaStack<StringLiteral *> ConstSegStack;
587   PragmaStack<StringLiteral *> CodeSegStack;
588 
589   // This stack tracks the current state of Sema.CurFPFeatures.
590   PragmaStack<unsigned> FpPragmaStack;
CurFPFeatureOverrides()591   FPOptionsOverride CurFPFeatureOverrides() {
592     FPOptionsOverride result;
593     if (!FpPragmaStack.hasValue()) {
594       result = FPOptionsOverride();
595     } else {
596       result = FPOptionsOverride(FpPragmaStack.CurrentValue);
597     }
598     return result;
599   }
600 
601   // RAII object to push / pop sentinel slots for all MS #pragma stacks.
602   // Actions should be performed only if we enter / exit a C++ method body.
603   class PragmaStackSentinelRAII {
604   public:
605     PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
606     ~PragmaStackSentinelRAII();
607 
608   private:
609     Sema &S;
610     StringRef SlotLabel;
611     bool ShouldAct;
612   };
613 
614   /// A mapping that describes the nullability we've seen in each header file.
615   FileNullabilityMap NullabilityMap;
616 
617   /// Last section used with #pragma init_seg.
618   StringLiteral *CurInitSeg;
619   SourceLocation CurInitSegLoc;
620 
621   /// VisContext - Manages the stack for \#pragma GCC visibility.
622   void *VisContext; // Really a "PragmaVisStack*"
623 
624   /// This an attribute introduced by \#pragma clang attribute.
625   struct PragmaAttributeEntry {
626     SourceLocation Loc;
627     ParsedAttr *Attribute;
628     SmallVector<attr::SubjectMatchRule, 4> MatchRules;
629     bool IsUsed;
630   };
631 
632   /// A push'd group of PragmaAttributeEntries.
633   struct PragmaAttributeGroup {
634     /// The location of the push attribute.
635     SourceLocation Loc;
636     /// The namespace of this push group.
637     const IdentifierInfo *Namespace;
638     SmallVector<PragmaAttributeEntry, 2> Entries;
639   };
640 
641   SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
642 
643   /// The declaration that is currently receiving an attribute from the
644   /// #pragma attribute stack.
645   const Decl *PragmaAttributeCurrentTargetDecl;
646 
647   /// This represents the last location of a "#pragma clang optimize off"
648   /// directive if such a directive has not been closed by an "on" yet. If
649   /// optimizations are currently "on", this is set to an invalid location.
650   SourceLocation OptimizeOffPragmaLocation;
651 
652   /// Flag indicating if Sema is building a recovery call expression.
653   ///
654   /// This flag is used to avoid building recovery call expressions
655   /// if Sema is already doing so, which would cause infinite recursions.
656   bool IsBuildingRecoveryCallExpr;
657 
658   /// Used to control the generation of ExprWithCleanups.
659   CleanupInfo Cleanup;
660 
661   /// ExprCleanupObjects - This is the stack of objects requiring
662   /// cleanup that are created by the current full expression.
663   SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects;
664 
665   /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
666   /// to a variable (constant) that may or may not be odr-used in this Expr, and
667   /// we won't know until all lvalue-to-rvalue and discarded value conversions
668   /// have been applied to all subexpressions of the enclosing full expression.
669   /// This is cleared at the end of each full expression.
670   using MaybeODRUseExprSet = llvm::SetVector<Expr *, SmallVector<Expr *, 4>,
671                                              llvm::SmallPtrSet<Expr *, 4>>;
672   MaybeODRUseExprSet MaybeODRUseExprs;
673 
674   std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
675 
676   /// Stack containing information about each of the nested
677   /// function, block, and method scopes that are currently active.
678   SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
679 
680   /// The index of the first FunctionScope that corresponds to the current
681   /// context.
682   unsigned FunctionScopesStart = 0;
683 
getFunctionScopes()684   ArrayRef<sema::FunctionScopeInfo*> getFunctionScopes() const {
685     return llvm::makeArrayRef(FunctionScopes.begin() + FunctionScopesStart,
686                               FunctionScopes.end());
687   }
688 
689   /// Stack containing information needed when in C++2a an 'auto' is encountered
690   /// in a function declaration parameter type specifier in order to invent a
691   /// corresponding template parameter in the enclosing abbreviated function
692   /// template. This information is also present in LambdaScopeInfo, stored in
693   /// the FunctionScopes stack.
694   SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos;
695 
696   /// The index of the first InventedParameterInfo that refers to the current
697   /// context.
698   unsigned InventedParameterInfosStart = 0;
699 
getInventedParameterInfos()700   ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const {
701     return llvm::makeArrayRef(InventedParameterInfos.begin() +
702                                   InventedParameterInfosStart,
703                               InventedParameterInfos.end());
704   }
705 
706   typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
707                      &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
708     ExtVectorDeclsType;
709 
710   /// ExtVectorDecls - This is a list all the extended vector types. This allows
711   /// us to associate a raw vector type with one of the ext_vector type names.
712   /// This is only necessary for issuing pretty diagnostics.
713   ExtVectorDeclsType ExtVectorDecls;
714 
715   /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
716   std::unique_ptr<CXXFieldCollector> FieldCollector;
717 
718   typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType;
719 
720   /// Set containing all declared private fields that are not used.
721   NamedDeclSetType UnusedPrivateFields;
722 
723   /// Set containing all typedefs that are likely unused.
724   llvm::SmallSetVector<const TypedefNameDecl *, 4>
725       UnusedLocalTypedefNameCandidates;
726 
727   /// Delete-expressions to be analyzed at the end of translation unit
728   ///
729   /// This list contains class members, and locations of delete-expressions
730   /// that could not be proven as to whether they mismatch with new-expression
731   /// used in initializer of the field.
732   typedef std::pair<SourceLocation, bool> DeleteExprLoc;
733   typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
734   llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
735 
736   typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
737 
738   /// PureVirtualClassDiagSet - a set of class declarations which we have
739   /// emitted a list of pure virtual functions. Used to prevent emitting the
740   /// same list more than once.
741   std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
742 
743   /// ParsingInitForAutoVars - a set of declarations with auto types for which
744   /// we are currently parsing the initializer.
745   llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
746 
747   /// Look for a locally scoped extern "C" declaration by the given name.
748   NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
749 
750   typedef LazyVector<VarDecl *, ExternalSemaSource,
751                      &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
752     TentativeDefinitionsType;
753 
754   /// All the tentative definitions encountered in the TU.
755   TentativeDefinitionsType TentativeDefinitions;
756 
757   /// All the external declarations encoutered and used in the TU.
758   SmallVector<VarDecl *, 4> ExternalDeclarations;
759 
760   typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
761                      &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
762     UnusedFileScopedDeclsType;
763 
764   /// The set of file scoped decls seen so far that have not been used
765   /// and must warn if not used. Only contains the first declaration.
766   UnusedFileScopedDeclsType UnusedFileScopedDecls;
767 
768   typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
769                      &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
770     DelegatingCtorDeclsType;
771 
772   /// All the delegating constructors seen so far in the file, used for
773   /// cycle detection at the end of the TU.
774   DelegatingCtorDeclsType DelegatingCtorDecls;
775 
776   /// All the overriding functions seen during a class definition
777   /// that had their exception spec checks delayed, plus the overridden
778   /// function.
779   SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
780     DelayedOverridingExceptionSpecChecks;
781 
782   /// All the function redeclarations seen during a class definition that had
783   /// their exception spec checks delayed, plus the prior declaration they
784   /// should be checked against. Except during error recovery, the new decl
785   /// should always be a friend declaration, as that's the only valid way to
786   /// redeclare a special member before its class is complete.
787   SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2>
788     DelayedEquivalentExceptionSpecChecks;
789 
790   typedef llvm::MapVector<const FunctionDecl *,
791                           std::unique_ptr<LateParsedTemplate>>
792       LateParsedTemplateMapT;
793   LateParsedTemplateMapT LateParsedTemplateMap;
794 
795   /// Callback to the parser to parse templated functions when needed.
796   typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
797   typedef void LateTemplateParserCleanupCB(void *P);
798   LateTemplateParserCB *LateTemplateParser;
799   LateTemplateParserCleanupCB *LateTemplateParserCleanup;
800   void *OpaqueParser;
801 
SetLateTemplateParser(LateTemplateParserCB * LTP,LateTemplateParserCleanupCB * LTPCleanup,void * P)802   void SetLateTemplateParser(LateTemplateParserCB *LTP,
803                              LateTemplateParserCleanupCB *LTPCleanup,
804                              void *P) {
805     LateTemplateParser = LTP;
806     LateTemplateParserCleanup = LTPCleanup;
807     OpaqueParser = P;
808   }
809 
810   class DelayedDiagnostics;
811 
812   class DelayedDiagnosticsState {
813     sema::DelayedDiagnosticPool *SavedPool;
814     friend class Sema::DelayedDiagnostics;
815   };
816   typedef DelayedDiagnosticsState ParsingDeclState;
817   typedef DelayedDiagnosticsState ProcessingContextState;
818 
819   /// A class which encapsulates the logic for delaying diagnostics
820   /// during parsing and other processing.
821   class DelayedDiagnostics {
822     /// The current pool of diagnostics into which delayed
823     /// diagnostics should go.
824     sema::DelayedDiagnosticPool *CurPool;
825 
826   public:
DelayedDiagnostics()827     DelayedDiagnostics() : CurPool(nullptr) {}
828 
829     /// Adds a delayed diagnostic.
830     void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
831 
832     /// Determines whether diagnostics should be delayed.
shouldDelayDiagnostics()833     bool shouldDelayDiagnostics() { return CurPool != nullptr; }
834 
835     /// Returns the current delayed-diagnostics pool.
getCurrentPool()836     sema::DelayedDiagnosticPool *getCurrentPool() const {
837       return CurPool;
838     }
839 
840     /// Enter a new scope.  Access and deprecation diagnostics will be
841     /// collected in this pool.
push(sema::DelayedDiagnosticPool & pool)842     DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
843       DelayedDiagnosticsState state;
844       state.SavedPool = CurPool;
845       CurPool = &pool;
846       return state;
847     }
848 
849     /// Leave a delayed-diagnostic state that was previously pushed.
850     /// Do not emit any of the diagnostics.  This is performed as part
851     /// of the bookkeeping of popping a pool "properly".
popWithoutEmitting(DelayedDiagnosticsState state)852     void popWithoutEmitting(DelayedDiagnosticsState state) {
853       CurPool = state.SavedPool;
854     }
855 
856     /// Enter a new scope where access and deprecation diagnostics are
857     /// not delayed.
pushUndelayed()858     DelayedDiagnosticsState pushUndelayed() {
859       DelayedDiagnosticsState state;
860       state.SavedPool = CurPool;
861       CurPool = nullptr;
862       return state;
863     }
864 
865     /// Undo a previous pushUndelayed().
popUndelayed(DelayedDiagnosticsState state)866     void popUndelayed(DelayedDiagnosticsState state) {
867       assert(CurPool == nullptr);
868       CurPool = state.SavedPool;
869     }
870   } DelayedDiagnostics;
871 
872   /// A RAII object to temporarily push a declaration context.
873   class ContextRAII {
874   private:
875     Sema &S;
876     DeclContext *SavedContext;
877     ProcessingContextState SavedContextState;
878     QualType SavedCXXThisTypeOverride;
879     unsigned SavedFunctionScopesStart;
880     unsigned SavedInventedParameterInfosStart;
881 
882   public:
883     ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
S(S)884       : S(S), SavedContext(S.CurContext),
885         SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
886         SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
887         SavedFunctionScopesStart(S.FunctionScopesStart),
888         SavedInventedParameterInfosStart(S.InventedParameterInfosStart)
889     {
890       assert(ContextToPush && "pushing null context");
891       S.CurContext = ContextToPush;
892       if (NewThisContext)
893         S.CXXThisTypeOverride = QualType();
894       // Any saved FunctionScopes do not refer to this context.
895       S.FunctionScopesStart = S.FunctionScopes.size();
896       S.InventedParameterInfosStart = S.InventedParameterInfos.size();
897     }
898 
pop()899     void pop() {
900       if (!SavedContext) return;
901       S.CurContext = SavedContext;
902       S.DelayedDiagnostics.popUndelayed(SavedContextState);
903       S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
904       S.FunctionScopesStart = SavedFunctionScopesStart;
905       S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
906       SavedContext = nullptr;
907     }
908 
~ContextRAII()909     ~ContextRAII() {
910       pop();
911     }
912   };
913 
914   /// Whether the AST is currently being rebuilt to correct immediate
915   /// invocations. Immediate invocation candidates and references to consteval
916   /// functions aren't tracked when this is set.
917   bool RebuildingImmediateInvocation = false;
918 
919   /// Used to change context to isConstantEvaluated without pushing a heavy
920   /// ExpressionEvaluationContextRecord object.
921   bool isConstantEvaluatedOverride;
922 
isConstantEvaluated()923   bool isConstantEvaluated() {
924     return ExprEvalContexts.back().isConstantEvaluated() ||
925            isConstantEvaluatedOverride;
926   }
927 
928   /// RAII object to handle the state changes required to synthesize
929   /// a function body.
930   class SynthesizedFunctionScope {
931     Sema &S;
932     Sema::ContextRAII SavedContext;
933     bool PushedCodeSynthesisContext = false;
934 
935   public:
SynthesizedFunctionScope(Sema & S,DeclContext * DC)936     SynthesizedFunctionScope(Sema &S, DeclContext *DC)
937         : S(S), SavedContext(S, DC) {
938       S.PushFunctionScope();
939       S.PushExpressionEvaluationContext(
940           Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
941       if (auto *FD = dyn_cast<FunctionDecl>(DC))
942         FD->setWillHaveBody(true);
943       else
944         assert(isa<ObjCMethodDecl>(DC));
945     }
946 
addContextNote(SourceLocation UseLoc)947     void addContextNote(SourceLocation UseLoc) {
948       assert(!PushedCodeSynthesisContext);
949 
950       Sema::CodeSynthesisContext Ctx;
951       Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
952       Ctx.PointOfInstantiation = UseLoc;
953       Ctx.Entity = cast<Decl>(S.CurContext);
954       S.pushCodeSynthesisContext(Ctx);
955 
956       PushedCodeSynthesisContext = true;
957     }
958 
~SynthesizedFunctionScope()959     ~SynthesizedFunctionScope() {
960       if (PushedCodeSynthesisContext)
961         S.popCodeSynthesisContext();
962       if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
963         FD->setWillHaveBody(false);
964       S.PopExpressionEvaluationContext();
965       S.PopFunctionScopeInfo();
966     }
967   };
968 
969   /// WeakUndeclaredIdentifiers - Identifiers contained in
970   /// \#pragma weak before declared. rare. may alias another
971   /// identifier, declared or undeclared
972   llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
973 
974   /// ExtnameUndeclaredIdentifiers - Identifiers contained in
975   /// \#pragma redefine_extname before declared.  Used in Solaris system headers
976   /// to define functions that occur in multiple standards to call the version
977   /// in the currently selected standard.
978   llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
979 
980 
981   /// Load weak undeclared identifiers from the external source.
982   void LoadExternalWeakUndeclaredIdentifiers();
983 
984   /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
985   /// \#pragma weak during processing of other Decls.
986   /// I couldn't figure out a clean way to generate these in-line, so
987   /// we store them here and handle separately -- which is a hack.
988   /// It would be best to refactor this.
989   SmallVector<Decl*,2> WeakTopLevelDecl;
990 
991   IdentifierResolver IdResolver;
992 
993   /// Translation Unit Scope - useful to Objective-C actions that need
994   /// to lookup file scope declarations in the "ordinary" C decl namespace.
995   /// For example, user-defined classes, built-in "id" type, etc.
996   Scope *TUScope;
997 
998   /// The C++ "std" namespace, where the standard library resides.
999   LazyDeclPtr StdNamespace;
1000 
1001   /// The C++ "std::bad_alloc" class, which is defined by the C++
1002   /// standard library.
1003   LazyDeclPtr StdBadAlloc;
1004 
1005   /// The C++ "std::align_val_t" enum class, which is defined by the C++
1006   /// standard library.
1007   LazyDeclPtr StdAlignValT;
1008 
1009   /// The C++ "std::experimental" namespace, where the experimental parts
1010   /// of the standard library resides.
1011   NamespaceDecl *StdExperimentalNamespaceCache;
1012 
1013   /// The C++ "std::initializer_list" template, which is defined in
1014   /// \<initializer_list>.
1015   ClassTemplateDecl *StdInitializerList;
1016 
1017   /// The C++ "std::coroutine_traits" template, which is defined in
1018   /// \<coroutine_traits>
1019   ClassTemplateDecl *StdCoroutineTraitsCache;
1020 
1021   /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
1022   RecordDecl *CXXTypeInfoDecl;
1023 
1024   /// The MSVC "_GUID" struct, which is defined in MSVC header files.
1025   RecordDecl *MSVCGuidDecl;
1026 
1027   /// Caches identifiers/selectors for NSFoundation APIs.
1028   std::unique_ptr<NSAPI> NSAPIObj;
1029 
1030   /// The declaration of the Objective-C NSNumber class.
1031   ObjCInterfaceDecl *NSNumberDecl;
1032 
1033   /// The declaration of the Objective-C NSValue class.
1034   ObjCInterfaceDecl *NSValueDecl;
1035 
1036   /// Pointer to NSNumber type (NSNumber *).
1037   QualType NSNumberPointer;
1038 
1039   /// Pointer to NSValue type (NSValue *).
1040   QualType NSValuePointer;
1041 
1042   /// The Objective-C NSNumber methods used to create NSNumber literals.
1043   ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
1044 
1045   /// The declaration of the Objective-C NSString class.
1046   ObjCInterfaceDecl *NSStringDecl;
1047 
1048   /// Pointer to NSString type (NSString *).
1049   QualType NSStringPointer;
1050 
1051   /// The declaration of the stringWithUTF8String: method.
1052   ObjCMethodDecl *StringWithUTF8StringMethod;
1053 
1054   /// The declaration of the valueWithBytes:objCType: method.
1055   ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
1056 
1057   /// The declaration of the Objective-C NSArray class.
1058   ObjCInterfaceDecl *NSArrayDecl;
1059 
1060   /// The declaration of the arrayWithObjects:count: method.
1061   ObjCMethodDecl *ArrayWithObjectsMethod;
1062 
1063   /// The declaration of the Objective-C NSDictionary class.
1064   ObjCInterfaceDecl *NSDictionaryDecl;
1065 
1066   /// The declaration of the dictionaryWithObjects:forKeys:count: method.
1067   ObjCMethodDecl *DictionaryWithObjectsMethod;
1068 
1069   /// id<NSCopying> type.
1070   QualType QIDNSCopying;
1071 
1072   /// will hold 'respondsToSelector:'
1073   Selector RespondsToSelectorSel;
1074 
1075   /// A flag to remember whether the implicit forms of operator new and delete
1076   /// have been declared.
1077   bool GlobalNewDeleteDeclared;
1078 
1079   /// A flag to indicate that we're in a context that permits abstract
1080   /// references to fields.  This is really a
1081   bool AllowAbstractFieldReference;
1082 
1083   /// Describes how the expressions currently being parsed are
1084   /// evaluated at run-time, if at all.
1085   enum class ExpressionEvaluationContext {
1086     /// The current expression and its subexpressions occur within an
1087     /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
1088     /// \c sizeof, where the type of the expression may be significant but
1089     /// no code will be generated to evaluate the value of the expression at
1090     /// run time.
1091     Unevaluated,
1092 
1093     /// The current expression occurs within a braced-init-list within
1094     /// an unevaluated operand. This is mostly like a regular unevaluated
1095     /// context, except that we still instantiate constexpr functions that are
1096     /// referenced here so that we can perform narrowing checks correctly.
1097     UnevaluatedList,
1098 
1099     /// The current expression occurs within a discarded statement.
1100     /// This behaves largely similarly to an unevaluated operand in preventing
1101     /// definitions from being required, but not in other ways.
1102     DiscardedStatement,
1103 
1104     /// The current expression occurs within an unevaluated
1105     /// operand that unconditionally permits abstract references to
1106     /// fields, such as a SIZE operator in MS-style inline assembly.
1107     UnevaluatedAbstract,
1108 
1109     /// The current context is "potentially evaluated" in C++11 terms,
1110     /// but the expression is evaluated at compile-time (like the values of
1111     /// cases in a switch statement).
1112     ConstantEvaluated,
1113 
1114     /// The current expression is potentially evaluated at run time,
1115     /// which means that code may be generated to evaluate the value of the
1116     /// expression at run time.
1117     PotentiallyEvaluated,
1118 
1119     /// The current expression is potentially evaluated, but any
1120     /// declarations referenced inside that expression are only used if
1121     /// in fact the current expression is used.
1122     ///
1123     /// This value is used when parsing default function arguments, for which
1124     /// we would like to provide diagnostics (e.g., passing non-POD arguments
1125     /// through varargs) but do not want to mark declarations as "referenced"
1126     /// until the default argument is used.
1127     PotentiallyEvaluatedIfUsed
1128   };
1129 
1130   using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
1131 
1132   /// Data structure used to record current or nested
1133   /// expression evaluation contexts.
1134   struct ExpressionEvaluationContextRecord {
1135     /// The expression evaluation context.
1136     ExpressionEvaluationContext Context;
1137 
1138     /// Whether the enclosing context needed a cleanup.
1139     CleanupInfo ParentCleanup;
1140 
1141     /// Whether we are in a decltype expression.
1142     bool IsDecltype;
1143 
1144     /// The number of active cleanup objects when we entered
1145     /// this expression evaluation context.
1146     unsigned NumCleanupObjects;
1147 
1148     /// The number of typos encountered during this expression evaluation
1149     /// context (i.e. the number of TypoExprs created).
1150     unsigned NumTypos;
1151 
1152     MaybeODRUseExprSet SavedMaybeODRUseExprs;
1153 
1154     /// The lambdas that are present within this context, if it
1155     /// is indeed an unevaluated context.
1156     SmallVector<LambdaExpr *, 2> Lambdas;
1157 
1158     /// The declaration that provides context for lambda expressions
1159     /// and block literals if the normal declaration context does not
1160     /// suffice, e.g., in a default function argument.
1161     Decl *ManglingContextDecl;
1162 
1163     /// If we are processing a decltype type, a set of call expressions
1164     /// for which we have deferred checking the completeness of the return type.
1165     SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
1166 
1167     /// If we are processing a decltype type, a set of temporary binding
1168     /// expressions for which we have deferred checking the destructor.
1169     SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
1170 
1171     llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
1172 
1173     /// Expressions appearing as the LHS of a volatile assignment in this
1174     /// context. We produce a warning for these when popping the context if
1175     /// they are not discarded-value expressions nor unevaluated operands.
1176     SmallVector<Expr*, 2> VolatileAssignmentLHSs;
1177 
1178     /// Set of candidates for starting an immediate invocation.
1179     llvm::SmallVector<ImmediateInvocationCandidate, 4> ImmediateInvocationCandidates;
1180 
1181     /// Set of DeclRefExprs referencing a consteval function when used in a
1182     /// context not already known to be immediately invoked.
1183     llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval;
1184 
1185     /// \brief Describes whether we are in an expression constext which we have
1186     /// to handle differently.
1187     enum ExpressionKind {
1188       EK_Decltype, EK_TemplateArgument, EK_Other
1189     } ExprContext;
1190 
ExpressionEvaluationContextRecordExpressionEvaluationContextRecord1191     ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
1192                                       unsigned NumCleanupObjects,
1193                                       CleanupInfo ParentCleanup,
1194                                       Decl *ManglingContextDecl,
1195                                       ExpressionKind ExprContext)
1196         : Context(Context), ParentCleanup(ParentCleanup),
1197           NumCleanupObjects(NumCleanupObjects), NumTypos(0),
1198           ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {}
1199 
isUnevaluatedExpressionEvaluationContextRecord1200     bool isUnevaluated() const {
1201       return Context == ExpressionEvaluationContext::Unevaluated ||
1202              Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
1203              Context == ExpressionEvaluationContext::UnevaluatedList;
1204     }
isConstantEvaluatedExpressionEvaluationContextRecord1205     bool isConstantEvaluated() const {
1206       return Context == ExpressionEvaluationContext::ConstantEvaluated;
1207     }
1208   };
1209 
1210   /// A stack of expression evaluation contexts.
1211   SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
1212 
1213   /// Emit a warning for all pending noderef expressions that we recorded.
1214   void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
1215 
1216   /// Compute the mangling number context for a lambda expression or
1217   /// block literal. Also return the extra mangling decl if any.
1218   ///
1219   /// \param DC - The DeclContext containing the lambda expression or
1220   /// block literal.
1221   std::tuple<MangleNumberingContext *, Decl *>
1222   getCurrentMangleNumberContext(const DeclContext *DC);
1223 
1224 
1225   /// SpecialMemberOverloadResult - The overloading result for a special member
1226   /// function.
1227   ///
1228   /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1229   /// integer are used to determine whether overload resolution succeeded.
1230   class SpecialMemberOverloadResult {
1231   public:
1232     enum Kind {
1233       NoMemberOrDeleted,
1234       Ambiguous,
1235       Success
1236     };
1237 
1238   private:
1239     llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
1240 
1241   public:
SpecialMemberOverloadResult()1242     SpecialMemberOverloadResult() : Pair() {}
SpecialMemberOverloadResult(CXXMethodDecl * MD)1243     SpecialMemberOverloadResult(CXXMethodDecl *MD)
1244         : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1245 
getMethod()1246     CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
setMethod(CXXMethodDecl * MD)1247     void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1248 
getKind()1249     Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
setKind(Kind K)1250     void setKind(Kind K) { Pair.setInt(K); }
1251   };
1252 
1253   class SpecialMemberOverloadResultEntry
1254       : public llvm::FastFoldingSetNode,
1255         public SpecialMemberOverloadResult {
1256   public:
SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID & ID)1257     SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1258       : FastFoldingSetNode(ID)
1259     {}
1260   };
1261 
1262   /// A cache of special member function overload resolution results
1263   /// for C++ records.
1264   llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1265 
1266   /// A cache of the flags available in enumerations with the flag_bits
1267   /// attribute.
1268   mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1269 
1270   /// The kind of translation unit we are processing.
1271   ///
1272   /// When we're processing a complete translation unit, Sema will perform
1273   /// end-of-translation-unit semantic tasks (such as creating
1274   /// initializers for tentative definitions in C) once parsing has
1275   /// completed. Modules and precompiled headers perform different kinds of
1276   /// checks.
1277   TranslationUnitKind TUKind;
1278 
1279   llvm::BumpPtrAllocator BumpAlloc;
1280 
1281   /// The number of SFINAE diagnostics that have been trapped.
1282   unsigned NumSFINAEErrors;
1283 
1284   typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1285     UnparsedDefaultArgInstantiationsMap;
1286 
1287   /// A mapping from parameters with unparsed default arguments to the
1288   /// set of instantiations of each parameter.
1289   ///
1290   /// This mapping is a temporary data structure used when parsing
1291   /// nested class templates or nested classes of class templates,
1292   /// where we might end up instantiating an inner class before the
1293   /// default arguments of its methods have been parsed.
1294   UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1295 
1296   // Contains the locations of the beginning of unparsed default
1297   // argument locations.
1298   llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1299 
1300   /// UndefinedInternals - all the used, undefined objects which require a
1301   /// definition in this translation unit.
1302   llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1303 
1304   /// Determine if VD, which must be a variable or function, is an external
1305   /// symbol that nonetheless can't be referenced from outside this translation
1306   /// unit because its type has no linkage and it's not extern "C".
1307   bool isExternalWithNoLinkageType(ValueDecl *VD);
1308 
1309   /// Obtain a sorted list of functions that are undefined but ODR-used.
1310   void getUndefinedButUsed(
1311       SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1312 
1313   /// Retrieves list of suspicious delete-expressions that will be checked at
1314   /// the end of translation unit.
1315   const llvm::MapVector<FieldDecl *, DeleteLocs> &
1316   getMismatchingDeleteExpressions() const;
1317 
1318   typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
1319   typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
1320 
1321   /// Method Pool - allows efficient lookup when typechecking messages to "id".
1322   /// We need to maintain a list, since selectors can have differing signatures
1323   /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1324   /// of selectors are "overloaded").
1325   /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1326   /// methods inside categories with a particular selector.
1327   GlobalMethodPool MethodPool;
1328 
1329   /// Method selectors used in a \@selector expression. Used for implementation
1330   /// of -Wselector.
1331   llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1332 
1333   /// List of SourceLocations where 'self' is implicitly retained inside a
1334   /// block.
1335   llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
1336       ImplicitlyRetainedSelfLocs;
1337 
1338   /// Kinds of C++ special members.
1339   enum CXXSpecialMember {
1340     CXXDefaultConstructor,
1341     CXXCopyConstructor,
1342     CXXMoveConstructor,
1343     CXXCopyAssignment,
1344     CXXMoveAssignment,
1345     CXXDestructor,
1346     CXXInvalid
1347   };
1348 
1349   typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1350       SpecialMemberDecl;
1351 
1352   /// The C++ special members which we are currently in the process of
1353   /// declaring. If this process recursively triggers the declaration of the
1354   /// same special member, we should act as if it is not yet declared.
1355   llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1356 
1357   /// Kinds of defaulted comparison operator functions.
1358   enum class DefaultedComparisonKind : unsigned char {
1359     /// This is not a defaultable comparison operator.
1360     None,
1361     /// This is an operator== that should be implemented as a series of
1362     /// subobject comparisons.
1363     Equal,
1364     /// This is an operator<=> that should be implemented as a series of
1365     /// subobject comparisons.
1366     ThreeWay,
1367     /// This is an operator!= that should be implemented as a rewrite in terms
1368     /// of a == comparison.
1369     NotEqual,
1370     /// This is an <, <=, >, or >= that should be implemented as a rewrite in
1371     /// terms of a <=> comparison.
1372     Relational,
1373   };
1374 
1375   /// The function definitions which were renamed as part of typo-correction
1376   /// to match their respective declarations. We want to keep track of them
1377   /// to ensure that we don't emit a "redefinition" error if we encounter a
1378   /// correctly named definition after the renamed definition.
1379   llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1380 
1381   /// Stack of types that correspond to the parameter entities that are
1382   /// currently being copy-initialized. Can be empty.
1383   llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1384 
1385   void ReadMethodPool(Selector Sel);
1386   void updateOutOfDateSelector(Selector Sel);
1387 
1388   /// Private Helper predicate to check for 'self'.
1389   bool isSelfExpr(Expr *RExpr);
1390   bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1391 
1392   /// Cause the active diagnostic on the DiagosticsEngine to be
1393   /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1394   /// should not be used elsewhere.
1395   void EmitCurrentDiagnostic(unsigned DiagID);
1396 
1397   /// Records and restores the CurFPFeatures state on entry/exit of compound
1398   /// statements.
1399   class FPFeaturesStateRAII {
1400   public:
FPFeaturesStateRAII(Sema & S)1401     FPFeaturesStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.CurFPFeatures) {
1402       OldOverrides = S.FpPragmaStack.CurrentValue;
1403     }
~FPFeaturesStateRAII()1404     ~FPFeaturesStateRAII() {
1405       S.CurFPFeatures = OldFPFeaturesState;
1406       S.FpPragmaStack.CurrentValue = OldOverrides;
1407     }
getOverrides()1408     unsigned getOverrides() { return OldOverrides; }
1409 
1410   private:
1411     Sema& S;
1412     FPOptions OldFPFeaturesState;
1413     unsigned OldOverrides;
1414   };
1415 
1416   void addImplicitTypedef(StringRef Name, QualType T);
1417 
1418   bool WarnedStackExhausted = false;
1419 
1420 public:
1421   Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1422        TranslationUnitKind TUKind = TU_Complete,
1423        CodeCompleteConsumer *CompletionConsumer = nullptr);
1424   ~Sema();
1425 
1426   /// Perform initialization that occurs after the parser has been
1427   /// initialized but before it parses anything.
1428   void Initialize();
1429 
getLangOpts()1430   const LangOptions &getLangOpts() const { return LangOpts; }
getOpenCLOptions()1431   OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
getCurFPFeatures()1432   FPOptions     &getCurFPFeatures() { return CurFPFeatures; }
1433 
getDiagnostics()1434   DiagnosticsEngine &getDiagnostics() const { return Diags; }
getSourceManager()1435   SourceManager &getSourceManager() const { return SourceMgr; }
getPreprocessor()1436   Preprocessor &getPreprocessor() const { return PP; }
getASTContext()1437   ASTContext &getASTContext() const { return Context; }
getASTConsumer()1438   ASTConsumer &getASTConsumer() const { return Consumer; }
1439   ASTMutationListener *getASTMutationListener() const;
getExternalSource()1440   ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1441 
1442   ///Registers an external source. If an external source already exists,
1443   /// creates a multiplex external source and appends to it.
1444   ///
1445   ///\param[in] E - A non-null external sema source.
1446   ///
1447   void addExternalSource(ExternalSemaSource *E);
1448 
1449   void PrintStats() const;
1450 
1451   /// Warn that the stack is nearly exhausted.
1452   void warnStackExhausted(SourceLocation Loc);
1453 
1454   /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1455   /// guaranteed). Produces a warning if we're low on stack space and allocates
1456   /// more in that case. Use this in code that may recurse deeply (for example,
1457   /// in template instantiation) to avoid stack overflow.
1458   void runWithSufficientStackSpace(SourceLocation Loc,
1459                                    llvm::function_ref<void()> Fn);
1460 
1461   /// Helper class that creates diagnostics with optional
1462   /// template instantiation stacks.
1463   ///
1464   /// This class provides a wrapper around the basic DiagnosticBuilder
1465   /// class that emits diagnostics. SemaDiagnosticBuilder is
1466   /// responsible for emitting the diagnostic (as DiagnosticBuilder
1467   /// does) and, if the diagnostic comes from inside a template
1468   /// instantiation, printing the template instantiation stack as
1469   /// well.
1470   class SemaDiagnosticBuilder : public DiagnosticBuilder {
1471     Sema &SemaRef;
1472     unsigned DiagID;
1473 
1474   public:
SemaDiagnosticBuilder(DiagnosticBuilder & DB,Sema & SemaRef,unsigned DiagID)1475     SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1476       : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1477 
1478     // This is a cunning lie. DiagnosticBuilder actually performs move
1479     // construction in its copy constructor (but due to varied uses, it's not
1480     // possible to conveniently express this as actual move construction). So
1481     // the default copy ctor here is fine, because the base class disables the
1482     // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
1483     // in that case anwyay.
1484     SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
1485 
~SemaDiagnosticBuilder()1486     ~SemaDiagnosticBuilder() {
1487       // If we aren't active, there is nothing to do.
1488       if (!isActive()) return;
1489 
1490       // Otherwise, we need to emit the diagnostic. First flush the underlying
1491       // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1492       // won't emit the diagnostic in its own destructor.
1493       //
1494       // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1495       // do its own needless checks to see if the diagnostic needs to be
1496       // emitted. However, because we take care to ensure that the builder
1497       // objects never escape, a sufficiently smart compiler will be able to
1498       // eliminate that code.
1499       FlushCounts();
1500       Clear();
1501 
1502       // Dispatch to Sema to emit the diagnostic.
1503       SemaRef.EmitCurrentDiagnostic(DiagID);
1504     }
1505 
1506     /// Teach operator<< to produce an object of the correct type.
1507     template<typename T>
1508     friend const SemaDiagnosticBuilder &operator<<(
1509         const SemaDiagnosticBuilder &Diag, const T &Value) {
1510       const DiagnosticBuilder &BaseDiag = Diag;
1511       BaseDiag << Value;
1512       return Diag;
1513     }
1514   };
1515 
1516   /// Emit a diagnostic.
Diag(SourceLocation Loc,unsigned DiagID)1517   SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1518     DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1519     return SemaDiagnosticBuilder(DB, *this, DiagID);
1520   }
1521 
1522   /// Emit a partial diagnostic.
1523   SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1524 
1525   /// Build a partial diagnostic.
1526   PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1527 
1528   bool findMacroSpelling(SourceLocation &loc, StringRef name);
1529 
1530   /// Get a string to suggest for zero-initialization of a type.
1531   std::string
1532   getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1533   std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1534 
1535   /// Calls \c Lexer::getLocForEndOfToken()
1536   SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1537 
1538   /// Retrieve the module loader associated with the preprocessor.
1539   ModuleLoader &getModuleLoader() const;
1540 
1541   /// Invent a new identifier for parameters of abbreviated templates.
1542   IdentifierInfo *
1543   InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName,
1544                                              unsigned Index);
1545 
1546   void emitAndClearUnusedLocalTypedefWarnings();
1547 
1548   private:
1549     /// Function or variable declarations to be checked for whether the deferred
1550     /// diagnostics should be emitted.
1551     SmallVector<Decl *, 4> DeclsToCheckForDeferredDiags;
1552 
1553   public:
1554   // Emit all deferred diagnostics.
1555   void emitDeferredDiags();
1556 
1557   enum TUFragmentKind {
1558     /// The global module fragment, between 'module;' and a module-declaration.
1559     Global,
1560     /// A normal translation unit fragment. For a non-module unit, this is the
1561     /// entire translation unit. Otherwise, it runs from the module-declaration
1562     /// to the private-module-fragment (if any) or the end of the TU (if not).
1563     Normal,
1564     /// The private module fragment, between 'module :private;' and the end of
1565     /// the translation unit.
1566     Private
1567   };
1568 
1569   void ActOnStartOfTranslationUnit();
1570   void ActOnEndOfTranslationUnit();
1571   void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1572 
1573   void CheckDelegatingCtorCycles();
1574 
1575   Scope *getScopeForContext(DeclContext *Ctx);
1576 
1577   void PushFunctionScope();
1578   void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1579   sema::LambdaScopeInfo *PushLambdaScope();
1580 
1581   /// This is used to inform Sema what the current TemplateParameterDepth
1582   /// is during Parsing.  Currently it is used to pass on the depth
1583   /// when parsing generic lambda 'auto' parameters.
1584   void RecordParsingTemplateParameterDepth(unsigned Depth);
1585 
1586   void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1587                                RecordDecl *RD, CapturedRegionKind K,
1588                                unsigned OpenMPCaptureLevel = 0);
1589 
1590   /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1591   /// time after they've been popped.
1592   class PoppedFunctionScopeDeleter {
1593     Sema *Self;
1594 
1595   public:
PoppedFunctionScopeDeleter(Sema * Self)1596     explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1597     void operator()(sema::FunctionScopeInfo *Scope) const;
1598   };
1599 
1600   using PoppedFunctionScopePtr =
1601       std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1602 
1603   PoppedFunctionScopePtr
1604   PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1605                        const Decl *D = nullptr,
1606                        QualType BlockType = QualType());
1607 
getCurFunction()1608   sema::FunctionScopeInfo *getCurFunction() const {
1609     return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1610   }
1611 
1612   sema::FunctionScopeInfo *getEnclosingFunction() const;
1613 
1614   void setFunctionHasBranchIntoScope();
1615   void setFunctionHasBranchProtectedScope();
1616   void setFunctionHasIndirectGoto();
1617 
1618   void PushCompoundScope(bool IsStmtExpr);
1619   void PopCompoundScope();
1620 
1621   sema::CompoundScopeInfo &getCurCompoundScope() const;
1622 
1623   bool hasAnyUnrecoverableErrorsInThisFunction() const;
1624 
1625   /// Retrieve the current block, if any.
1626   sema::BlockScopeInfo *getCurBlock();
1627 
1628   /// Get the innermost lambda enclosing the current location, if any. This
1629   /// looks through intervening non-lambda scopes such as local functions and
1630   /// blocks.
1631   sema::LambdaScopeInfo *getEnclosingLambda() const;
1632 
1633   /// Retrieve the current lambda scope info, if any.
1634   /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1635   /// lambda scope info ignoring all inner capturing scopes that are not
1636   /// lambda scopes.
1637   sema::LambdaScopeInfo *
1638   getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1639 
1640   /// Retrieve the current generic lambda info, if any.
1641   sema::LambdaScopeInfo *getCurGenericLambda();
1642 
1643   /// Retrieve the current captured region, if any.
1644   sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1645 
1646   /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
WeakTopLevelDecls()1647   SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1648 
1649   /// Called before parsing a function declarator belonging to a function
1650   /// declaration.
1651   void ActOnStartFunctionDeclarationDeclarator(Declarator &D,
1652                                                unsigned TemplateParameterDepth);
1653 
1654   /// Called after parsing a function declarator belonging to a function
1655   /// declaration.
1656   void ActOnFinishFunctionDeclarationDeclarator(Declarator &D);
1657 
1658   void ActOnComment(SourceRange Comment);
1659 
1660   //===--------------------------------------------------------------------===//
1661   // Type Analysis / Processing: SemaType.cpp.
1662   //
1663 
1664   QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1665                               const DeclSpec *DS = nullptr);
1666   QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1667                               const DeclSpec *DS = nullptr);
1668   QualType BuildPointerType(QualType T,
1669                             SourceLocation Loc, DeclarationName Entity);
1670   QualType BuildReferenceType(QualType T, bool LValueRef,
1671                               SourceLocation Loc, DeclarationName Entity);
1672   QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1673                           Expr *ArraySize, unsigned Quals,
1674                           SourceRange Brackets, DeclarationName Entity);
1675   QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
1676   QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1677                               SourceLocation AttrLoc);
1678   QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
1679                            SourceLocation AttrLoc);
1680 
1681   QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
1682                                  SourceLocation AttrLoc);
1683 
1684   /// Same as above, but constructs the AddressSpace index if not provided.
1685   QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
1686                                  SourceLocation AttrLoc);
1687 
1688   bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
1689 
1690   bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1691 
1692   /// Build a function type.
1693   ///
1694   /// This routine checks the function type according to C++ rules and
1695   /// under the assumption that the result type and parameter types have
1696   /// just been instantiated from a template. It therefore duplicates
1697   /// some of the behavior of GetTypeForDeclarator, but in a much
1698   /// simpler form that is only suitable for this narrow use case.
1699   ///
1700   /// \param T The return type of the function.
1701   ///
1702   /// \param ParamTypes The parameter types of the function. This array
1703   /// will be modified to account for adjustments to the types of the
1704   /// function parameters.
1705   ///
1706   /// \param Loc The location of the entity whose type involves this
1707   /// function type or, if there is no such entity, the location of the
1708   /// type that will have function type.
1709   ///
1710   /// \param Entity The name of the entity that involves the function
1711   /// type, if known.
1712   ///
1713   /// \param EPI Extra information about the function type. Usually this will
1714   /// be taken from an existing function with the same prototype.
1715   ///
1716   /// \returns A suitable function type, if there are no errors. The
1717   /// unqualified type will always be a FunctionProtoType.
1718   /// Otherwise, returns a NULL type.
1719   QualType BuildFunctionType(QualType T,
1720                              MutableArrayRef<QualType> ParamTypes,
1721                              SourceLocation Loc, DeclarationName Entity,
1722                              const FunctionProtoType::ExtProtoInfo &EPI);
1723 
1724   QualType BuildMemberPointerType(QualType T, QualType Class,
1725                                   SourceLocation Loc,
1726                                   DeclarationName Entity);
1727   QualType BuildBlockPointerType(QualType T,
1728                                  SourceLocation Loc, DeclarationName Entity);
1729   QualType BuildParenType(QualType T);
1730   QualType BuildAtomicType(QualType T, SourceLocation Loc);
1731   QualType BuildReadPipeType(QualType T,
1732                          SourceLocation Loc);
1733   QualType BuildWritePipeType(QualType T,
1734                          SourceLocation Loc);
1735   QualType BuildExtIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
1736 
1737   TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1738   TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1739 
1740   /// Package the given type and TSI into a ParsedType.
1741   ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1742   DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1743   DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1744   static QualType GetTypeFromParser(ParsedType Ty,
1745                                     TypeSourceInfo **TInfo = nullptr);
1746   CanThrowResult canThrow(const Stmt *E);
1747   /// Determine whether the callee of a particular function call can throw.
1748   /// E, D and Loc are all optional.
1749   static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
1750                                        SourceLocation Loc = SourceLocation());
1751   const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1752                                                 const FunctionProtoType *FPT);
1753   void UpdateExceptionSpec(FunctionDecl *FD,
1754                            const FunctionProtoType::ExceptionSpecInfo &ESI);
1755   bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1756   bool CheckDistantExceptionSpec(QualType T);
1757   bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1758   bool CheckEquivalentExceptionSpec(
1759       const FunctionProtoType *Old, SourceLocation OldLoc,
1760       const FunctionProtoType *New, SourceLocation NewLoc);
1761   bool CheckEquivalentExceptionSpec(
1762       const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1763       const FunctionProtoType *Old, SourceLocation OldLoc,
1764       const FunctionProtoType *New, SourceLocation NewLoc);
1765   bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
1766   bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
1767                                 const PartialDiagnostic &NestedDiagID,
1768                                 const PartialDiagnostic &NoteID,
1769                                 const PartialDiagnostic &NoThrowDiagID,
1770                                 const FunctionProtoType *Superset,
1771                                 SourceLocation SuperLoc,
1772                                 const FunctionProtoType *Subset,
1773                                 SourceLocation SubLoc);
1774   bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
1775                                const PartialDiagnostic &NoteID,
1776                                const FunctionProtoType *Target,
1777                                SourceLocation TargetLoc,
1778                                const FunctionProtoType *Source,
1779                                SourceLocation SourceLoc);
1780 
1781   TypeResult ActOnTypeName(Scope *S, Declarator &D);
1782 
1783   /// The parser has parsed the context-sensitive type 'instancetype'
1784   /// in an Objective-C message declaration. Return the appropriate type.
1785   ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1786 
1787   /// Abstract class used to diagnose incomplete types.
1788   struct TypeDiagnoser {
TypeDiagnoserTypeDiagnoser1789     TypeDiagnoser() {}
1790 
1791     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
~TypeDiagnoserTypeDiagnoser1792     virtual ~TypeDiagnoser() {}
1793   };
1794 
getPrintable(int I)1795   static int getPrintable(int I) { return I; }
getPrintable(unsigned I)1796   static unsigned getPrintable(unsigned I) { return I; }
getPrintable(bool B)1797   static bool getPrintable(bool B) { return B; }
getPrintable(const char * S)1798   static const char * getPrintable(const char *S) { return S; }
getPrintable(StringRef S)1799   static StringRef getPrintable(StringRef S) { return S; }
getPrintable(const std::string & S)1800   static const std::string &getPrintable(const std::string &S) { return S; }
getPrintable(const IdentifierInfo * II)1801   static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1802     return II;
1803   }
getPrintable(DeclarationName N)1804   static DeclarationName getPrintable(DeclarationName N) { return N; }
getPrintable(QualType T)1805   static QualType getPrintable(QualType T) { return T; }
getPrintable(SourceRange R)1806   static SourceRange getPrintable(SourceRange R) { return R; }
getPrintable(SourceLocation L)1807   static SourceRange getPrintable(SourceLocation L) { return L; }
getPrintable(const Expr * E)1808   static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
getPrintable(TypeLoc TL)1809   static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1810 
1811   template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1812   protected:
1813     unsigned DiagID;
1814     std::tuple<const Ts &...> Args;
1815 
1816     template <std::size_t... Is>
emit(const SemaDiagnosticBuilder & DB,std::index_sequence<Is...>)1817     void emit(const SemaDiagnosticBuilder &DB,
1818               std::index_sequence<Is...>) const {
1819       // Apply all tuple elements to the builder in order.
1820       bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1821       (void)Dummy;
1822     }
1823 
1824   public:
BoundTypeDiagnoser(unsigned DiagID,const Ts &...Args)1825     BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1826         : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1827       assert(DiagID != 0 && "no diagnostic for type diagnoser");
1828     }
1829 
diagnose(Sema & S,SourceLocation Loc,QualType T)1830     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1831       const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1832       emit(DB, std::index_sequence_for<Ts...>());
1833       DB << T;
1834     }
1835   };
1836 
1837   /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
1838   /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
1839   /// For example, a diagnostic with no other parameters would generally have
1840   /// the form "...%select{incomplete|sizeless}0 type %1...".
1841   template <typename... Ts>
1842   class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> {
1843   public:
SizelessTypeDiagnoser(unsigned DiagID,const Ts &...Args)1844     SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args)
1845         : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
1846 
diagnose(Sema & S,SourceLocation Loc,QualType T)1847     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1848       const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
1849       this->emit(DB, std::index_sequence_for<Ts...>());
1850       DB << T->isSizelessType() << T;
1851     }
1852   };
1853 
1854   enum class CompleteTypeKind {
1855     /// Apply the normal rules for complete types.  In particular,
1856     /// treat all sizeless types as incomplete.
1857     Normal,
1858 
1859     /// Relax the normal rules for complete types so that they include
1860     /// sizeless built-in types.
1861     AcceptSizeless,
1862 
1863     // FIXME: Eventually we should flip the default to Normal and opt in
1864     // to AcceptSizeless rather than opt out of it.
1865     Default = AcceptSizeless
1866   };
1867 
1868 private:
1869   /// Methods for marking which expressions involve dereferencing a pointer
1870   /// marked with the 'noderef' attribute. Expressions are checked bottom up as
1871   /// they are parsed, meaning that a noderef pointer may not be accessed. For
1872   /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
1873   /// `*p`, but need to check that `address of` is called on it. This requires
1874   /// keeping a container of all pending expressions and checking if the address
1875   /// of them are eventually taken.
1876   void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
1877   void CheckAddressOfNoDeref(const Expr *E);
1878   void CheckMemberAccessOfNoDeref(const MemberExpr *E);
1879 
1880   bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1881                                CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
1882 
1883   struct ModuleScope {
1884     SourceLocation BeginLoc;
1885     clang::Module *Module = nullptr;
1886     bool ModuleInterface = false;
1887     bool ImplicitGlobalModuleFragment = false;
1888     VisibleModuleSet OuterVisibleModules;
1889   };
1890   /// The modules we're currently parsing.
1891   llvm::SmallVector<ModuleScope, 16> ModuleScopes;
1892 
1893   /// Namespace definitions that we will export when they finish.
1894   llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
1895 
1896   /// Get the module whose scope we are currently within.
getCurrentModule()1897   Module *getCurrentModule() const {
1898     return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
1899   }
1900 
1901   VisibleModuleSet VisibleModules;
1902 
1903 public:
1904   /// Get the module owning an entity.
getOwningModule(const Decl * Entity)1905   Module *getOwningModule(const Decl *Entity) {
1906     return Entity->getOwningModule();
1907   }
1908 
1909   /// Make a merged definition of an existing hidden definition \p ND
1910   /// visible at the specified location.
1911   void makeMergedDefinitionVisible(NamedDecl *ND);
1912 
1913   bool isModuleVisible(const Module *M, bool ModulePrivate = false);
1914 
1915   /// Determine whether a declaration is visible to name lookup.
isVisible(const NamedDecl * D)1916   bool isVisible(const NamedDecl *D) {
1917     return D->isUnconditionallyVisible() || isVisibleSlow(D);
1918   }
1919 
1920   /// Determine whether any declaration of an entity is visible.
1921   bool
1922   hasVisibleDeclaration(const NamedDecl *D,
1923                         llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
1924     return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
1925   }
1926   bool hasVisibleDeclarationSlow(const NamedDecl *D,
1927                                  llvm::SmallVectorImpl<Module *> *Modules);
1928 
1929   bool hasVisibleMergedDefinition(NamedDecl *Def);
1930   bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
1931 
1932   /// Determine if \p D and \p Suggested have a structurally compatible
1933   /// layout as described in C11 6.2.7/1.
1934   bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
1935 
1936   /// Determine if \p D has a visible definition. If not, suggest a declaration
1937   /// that should be made visible to expose the definition.
1938   bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1939                             bool OnlyNeedComplete = false);
hasVisibleDefinition(const NamedDecl * D)1940   bool hasVisibleDefinition(const NamedDecl *D) {
1941     NamedDecl *Hidden;
1942     return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1943   }
1944 
1945   /// Determine if the template parameter \p D has a visible default argument.
1946   bool
1947   hasVisibleDefaultArgument(const NamedDecl *D,
1948                             llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1949 
1950   /// Determine if there is a visible declaration of \p D that is an explicit
1951   /// specialization declaration for a specialization of a template. (For a
1952   /// member specialization, use hasVisibleMemberSpecialization.)
1953   bool hasVisibleExplicitSpecialization(
1954       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1955 
1956   /// Determine if there is a visible declaration of \p D that is a member
1957   /// specialization declaration (as opposed to an instantiated declaration).
1958   bool hasVisibleMemberSpecialization(
1959       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1960 
1961   /// Determine if \p A and \p B are equivalent internal linkage declarations
1962   /// from different modules, and thus an ambiguity error can be downgraded to
1963   /// an extension warning.
1964   bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
1965                                               const NamedDecl *B);
1966   void diagnoseEquivalentInternalLinkageDeclarations(
1967       SourceLocation Loc, const NamedDecl *D,
1968       ArrayRef<const NamedDecl *> Equiv);
1969 
1970   bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
1971 
1972   bool isCompleteType(SourceLocation Loc, QualType T,
1973                       CompleteTypeKind Kind = CompleteTypeKind::Default) {
1974     return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr);
1975   }
1976   bool RequireCompleteType(SourceLocation Loc, QualType T,
1977                            CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
1978   bool RequireCompleteType(SourceLocation Loc, QualType T,
1979                            CompleteTypeKind Kind, unsigned DiagID);
1980 
RequireCompleteType(SourceLocation Loc,QualType T,TypeDiagnoser & Diagnoser)1981   bool RequireCompleteType(SourceLocation Loc, QualType T,
1982                            TypeDiagnoser &Diagnoser) {
1983     return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser);
1984   }
RequireCompleteType(SourceLocation Loc,QualType T,unsigned DiagID)1985   bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
1986     return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID);
1987   }
1988 
1989   template <typename... Ts>
RequireCompleteType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)1990   bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1991                            const Ts &...Args) {
1992     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1993     return RequireCompleteType(Loc, T, Diagnoser);
1994   }
1995 
1996   template <typename... Ts>
RequireCompleteSizedType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)1997   bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID,
1998                                 const Ts &... Args) {
1999     SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2000     return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
2001   }
2002 
2003   void completeExprArrayBound(Expr *E);
2004   bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
2005                                TypeDiagnoser &Diagnoser);
2006   bool RequireCompleteExprType(Expr *E, unsigned DiagID);
2007 
2008   template <typename... Ts>
RequireCompleteExprType(Expr * E,unsigned DiagID,const Ts &...Args)2009   bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
2010     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2011     return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
2012   }
2013 
2014   template <typename... Ts>
RequireCompleteSizedExprType(Expr * E,unsigned DiagID,const Ts &...Args)2015   bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
2016                                     const Ts &... Args) {
2017     SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2018     return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser);
2019   }
2020 
2021   bool RequireLiteralType(SourceLocation Loc, QualType T,
2022                           TypeDiagnoser &Diagnoser);
2023   bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
2024 
2025   template <typename... Ts>
RequireLiteralType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)2026   bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
2027                           const Ts &...Args) {
2028     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2029     return RequireLiteralType(Loc, T, Diagnoser);
2030   }
2031 
2032   QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
2033                              const CXXScopeSpec &SS, QualType T,
2034                              TagDecl *OwnedTagDecl = nullptr);
2035 
2036   QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
2037   /// If AsUnevaluated is false, E is treated as though it were an evaluated
2038   /// context, such as when building a type for decltype(auto).
2039   QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
2040                              bool AsUnevaluated = true);
2041   QualType BuildUnaryTransformType(QualType BaseType,
2042                                    UnaryTransformType::UTTKind UKind,
2043                                    SourceLocation Loc);
2044 
2045   //===--------------------------------------------------------------------===//
2046   // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
2047   //
2048 
2049   struct SkipBodyInfo {
SkipBodyInfoSkipBodyInfo2050     SkipBodyInfo()
2051         : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
2052           New(nullptr) {}
2053     bool ShouldSkip;
2054     bool CheckSameAsPrevious;
2055     NamedDecl *Previous;
2056     NamedDecl *New;
2057   };
2058 
2059   DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
2060 
2061   void DiagnoseUseOfUnimplementedSelectors();
2062 
2063   bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
2064 
2065   ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
2066                          Scope *S, CXXScopeSpec *SS = nullptr,
2067                          bool isClassName = false, bool HasTrailingDot = false,
2068                          ParsedType ObjectType = nullptr,
2069                          bool IsCtorOrDtorName = false,
2070                          bool WantNontrivialTypeSourceInfo = false,
2071                          bool IsClassTemplateDeductionContext = true,
2072                          IdentifierInfo **CorrectedII = nullptr);
2073   TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
2074   bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
2075   void DiagnoseUnknownTypeName(IdentifierInfo *&II,
2076                                SourceLocation IILoc,
2077                                Scope *S,
2078                                CXXScopeSpec *SS,
2079                                ParsedType &SuggestedType,
2080                                bool IsTemplateName = false);
2081 
2082   /// Attempt to behave like MSVC in situations where lookup of an unqualified
2083   /// type name has failed in a dependent context. In these situations, we
2084   /// automatically form a DependentTypeName that will retry lookup in a related
2085   /// scope during instantiation.
2086   ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
2087                                       SourceLocation NameLoc,
2088                                       bool IsTemplateTypeArg);
2089 
2090   /// Describes the result of the name lookup and resolution performed
2091   /// by \c ClassifyName().
2092   enum NameClassificationKind {
2093     /// This name is not a type or template in this context, but might be
2094     /// something else.
2095     NC_Unknown,
2096     /// Classification failed; an error has been produced.
2097     NC_Error,
2098     /// The name has been typo-corrected to a keyword.
2099     NC_Keyword,
2100     /// The name was classified as a type.
2101     NC_Type,
2102     /// The name was classified as a specific non-type, non-template
2103     /// declaration. ActOnNameClassifiedAsNonType should be called to
2104     /// convert the declaration to an expression.
2105     NC_NonType,
2106     /// The name was classified as an ADL-only function name.
2107     /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
2108     /// result to an expression.
2109     NC_UndeclaredNonType,
2110     /// The name denotes a member of a dependent type that could not be
2111     /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
2112     /// convert the result to an expression.
2113     NC_DependentNonType,
2114     /// The name was classified as a non-type, and an expression representing
2115     /// that name has been formed.
2116     NC_ContextIndependentExpr,
2117     /// The name was classified as a template whose specializations are types.
2118     NC_TypeTemplate,
2119     /// The name was classified as a variable template name.
2120     NC_VarTemplate,
2121     /// The name was classified as a function template name.
2122     NC_FunctionTemplate,
2123     /// The name was classified as an ADL-only function template name.
2124     NC_UndeclaredTemplate,
2125     /// The name was classified as a concept name.
2126     NC_Concept,
2127   };
2128 
2129   class NameClassification {
2130     NameClassificationKind Kind;
2131     union {
2132       ExprResult Expr;
2133       NamedDecl *NonTypeDecl;
2134       TemplateName Template;
2135       ParsedType Type;
2136     };
2137 
NameClassification(NameClassificationKind Kind)2138     explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
2139 
2140   public:
NameClassification(ParsedType Type)2141     NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
2142 
NameClassification(const IdentifierInfo * Keyword)2143     NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
2144 
Error()2145     static NameClassification Error() {
2146       return NameClassification(NC_Error);
2147     }
2148 
Unknown()2149     static NameClassification Unknown() {
2150       return NameClassification(NC_Unknown);
2151     }
2152 
ContextIndependentExpr(ExprResult E)2153     static NameClassification ContextIndependentExpr(ExprResult E) {
2154       NameClassification Result(NC_ContextIndependentExpr);
2155       Result.Expr = E;
2156       return Result;
2157     }
2158 
NonType(NamedDecl * D)2159     static NameClassification NonType(NamedDecl *D) {
2160       NameClassification Result(NC_NonType);
2161       Result.NonTypeDecl = D;
2162       return Result;
2163     }
2164 
UndeclaredNonType()2165     static NameClassification UndeclaredNonType() {
2166       return NameClassification(NC_UndeclaredNonType);
2167     }
2168 
DependentNonType()2169     static NameClassification DependentNonType() {
2170       return NameClassification(NC_DependentNonType);
2171     }
2172 
TypeTemplate(TemplateName Name)2173     static NameClassification TypeTemplate(TemplateName Name) {
2174       NameClassification Result(NC_TypeTemplate);
2175       Result.Template = Name;
2176       return Result;
2177     }
2178 
VarTemplate(TemplateName Name)2179     static NameClassification VarTemplate(TemplateName Name) {
2180       NameClassification Result(NC_VarTemplate);
2181       Result.Template = Name;
2182       return Result;
2183     }
2184 
FunctionTemplate(TemplateName Name)2185     static NameClassification FunctionTemplate(TemplateName Name) {
2186       NameClassification Result(NC_FunctionTemplate);
2187       Result.Template = Name;
2188       return Result;
2189     }
2190 
Concept(TemplateName Name)2191     static NameClassification Concept(TemplateName Name) {
2192       NameClassification Result(NC_Concept);
2193       Result.Template = Name;
2194       return Result;
2195     }
2196 
UndeclaredTemplate(TemplateName Name)2197     static NameClassification UndeclaredTemplate(TemplateName Name) {
2198       NameClassification Result(NC_UndeclaredTemplate);
2199       Result.Template = Name;
2200       return Result;
2201     }
2202 
getKind()2203     NameClassificationKind getKind() const { return Kind; }
2204 
getExpression()2205     ExprResult getExpression() const {
2206       assert(Kind == NC_ContextIndependentExpr);
2207       return Expr;
2208     }
2209 
getType()2210     ParsedType getType() const {
2211       assert(Kind == NC_Type);
2212       return Type;
2213     }
2214 
getNonTypeDecl()2215     NamedDecl *getNonTypeDecl() const {
2216       assert(Kind == NC_NonType);
2217       return NonTypeDecl;
2218     }
2219 
getTemplateName()2220     TemplateName getTemplateName() const {
2221       assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
2222              Kind == NC_VarTemplate || Kind == NC_Concept ||
2223              Kind == NC_UndeclaredTemplate);
2224       return Template;
2225     }
2226 
getTemplateNameKind()2227     TemplateNameKind getTemplateNameKind() const {
2228       switch (Kind) {
2229       case NC_TypeTemplate:
2230         return TNK_Type_template;
2231       case NC_FunctionTemplate:
2232         return TNK_Function_template;
2233       case NC_VarTemplate:
2234         return TNK_Var_template;
2235       case NC_Concept:
2236         return TNK_Concept_template;
2237       case NC_UndeclaredTemplate:
2238         return TNK_Undeclared_template;
2239       default:
2240         llvm_unreachable("unsupported name classification.");
2241       }
2242     }
2243   };
2244 
2245   /// Perform name lookup on the given name, classifying it based on
2246   /// the results of name lookup and the following token.
2247   ///
2248   /// This routine is used by the parser to resolve identifiers and help direct
2249   /// parsing. When the identifier cannot be found, this routine will attempt
2250   /// to correct the typo and classify based on the resulting name.
2251   ///
2252   /// \param S The scope in which we're performing name lookup.
2253   ///
2254   /// \param SS The nested-name-specifier that precedes the name.
2255   ///
2256   /// \param Name The identifier. If typo correction finds an alternative name,
2257   /// this pointer parameter will be updated accordingly.
2258   ///
2259   /// \param NameLoc The location of the identifier.
2260   ///
2261   /// \param NextToken The token following the identifier. Used to help
2262   /// disambiguate the name.
2263   ///
2264   /// \param CCC The correction callback, if typo correction is desired.
2265   NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
2266                                   IdentifierInfo *&Name, SourceLocation NameLoc,
2267                                   const Token &NextToken,
2268                                   CorrectionCandidateCallback *CCC = nullptr);
2269 
2270   /// Act on the result of classifying a name as an undeclared (ADL-only)
2271   /// non-type declaration.
2272   ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
2273                                                     SourceLocation NameLoc);
2274   /// Act on the result of classifying a name as an undeclared member of a
2275   /// dependent base class.
2276   ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
2277                                                    IdentifierInfo *Name,
2278                                                    SourceLocation NameLoc,
2279                                                    bool IsAddressOfOperand);
2280   /// Act on the result of classifying a name as a specific non-type
2281   /// declaration.
2282   ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
2283                                           NamedDecl *Found,
2284                                           SourceLocation NameLoc,
2285                                           const Token &NextToken);
2286 
2287   /// Describes the detailed kind of a template name. Used in diagnostics.
2288   enum class TemplateNameKindForDiagnostics {
2289     ClassTemplate,
2290     FunctionTemplate,
2291     VarTemplate,
2292     AliasTemplate,
2293     TemplateTemplateParam,
2294     Concept,
2295     DependentTemplate
2296   };
2297   TemplateNameKindForDiagnostics
2298   getTemplateNameKindForDiagnostics(TemplateName Name);
2299 
2300   /// Determine whether it's plausible that E was intended to be a
2301   /// template-name.
mightBeIntendedToBeTemplateName(ExprResult E,bool & Dependent)2302   bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
2303     if (!getLangOpts().CPlusPlus || E.isInvalid())
2304       return false;
2305     Dependent = false;
2306     if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
2307       return !DRE->hasExplicitTemplateArgs();
2308     if (auto *ME = dyn_cast<MemberExpr>(E.get()))
2309       return !ME->hasExplicitTemplateArgs();
2310     Dependent = true;
2311     if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2312       return !DSDRE->hasExplicitTemplateArgs();
2313     if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2314       return !DSME->hasExplicitTemplateArgs();
2315     // Any additional cases recognized here should also be handled by
2316     // diagnoseExprIntendedAsTemplateName.
2317     return false;
2318   }
2319   void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
2320                                           SourceLocation Less,
2321                                           SourceLocation Greater);
2322 
2323   Decl *ActOnDeclarator(Scope *S, Declarator &D);
2324 
2325   NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
2326                               MultiTemplateParamsArg TemplateParameterLists);
2327   void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
2328   bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
2329   bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
2330                                     DeclarationName Name, SourceLocation Loc,
2331                                     bool IsTemplateId);
2332   void
2333   diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2334                             SourceLocation FallbackLoc,
2335                             SourceLocation ConstQualLoc = SourceLocation(),
2336                             SourceLocation VolatileQualLoc = SourceLocation(),
2337                             SourceLocation RestrictQualLoc = SourceLocation(),
2338                             SourceLocation AtomicQualLoc = SourceLocation(),
2339                             SourceLocation UnalignedQualLoc = SourceLocation());
2340 
2341   static bool adjustContextForLocalExternDecl(DeclContext *&DC);
2342   void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2343   NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
2344                                     const LookupResult &R);
2345   NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
2346   void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2347                    const LookupResult &R);
2348   void CheckShadow(Scope *S, VarDecl *D);
2349 
2350   /// Warn if 'E', which is an expression that is about to be modified, refers
2351   /// to a shadowing declaration.
2352   void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
2353 
2354   void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
2355 
2356 private:
2357   /// Map of current shadowing declarations to shadowed declarations. Warn if
2358   /// it looks like the user is trying to modify the shadowing declaration.
2359   llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2360 
2361 public:
2362   void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2363   void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2364   void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2365                                     TypedefNameDecl *NewTD);
2366   void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
2367   NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2368                                     TypeSourceInfo *TInfo,
2369                                     LookupResult &Previous);
2370   NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
2371                                   LookupResult &Previous, bool &Redeclaration);
2372   NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
2373                                      TypeSourceInfo *TInfo,
2374                                      LookupResult &Previous,
2375                                      MultiTemplateParamsArg TemplateParamLists,
2376                                      bool &AddToScope,
2377                                      ArrayRef<BindingDecl *> Bindings = None);
2378   NamedDecl *
2379   ActOnDecompositionDeclarator(Scope *S, Declarator &D,
2380                                MultiTemplateParamsArg TemplateParamLists);
2381   // Returns true if the variable declaration is a redeclaration
2382   bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
2383   void CheckVariableDeclarationType(VarDecl *NewVD);
2384   bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
2385                                      Expr *Init);
2386   void CheckCompleteVariableDeclaration(VarDecl *VD);
2387   void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
2388   void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
2389 
2390   NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2391                                      TypeSourceInfo *TInfo,
2392                                      LookupResult &Previous,
2393                                      MultiTemplateParamsArg TemplateParamLists,
2394                                      bool &AddToScope);
2395   bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
2396 
2397   enum class CheckConstexprKind {
2398     /// Diagnose issues that are non-constant or that are extensions.
2399     Diagnose,
2400     /// Identify whether this function satisfies the formal rules for constexpr
2401     /// functions in the current lanugage mode (with no extensions).
2402     CheckValid
2403   };
2404 
2405   bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
2406                                         CheckConstexprKind Kind);
2407 
2408   void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
2409   void FindHiddenVirtualMethods(CXXMethodDecl *MD,
2410                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2411   void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
2412                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2413   // Returns true if the function declaration is a redeclaration
2414   bool CheckFunctionDeclaration(Scope *S,
2415                                 FunctionDecl *NewFD, LookupResult &Previous,
2416                                 bool IsMemberSpecialization);
2417   bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
2418   bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
2419                                       QualType NewT, QualType OldT);
2420   void CheckMain(FunctionDecl *FD, const DeclSpec &D);
2421   void CheckMSVCRTEntryPoint(FunctionDecl *FD);
2422   Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
2423                                                    bool IsDefinition);
2424   void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
2425   Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
2426   ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
2427                                           SourceLocation Loc,
2428                                           QualType T);
2429   ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
2430                               SourceLocation NameLoc, IdentifierInfo *Name,
2431                               QualType T, TypeSourceInfo *TSInfo,
2432                               StorageClass SC);
2433   void ActOnParamDefaultArgument(Decl *param,
2434                                  SourceLocation EqualLoc,
2435                                  Expr *defarg);
2436   void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc,
2437                                          SourceLocation ArgLoc);
2438   void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
2439   ExprResult ConvertParamDefaultArgument(const ParmVarDecl *Param,
2440                                          Expr *DefaultArg,
2441                                          SourceLocation EqualLoc);
2442   void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2443                                SourceLocation EqualLoc);
2444 
2445   // Contexts where using non-trivial C union types can be disallowed. This is
2446   // passed to err_non_trivial_c_union_in_invalid_context.
2447   enum NonTrivialCUnionContext {
2448     // Function parameter.
2449     NTCUC_FunctionParam,
2450     // Function return.
2451     NTCUC_FunctionReturn,
2452     // Default-initialized object.
2453     NTCUC_DefaultInitializedObject,
2454     // Variable with automatic storage duration.
2455     NTCUC_AutoVar,
2456     // Initializer expression that might copy from another object.
2457     NTCUC_CopyInit,
2458     // Assignment.
2459     NTCUC_Assignment,
2460     // Compound literal.
2461     NTCUC_CompoundLiteral,
2462     // Block capture.
2463     NTCUC_BlockCapture,
2464     // lvalue-to-rvalue conversion of volatile type.
2465     NTCUC_LValueToRValueVolatile,
2466   };
2467 
2468   /// Emit diagnostics if the initializer or any of its explicit or
2469   /// implicitly-generated subexpressions require copying or
2470   /// default-initializing a type that is or contains a C union type that is
2471   /// non-trivial to copy or default-initialize.
2472   void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
2473 
2474   // These flags are passed to checkNonTrivialCUnion.
2475   enum NonTrivialCUnionKind {
2476     NTCUK_Init = 0x1,
2477     NTCUK_Destruct = 0x2,
2478     NTCUK_Copy = 0x4,
2479   };
2480 
2481   /// Emit diagnostics if a non-trivial C union type or a struct that contains
2482   /// a non-trivial C union is used in an invalid context.
2483   void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
2484                              NonTrivialCUnionContext UseContext,
2485                              unsigned NonTrivialKind);
2486 
2487   void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
2488   void ActOnUninitializedDecl(Decl *dcl);
2489   void ActOnInitializerError(Decl *Dcl);
2490 
2491   void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
2492   void ActOnCXXForRangeDecl(Decl *D);
2493   StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
2494                                         IdentifierInfo *Ident,
2495                                         ParsedAttributes &Attrs,
2496                                         SourceLocation AttrEnd);
2497   void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
2498   void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
2499   void CheckStaticLocalForDllExport(VarDecl *VD);
2500   void FinalizeDeclaration(Decl *D);
2501   DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
2502                                          ArrayRef<Decl *> Group);
2503   DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
2504 
2505   /// Should be called on all declarations that might have attached
2506   /// documentation comments.
2507   void ActOnDocumentableDecl(Decl *D);
2508   void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
2509 
2510   void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
2511                                        SourceLocation LocAfterDecls);
2512   void CheckForFunctionRedefinition(
2513       FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
2514       SkipBodyInfo *SkipBody = nullptr);
2515   Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
2516                                 MultiTemplateParamsArg TemplateParamLists,
2517                                 SkipBodyInfo *SkipBody = nullptr);
2518   Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
2519                                 SkipBodyInfo *SkipBody = nullptr);
2520   void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D);
2521   ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr);
2522   void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
isObjCMethodDecl(Decl * D)2523   bool isObjCMethodDecl(Decl *D) {
2524     return D && isa<ObjCMethodDecl>(D);
2525   }
2526 
2527   /// Determine whether we can delay parsing the body of a function or
2528   /// function template until it is used, assuming we don't care about emitting
2529   /// code for that function.
2530   ///
2531   /// This will be \c false if we may need the body of the function in the
2532   /// middle of parsing an expression (where it's impractical to switch to
2533   /// parsing a different function), for instance, if it's constexpr in C++11
2534   /// or has an 'auto' return type in C++14. These cases are essentially bugs.
2535   bool canDelayFunctionBody(const Declarator &D);
2536 
2537   /// Determine whether we can skip parsing the body of a function
2538   /// definition, assuming we don't care about analyzing its body or emitting
2539   /// code for that function.
2540   ///
2541   /// This will be \c false only if we may need the body of the function in
2542   /// order to parse the rest of the program (for instance, if it is
2543   /// \c constexpr in C++11 or has an 'auto' return type in C++14).
2544   bool canSkipFunctionBody(Decl *D);
2545 
2546   void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
2547   Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
2548   Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
2549   Decl *ActOnSkippedFunctionBody(Decl *Decl);
2550   void ActOnFinishInlineFunctionDef(FunctionDecl *D);
2551 
2552   /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
2553   /// attribute for which parsing is delayed.
2554   void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
2555 
2556   /// Diagnose any unused parameters in the given sequence of
2557   /// ParmVarDecl pointers.
2558   void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
2559 
2560   /// Diagnose whether the size of parameters or return value of a
2561   /// function or obj-c method definition is pass-by-value and larger than a
2562   /// specified threshold.
2563   void
2564   DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
2565                                          QualType ReturnTy, NamedDecl *D);
2566 
2567   void DiagnoseInvalidJumps(Stmt *Body);
2568   Decl *ActOnFileScopeAsmDecl(Expr *expr,
2569                               SourceLocation AsmLoc,
2570                               SourceLocation RParenLoc);
2571 
2572   /// Handle a C++11 empty-declaration and attribute-declaration.
2573   Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
2574                               SourceLocation SemiLoc);
2575 
2576   enum class ModuleDeclKind {
2577     Interface,      ///< 'export module X;'
2578     Implementation, ///< 'module X;'
2579   };
2580 
2581   /// The parser has processed a module-declaration that begins the definition
2582   /// of a module interface or implementation.
2583   DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
2584                                  SourceLocation ModuleLoc, ModuleDeclKind MDK,
2585                                  ModuleIdPath Path, bool IsFirstDecl);
2586 
2587   /// The parser has processed a global-module-fragment declaration that begins
2588   /// the definition of the global module fragment of the current module unit.
2589   /// \param ModuleLoc The location of the 'module' keyword.
2590   DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
2591 
2592   /// The parser has processed a private-module-fragment declaration that begins
2593   /// the definition of the private module fragment of the current module unit.
2594   /// \param ModuleLoc The location of the 'module' keyword.
2595   /// \param PrivateLoc The location of the 'private' keyword.
2596   DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
2597                                                 SourceLocation PrivateLoc);
2598 
2599   /// The parser has processed a module import declaration.
2600   ///
2601   /// \param StartLoc The location of the first token in the declaration. This
2602   ///        could be the location of an '@', 'export', or 'import'.
2603   /// \param ExportLoc The location of the 'export' keyword, if any.
2604   /// \param ImportLoc The location of the 'import' keyword.
2605   /// \param Path The module access path.
2606   DeclResult ActOnModuleImport(SourceLocation StartLoc,
2607                                SourceLocation ExportLoc,
2608                                SourceLocation ImportLoc, ModuleIdPath Path);
2609   DeclResult ActOnModuleImport(SourceLocation StartLoc,
2610                                SourceLocation ExportLoc,
2611                                SourceLocation ImportLoc, Module *M,
2612                                ModuleIdPath Path = {});
2613 
2614   /// The parser has processed a module import translated from a
2615   /// #include or similar preprocessing directive.
2616   void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2617   void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2618 
2619   /// The parsed has entered a submodule.
2620   void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
2621   /// The parser has left a submodule.
2622   void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
2623 
2624   /// Create an implicit import of the given module at the given
2625   /// source location, for error recovery, if possible.
2626   ///
2627   /// This routine is typically used when an entity found by name lookup
2628   /// is actually hidden within a module that we know about but the user
2629   /// has forgotten to import.
2630   void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
2631                                                   Module *Mod);
2632 
2633   /// Kinds of missing import. Note, the values of these enumerators correspond
2634   /// to %select values in diagnostics.
2635   enum class MissingImportKind {
2636     Declaration,
2637     Definition,
2638     DefaultArgument,
2639     ExplicitSpecialization,
2640     PartialSpecialization
2641   };
2642 
2643   /// Diagnose that the specified declaration needs to be visible but
2644   /// isn't, and suggest a module import that would resolve the problem.
2645   void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2646                              MissingImportKind MIK, bool Recover = true);
2647   void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2648                              SourceLocation DeclLoc, ArrayRef<Module *> Modules,
2649                              MissingImportKind MIK, bool Recover);
2650 
2651   Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
2652                              SourceLocation LBraceLoc);
2653   Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
2654                               SourceLocation RBraceLoc);
2655 
2656   /// We've found a use of a templated declaration that would trigger an
2657   /// implicit instantiation. Check that any relevant explicit specializations
2658   /// and partial specializations are visible, and diagnose if not.
2659   void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
2660 
2661   /// We've found a use of a template specialization that would select a
2662   /// partial specialization. Check that the partial specialization is visible,
2663   /// and diagnose if not.
2664   void checkPartialSpecializationVisibility(SourceLocation Loc,
2665                                             NamedDecl *Spec);
2666 
2667   /// Retrieve a suitable printing policy for diagnostics.
getPrintingPolicy()2668   PrintingPolicy getPrintingPolicy() const {
2669     return getPrintingPolicy(Context, PP);
2670   }
2671 
2672   /// Retrieve a suitable printing policy for diagnostics.
2673   static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
2674                                           const Preprocessor &PP);
2675 
2676   /// Scope actions.
2677   void ActOnPopScope(SourceLocation Loc, Scope *S);
2678   void ActOnTranslationUnitScope(Scope *S);
2679 
2680   Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2681                                    RecordDecl *&AnonRecord);
2682   Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2683                                    MultiTemplateParamsArg TemplateParams,
2684                                    bool IsExplicitInstantiation,
2685                                    RecordDecl *&AnonRecord);
2686 
2687   Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2688                                     AccessSpecifier AS,
2689                                     RecordDecl *Record,
2690                                     const PrintingPolicy &Policy);
2691 
2692   Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2693                                        RecordDecl *Record);
2694 
2695   /// Common ways to introduce type names without a tag for use in diagnostics.
2696   /// Keep in sync with err_tag_reference_non_tag.
2697   enum NonTagKind {
2698     NTK_NonStruct,
2699     NTK_NonClass,
2700     NTK_NonUnion,
2701     NTK_NonEnum,
2702     NTK_Typedef,
2703     NTK_TypeAlias,
2704     NTK_Template,
2705     NTK_TypeAliasTemplate,
2706     NTK_TemplateTemplateArgument,
2707   };
2708 
2709   /// Given a non-tag type declaration, returns an enum useful for indicating
2710   /// what kind of non-tag type this is.
2711   NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
2712 
2713   bool isAcceptableTagRedeclaration(const TagDecl *Previous,
2714                                     TagTypeKind NewTag, bool isDefinition,
2715                                     SourceLocation NewTagLoc,
2716                                     const IdentifierInfo *Name);
2717 
2718   enum TagUseKind {
2719     TUK_Reference,   // Reference to a tag:  'struct foo *X;'
2720     TUK_Declaration, // Fwd decl of a tag:   'struct foo;'
2721     TUK_Definition,  // Definition of a tag: 'struct foo { int X; } Y;'
2722     TUK_Friend       // Friend declaration:  'friend struct foo;'
2723   };
2724 
2725   Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
2726                  SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
2727                  SourceLocation NameLoc, const ParsedAttributesView &Attr,
2728                  AccessSpecifier AS, SourceLocation ModulePrivateLoc,
2729                  MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
2730                  bool &IsDependent, SourceLocation ScopedEnumKWLoc,
2731                  bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
2732                  bool IsTypeSpecifier, bool IsTemplateParamOrArg,
2733                  SkipBodyInfo *SkipBody = nullptr);
2734 
2735   Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
2736                                 unsigned TagSpec, SourceLocation TagLoc,
2737                                 CXXScopeSpec &SS, IdentifierInfo *Name,
2738                                 SourceLocation NameLoc,
2739                                 const ParsedAttributesView &Attr,
2740                                 MultiTemplateParamsArg TempParamLists);
2741 
2742   TypeResult ActOnDependentTag(Scope *S,
2743                                unsigned TagSpec,
2744                                TagUseKind TUK,
2745                                const CXXScopeSpec &SS,
2746                                IdentifierInfo *Name,
2747                                SourceLocation TagLoc,
2748                                SourceLocation NameLoc);
2749 
2750   void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2751                  IdentifierInfo *ClassName,
2752                  SmallVectorImpl<Decl *> &Decls);
2753   Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
2754                    Declarator &D, Expr *BitfieldWidth);
2755 
2756   FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
2757                          Declarator &D, Expr *BitfieldWidth,
2758                          InClassInitStyle InitStyle,
2759                          AccessSpecifier AS);
2760   MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
2761                                    SourceLocation DeclStart, Declarator &D,
2762                                    Expr *BitfieldWidth,
2763                                    InClassInitStyle InitStyle,
2764                                    AccessSpecifier AS,
2765                                    const ParsedAttr &MSPropertyAttr);
2766 
2767   FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
2768                             TypeSourceInfo *TInfo,
2769                             RecordDecl *Record, SourceLocation Loc,
2770                             bool Mutable, Expr *BitfieldWidth,
2771                             InClassInitStyle InitStyle,
2772                             SourceLocation TSSL,
2773                             AccessSpecifier AS, NamedDecl *PrevDecl,
2774                             Declarator *D = nullptr);
2775 
2776   bool CheckNontrivialField(FieldDecl *FD);
2777   void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
2778 
2779   enum TrivialABIHandling {
2780     /// The triviality of a method unaffected by "trivial_abi".
2781     TAH_IgnoreTrivialABI,
2782 
2783     /// The triviality of a method affected by "trivial_abi".
2784     TAH_ConsiderTrivialABI
2785   };
2786 
2787   bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
2788                               TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
2789                               bool Diagnose = false);
2790 
2791   /// For a defaulted function, the kind of defaulted function that it is.
2792   class DefaultedFunctionKind {
2793     CXXSpecialMember SpecialMember : 8;
2794     DefaultedComparisonKind Comparison : 8;
2795 
2796   public:
DefaultedFunctionKind()2797     DefaultedFunctionKind()
2798         : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) {
2799     }
DefaultedFunctionKind(CXXSpecialMember CSM)2800     DefaultedFunctionKind(CXXSpecialMember CSM)
2801         : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {}
DefaultedFunctionKind(DefaultedComparisonKind Comp)2802     DefaultedFunctionKind(DefaultedComparisonKind Comp)
2803         : SpecialMember(CXXInvalid), Comparison(Comp) {}
2804 
isSpecialMember()2805     bool isSpecialMember() const { return SpecialMember != CXXInvalid; }
isComparison()2806     bool isComparison() const {
2807       return Comparison != DefaultedComparisonKind::None;
2808     }
2809 
2810     explicit operator bool() const {
2811       return isSpecialMember() || isComparison();
2812     }
2813 
asSpecialMember()2814     CXXSpecialMember asSpecialMember() const { return SpecialMember; }
asComparison()2815     DefaultedComparisonKind asComparison() const { return Comparison; }
2816 
2817     /// Get the index of this function kind for use in diagnostics.
getDiagnosticIndex()2818     unsigned getDiagnosticIndex() const {
2819       static_assert(CXXInvalid > CXXDestructor,
2820                     "invalid should have highest index");
2821       static_assert((unsigned)DefaultedComparisonKind::None == 0,
2822                     "none should be equal to zero");
2823       return SpecialMember + (unsigned)Comparison;
2824     }
2825   };
2826 
2827   DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
2828 
getSpecialMember(const CXXMethodDecl * MD)2829   CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) {
2830     return getDefaultedFunctionKind(MD).asSpecialMember();
2831   }
getDefaultedComparisonKind(const FunctionDecl * FD)2832   DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) {
2833     return getDefaultedFunctionKind(FD).asComparison();
2834   }
2835 
2836   void ActOnLastBitfield(SourceLocation DeclStart,
2837                          SmallVectorImpl<Decl *> &AllIvarDecls);
2838   Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
2839                   Declarator &D, Expr *BitfieldWidth,
2840                   tok::ObjCKeywordKind visibility);
2841 
2842   // This is used for both record definitions and ObjC interface declarations.
2843   void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
2844                    ArrayRef<Decl *> Fields, SourceLocation LBrac,
2845                    SourceLocation RBrac, const ParsedAttributesView &AttrList);
2846 
2847   /// ActOnTagStartDefinition - Invoked when we have entered the
2848   /// scope of a tag's definition (e.g., for an enumeration, class,
2849   /// struct, or union).
2850   void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
2851 
2852   /// Perform ODR-like check for C/ObjC when merging tag types from modules.
2853   /// Differently from C++, actually parse the body and reject / error out
2854   /// in case of a structural mismatch.
2855   bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
2856                                 SkipBodyInfo &SkipBody);
2857 
2858   typedef void *SkippedDefinitionContext;
2859 
2860   /// Invoked when we enter a tag definition that we're skipping.
2861   SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
2862 
2863   Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
2864 
2865   /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
2866   /// C++ record definition's base-specifiers clause and are starting its
2867   /// member declarations.
2868   void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
2869                                        SourceLocation FinalLoc,
2870                                        bool IsFinalSpelledSealed,
2871                                        SourceLocation LBraceLoc);
2872 
2873   /// ActOnTagFinishDefinition - Invoked once we have finished parsing
2874   /// the definition of a tag (enumeration, class, struct, or union).
2875   void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
2876                                 SourceRange BraceRange);
2877 
2878   void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
2879 
2880   void ActOnObjCContainerFinishDefinition();
2881 
2882   /// Invoked when we must temporarily exit the objective-c container
2883   /// scope for parsing/looking-up C constructs.
2884   ///
2885   /// Must be followed by a call to \see ActOnObjCReenterContainerContext
2886   void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
2887   void ActOnObjCReenterContainerContext(DeclContext *DC);
2888 
2889   /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
2890   /// error parsing the definition of a tag.
2891   void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
2892 
2893   EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
2894                                       EnumConstantDecl *LastEnumConst,
2895                                       SourceLocation IdLoc,
2896                                       IdentifierInfo *Id,
2897                                       Expr *val);
2898   bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
2899   bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
2900                               QualType EnumUnderlyingTy, bool IsFixed,
2901                               const EnumDecl *Prev);
2902 
2903   /// Determine whether the body of an anonymous enumeration should be skipped.
2904   /// \param II The name of the first enumerator.
2905   SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
2906                                       SourceLocation IILoc);
2907 
2908   Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
2909                           SourceLocation IdLoc, IdentifierInfo *Id,
2910                           const ParsedAttributesView &Attrs,
2911                           SourceLocation EqualLoc, Expr *Val);
2912   void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
2913                      Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
2914                      const ParsedAttributesView &Attr);
2915 
2916   /// Set the current declaration context until it gets popped.
2917   void PushDeclContext(Scope *S, DeclContext *DC);
2918   void PopDeclContext();
2919 
2920   /// EnterDeclaratorContext - Used when we must lookup names in the context
2921   /// of a declarator's nested name specifier.
2922   void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2923   void ExitDeclaratorContext(Scope *S);
2924 
2925   /// Enter a template parameter scope, after it's been associated with a particular
2926   /// DeclContext. Causes lookup within the scope to chain through enclosing contexts
2927   /// in the correct order.
2928   void EnterTemplatedContext(Scope *S, DeclContext *DC);
2929 
2930   /// Push the parameters of D, which must be a function, into scope.
2931   void ActOnReenterFunctionContext(Scope* S, Decl* D);
2932   void ActOnExitFunctionContext();
2933 
2934   DeclContext *getFunctionLevelDeclContext();
2935 
2936   /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2937   /// to the function decl for the function being parsed.  If we're currently
2938   /// in a 'block', this returns the containing context.
2939   FunctionDecl *getCurFunctionDecl();
2940 
2941   /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2942   /// the method decl for the method being parsed.  If we're currently
2943   /// in a 'block', this returns the containing context.
2944   ObjCMethodDecl *getCurMethodDecl();
2945 
2946   /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2947   /// or C function we're in, otherwise return null.  If we're currently
2948   /// in a 'block', this returns the containing context.
2949   NamedDecl *getCurFunctionOrMethodDecl();
2950 
2951   /// Add this decl to the scope shadowed decl chains.
2952   void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2953 
2954   /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2955   /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2956   /// true if 'D' belongs to the given declaration context.
2957   ///
2958   /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2959   ///        enclosing namespace set of the context, rather than contained
2960   ///        directly within it.
2961   bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2962                      bool AllowInlineNamespace = false);
2963 
2964   /// Finds the scope corresponding to the given decl context, if it
2965   /// happens to be an enclosing scope.  Otherwise return NULL.
2966   static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2967 
2968   /// Subroutines of ActOnDeclarator().
2969   TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2970                                 TypeSourceInfo *TInfo);
2971   bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2972 
2973   /// Describes the kind of merge to perform for availability
2974   /// attributes (including "deprecated", "unavailable", and "availability").
2975   enum AvailabilityMergeKind {
2976     /// Don't merge availability attributes at all.
2977     AMK_None,
2978     /// Merge availability attributes for a redeclaration, which requires
2979     /// an exact match.
2980     AMK_Redeclaration,
2981     /// Merge availability attributes for an override, which requires
2982     /// an exact match or a weakening of constraints.
2983     AMK_Override,
2984     /// Merge availability attributes for an implementation of
2985     /// a protocol requirement.
2986     AMK_ProtocolImplementation,
2987   };
2988 
2989   /// Describes the kind of priority given to an availability attribute.
2990   ///
2991   /// The sum of priorities deteremines the final priority of the attribute.
2992   /// The final priority determines how the attribute will be merged.
2993   /// An attribute with a lower priority will always remove higher priority
2994   /// attributes for the specified platform when it is being applied. An
2995   /// attribute with a higher priority will not be applied if the declaration
2996   /// already has an availability attribute with a lower priority for the
2997   /// specified platform. The final prirority values are not expected to match
2998   /// the values in this enumeration, but instead should be treated as a plain
2999   /// integer value. This enumeration just names the priority weights that are
3000   /// used to calculate that final vaue.
3001   enum AvailabilityPriority : int {
3002     /// The availability attribute was specified explicitly next to the
3003     /// declaration.
3004     AP_Explicit = 0,
3005 
3006     /// The availability attribute was applied using '#pragma clang attribute'.
3007     AP_PragmaClangAttribute = 1,
3008 
3009     /// The availability attribute for a specific platform was inferred from
3010     /// an availability attribute for another platform.
3011     AP_InferredFromOtherPlatform = 2
3012   };
3013 
3014   /// Attribute merging methods. Return true if a new attribute was added.
3015   AvailabilityAttr *
3016   mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
3017                         IdentifierInfo *Platform, bool Implicit,
3018                         VersionTuple Introduced, VersionTuple Deprecated,
3019                         VersionTuple Obsoleted, bool IsUnavailable,
3020                         StringRef Message, bool IsStrict, StringRef Replacement,
3021                         AvailabilityMergeKind AMK, int Priority);
3022   TypeVisibilityAttr *
3023   mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3024                           TypeVisibilityAttr::VisibilityType Vis);
3025   VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3026                                       VisibilityAttr::VisibilityType Vis);
3027   UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
3028                           StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
3029   DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
3030   DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
3031   MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
3032                                             const AttributeCommonInfo &CI,
3033                                             bool BestCase,
3034                                             MSInheritanceModel Model);
3035   FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
3036                               IdentifierInfo *Format, int FormatIdx,
3037                               int FirstArg);
3038   SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
3039                                 StringRef Name);
3040   CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
3041                                 StringRef Name);
3042   AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
3043                                           const AttributeCommonInfo &CI,
3044                                           const IdentifierInfo *Ident);
3045   MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
3046   NoSpeculativeLoadHardeningAttr *
3047   mergeNoSpeculativeLoadHardeningAttr(Decl *D,
3048                                       const NoSpeculativeLoadHardeningAttr &AL);
3049   SpeculativeLoadHardeningAttr *
3050   mergeSpeculativeLoadHardeningAttr(Decl *D,
3051                                     const SpeculativeLoadHardeningAttr &AL);
3052   OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
3053                                           const AttributeCommonInfo &CI);
3054   InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
3055   InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
3056                                                 const InternalLinkageAttr &AL);
3057   CommonAttr *mergeCommonAttr(Decl *D, const ParsedAttr &AL);
3058   CommonAttr *mergeCommonAttr(Decl *D, const CommonAttr &AL);
3059   WebAssemblyImportNameAttr *mergeImportNameAttr(
3060       Decl *D, const WebAssemblyImportNameAttr &AL);
3061   WebAssemblyImportModuleAttr *mergeImportModuleAttr(
3062       Decl *D, const WebAssemblyImportModuleAttr &AL);
3063 
3064   void mergeDeclAttributes(NamedDecl *New, Decl *Old,
3065                            AvailabilityMergeKind AMK = AMK_Redeclaration);
3066   void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
3067                             LookupResult &OldDecls);
3068   bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
3069                          bool MergeTypeWithOld);
3070   bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3071                                     Scope *S, bool MergeTypeWithOld);
3072   void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
3073   void MergeVarDecl(VarDecl *New, LookupResult &Previous);
3074   void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
3075   void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
3076   bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
3077   void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
3078   bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
3079 
3080   // AssignmentAction - This is used by all the assignment diagnostic functions
3081   // to represent what is actually causing the operation
3082   enum AssignmentAction {
3083     AA_Assigning,
3084     AA_Passing,
3085     AA_Returning,
3086     AA_Converting,
3087     AA_Initializing,
3088     AA_Sending,
3089     AA_Casting,
3090     AA_Passing_CFAudited
3091   };
3092 
3093   /// C++ Overloading.
3094   enum OverloadKind {
3095     /// This is a legitimate overload: the existing declarations are
3096     /// functions or function templates with different signatures.
3097     Ovl_Overload,
3098 
3099     /// This is not an overload because the signature exactly matches
3100     /// an existing declaration.
3101     Ovl_Match,
3102 
3103     /// This is not an overload because the lookup results contain a
3104     /// non-function.
3105     Ovl_NonFunction
3106   };
3107   OverloadKind CheckOverload(Scope *S,
3108                              FunctionDecl *New,
3109                              const LookupResult &OldDecls,
3110                              NamedDecl *&OldDecl,
3111                              bool IsForUsingDecl);
3112   bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
3113                   bool ConsiderCudaAttrs = true,
3114                   bool ConsiderRequiresClauses = true);
3115 
3116   enum class AllowedExplicit {
3117     /// Allow no explicit functions to be used.
3118     None,
3119     /// Allow explicit conversion functions but not explicit constructors.
3120     Conversions,
3121     /// Allow both explicit conversion functions and explicit constructors.
3122     All
3123   };
3124 
3125   ImplicitConversionSequence
3126   TryImplicitConversion(Expr *From, QualType ToType,
3127                         bool SuppressUserConversions,
3128                         AllowedExplicit AllowExplicit,
3129                         bool InOverloadResolution,
3130                         bool CStyle,
3131                         bool AllowObjCWritebackConversion);
3132 
3133   bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
3134   bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
3135   bool IsComplexPromotion(QualType FromType, QualType ToType);
3136   bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
3137                            bool InOverloadResolution,
3138                            QualType& ConvertedType, bool &IncompatibleObjC);
3139   bool isObjCPointerConversion(QualType FromType, QualType ToType,
3140                                QualType& ConvertedType, bool &IncompatibleObjC);
3141   bool isObjCWritebackConversion(QualType FromType, QualType ToType,
3142                                  QualType &ConvertedType);
3143   bool IsBlockPointerConversion(QualType FromType, QualType ToType,
3144                                 QualType& ConvertedType);
3145   bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3146                                   const FunctionProtoType *NewType,
3147                                   unsigned *ArgPos = nullptr);
3148   void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
3149                                   QualType FromType, QualType ToType);
3150 
3151   void maybeExtendBlockObject(ExprResult &E);
3152   CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
3153   bool CheckPointerConversion(Expr *From, QualType ToType,
3154                               CastKind &Kind,
3155                               CXXCastPath& BasePath,
3156                               bool IgnoreBaseAccess,
3157                               bool Diagnose = true);
3158   bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
3159                                  bool InOverloadResolution,
3160                                  QualType &ConvertedType);
3161   bool CheckMemberPointerConversion(Expr *From, QualType ToType,
3162                                     CastKind &Kind,
3163                                     CXXCastPath &BasePath,
3164                                     bool IgnoreBaseAccess);
3165   bool IsQualificationConversion(QualType FromType, QualType ToType,
3166                                  bool CStyle, bool &ObjCLifetimeConversion);
3167   bool IsFunctionConversion(QualType FromType, QualType ToType,
3168                             QualType &ResultTy);
3169   bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
3170   bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
3171 
3172   ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
3173                                              const VarDecl *NRVOCandidate,
3174                                              QualType ResultType,
3175                                              Expr *Value,
3176                                              bool AllowNRVO = true);
3177 
3178   bool CanPerformAggregateInitializationForOverloadResolution(
3179       const InitializedEntity &Entity, InitListExpr *From);
3180 
3181   bool CanPerformCopyInitialization(const InitializedEntity &Entity,
3182                                     ExprResult Init);
3183   ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
3184                                        SourceLocation EqualLoc,
3185                                        ExprResult Init,
3186                                        bool TopLevelOfInitList = false,
3187                                        bool AllowExplicit = false);
3188   ExprResult PerformObjectArgumentInitialization(Expr *From,
3189                                                  NestedNameSpecifier *Qualifier,
3190                                                  NamedDecl *FoundDecl,
3191                                                  CXXMethodDecl *Method);
3192 
3193   /// Check that the lifetime of the initializer (and its subobjects) is
3194   /// sufficient for initializing the entity, and perform lifetime extension
3195   /// (when permitted) if not.
3196   void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
3197 
3198   ExprResult PerformContextuallyConvertToBool(Expr *From);
3199   ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
3200 
3201   /// Contexts in which a converted constant expression is required.
3202   enum CCEKind {
3203     CCEK_CaseValue,   ///< Expression in a case label.
3204     CCEK_Enumerator,  ///< Enumerator value with fixed underlying type.
3205     CCEK_TemplateArg, ///< Value of a non-type template parameter.
3206     CCEK_NewExpr,     ///< Constant expression in a noptr-new-declarator.
3207     CCEK_ConstexprIf, ///< Condition in a constexpr if statement.
3208     CCEK_ExplicitBool ///< Condition in an explicit(bool) specifier.
3209   };
3210   ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
3211                                               llvm::APSInt &Value, CCEKind CCE);
3212   ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
3213                                               APValue &Value, CCEKind CCE);
3214 
3215   /// Abstract base class used to perform a contextual implicit
3216   /// conversion from an expression to any type passing a filter.
3217   class ContextualImplicitConverter {
3218   public:
3219     bool Suppress;
3220     bool SuppressConversion;
3221 
3222     ContextualImplicitConverter(bool Suppress = false,
3223                                 bool SuppressConversion = false)
Suppress(Suppress)3224         : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
3225 
3226     /// Determine whether the specified type is a valid destination type
3227     /// for this conversion.
3228     virtual bool match(QualType T) = 0;
3229 
3230     /// Emits a diagnostic complaining that the expression does not have
3231     /// integral or enumeration type.
3232     virtual SemaDiagnosticBuilder
3233     diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
3234 
3235     /// Emits a diagnostic when the expression has incomplete class type.
3236     virtual SemaDiagnosticBuilder
3237     diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
3238 
3239     /// Emits a diagnostic when the only matching conversion function
3240     /// is explicit.
3241     virtual SemaDiagnosticBuilder diagnoseExplicitConv(
3242         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3243 
3244     /// Emits a note for the explicit conversion function.
3245     virtual SemaDiagnosticBuilder
3246     noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3247 
3248     /// Emits a diagnostic when there are multiple possible conversion
3249     /// functions.
3250     virtual SemaDiagnosticBuilder
3251     diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
3252 
3253     /// Emits a note for one of the candidate conversions.
3254     virtual SemaDiagnosticBuilder
3255     noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3256 
3257     /// Emits a diagnostic when we picked a conversion function
3258     /// (for cases when we are not allowed to pick a conversion function).
3259     virtual SemaDiagnosticBuilder diagnoseConversion(
3260         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3261 
~ContextualImplicitConverter()3262     virtual ~ContextualImplicitConverter() {}
3263   };
3264 
3265   class ICEConvertDiagnoser : public ContextualImplicitConverter {
3266     bool AllowScopedEnumerations;
3267 
3268   public:
ICEConvertDiagnoser(bool AllowScopedEnumerations,bool Suppress,bool SuppressConversion)3269     ICEConvertDiagnoser(bool AllowScopedEnumerations,
3270                         bool Suppress, bool SuppressConversion)
3271         : ContextualImplicitConverter(Suppress, SuppressConversion),
3272           AllowScopedEnumerations(AllowScopedEnumerations) {}
3273 
3274     /// Match an integral or (possibly scoped) enumeration type.
3275     bool match(QualType T) override;
3276 
3277     SemaDiagnosticBuilder
diagnoseNoMatch(Sema & S,SourceLocation Loc,QualType T)3278     diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
3279       return diagnoseNotInt(S, Loc, T);
3280     }
3281 
3282     /// Emits a diagnostic complaining that the expression does not have
3283     /// integral or enumeration type.
3284     virtual SemaDiagnosticBuilder
3285     diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
3286   };
3287 
3288   /// Perform a contextual implicit conversion.
3289   ExprResult PerformContextualImplicitConversion(
3290       SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
3291 
3292 
3293   enum ObjCSubscriptKind {
3294     OS_Array,
3295     OS_Dictionary,
3296     OS_Error
3297   };
3298   ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
3299 
3300   // Note that LK_String is intentionally after the other literals, as
3301   // this is used for diagnostics logic.
3302   enum ObjCLiteralKind {
3303     LK_Array,
3304     LK_Dictionary,
3305     LK_Numeric,
3306     LK_Boxed,
3307     LK_String,
3308     LK_Block,
3309     LK_None
3310   };
3311   ObjCLiteralKind CheckLiteralKind(Expr *FromE);
3312 
3313   ExprResult PerformObjectMemberConversion(Expr *From,
3314                                            NestedNameSpecifier *Qualifier,
3315                                            NamedDecl *FoundDecl,
3316                                            NamedDecl *Member);
3317 
3318   // Members have to be NamespaceDecl* or TranslationUnitDecl*.
3319   // TODO: make this is a typesafe union.
3320   typedef llvm::SmallSetVector<DeclContext   *, 16> AssociatedNamespaceSet;
3321   typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
3322 
3323   using ADLCallKind = CallExpr::ADLCallKind;
3324 
3325   void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl,
3326                             ArrayRef<Expr *> Args,
3327                             OverloadCandidateSet &CandidateSet,
3328                             bool SuppressUserConversions = false,
3329                             bool PartialOverloading = false,
3330                             bool AllowExplicit = true,
3331                             bool AllowExplicitConversion = false,
3332                             ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3333                             ConversionSequenceList EarlyConversions = None,
3334                             OverloadCandidateParamOrder PO = {});
3335   void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
3336                       ArrayRef<Expr *> Args,
3337                       OverloadCandidateSet &CandidateSet,
3338                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3339                       bool SuppressUserConversions = false,
3340                       bool PartialOverloading = false,
3341                       bool FirstArgumentIsBase = false);
3342   void AddMethodCandidate(DeclAccessPair FoundDecl,
3343                           QualType ObjectType,
3344                           Expr::Classification ObjectClassification,
3345                           ArrayRef<Expr *> Args,
3346                           OverloadCandidateSet& CandidateSet,
3347                           bool SuppressUserConversion = false,
3348                           OverloadCandidateParamOrder PO = {});
3349   void AddMethodCandidate(CXXMethodDecl *Method,
3350                           DeclAccessPair FoundDecl,
3351                           CXXRecordDecl *ActingContext, QualType ObjectType,
3352                           Expr::Classification ObjectClassification,
3353                           ArrayRef<Expr *> Args,
3354                           OverloadCandidateSet& CandidateSet,
3355                           bool SuppressUserConversions = false,
3356                           bool PartialOverloading = false,
3357                           ConversionSequenceList EarlyConversions = None,
3358                           OverloadCandidateParamOrder PO = {});
3359   void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
3360                                   DeclAccessPair FoundDecl,
3361                                   CXXRecordDecl *ActingContext,
3362                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
3363                                   QualType ObjectType,
3364                                   Expr::Classification ObjectClassification,
3365                                   ArrayRef<Expr *> Args,
3366                                   OverloadCandidateSet& CandidateSet,
3367                                   bool SuppressUserConversions = false,
3368                                   bool PartialOverloading = false,
3369                                   OverloadCandidateParamOrder PO = {});
3370   void AddTemplateOverloadCandidate(
3371       FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3372       TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
3373       OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
3374       bool PartialOverloading = false, bool AllowExplicit = true,
3375       ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3376       OverloadCandidateParamOrder PO = {});
3377   bool CheckNonDependentConversions(
3378       FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
3379       ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
3380       ConversionSequenceList &Conversions, bool SuppressUserConversions,
3381       CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
3382       Expr::Classification ObjectClassification = {},
3383       OverloadCandidateParamOrder PO = {});
3384   void AddConversionCandidate(
3385       CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
3386       CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3387       OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3388       bool AllowExplicit, bool AllowResultConversion = true);
3389   void AddTemplateConversionCandidate(
3390       FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3391       CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3392       OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3393       bool AllowExplicit, bool AllowResultConversion = true);
3394   void AddSurrogateCandidate(CXXConversionDecl *Conversion,
3395                              DeclAccessPair FoundDecl,
3396                              CXXRecordDecl *ActingContext,
3397                              const FunctionProtoType *Proto,
3398                              Expr *Object, ArrayRef<Expr *> Args,
3399                              OverloadCandidateSet& CandidateSet);
3400   void AddNonMemberOperatorCandidates(
3401       const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
3402       OverloadCandidateSet &CandidateSet,
3403       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
3404   void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3405                                    SourceLocation OpLoc, ArrayRef<Expr *> Args,
3406                                    OverloadCandidateSet &CandidateSet,
3407                                    OverloadCandidateParamOrder PO = {});
3408   void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
3409                            OverloadCandidateSet& CandidateSet,
3410                            bool IsAssignmentOperator = false,
3411                            unsigned NumContextualBoolArguments = 0);
3412   void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
3413                                     SourceLocation OpLoc, ArrayRef<Expr *> Args,
3414                                     OverloadCandidateSet& CandidateSet);
3415   void AddArgumentDependentLookupCandidates(DeclarationName Name,
3416                                             SourceLocation Loc,
3417                                             ArrayRef<Expr *> Args,
3418                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
3419                                             OverloadCandidateSet& CandidateSet,
3420                                             bool PartialOverloading = false);
3421 
3422   // Emit as a 'note' the specific overload candidate
3423   void NoteOverloadCandidate(
3424       NamedDecl *Found, FunctionDecl *Fn,
3425       OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(),
3426       QualType DestType = QualType(), bool TakingAddress = false);
3427 
3428   // Emit as a series of 'note's all template and non-templates identified by
3429   // the expression Expr
3430   void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
3431                                  bool TakingAddress = false);
3432 
3433   /// Check the enable_if expressions on the given function. Returns the first
3434   /// failing attribute, or NULL if they were all successful.
3435   EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc,
3436                               ArrayRef<Expr *> Args,
3437                               bool MissingImplicitThis = false);
3438 
3439   /// Find the failed Boolean condition within a given Boolean
3440   /// constant expression, and describe it with a string.
3441   std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
3442 
3443   /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3444   /// non-ArgDependent DiagnoseIfAttrs.
3445   ///
3446   /// Argument-dependent diagnose_if attributes should be checked each time a
3447   /// function is used as a direct callee of a function call.
3448   ///
3449   /// Returns true if any errors were emitted.
3450   bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
3451                                            const Expr *ThisArg,
3452                                            ArrayRef<const Expr *> Args,
3453                                            SourceLocation Loc);
3454 
3455   /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3456   /// ArgDependent DiagnoseIfAttrs.
3457   ///
3458   /// Argument-independent diagnose_if attributes should be checked on every use
3459   /// of a function.
3460   ///
3461   /// Returns true if any errors were emitted.
3462   bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
3463                                              SourceLocation Loc);
3464 
3465   /// Returns whether the given function's address can be taken or not,
3466   /// optionally emitting a diagnostic if the address can't be taken.
3467   ///
3468   /// Returns false if taking the address of the function is illegal.
3469   bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
3470                                          bool Complain = false,
3471                                          SourceLocation Loc = SourceLocation());
3472 
3473   // [PossiblyAFunctionType]  -->   [Return]
3474   // NonFunctionType --> NonFunctionType
3475   // R (A) --> R(A)
3476   // R (*)(A) --> R (A)
3477   // R (&)(A) --> R (A)
3478   // R (S::*)(A) --> R (A)
3479   QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
3480 
3481   FunctionDecl *
3482   ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
3483                                      QualType TargetType,
3484                                      bool Complain,
3485                                      DeclAccessPair &Found,
3486                                      bool *pHadMultipleCandidates = nullptr);
3487 
3488   FunctionDecl *
3489   resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
3490 
3491   bool resolveAndFixAddressOfSingleOverloadCandidate(
3492       ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
3493 
3494   FunctionDecl *
3495   ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
3496                                               bool Complain = false,
3497                                               DeclAccessPair *Found = nullptr);
3498 
3499   bool ResolveAndFixSingleFunctionTemplateSpecialization(
3500                       ExprResult &SrcExpr,
3501                       bool DoFunctionPointerConverion = false,
3502                       bool Complain = false,
3503                       SourceRange OpRangeForComplaining = SourceRange(),
3504                       QualType DestTypeForComplaining = QualType(),
3505                       unsigned DiagIDForComplaining = 0);
3506 
3507 
3508   Expr *FixOverloadedFunctionReference(Expr *E,
3509                                        DeclAccessPair FoundDecl,
3510                                        FunctionDecl *Fn);
3511   ExprResult FixOverloadedFunctionReference(ExprResult,
3512                                             DeclAccessPair FoundDecl,
3513                                             FunctionDecl *Fn);
3514 
3515   void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
3516                                    ArrayRef<Expr *> Args,
3517                                    OverloadCandidateSet &CandidateSet,
3518                                    bool PartialOverloading = false);
3519 
3520   // An enum used to represent the different possible results of building a
3521   // range-based for loop.
3522   enum ForRangeStatus {
3523     FRS_Success,
3524     FRS_NoViableFunction,
3525     FRS_DiagnosticIssued
3526   };
3527 
3528   ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
3529                                            SourceLocation RangeLoc,
3530                                            const DeclarationNameInfo &NameInfo,
3531                                            LookupResult &MemberLookup,
3532                                            OverloadCandidateSet *CandidateSet,
3533                                            Expr *Range, ExprResult *CallExpr);
3534 
3535   ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
3536                                      UnresolvedLookupExpr *ULE,
3537                                      SourceLocation LParenLoc,
3538                                      MultiExprArg Args,
3539                                      SourceLocation RParenLoc,
3540                                      Expr *ExecConfig,
3541                                      bool AllowTypoCorrection=true,
3542                                      bool CalleesAddressIsTaken=false);
3543 
3544   bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
3545                               MultiExprArg Args, SourceLocation RParenLoc,
3546                               OverloadCandidateSet *CandidateSet,
3547                               ExprResult *Result);
3548 
3549   ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
3550                                      UnaryOperatorKind Opc,
3551                                      const UnresolvedSetImpl &Fns,
3552                                      Expr *input, bool RequiresADL = true);
3553 
3554   void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
3555                              OverloadedOperatorKind Op,
3556                              const UnresolvedSetImpl &Fns,
3557                              ArrayRef<Expr *> Args, bool RequiresADL = true);
3558   ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
3559                                    BinaryOperatorKind Opc,
3560                                    const UnresolvedSetImpl &Fns,
3561                                    Expr *LHS, Expr *RHS,
3562                                    bool RequiresADL = true,
3563                                    bool AllowRewrittenCandidates = true,
3564                                    FunctionDecl *DefaultedFn = nullptr);
3565   ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc,
3566                                                 const UnresolvedSetImpl &Fns,
3567                                                 Expr *LHS, Expr *RHS,
3568                                                 FunctionDecl *DefaultedFn);
3569 
3570   ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
3571                                                 SourceLocation RLoc,
3572                                                 Expr *Base,Expr *Idx);
3573 
3574   ExprResult
3575   BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
3576                             SourceLocation LParenLoc,
3577                             MultiExprArg Args,
3578                             SourceLocation RParenLoc);
3579   ExprResult
3580   BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
3581                                MultiExprArg Args,
3582                                SourceLocation RParenLoc);
3583 
3584   ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
3585                                       SourceLocation OpLoc,
3586                                       bool *NoArrowOperatorFound = nullptr);
3587 
3588   /// CheckCallReturnType - Checks that a call expression's return type is
3589   /// complete. Returns true on failure. The location passed in is the location
3590   /// that best represents the call.
3591   bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
3592                            CallExpr *CE, FunctionDecl *FD);
3593 
3594   /// Helpers for dealing with blocks and functions.
3595   bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
3596                                 bool CheckParameterNames);
3597   void CheckCXXDefaultArguments(FunctionDecl *FD);
3598   void CheckExtraCXXDefaultArguments(Declarator &D);
3599   Scope *getNonFieldDeclScope(Scope *S);
3600 
3601   /// \name Name lookup
3602   ///
3603   /// These routines provide name lookup that is used during semantic
3604   /// analysis to resolve the various kinds of names (identifiers,
3605   /// overloaded operator names, constructor names, etc.) into zero or
3606   /// more declarations within a particular scope. The major entry
3607   /// points are LookupName, which performs unqualified name lookup,
3608   /// and LookupQualifiedName, which performs qualified name lookup.
3609   ///
3610   /// All name lookup is performed based on some specific criteria,
3611   /// which specify what names will be visible to name lookup and how
3612   /// far name lookup should work. These criteria are important both
3613   /// for capturing language semantics (certain lookups will ignore
3614   /// certain names, for example) and for performance, since name
3615   /// lookup is often a bottleneck in the compilation of C++. Name
3616   /// lookup criteria is specified via the LookupCriteria enumeration.
3617   ///
3618   /// The results of name lookup can vary based on the kind of name
3619   /// lookup performed, the current language, and the translation
3620   /// unit. In C, for example, name lookup will either return nothing
3621   /// (no entity found) or a single declaration. In C++, name lookup
3622   /// can additionally refer to a set of overloaded functions or
3623   /// result in an ambiguity. All of the possible results of name
3624   /// lookup are captured by the LookupResult class, which provides
3625   /// the ability to distinguish among them.
3626   //@{
3627 
3628   /// Describes the kind of name lookup to perform.
3629   enum LookupNameKind {
3630     /// Ordinary name lookup, which finds ordinary names (functions,
3631     /// variables, typedefs, etc.) in C and most kinds of names
3632     /// (functions, variables, members, types, etc.) in C++.
3633     LookupOrdinaryName = 0,
3634     /// Tag name lookup, which finds the names of enums, classes,
3635     /// structs, and unions.
3636     LookupTagName,
3637     /// Label name lookup.
3638     LookupLabel,
3639     /// Member name lookup, which finds the names of
3640     /// class/struct/union members.
3641     LookupMemberName,
3642     /// Look up of an operator name (e.g., operator+) for use with
3643     /// operator overloading. This lookup is similar to ordinary name
3644     /// lookup, but will ignore any declarations that are class members.
3645     LookupOperatorName,
3646     /// Look up a name following ~ in a destructor name. This is an ordinary
3647     /// lookup, but prefers tags to typedefs.
3648     LookupDestructorName,
3649     /// Look up of a name that precedes the '::' scope resolution
3650     /// operator in C++. This lookup completely ignores operator, object,
3651     /// function, and enumerator names (C++ [basic.lookup.qual]p1).
3652     LookupNestedNameSpecifierName,
3653     /// Look up a namespace name within a C++ using directive or
3654     /// namespace alias definition, ignoring non-namespace names (C++
3655     /// [basic.lookup.udir]p1).
3656     LookupNamespaceName,
3657     /// Look up all declarations in a scope with the given name,
3658     /// including resolved using declarations.  This is appropriate
3659     /// for checking redeclarations for a using declaration.
3660     LookupUsingDeclName,
3661     /// Look up an ordinary name that is going to be redeclared as a
3662     /// name with linkage. This lookup ignores any declarations that
3663     /// are outside of the current scope unless they have linkage. See
3664     /// C99 6.2.2p4-5 and C++ [basic.link]p6.
3665     LookupRedeclarationWithLinkage,
3666     /// Look up a friend of a local class. This lookup does not look
3667     /// outside the innermost non-class scope. See C++11 [class.friend]p11.
3668     LookupLocalFriendName,
3669     /// Look up the name of an Objective-C protocol.
3670     LookupObjCProtocolName,
3671     /// Look up implicit 'self' parameter of an objective-c method.
3672     LookupObjCImplicitSelfParam,
3673     /// Look up the name of an OpenMP user-defined reduction operation.
3674     LookupOMPReductionName,
3675     /// Look up the name of an OpenMP user-defined mapper.
3676     LookupOMPMapperName,
3677     /// Look up any declaration with any name.
3678     LookupAnyName
3679   };
3680 
3681   /// Specifies whether (or how) name lookup is being performed for a
3682   /// redeclaration (vs. a reference).
3683   enum RedeclarationKind {
3684     /// The lookup is a reference to this name that is not for the
3685     /// purpose of redeclaring the name.
3686     NotForRedeclaration = 0,
3687     /// The lookup results will be used for redeclaration of a name,
3688     /// if an entity by that name already exists and is visible.
3689     ForVisibleRedeclaration,
3690     /// The lookup results will be used for redeclaration of a name
3691     /// with external linkage; non-visible lookup results with external linkage
3692     /// may also be found.
3693     ForExternalRedeclaration
3694   };
3695 
forRedeclarationInCurContext()3696   RedeclarationKind forRedeclarationInCurContext() {
3697     // A declaration with an owning module for linkage can never link against
3698     // anything that is not visible. We don't need to check linkage here; if
3699     // the context has internal linkage, redeclaration lookup won't find things
3700     // from other TUs, and we can't safely compute linkage yet in general.
3701     if (cast<Decl>(CurContext)
3702             ->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
3703       return ForVisibleRedeclaration;
3704     return ForExternalRedeclaration;
3705   }
3706 
3707   /// The possible outcomes of name lookup for a literal operator.
3708   enum LiteralOperatorLookupResult {
3709     /// The lookup resulted in an error.
3710     LOLR_Error,
3711     /// The lookup found no match but no diagnostic was issued.
3712     LOLR_ErrorNoDiagnostic,
3713     /// The lookup found a single 'cooked' literal operator, which
3714     /// expects a normal literal to be built and passed to it.
3715     LOLR_Cooked,
3716     /// The lookup found a single 'raw' literal operator, which expects
3717     /// a string literal containing the spelling of the literal token.
3718     LOLR_Raw,
3719     /// The lookup found an overload set of literal operator templates,
3720     /// which expect the characters of the spelling of the literal token to be
3721     /// passed as a non-type template argument pack.
3722     LOLR_Template,
3723     /// The lookup found an overload set of literal operator templates,
3724     /// which expect the character type and characters of the spelling of the
3725     /// string literal token to be passed as template arguments.
3726     LOLR_StringTemplate
3727   };
3728 
3729   SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
3730                                                   CXXSpecialMember SM,
3731                                                   bool ConstArg,
3732                                                   bool VolatileArg,
3733                                                   bool RValueThis,
3734                                                   bool ConstThis,
3735                                                   bool VolatileThis);
3736 
3737   typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
3738   typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
3739       TypoRecoveryCallback;
3740 
3741 private:
3742   bool CppLookupName(LookupResult &R, Scope *S);
3743 
3744   struct TypoExprState {
3745     std::unique_ptr<TypoCorrectionConsumer> Consumer;
3746     TypoDiagnosticGenerator DiagHandler;
3747     TypoRecoveryCallback RecoveryHandler;
3748     TypoExprState();
3749     TypoExprState(TypoExprState &&other) noexcept;
3750     TypoExprState &operator=(TypoExprState &&other) noexcept;
3751   };
3752 
3753   /// The set of unhandled TypoExprs and their associated state.
3754   llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
3755 
3756   /// Creates a new TypoExpr AST node.
3757   TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
3758                               TypoDiagnosticGenerator TDG,
3759                               TypoRecoveryCallback TRC, SourceLocation TypoLoc);
3760 
3761   // The set of known/encountered (unique, canonicalized) NamespaceDecls.
3762   //
3763   // The boolean value will be true to indicate that the namespace was loaded
3764   // from an AST/PCH file, or false otherwise.
3765   llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
3766 
3767   /// Whether we have already loaded known namespaces from an extenal
3768   /// source.
3769   bool LoadedExternalKnownNamespaces;
3770 
3771   /// Helper for CorrectTypo and CorrectTypoDelayed used to create and
3772   /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
3773   /// should be skipped entirely.
3774   std::unique_ptr<TypoCorrectionConsumer>
3775   makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
3776                              Sema::LookupNameKind LookupKind, Scope *S,
3777                              CXXScopeSpec *SS,
3778                              CorrectionCandidateCallback &CCC,
3779                              DeclContext *MemberContext, bool EnteringContext,
3780                              const ObjCObjectPointerType *OPT,
3781                              bool ErrorRecovery);
3782 
3783 public:
3784   const TypoExprState &getTypoExprState(TypoExpr *TE) const;
3785 
3786   /// Clears the state of the given TypoExpr.
3787   void clearDelayedTypo(TypoExpr *TE);
3788 
3789   /// Look up a name, looking for a single declaration.  Return
3790   /// null if the results were absent, ambiguous, or overloaded.
3791   ///
3792   /// It is preferable to use the elaborated form and explicitly handle
3793   /// ambiguity and overloaded.
3794   NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
3795                               SourceLocation Loc,
3796                               LookupNameKind NameKind,
3797                               RedeclarationKind Redecl
3798                                 = NotForRedeclaration);
3799   bool LookupBuiltin(LookupResult &R);
3800   bool LookupName(LookupResult &R, Scope *S,
3801                   bool AllowBuiltinCreation = false);
3802   bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3803                            bool InUnqualifiedLookup = false);
3804   bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3805                            CXXScopeSpec &SS);
3806   bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
3807                         bool AllowBuiltinCreation = false,
3808                         bool EnteringContext = false);
3809   ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
3810                                    RedeclarationKind Redecl
3811                                      = NotForRedeclaration);
3812   bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
3813 
3814   void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
3815                                     QualType T1, QualType T2,
3816                                     UnresolvedSetImpl &Functions);
3817 
3818   LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
3819                                  SourceLocation GnuLabelLoc = SourceLocation());
3820 
3821   DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
3822   CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
3823   CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
3824                                                unsigned Quals);
3825   CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
3826                                          bool RValueThis, unsigned ThisQuals);
3827   CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
3828                                               unsigned Quals);
3829   CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
3830                                         bool RValueThis, unsigned ThisQuals);
3831   CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
3832 
3833   bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
3834   LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
3835                                                     ArrayRef<QualType> ArgTys,
3836                                                     bool AllowRaw,
3837                                                     bool AllowTemplate,
3838                                                     bool AllowStringTemplate,
3839                                                     bool DiagnoseMissing);
3840   bool isKnownName(StringRef name);
3841 
3842   /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
3843   enum class FunctionEmissionStatus {
3844     Emitted,
3845     CUDADiscarded,     // Discarded due to CUDA/HIP hostness
3846     OMPDiscarded,      // Discarded due to OpenMP hostness
3847     TemplateDiscarded, // Discarded due to uninstantiated templates
3848     Unknown,
3849   };
3850   FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl,
3851                                            bool Final = false);
3852 
3853   // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
3854   bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee);
3855 
3856   void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3857                                ArrayRef<Expr *> Args, ADLResult &Functions);
3858 
3859   void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3860                           VisibleDeclConsumer &Consumer,
3861                           bool IncludeGlobalScope = true,
3862                           bool LoadExternal = true);
3863   void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3864                           VisibleDeclConsumer &Consumer,
3865                           bool IncludeGlobalScope = true,
3866                           bool IncludeDependentBases = false,
3867                           bool LoadExternal = true);
3868 
3869   enum CorrectTypoKind {
3870     CTK_NonError,     // CorrectTypo used in a non error recovery situation.
3871     CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
3872   };
3873 
3874   TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
3875                              Sema::LookupNameKind LookupKind,
3876                              Scope *S, CXXScopeSpec *SS,
3877                              CorrectionCandidateCallback &CCC,
3878                              CorrectTypoKind Mode,
3879                              DeclContext *MemberContext = nullptr,
3880                              bool EnteringContext = false,
3881                              const ObjCObjectPointerType *OPT = nullptr,
3882                              bool RecordFailure = true);
3883 
3884   TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
3885                                Sema::LookupNameKind LookupKind, Scope *S,
3886                                CXXScopeSpec *SS,
3887                                CorrectionCandidateCallback &CCC,
3888                                TypoDiagnosticGenerator TDG,
3889                                TypoRecoveryCallback TRC, CorrectTypoKind Mode,
3890                                DeclContext *MemberContext = nullptr,
3891                                bool EnteringContext = false,
3892                                const ObjCObjectPointerType *OPT = nullptr);
3893 
3894   /// Process any TypoExprs in the given Expr and its children,
3895   /// generating diagnostics as appropriate and returning a new Expr if there
3896   /// were typos that were all successfully corrected and ExprError if one or
3897   /// more typos could not be corrected.
3898   ///
3899   /// \param E The Expr to check for TypoExprs.
3900   ///
3901   /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
3902   /// initializer.
3903   ///
3904   /// \param RecoverUncorrectedTypos If true, when typo correction fails, it
3905   /// will rebuild the given Expr with all TypoExprs degraded to RecoveryExprs.
3906   ///
3907   /// \param Filter A function applied to a newly rebuilt Expr to determine if
3908   /// it is an acceptable/usable result from a single combination of typo
3909   /// corrections. As long as the filter returns ExprError, different
3910   /// combinations of corrections will be tried until all are exhausted.
3911   ExprResult CorrectDelayedTyposInExpr(
3912       Expr *E, VarDecl *InitDecl = nullptr,
3913       bool RecoverUncorrectedTypos = false,
3914       llvm::function_ref<ExprResult(Expr *)> Filter =
3915           [](Expr *E) -> ExprResult { return E; });
3916 
3917   ExprResult CorrectDelayedTyposInExpr(
3918       ExprResult ER, VarDecl *InitDecl = nullptr,
3919       bool RecoverUncorrectedTypos = false,
3920       llvm::function_ref<ExprResult(Expr *)> Filter =
3921           [](Expr *E) -> ExprResult { return E; }) {
3922     return ER.isInvalid()
3923                ? ER
3924                : CorrectDelayedTyposInExpr(ER.get(), InitDecl,
3925                                            RecoverUncorrectedTypos, Filter);
3926   }
3927 
3928   void diagnoseTypo(const TypoCorrection &Correction,
3929                     const PartialDiagnostic &TypoDiag,
3930                     bool ErrorRecovery = true);
3931 
3932   void diagnoseTypo(const TypoCorrection &Correction,
3933                     const PartialDiagnostic &TypoDiag,
3934                     const PartialDiagnostic &PrevNote,
3935                     bool ErrorRecovery = true);
3936 
3937   void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
3938 
3939   void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
3940                                           ArrayRef<Expr *> Args,
3941                                    AssociatedNamespaceSet &AssociatedNamespaces,
3942                                    AssociatedClassSet &AssociatedClasses);
3943 
3944   void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
3945                             bool ConsiderLinkage, bool AllowInlineNamespace);
3946 
3947   bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
3948 
3949   void DiagnoseAmbiguousLookup(LookupResult &Result);
3950   //@}
3951 
3952   /// Attempts to produce a RecoveryExpr after some AST node cannot be created.
3953   ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
3954                                 ArrayRef<Expr *> SubExprs,
3955                                 QualType T = QualType());
3956 
3957   ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
3958                                           SourceLocation IdLoc,
3959                                           bool TypoCorrection = false);
3960   FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID,
3961                               SourceLocation Loc);
3962   NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
3963                                  Scope *S, bool ForRedeclaration,
3964                                  SourceLocation Loc);
3965   NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
3966                                       Scope *S);
3967   void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
3968       FunctionDecl *FD);
3969   void AddKnownFunctionAttributes(FunctionDecl *FD);
3970 
3971   // More parsing and symbol table subroutines.
3972 
3973   void ProcessPragmaWeak(Scope *S, Decl *D);
3974   // Decl attributes - this routine is the top level dispatcher.
3975   void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
3976   // Helper for delayed processing of attributes.
3977   void ProcessDeclAttributeDelayed(Decl *D,
3978                                    const ParsedAttributesView &AttrList);
3979   void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL,
3980                              bool IncludeCXX11Attributes = true);
3981   bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
3982                                    const ParsedAttributesView &AttrList);
3983 
3984   void checkUnusedDeclAttributes(Declarator &D);
3985 
3986   /// Determine if type T is a valid subject for a nonnull and similar
3987   /// attributes. By default, we look through references (the behavior used by
3988   /// nonnull), but if the second parameter is true, then we treat a reference
3989   /// type as valid.
3990   bool isValidPointerAttrType(QualType T, bool RefOkay = false);
3991 
3992   bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
3993   bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC,
3994                             const FunctionDecl *FD = nullptr);
3995   bool CheckAttrTarget(const ParsedAttr &CurrAttr);
3996   bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
3997   bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
3998                                       StringRef &Str,
3999                                       SourceLocation *ArgLocation = nullptr);
4000   bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
4001   bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
4002   bool checkMSInheritanceAttrOnDefinition(
4003       CXXRecordDecl *RD, SourceRange Range, bool BestCase,
4004       MSInheritanceModel SemanticSpelling);
4005 
4006   void CheckAlignasUnderalignment(Decl *D);
4007 
4008   /// Adjust the calling convention of a method to be the ABI default if it
4009   /// wasn't specified explicitly.  This handles method types formed from
4010   /// function type typedefs and typename template arguments.
4011   void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
4012                               SourceLocation Loc);
4013 
4014   // Check if there is an explicit attribute, but only look through parens.
4015   // The intent is to look for an attribute on the current declarator, but not
4016   // one that came from a typedef.
4017   bool hasExplicitCallingConv(QualType T);
4018 
4019   /// Get the outermost AttributedType node that sets a calling convention.
4020   /// Valid types should not have multiple attributes with different CCs.
4021   const AttributedType *getCallingConvAttributedType(QualType T) const;
4022 
4023   /// Stmt attributes - this routine is the top level dispatcher.
4024   StmtResult ProcessStmtAttributes(Stmt *Stmt,
4025                                    const ParsedAttributesView &Attrs,
4026                                    SourceRange Range);
4027 
4028   void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
4029                                    ObjCMethodDecl *MethodDecl,
4030                                    bool IsProtocolMethodDecl);
4031 
4032   void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
4033                                    ObjCMethodDecl *Overridden,
4034                                    bool IsProtocolMethodDecl);
4035 
4036   /// WarnExactTypedMethods - This routine issues a warning if method
4037   /// implementation declaration matches exactly that of its declaration.
4038   void WarnExactTypedMethods(ObjCMethodDecl *Method,
4039                              ObjCMethodDecl *MethodDecl,
4040                              bool IsProtocolMethodDecl);
4041 
4042   typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
4043 
4044   /// CheckImplementationIvars - This routine checks if the instance variables
4045   /// listed in the implelementation match those listed in the interface.
4046   void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
4047                                 ObjCIvarDecl **Fields, unsigned nIvars,
4048                                 SourceLocation Loc);
4049 
4050   /// ImplMethodsVsClassMethods - This is main routine to warn if any method
4051   /// remains unimplemented in the class or category \@implementation.
4052   void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
4053                                  ObjCContainerDecl* IDecl,
4054                                  bool IncompleteImpl = false);
4055 
4056   /// DiagnoseUnimplementedProperties - This routine warns on those properties
4057   /// which must be implemented by this implementation.
4058   void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
4059                                        ObjCContainerDecl *CDecl,
4060                                        bool SynthesizeProperties);
4061 
4062   /// Diagnose any null-resettable synthesized setters.
4063   void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
4064 
4065   /// DefaultSynthesizeProperties - This routine default synthesizes all
4066   /// properties which must be synthesized in the class's \@implementation.
4067   void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
4068                                    ObjCInterfaceDecl *IDecl,
4069                                    SourceLocation AtEnd);
4070   void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd);
4071 
4072   /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
4073   /// an ivar synthesized for 'Method' and 'Method' is a property accessor
4074   /// declared in class 'IFace'.
4075   bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
4076                                       ObjCMethodDecl *Method, ObjCIvarDecl *IV);
4077 
4078   /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
4079   /// backs the property is not used in the property's accessor.
4080   void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
4081                                            const ObjCImplementationDecl *ImplD);
4082 
4083   /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
4084   /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
4085   /// It also returns ivar's property on success.
4086   ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
4087                                                const ObjCPropertyDecl *&PDecl) const;
4088 
4089   /// Called by ActOnProperty to handle \@property declarations in
4090   /// class extensions.
4091   ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
4092                       SourceLocation AtLoc,
4093                       SourceLocation LParenLoc,
4094                       FieldDeclarator &FD,
4095                       Selector GetterSel,
4096                       SourceLocation GetterNameLoc,
4097                       Selector SetterSel,
4098                       SourceLocation SetterNameLoc,
4099                       const bool isReadWrite,
4100                       unsigned &Attributes,
4101                       const unsigned AttributesAsWritten,
4102                       QualType T,
4103                       TypeSourceInfo *TSI,
4104                       tok::ObjCKeywordKind MethodImplKind);
4105 
4106   /// Called by ActOnProperty and HandlePropertyInClassExtension to
4107   /// handle creating the ObjcPropertyDecl for a category or \@interface.
4108   ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
4109                                        ObjCContainerDecl *CDecl,
4110                                        SourceLocation AtLoc,
4111                                        SourceLocation LParenLoc,
4112                                        FieldDeclarator &FD,
4113                                        Selector GetterSel,
4114                                        SourceLocation GetterNameLoc,
4115                                        Selector SetterSel,
4116                                        SourceLocation SetterNameLoc,
4117                                        const bool isReadWrite,
4118                                        const unsigned Attributes,
4119                                        const unsigned AttributesAsWritten,
4120                                        QualType T,
4121                                        TypeSourceInfo *TSI,
4122                                        tok::ObjCKeywordKind MethodImplKind,
4123                                        DeclContext *lexicalDC = nullptr);
4124 
4125   /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
4126   /// warning) when atomic property has one but not the other user-declared
4127   /// setter or getter.
4128   void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
4129                                        ObjCInterfaceDecl* IDecl);
4130 
4131   void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
4132 
4133   void DiagnoseMissingDesignatedInitOverrides(
4134                                           const ObjCImplementationDecl *ImplD,
4135                                           const ObjCInterfaceDecl *IFD);
4136 
4137   void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
4138 
4139   enum MethodMatchStrategy {
4140     MMS_loose,
4141     MMS_strict
4142   };
4143 
4144   /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
4145   /// true, or false, accordingly.
4146   bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
4147                                   const ObjCMethodDecl *PrevMethod,
4148                                   MethodMatchStrategy strategy = MMS_strict);
4149 
4150   /// MatchAllMethodDeclarations - Check methods declaraed in interface or
4151   /// or protocol against those declared in their implementations.
4152   void MatchAllMethodDeclarations(const SelectorSet &InsMap,
4153                                   const SelectorSet &ClsMap,
4154                                   SelectorSet &InsMapSeen,
4155                                   SelectorSet &ClsMapSeen,
4156                                   ObjCImplDecl* IMPDecl,
4157                                   ObjCContainerDecl* IDecl,
4158                                   bool &IncompleteImpl,
4159                                   bool ImmediateClass,
4160                                   bool WarnCategoryMethodImpl=false);
4161 
4162   /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
4163   /// category matches with those implemented in its primary class and
4164   /// warns each time an exact match is found.
4165   void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
4166 
4167   /// Add the given method to the list of globally-known methods.
4168   void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
4169 
4170   /// Returns default addr space for method qualifiers.
4171   LangAS getDefaultCXXMethodAddrSpace() const;
4172 
4173 private:
4174   /// AddMethodToGlobalPool - Add an instance or factory method to the global
4175   /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
4176   void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
4177 
4178   /// LookupMethodInGlobalPool - Returns the instance or factory method and
4179   /// optionally warns if there are multiple signatures.
4180   ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
4181                                            bool receiverIdOrClass,
4182                                            bool instance);
4183 
4184 public:
4185   /// - Returns instance or factory methods in global method pool for
4186   /// given selector. It checks the desired kind first, if none is found, and
4187   /// parameter checkTheOther is set, it then checks the other kind. If no such
4188   /// method or only one method is found, function returns false; otherwise, it
4189   /// returns true.
4190   bool
4191   CollectMultipleMethodsInGlobalPool(Selector Sel,
4192                                      SmallVectorImpl<ObjCMethodDecl*>& Methods,
4193                                      bool InstanceFirst, bool CheckTheOther,
4194                                      const ObjCObjectType *TypeBound = nullptr);
4195 
4196   bool
4197   AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
4198                                  SourceRange R, bool receiverIdOrClass,
4199                                  SmallVectorImpl<ObjCMethodDecl*>& Methods);
4200 
4201   void
4202   DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
4203                                      Selector Sel, SourceRange R,
4204                                      bool receiverIdOrClass);
4205 
4206 private:
4207   /// - Returns a selector which best matches given argument list or
4208   /// nullptr if none could be found
4209   ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
4210                                    bool IsInstance,
4211                                    SmallVectorImpl<ObjCMethodDecl*>& Methods);
4212 
4213 
4214   /// Record the typo correction failure and return an empty correction.
4215   TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
4216                                   bool RecordFailure = true) {
4217     if (RecordFailure)
4218       TypoCorrectionFailures[Typo].insert(TypoLoc);
4219     return TypoCorrection();
4220   }
4221 
4222 public:
4223   /// AddInstanceMethodToGlobalPool - All instance methods in a translation
4224   /// unit are added to a global pool. This allows us to efficiently associate
4225   /// a selector with a method declaraation for purposes of typechecking
4226   /// messages sent to "id" (where the class of the object is unknown).
4227   void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
4228     AddMethodToGlobalPool(Method, impl, /*instance*/true);
4229   }
4230 
4231   /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
4232   void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
4233     AddMethodToGlobalPool(Method, impl, /*instance*/false);
4234   }
4235 
4236   /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
4237   /// pool.
4238   void AddAnyMethodToGlobalPool(Decl *D);
4239 
4240   /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
4241   /// there are multiple signatures.
4242   ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
4243                                                    bool receiverIdOrClass=false) {
4244     return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
4245                                     /*instance*/true);
4246   }
4247 
4248   /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
4249   /// there are multiple signatures.
4250   ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
4251                                                   bool receiverIdOrClass=false) {
4252     return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
4253                                     /*instance*/false);
4254   }
4255 
4256   const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
4257                               QualType ObjectType=QualType());
4258   /// LookupImplementedMethodInGlobalPool - Returns the method which has an
4259   /// implementation.
4260   ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
4261 
4262   /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
4263   /// initialization.
4264   void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
4265                                   SmallVectorImpl<ObjCIvarDecl*> &Ivars);
4266 
4267   //===--------------------------------------------------------------------===//
4268   // Statement Parsing Callbacks: SemaStmt.cpp.
4269 public:
4270   class FullExprArg {
4271   public:
FullExprArg()4272     FullExprArg() : E(nullptr) { }
FullExprArg(Sema & actions)4273     FullExprArg(Sema &actions) : E(nullptr) { }
4274 
release()4275     ExprResult release() {
4276       return E;
4277     }
4278 
get()4279     Expr *get() const { return E; }
4280 
4281     Expr *operator->() {
4282       return E;
4283     }
4284 
4285   private:
4286     // FIXME: No need to make the entire Sema class a friend when it's just
4287     // Sema::MakeFullExpr that needs access to the constructor below.
4288     friend class Sema;
4289 
FullExprArg(Expr * expr)4290     explicit FullExprArg(Expr *expr) : E(expr) {}
4291 
4292     Expr *E;
4293   };
4294 
MakeFullExpr(Expr * Arg)4295   FullExprArg MakeFullExpr(Expr *Arg) {
4296     return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
4297   }
MakeFullExpr(Expr * Arg,SourceLocation CC)4298   FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
4299     return FullExprArg(
4300         ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get());
4301   }
MakeFullDiscardedValueExpr(Expr * Arg)4302   FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
4303     ExprResult FE =
4304         ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
4305                             /*DiscardedValue*/ true);
4306     return FullExprArg(FE.get());
4307   }
4308 
4309   StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
4310   StmtResult ActOnExprStmtError();
4311 
4312   StmtResult ActOnNullStmt(SourceLocation SemiLoc,
4313                            bool HasLeadingEmptyMacro = false);
4314 
4315   void ActOnStartOfCompoundStmt(bool IsStmtExpr);
4316   void ActOnFinishOfCompoundStmt();
4317   StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
4318                                ArrayRef<Stmt *> Elts, bool isStmtExpr);
4319 
4320   /// A RAII object to enter scope of a compound statement.
4321   class CompoundScopeRAII {
4322   public:
S(S)4323     CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
4324       S.ActOnStartOfCompoundStmt(IsStmtExpr);
4325     }
4326 
~CompoundScopeRAII()4327     ~CompoundScopeRAII() {
4328       S.ActOnFinishOfCompoundStmt();
4329     }
4330 
4331   private:
4332     Sema &S;
4333   };
4334 
4335   /// An RAII helper that pops function a function scope on exit.
4336   struct FunctionScopeRAII {
4337     Sema &S;
4338     bool Active;
FunctionScopeRAIIFunctionScopeRAII4339     FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
~FunctionScopeRAIIFunctionScopeRAII4340     ~FunctionScopeRAII() {
4341       if (Active)
4342         S.PopFunctionScopeInfo();
4343     }
disableFunctionScopeRAII4344     void disable() { Active = false; }
4345   };
4346 
4347   StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
4348                                    SourceLocation StartLoc,
4349                                    SourceLocation EndLoc);
4350   void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
4351   StmtResult ActOnForEachLValueExpr(Expr *E);
4352   ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
4353   StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
4354                            SourceLocation DotDotDotLoc, ExprResult RHS,
4355                            SourceLocation ColonLoc);
4356   void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
4357 
4358   StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
4359                                       SourceLocation ColonLoc,
4360                                       Stmt *SubStmt, Scope *CurScope);
4361   StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
4362                             SourceLocation ColonLoc, Stmt *SubStmt);
4363 
4364   StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
4365                                  ArrayRef<const Attr*> Attrs,
4366                                  Stmt *SubStmt);
4367 
4368   class ConditionResult;
4369   StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
4370                          Stmt *InitStmt,
4371                          ConditionResult Cond, Stmt *ThenVal,
4372                          SourceLocation ElseLoc, Stmt *ElseVal);
4373   StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
4374                          Stmt *InitStmt,
4375                          ConditionResult Cond, Stmt *ThenVal,
4376                          SourceLocation ElseLoc, Stmt *ElseVal);
4377   StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
4378                                     Stmt *InitStmt,
4379                                     ConditionResult Cond);
4380   StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
4381                                            Stmt *Switch, Stmt *Body);
4382   StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
4383                             ConditionResult Cond, SourceLocation RParenLoc,
4384                             Stmt *Body);
4385   StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
4386                          SourceLocation WhileLoc, SourceLocation CondLParen,
4387                          Expr *Cond, SourceLocation CondRParen);
4388 
4389   StmtResult ActOnForStmt(SourceLocation ForLoc,
4390                           SourceLocation LParenLoc,
4391                           Stmt *First,
4392                           ConditionResult Second,
4393                           FullExprArg Third,
4394                           SourceLocation RParenLoc,
4395                           Stmt *Body);
4396   ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
4397                                            Expr *collection);
4398   StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
4399                                         Stmt *First, Expr *collection,
4400                                         SourceLocation RParenLoc);
4401   StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
4402 
4403   enum BuildForRangeKind {
4404     /// Initial building of a for-range statement.
4405     BFRK_Build,
4406     /// Instantiation or recovery rebuild of a for-range statement. Don't
4407     /// attempt any typo-correction.
4408     BFRK_Rebuild,
4409     /// Determining whether a for-range statement could be built. Avoid any
4410     /// unnecessary or irreversible actions.
4411     BFRK_Check
4412   };
4413 
4414   StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
4415                                   SourceLocation CoawaitLoc,
4416                                   Stmt *InitStmt,
4417                                   Stmt *LoopVar,
4418                                   SourceLocation ColonLoc, Expr *Collection,
4419                                   SourceLocation RParenLoc,
4420                                   BuildForRangeKind Kind);
4421   StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
4422                                   SourceLocation CoawaitLoc,
4423                                   Stmt *InitStmt,
4424                                   SourceLocation ColonLoc,
4425                                   Stmt *RangeDecl, Stmt *Begin, Stmt *End,
4426                                   Expr *Cond, Expr *Inc,
4427                                   Stmt *LoopVarDecl,
4428                                   SourceLocation RParenLoc,
4429                                   BuildForRangeKind Kind);
4430   StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
4431 
4432   StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
4433                            SourceLocation LabelLoc,
4434                            LabelDecl *TheDecl);
4435   StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
4436                                    SourceLocation StarLoc,
4437                                    Expr *DestExp);
4438   StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
4439   StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
4440 
4441   void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4442                                 CapturedRegionKind Kind, unsigned NumParams);
4443   typedef std::pair<StringRef, QualType> CapturedParamNameType;
4444   void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4445                                 CapturedRegionKind Kind,
4446                                 ArrayRef<CapturedParamNameType> Params,
4447                                 unsigned OpenMPCaptureLevel = 0);
4448   StmtResult ActOnCapturedRegionEnd(Stmt *S);
4449   void ActOnCapturedRegionError();
4450   RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
4451                                            SourceLocation Loc,
4452                                            unsigned NumParams);
4453 
4454   enum CopyElisionSemanticsKind {
4455     CES_Strict = 0,
4456     CES_AllowParameters = 1,
4457     CES_AllowDifferentTypes = 2,
4458     CES_AllowExceptionVariables = 4,
4459     CES_FormerDefault = (CES_AllowParameters),
4460     CES_Default = (CES_AllowParameters | CES_AllowDifferentTypes),
4461     CES_AsIfByStdMove = (CES_AllowParameters | CES_AllowDifferentTypes |
4462                          CES_AllowExceptionVariables),
4463   };
4464 
4465   VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
4466                                    CopyElisionSemanticsKind CESK);
4467   bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
4468                               CopyElisionSemanticsKind CESK);
4469 
4470   StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
4471                              Scope *CurScope);
4472   StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
4473   StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
4474 
4475   StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
4476                              bool IsVolatile, unsigned NumOutputs,
4477                              unsigned NumInputs, IdentifierInfo **Names,
4478                              MultiExprArg Constraints, MultiExprArg Exprs,
4479                              Expr *AsmString, MultiExprArg Clobbers,
4480                              unsigned NumLabels,
4481                              SourceLocation RParenLoc);
4482 
4483   void FillInlineAsmIdentifierInfo(Expr *Res,
4484                                    llvm::InlineAsmIdentifierInfo &Info);
4485   ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
4486                                        SourceLocation TemplateKWLoc,
4487                                        UnqualifiedId &Id,
4488                                        bool IsUnevaluatedContext);
4489   bool LookupInlineAsmField(StringRef Base, StringRef Member,
4490                             unsigned &Offset, SourceLocation AsmLoc);
4491   ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
4492                                          SourceLocation AsmLoc);
4493   StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
4494                             ArrayRef<Token> AsmToks,
4495                             StringRef AsmString,
4496                             unsigned NumOutputs, unsigned NumInputs,
4497                             ArrayRef<StringRef> Constraints,
4498                             ArrayRef<StringRef> Clobbers,
4499                             ArrayRef<Expr*> Exprs,
4500                             SourceLocation EndLoc);
4501   LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
4502                                    SourceLocation Location,
4503                                    bool AlwaysCreate);
4504 
4505   VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
4506                                   SourceLocation StartLoc,
4507                                   SourceLocation IdLoc, IdentifierInfo *Id,
4508                                   bool Invalid = false);
4509 
4510   Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
4511 
4512   StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
4513                                   Decl *Parm, Stmt *Body);
4514 
4515   StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
4516 
4517   StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
4518                                 MultiStmtArg Catch, Stmt *Finally);
4519 
4520   StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
4521   StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
4522                                   Scope *CurScope);
4523   ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
4524                                             Expr *operand);
4525   StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
4526                                          Expr *SynchExpr,
4527                                          Stmt *SynchBody);
4528 
4529   StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
4530 
4531   VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
4532                                      SourceLocation StartLoc,
4533                                      SourceLocation IdLoc,
4534                                      IdentifierInfo *Id);
4535 
4536   Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
4537 
4538   StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
4539                                 Decl *ExDecl, Stmt *HandlerBlock);
4540   StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
4541                               ArrayRef<Stmt *> Handlers);
4542 
4543   StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
4544                               SourceLocation TryLoc, Stmt *TryBlock,
4545                               Stmt *Handler);
4546   StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
4547                                  Expr *FilterExpr,
4548                                  Stmt *Block);
4549   void ActOnStartSEHFinallyBlock();
4550   void ActOnAbortSEHFinallyBlock();
4551   StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
4552   StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
4553 
4554   void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
4555 
4556   bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
4557 
4558   /// If it's a file scoped decl that must warn if not used, keep track
4559   /// of it.
4560   void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
4561 
4562   /// DiagnoseUnusedExprResult - If the statement passed in is an expression
4563   /// whose result is unused, warn.
4564   void DiagnoseUnusedExprResult(const Stmt *S);
4565   void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
4566   void DiagnoseUnusedDecl(const NamedDecl *ND);
4567 
4568   /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
4569   /// statement as a \p Body, and it is located on the same line.
4570   ///
4571   /// This helps prevent bugs due to typos, such as:
4572   ///     if (condition);
4573   ///       do_stuff();
4574   void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
4575                              const Stmt *Body,
4576                              unsigned DiagID);
4577 
4578   /// Warn if a for/while loop statement \p S, which is followed by
4579   /// \p PossibleBody, has a suspicious null statement as a body.
4580   void DiagnoseEmptyLoopBody(const Stmt *S,
4581                              const Stmt *PossibleBody);
4582 
4583   /// Warn if a value is moved to itself.
4584   void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
4585                         SourceLocation OpLoc);
4586 
4587   /// Warn if we're implicitly casting from a _Nullable pointer type to a
4588   /// _Nonnull one.
4589   void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
4590                                            SourceLocation Loc);
4591 
4592   /// Warn when implicitly casting 0 to nullptr.
4593   void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
4594 
PushParsingDeclaration(sema::DelayedDiagnosticPool & pool)4595   ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
4596     return DelayedDiagnostics.push(pool);
4597   }
4598   void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
4599 
4600   typedef ProcessingContextState ParsingClassState;
PushParsingClass()4601   ParsingClassState PushParsingClass() {
4602     ParsingClassDepth++;
4603     return DelayedDiagnostics.pushUndelayed();
4604   }
PopParsingClass(ParsingClassState state)4605   void PopParsingClass(ParsingClassState state) {
4606     ParsingClassDepth--;
4607     DelayedDiagnostics.popUndelayed(state);
4608   }
4609 
4610   void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
4611 
4612   void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
4613                                   const ObjCInterfaceDecl *UnknownObjCClass,
4614                                   bool ObjCPropertyAccess,
4615                                   bool AvoidPartialAvailabilityChecks = false,
4616                                   ObjCInterfaceDecl *ClassReceiver = nullptr);
4617 
4618   bool makeUnavailableInSystemHeader(SourceLocation loc,
4619                                      UnavailableAttr::ImplicitReason reason);
4620 
4621   /// Issue any -Wunguarded-availability warnings in \c FD
4622   void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
4623 
4624   void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
4625 
4626   //===--------------------------------------------------------------------===//
4627   // Expression Parsing Callbacks: SemaExpr.cpp.
4628 
4629   bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
4630   bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
4631                          const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
4632                          bool ObjCPropertyAccess = false,
4633                          bool AvoidPartialAvailabilityChecks = false,
4634                          ObjCInterfaceDecl *ClassReciever = nullptr);
4635   void NoteDeletedFunction(FunctionDecl *FD);
4636   void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
4637   bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
4638                                         ObjCMethodDecl *Getter,
4639                                         SourceLocation Loc);
4640   void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
4641                              ArrayRef<Expr *> Args);
4642 
4643   void PushExpressionEvaluationContext(
4644       ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
4645       ExpressionEvaluationContextRecord::ExpressionKind Type =
4646           ExpressionEvaluationContextRecord::EK_Other);
4647   enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
4648   void PushExpressionEvaluationContext(
4649       ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
4650       ExpressionEvaluationContextRecord::ExpressionKind Type =
4651           ExpressionEvaluationContextRecord::EK_Other);
4652   void PopExpressionEvaluationContext();
4653 
4654   void DiscardCleanupsInEvaluationContext();
4655 
4656   ExprResult TransformToPotentiallyEvaluated(Expr *E);
4657   ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
4658 
4659   ExprResult CheckUnevaluatedOperand(Expr *E);
4660   void CheckUnusedVolatileAssignment(Expr *E);
4661 
4662   ExprResult ActOnConstantExpression(ExprResult Res);
4663 
4664   // Functions for marking a declaration referenced.  These functions also
4665   // contain the relevant logic for marking if a reference to a function or
4666   // variable is an odr-use (in the C++11 sense).  There are separate variants
4667   // for expressions referring to a decl; these exist because odr-use marking
4668   // needs to be delayed for some constant variables when we build one of the
4669   // named expressions.
4670   //
4671   // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
4672   // should usually be true. This only needs to be set to false if the lack of
4673   // odr-use cannot be determined from the current context (for instance,
4674   // because the name denotes a virtual function and was written without an
4675   // explicit nested-name-specifier).
4676   void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
4677   void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
4678                               bool MightBeOdrUse = true);
4679   void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
4680   void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
4681   void MarkMemberReferenced(MemberExpr *E);
4682   void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E);
4683   void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc,
4684                                          unsigned CapturingScopeIndex);
4685 
4686   ExprResult CheckLValueToRValueConversionOperand(Expr *E);
4687   void CleanupVarDeclMarking();
4688 
4689   enum TryCaptureKind {
4690     TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
4691   };
4692 
4693   /// Try to capture the given variable.
4694   ///
4695   /// \param Var The variable to capture.
4696   ///
4697   /// \param Loc The location at which the capture occurs.
4698   ///
4699   /// \param Kind The kind of capture, which may be implicit (for either a
4700   /// block or a lambda), or explicit by-value or by-reference (for a lambda).
4701   ///
4702   /// \param EllipsisLoc The location of the ellipsis, if one is provided in
4703   /// an explicit lambda capture.
4704   ///
4705   /// \param BuildAndDiagnose Whether we are actually supposed to add the
4706   /// captures or diagnose errors. If false, this routine merely check whether
4707   /// the capture can occur without performing the capture itself or complaining
4708   /// if the variable cannot be captured.
4709   ///
4710   /// \param CaptureType Will be set to the type of the field used to capture
4711   /// this variable in the innermost block or lambda. Only valid when the
4712   /// variable can be captured.
4713   ///
4714   /// \param DeclRefType Will be set to the type of a reference to the capture
4715   /// from within the current scope. Only valid when the variable can be
4716   /// captured.
4717   ///
4718   /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4719   /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4720   /// This is useful when enclosing lambdas must speculatively capture
4721   /// variables that may or may not be used in certain specializations of
4722   /// a nested generic lambda.
4723   ///
4724   /// \returns true if an error occurred (i.e., the variable cannot be
4725   /// captured) and false if the capture succeeded.
4726   bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
4727                           SourceLocation EllipsisLoc, bool BuildAndDiagnose,
4728                           QualType &CaptureType,
4729                           QualType &DeclRefType,
4730                           const unsigned *const FunctionScopeIndexToStopAt);
4731 
4732   /// Try to capture the given variable.
4733   bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
4734                           TryCaptureKind Kind = TryCapture_Implicit,
4735                           SourceLocation EllipsisLoc = SourceLocation());
4736 
4737   /// Checks if the variable must be captured.
4738   bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
4739 
4740   /// Given a variable, determine the type that a reference to that
4741   /// variable will have in the given scope.
4742   QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
4743 
4744   /// Mark all of the declarations referenced within a particular AST node as
4745   /// referenced. Used when template instantiation instantiates a non-dependent
4746   /// type -- entities referenced by the type are now referenced.
4747   void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
4748   void MarkDeclarationsReferencedInExpr(Expr *E,
4749                                         bool SkipLocalVariables = false);
4750 
4751   /// Try to recover by turning the given expression into a
4752   /// call.  Returns true if recovery was attempted or an error was
4753   /// emitted; this may also leave the ExprResult invalid.
4754   bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
4755                             bool ForceComplain = false,
4756                             bool (*IsPlausibleResult)(QualType) = nullptr);
4757 
4758   /// Figure out if an expression could be turned into a call.
4759   bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
4760                      UnresolvedSetImpl &NonTemplateOverloads);
4761 
4762   /// Try to convert an expression \p E to type \p Ty. Returns the result of the
4763   /// conversion.
4764   ExprResult tryConvertExprToType(Expr *E, QualType Ty);
4765 
4766   /// Conditionally issue a diagnostic based on the current
4767   /// evaluation context.
4768   ///
4769   /// \param Statement If Statement is non-null, delay reporting the
4770   /// diagnostic until the function body is parsed, and then do a basic
4771   /// reachability analysis to determine if the statement is reachable.
4772   /// If it is unreachable, the diagnostic will not be emitted.
4773   bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
4774                            const PartialDiagnostic &PD);
4775   /// Similar, but diagnostic is only produced if all the specified statements
4776   /// are reachable.
4777   bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
4778                            const PartialDiagnostic &PD);
4779 
4780   // Primary Expressions.
4781   SourceRange getExprRange(Expr *E) const;
4782 
4783   ExprResult ActOnIdExpression(
4784       Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4785       UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
4786       CorrectionCandidateCallback *CCC = nullptr,
4787       bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
4788 
4789   void DecomposeUnqualifiedId(const UnqualifiedId &Id,
4790                               TemplateArgumentListInfo &Buffer,
4791                               DeclarationNameInfo &NameInfo,
4792                               const TemplateArgumentListInfo *&TemplateArgs);
4793 
4794   bool
4795   DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
4796                       CorrectionCandidateCallback &CCC,
4797                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
4798                       ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
4799 
4800   DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
4801                                     IdentifierInfo *II);
4802   ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV);
4803 
4804   ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
4805                                 IdentifierInfo *II,
4806                                 bool AllowBuiltinCreation=false);
4807 
4808   ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
4809                                         SourceLocation TemplateKWLoc,
4810                                         const DeclarationNameInfo &NameInfo,
4811                                         bool isAddressOfOperand,
4812                                 const TemplateArgumentListInfo *TemplateArgs);
4813 
4814   /// If \p D cannot be odr-used in the current expression evaluation context,
4815   /// return a reason explaining why. Otherwise, return NOUR_None.
4816   NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D);
4817 
4818   DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4819                                 SourceLocation Loc,
4820                                 const CXXScopeSpec *SS = nullptr);
4821   DeclRefExpr *
4822   BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4823                    const DeclarationNameInfo &NameInfo,
4824                    const CXXScopeSpec *SS = nullptr,
4825                    NamedDecl *FoundD = nullptr,
4826                    SourceLocation TemplateKWLoc = SourceLocation(),
4827                    const TemplateArgumentListInfo *TemplateArgs = nullptr);
4828   DeclRefExpr *
4829   BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4830                    const DeclarationNameInfo &NameInfo,
4831                    NestedNameSpecifierLoc NNS,
4832                    NamedDecl *FoundD = nullptr,
4833                    SourceLocation TemplateKWLoc = SourceLocation(),
4834                    const TemplateArgumentListInfo *TemplateArgs = nullptr);
4835 
4836   ExprResult
4837   BuildAnonymousStructUnionMemberReference(
4838       const CXXScopeSpec &SS,
4839       SourceLocation nameLoc,
4840       IndirectFieldDecl *indirectField,
4841       DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
4842       Expr *baseObjectExpr = nullptr,
4843       SourceLocation opLoc = SourceLocation());
4844 
4845   ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
4846                                              SourceLocation TemplateKWLoc,
4847                                              LookupResult &R,
4848                                 const TemplateArgumentListInfo *TemplateArgs,
4849                                              const Scope *S);
4850   ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
4851                                      SourceLocation TemplateKWLoc,
4852                                      LookupResult &R,
4853                                 const TemplateArgumentListInfo *TemplateArgs,
4854                                      bool IsDefiniteInstance,
4855                                      const Scope *S);
4856   bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
4857                                   const LookupResult &R,
4858                                   bool HasTrailingLParen);
4859 
4860   ExprResult
4861   BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
4862                                     const DeclarationNameInfo &NameInfo,
4863                                     bool IsAddressOfOperand, const Scope *S,
4864                                     TypeSourceInfo **RecoveryTSI = nullptr);
4865 
4866   ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
4867                                        SourceLocation TemplateKWLoc,
4868                                 const DeclarationNameInfo &NameInfo,
4869                                 const TemplateArgumentListInfo *TemplateArgs);
4870 
4871   ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
4872                                       LookupResult &R,
4873                                       bool NeedsADL,
4874                                       bool AcceptInvalidDecl = false);
4875   ExprResult BuildDeclarationNameExpr(
4876       const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
4877       NamedDecl *FoundD = nullptr,
4878       const TemplateArgumentListInfo *TemplateArgs = nullptr,
4879       bool AcceptInvalidDecl = false);
4880 
4881   ExprResult BuildLiteralOperatorCall(LookupResult &R,
4882                       DeclarationNameInfo &SuffixInfo,
4883                       ArrayRef<Expr *> Args,
4884                       SourceLocation LitEndLoc,
4885                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
4886 
4887   ExprResult BuildPredefinedExpr(SourceLocation Loc,
4888                                  PredefinedExpr::IdentKind IK);
4889   ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
4890   ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
4891 
4892   ExprResult BuildUniqueStableName(SourceLocation Loc, TypeSourceInfo *Operand);
4893   ExprResult BuildUniqueStableName(SourceLocation Loc, Expr *E);
4894   ExprResult ActOnUniqueStableNameExpr(SourceLocation OpLoc,
4895                                        SourceLocation LParen,
4896                                        SourceLocation RParen, ParsedType Ty);
4897   ExprResult ActOnUniqueStableNameExpr(SourceLocation OpLoc,
4898                                        SourceLocation LParen,
4899                                        SourceLocation RParen, Expr *E);
4900 
4901   bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
4902 
4903   ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
4904   ExprResult ActOnCharacterConstant(const Token &Tok,
4905                                     Scope *UDLScope = nullptr);
4906   ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
4907   ExprResult ActOnParenListExpr(SourceLocation L,
4908                                 SourceLocation R,
4909                                 MultiExprArg Val);
4910 
4911   /// ActOnStringLiteral - The specified tokens were lexed as pasted string
4912   /// fragments (e.g. "foo" "bar" L"baz").
4913   ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
4914                                 Scope *UDLScope = nullptr);
4915 
4916   ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
4917                                        SourceLocation DefaultLoc,
4918                                        SourceLocation RParenLoc,
4919                                        Expr *ControllingExpr,
4920                                        ArrayRef<ParsedType> ArgTypes,
4921                                        ArrayRef<Expr *> ArgExprs);
4922   ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
4923                                         SourceLocation DefaultLoc,
4924                                         SourceLocation RParenLoc,
4925                                         Expr *ControllingExpr,
4926                                         ArrayRef<TypeSourceInfo *> Types,
4927                                         ArrayRef<Expr *> Exprs);
4928 
4929   // Binary/Unary Operators.  'Tok' is the token for the operator.
4930   ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
4931                                   Expr *InputExpr);
4932   ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
4933                           UnaryOperatorKind Opc, Expr *Input);
4934   ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4935                           tok::TokenKind Op, Expr *Input);
4936 
4937   bool isQualifiedMemberAccess(Expr *E);
4938   QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
4939 
4940   ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4941                                             SourceLocation OpLoc,
4942                                             UnaryExprOrTypeTrait ExprKind,
4943                                             SourceRange R);
4944   ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4945                                             UnaryExprOrTypeTrait ExprKind);
4946   ExprResult
4947     ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4948                                   UnaryExprOrTypeTrait ExprKind,
4949                                   bool IsType, void *TyOrEx,
4950                                   SourceRange ArgRange);
4951 
4952   ExprResult CheckPlaceholderExpr(Expr *E);
4953   bool CheckVecStepExpr(Expr *E);
4954 
4955   bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
4956   bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
4957                                         SourceRange ExprRange,
4958                                         UnaryExprOrTypeTrait ExprKind);
4959   ExprResult ActOnSizeofParameterPackExpr(Scope *S,
4960                                           SourceLocation OpLoc,
4961                                           IdentifierInfo &Name,
4962                                           SourceLocation NameLoc,
4963                                           SourceLocation RParenLoc);
4964   ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4965                                  tok::TokenKind Kind, Expr *Input);
4966 
4967   ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
4968                                      Expr *Idx, SourceLocation RLoc);
4969   ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4970                                              Expr *Idx, SourceLocation RLoc);
4971 
4972   ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4973                                               Expr *ColumnIdx,
4974                                               SourceLocation RBLoc);
4975 
4976   ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4977                                       Expr *LowerBound,
4978                                       SourceLocation ColonLocFirst,
4979                                       SourceLocation ColonLocSecond,
4980                                       Expr *Length, Expr *Stride,
4981                                       SourceLocation RBLoc);
4982   ExprResult ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
4983                                       SourceLocation RParenLoc,
4984                                       ArrayRef<Expr *> Dims,
4985                                       ArrayRef<SourceRange> Brackets);
4986 
4987   /// Data structure for iterator expression.
4988   struct OMPIteratorData {
4989     IdentifierInfo *DeclIdent = nullptr;
4990     SourceLocation DeclIdentLoc;
4991     ParsedType Type;
4992     OMPIteratorExpr::IteratorRange Range;
4993     SourceLocation AssignLoc;
4994     SourceLocation ColonLoc;
4995     SourceLocation SecColonLoc;
4996   };
4997 
4998   ExprResult ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
4999                                   SourceLocation LLoc, SourceLocation RLoc,
5000                                   ArrayRef<OMPIteratorData> Data);
5001 
5002   // This struct is for use by ActOnMemberAccess to allow
5003   // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
5004   // changing the access operator from a '.' to a '->' (to see if that is the
5005   // change needed to fix an error about an unknown member, e.g. when the class
5006   // defines a custom operator->).
5007   struct ActOnMemberAccessExtraArgs {
5008     Scope *S;
5009     UnqualifiedId &Id;
5010     Decl *ObjCImpDecl;
5011   };
5012 
5013   ExprResult BuildMemberReferenceExpr(
5014       Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
5015       CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5016       NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
5017       const TemplateArgumentListInfo *TemplateArgs,
5018       const Scope *S,
5019       ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
5020 
5021   ExprResult
5022   BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
5023                            bool IsArrow, const CXXScopeSpec &SS,
5024                            SourceLocation TemplateKWLoc,
5025                            NamedDecl *FirstQualifierInScope, LookupResult &R,
5026                            const TemplateArgumentListInfo *TemplateArgs,
5027                            const Scope *S,
5028                            bool SuppressQualifierCheck = false,
5029                            ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
5030 
5031   ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
5032                                      SourceLocation OpLoc,
5033                                      const CXXScopeSpec &SS, FieldDecl *Field,
5034                                      DeclAccessPair FoundDecl,
5035                                      const DeclarationNameInfo &MemberNameInfo);
5036 
5037   ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
5038 
5039   bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
5040                                      const CXXScopeSpec &SS,
5041                                      const LookupResult &R);
5042 
5043   ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
5044                                       bool IsArrow, SourceLocation OpLoc,
5045                                       const CXXScopeSpec &SS,
5046                                       SourceLocation TemplateKWLoc,
5047                                       NamedDecl *FirstQualifierInScope,
5048                                const DeclarationNameInfo &NameInfo,
5049                                const TemplateArgumentListInfo *TemplateArgs);
5050 
5051   ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
5052                                    SourceLocation OpLoc,
5053                                    tok::TokenKind OpKind,
5054                                    CXXScopeSpec &SS,
5055                                    SourceLocation TemplateKWLoc,
5056                                    UnqualifiedId &Member,
5057                                    Decl *ObjCImpDecl);
5058 
5059   MemberExpr *
5060   BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
5061                   const CXXScopeSpec *SS, SourceLocation TemplateKWLoc,
5062                   ValueDecl *Member, DeclAccessPair FoundDecl,
5063                   bool HadMultipleCandidates,
5064                   const DeclarationNameInfo &MemberNameInfo, QualType Ty,
5065                   ExprValueKind VK, ExprObjectKind OK,
5066                   const TemplateArgumentListInfo *TemplateArgs = nullptr);
5067   MemberExpr *
5068   BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
5069                   NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
5070                   ValueDecl *Member, DeclAccessPair FoundDecl,
5071                   bool HadMultipleCandidates,
5072                   const DeclarationNameInfo &MemberNameInfo, QualType Ty,
5073                   ExprValueKind VK, ExprObjectKind OK,
5074                   const TemplateArgumentListInfo *TemplateArgs = nullptr);
5075 
5076   void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
5077   bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5078                                FunctionDecl *FDecl,
5079                                const FunctionProtoType *Proto,
5080                                ArrayRef<Expr *> Args,
5081                                SourceLocation RParenLoc,
5082                                bool ExecConfig = false);
5083   void CheckStaticArrayArgument(SourceLocation CallLoc,
5084                                 ParmVarDecl *Param,
5085                                 const Expr *ArgExpr);
5086 
5087   /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5088   /// This provides the location of the left/right parens and a list of comma
5089   /// locations.
5090   ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
5091                            MultiExprArg ArgExprs, SourceLocation RParenLoc,
5092                            Expr *ExecConfig = nullptr);
5093   ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
5094                            MultiExprArg ArgExprs, SourceLocation RParenLoc,
5095                            Expr *ExecConfig = nullptr,
5096                            bool IsExecConfig = false);
5097   enum class AtomicArgumentOrder { API, AST };
5098   ExprResult
5099   BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5100                   SourceLocation RParenLoc, MultiExprArg Args,
5101                   AtomicExpr::AtomicOp Op,
5102                   AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API);
5103   ExprResult
5104   BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
5105                         ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
5106                         Expr *Config = nullptr, bool IsExecConfig = false,
5107                         ADLCallKind UsesADL = ADLCallKind::NotADL);
5108 
5109   ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
5110                                      MultiExprArg ExecConfig,
5111                                      SourceLocation GGGLoc);
5112 
5113   ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5114                            Declarator &D, ParsedType &Ty,
5115                            SourceLocation RParenLoc, Expr *CastExpr);
5116   ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
5117                                  TypeSourceInfo *Ty,
5118                                  SourceLocation RParenLoc,
5119                                  Expr *Op);
5120   CastKind PrepareScalarCast(ExprResult &src, QualType destType);
5121 
5122   /// Build an altivec or OpenCL literal.
5123   ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
5124                                 SourceLocation RParenLoc, Expr *E,
5125                                 TypeSourceInfo *TInfo);
5126 
5127   ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
5128 
5129   ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
5130                                   ParsedType Ty,
5131                                   SourceLocation RParenLoc,
5132                                   Expr *InitExpr);
5133 
5134   ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
5135                                       TypeSourceInfo *TInfo,
5136                                       SourceLocation RParenLoc,
5137                                       Expr *LiteralExpr);
5138 
5139   ExprResult ActOnInitList(SourceLocation LBraceLoc,
5140                            MultiExprArg InitArgList,
5141                            SourceLocation RBraceLoc);
5142 
5143   ExprResult BuildInitList(SourceLocation LBraceLoc,
5144                            MultiExprArg InitArgList,
5145                            SourceLocation RBraceLoc);
5146 
5147   ExprResult ActOnDesignatedInitializer(Designation &Desig,
5148                                         SourceLocation EqualOrColonLoc,
5149                                         bool GNUSyntax,
5150                                         ExprResult Init);
5151 
5152 private:
5153   static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
5154 
5155 public:
5156   ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
5157                         tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
5158   ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
5159                         BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
5160   ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
5161                                 Expr *LHSExpr, Expr *RHSExpr);
5162 
5163   void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
5164 
5165   /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
5166   /// in the case of a the GNU conditional expr extension.
5167   ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
5168                                 SourceLocation ColonLoc,
5169                                 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
5170 
5171   /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
5172   ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
5173                             LabelDecl *TheDecl);
5174 
5175   void ActOnStartStmtExpr();
5176   ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
5177                            SourceLocation RPLoc);
5178   ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
5179                            SourceLocation RPLoc, unsigned TemplateDepth);
5180   // Handle the final expression in a statement expression.
5181   ExprResult ActOnStmtExprResult(ExprResult E);
5182   void ActOnStmtExprError();
5183 
5184   // __builtin_offsetof(type, identifier(.identifier|[expr])*)
5185   struct OffsetOfComponent {
5186     SourceLocation LocStart, LocEnd;
5187     bool isBrackets;  // true if [expr], false if .ident
5188     union {
5189       IdentifierInfo *IdentInfo;
5190       Expr *E;
5191     } U;
5192   };
5193 
5194   /// __builtin_offsetof(type, a.b[123][456].c)
5195   ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
5196                                   TypeSourceInfo *TInfo,
5197                                   ArrayRef<OffsetOfComponent> Components,
5198                                   SourceLocation RParenLoc);
5199   ExprResult ActOnBuiltinOffsetOf(Scope *S,
5200                                   SourceLocation BuiltinLoc,
5201                                   SourceLocation TypeLoc,
5202                                   ParsedType ParsedArgTy,
5203                                   ArrayRef<OffsetOfComponent> Components,
5204                                   SourceLocation RParenLoc);
5205 
5206   // __builtin_choose_expr(constExpr, expr1, expr2)
5207   ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
5208                              Expr *CondExpr, Expr *LHSExpr,
5209                              Expr *RHSExpr, SourceLocation RPLoc);
5210 
5211   // __builtin_va_arg(expr, type)
5212   ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
5213                         SourceLocation RPLoc);
5214   ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
5215                             TypeSourceInfo *TInfo, SourceLocation RPLoc);
5216 
5217   // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(),
5218   // __builtin_COLUMN()
5219   ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
5220                                 SourceLocation BuiltinLoc,
5221                                 SourceLocation RPLoc);
5222 
5223   // Build a potentially resolved SourceLocExpr.
5224   ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
5225                                 SourceLocation BuiltinLoc, SourceLocation RPLoc,
5226                                 DeclContext *ParentContext);
5227 
5228   // __null
5229   ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
5230 
5231   bool CheckCaseExpression(Expr *E);
5232 
5233   /// Describes the result of an "if-exists" condition check.
5234   enum IfExistsResult {
5235     /// The symbol exists.
5236     IER_Exists,
5237 
5238     /// The symbol does not exist.
5239     IER_DoesNotExist,
5240 
5241     /// The name is a dependent name, so the results will differ
5242     /// from one instantiation to the next.
5243     IER_Dependent,
5244 
5245     /// An error occurred.
5246     IER_Error
5247   };
5248 
5249   IfExistsResult
5250   CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
5251                                const DeclarationNameInfo &TargetNameInfo);
5252 
5253   IfExistsResult
5254   CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
5255                                bool IsIfExists, CXXScopeSpec &SS,
5256                                UnqualifiedId &Name);
5257 
5258   StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
5259                                         bool IsIfExists,
5260                                         NestedNameSpecifierLoc QualifierLoc,
5261                                         DeclarationNameInfo NameInfo,
5262                                         Stmt *Nested);
5263   StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
5264                                         bool IsIfExists,
5265                                         CXXScopeSpec &SS, UnqualifiedId &Name,
5266                                         Stmt *Nested);
5267 
5268   //===------------------------- "Block" Extension ------------------------===//
5269 
5270   /// ActOnBlockStart - This callback is invoked when a block literal is
5271   /// started.
5272   void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
5273 
5274   /// ActOnBlockArguments - This callback allows processing of block arguments.
5275   /// If there are no arguments, this is still invoked.
5276   void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
5277                            Scope *CurScope);
5278 
5279   /// ActOnBlockError - If there is an error parsing a block, this callback
5280   /// is invoked to pop the information about the block from the action impl.
5281   void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
5282 
5283   /// ActOnBlockStmtExpr - This is called when the body of a block statement
5284   /// literal was successfully completed.  ^(int x){...}
5285   ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
5286                                 Scope *CurScope);
5287 
5288   //===---------------------------- Clang Extensions ----------------------===//
5289 
5290   /// __builtin_convertvector(...)
5291   ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5292                                     SourceLocation BuiltinLoc,
5293                                     SourceLocation RParenLoc);
5294 
5295   //===---------------------------- OpenCL Features -----------------------===//
5296 
5297   /// __builtin_astype(...)
5298   ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5299                              SourceLocation BuiltinLoc,
5300                              SourceLocation RParenLoc);
5301 
5302   //===---------------------------- C++ Features --------------------------===//
5303 
5304   // Act on C++ namespaces
5305   Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
5306                                SourceLocation NamespaceLoc,
5307                                SourceLocation IdentLoc, IdentifierInfo *Ident,
5308                                SourceLocation LBrace,
5309                                const ParsedAttributesView &AttrList,
5310                                UsingDirectiveDecl *&UsingDecl);
5311   void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
5312 
5313   NamespaceDecl *getStdNamespace() const;
5314   NamespaceDecl *getOrCreateStdNamespace();
5315 
5316   NamespaceDecl *lookupStdExperimentalNamespace();
5317 
5318   CXXRecordDecl *getStdBadAlloc() const;
5319   EnumDecl *getStdAlignValT() const;
5320 
5321 private:
5322   // A cache representing if we've fully checked the various comparison category
5323   // types stored in ASTContext. The bit-index corresponds to the integer value
5324   // of a ComparisonCategoryType enumerator.
5325   llvm::SmallBitVector FullyCheckedComparisonCategories;
5326 
5327   ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
5328                                          CXXScopeSpec &SS,
5329                                          ParsedType TemplateTypeTy,
5330                                          IdentifierInfo *MemberOrBase);
5331 
5332 public:
5333   enum class ComparisonCategoryUsage {
5334     /// The '<=>' operator was used in an expression and a builtin operator
5335     /// was selected.
5336     OperatorInExpression,
5337     /// A defaulted 'operator<=>' needed the comparison category. This
5338     /// typically only applies to 'std::strong_ordering', due to the implicit
5339     /// fallback return value.
5340     DefaultedOperator,
5341   };
5342 
5343   /// Lookup the specified comparison category types in the standard
5344   ///   library, an check the VarDecls possibly returned by the operator<=>
5345   ///   builtins for that type.
5346   ///
5347   /// \return The type of the comparison category type corresponding to the
5348   ///   specified Kind, or a null type if an error occurs
5349   QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
5350                                        SourceLocation Loc,
5351                                        ComparisonCategoryUsage Usage);
5352 
5353   /// Tests whether Ty is an instance of std::initializer_list and, if
5354   /// it is and Element is not NULL, assigns the element type to Element.
5355   bool isStdInitializerList(QualType Ty, QualType *Element);
5356 
5357   /// Looks for the std::initializer_list template and instantiates it
5358   /// with Element, or emits an error if it's not found.
5359   ///
5360   /// \returns The instantiated template, or null on error.
5361   QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
5362 
5363   /// Determine whether Ctor is an initializer-list constructor, as
5364   /// defined in [dcl.init.list]p2.
5365   bool isInitListConstructor(const FunctionDecl *Ctor);
5366 
5367   Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
5368                             SourceLocation NamespcLoc, CXXScopeSpec &SS,
5369                             SourceLocation IdentLoc,
5370                             IdentifierInfo *NamespcName,
5371                             const ParsedAttributesView &AttrList);
5372 
5373   void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
5374 
5375   Decl *ActOnNamespaceAliasDef(Scope *CurScope,
5376                                SourceLocation NamespaceLoc,
5377                                SourceLocation AliasLoc,
5378                                IdentifierInfo *Alias,
5379                                CXXScopeSpec &SS,
5380                                SourceLocation IdentLoc,
5381                                IdentifierInfo *Ident);
5382 
5383   void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
5384   bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
5385                             const LookupResult &PreviousDecls,
5386                             UsingShadowDecl *&PrevShadow);
5387   UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
5388                                         NamedDecl *Target,
5389                                         UsingShadowDecl *PrevDecl);
5390 
5391   bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5392                                    bool HasTypenameKeyword,
5393                                    const CXXScopeSpec &SS,
5394                                    SourceLocation NameLoc,
5395                                    const LookupResult &Previous);
5396   bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
5397                                bool HasTypename,
5398                                const CXXScopeSpec &SS,
5399                                const DeclarationNameInfo &NameInfo,
5400                                SourceLocation NameLoc);
5401 
5402   NamedDecl *BuildUsingDeclaration(
5403       Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
5404       bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
5405       DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
5406       const ParsedAttributesView &AttrList, bool IsInstantiation);
5407   NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
5408                                 ArrayRef<NamedDecl *> Expansions);
5409 
5410   bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
5411 
5412   /// Given a derived-class using shadow declaration for a constructor and the
5413   /// correspnding base class constructor, find or create the implicit
5414   /// synthesized derived class constructor to use for this initialization.
5415   CXXConstructorDecl *
5416   findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
5417                             ConstructorUsingShadowDecl *DerivedShadow);
5418 
5419   Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
5420                               SourceLocation UsingLoc,
5421                               SourceLocation TypenameLoc, CXXScopeSpec &SS,
5422                               UnqualifiedId &Name, SourceLocation EllipsisLoc,
5423                               const ParsedAttributesView &AttrList);
5424   Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
5425                               MultiTemplateParamsArg TemplateParams,
5426                               SourceLocation UsingLoc, UnqualifiedId &Name,
5427                               const ParsedAttributesView &AttrList,
5428                               TypeResult Type, Decl *DeclFromDeclSpec);
5429 
5430   /// BuildCXXConstructExpr - Creates a complete call to a constructor,
5431   /// including handling of its default argument expressions.
5432   ///
5433   /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
5434   ExprResult
5435   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5436                         NamedDecl *FoundDecl,
5437                         CXXConstructorDecl *Constructor, MultiExprArg Exprs,
5438                         bool HadMultipleCandidates, bool IsListInitialization,
5439                         bool IsStdInitListInitialization,
5440                         bool RequiresZeroInit, unsigned ConstructKind,
5441                         SourceRange ParenRange);
5442 
5443   /// Build a CXXConstructExpr whose constructor has already been resolved if
5444   /// it denotes an inherited constructor.
5445   ExprResult
5446   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5447                         CXXConstructorDecl *Constructor, bool Elidable,
5448                         MultiExprArg Exprs,
5449                         bool HadMultipleCandidates, bool IsListInitialization,
5450                         bool IsStdInitListInitialization,
5451                         bool RequiresZeroInit, unsigned ConstructKind,
5452                         SourceRange ParenRange);
5453 
5454   // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
5455   // the constructor can be elidable?
5456   ExprResult
5457   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5458                         NamedDecl *FoundDecl,
5459                         CXXConstructorDecl *Constructor, bool Elidable,
5460                         MultiExprArg Exprs, bool HadMultipleCandidates,
5461                         bool IsListInitialization,
5462                         bool IsStdInitListInitialization, bool RequiresZeroInit,
5463                         unsigned ConstructKind, SourceRange ParenRange);
5464 
5465   ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
5466 
5467 
5468   /// Instantiate or parse a C++ default argument expression as necessary.
5469   /// Return true on error.
5470   bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5471                               ParmVarDecl *Param);
5472 
5473   /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
5474   /// the default expr if needed.
5475   ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5476                                     FunctionDecl *FD,
5477                                     ParmVarDecl *Param);
5478 
5479   /// FinalizeVarWithDestructor - Prepare for calling destructor on the
5480   /// constructed variable.
5481   void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
5482 
5483   /// Helper class that collects exception specifications for
5484   /// implicitly-declared special member functions.
5485   class ImplicitExceptionSpecification {
5486     // Pointer to allow copying
5487     Sema *Self;
5488     // We order exception specifications thus:
5489     // noexcept is the most restrictive, but is only used in C++11.
5490     // throw() comes next.
5491     // Then a throw(collected exceptions)
5492     // Finally no specification, which is expressed as noexcept(false).
5493     // throw(...) is used instead if any called function uses it.
5494     ExceptionSpecificationType ComputedEST;
5495     llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
5496     SmallVector<QualType, 4> Exceptions;
5497 
ClearExceptions()5498     void ClearExceptions() {
5499       ExceptionsSeen.clear();
5500       Exceptions.clear();
5501     }
5502 
5503   public:
ImplicitExceptionSpecification(Sema & Self)5504     explicit ImplicitExceptionSpecification(Sema &Self)
5505       : Self(&Self), ComputedEST(EST_BasicNoexcept) {
5506       if (!Self.getLangOpts().CPlusPlus11)
5507         ComputedEST = EST_DynamicNone;
5508     }
5509 
5510     /// Get the computed exception specification type.
getExceptionSpecType()5511     ExceptionSpecificationType getExceptionSpecType() const {
5512       assert(!isComputedNoexcept(ComputedEST) &&
5513              "noexcept(expr) should not be a possible result");
5514       return ComputedEST;
5515     }
5516 
5517     /// The number of exceptions in the exception specification.
size()5518     unsigned size() const { return Exceptions.size(); }
5519 
5520     /// The set of exceptions in the exception specification.
data()5521     const QualType *data() const { return Exceptions.data(); }
5522 
5523     /// Integrate another called method into the collected data.
5524     void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
5525 
5526     /// Integrate an invoked expression into the collected data.
CalledExpr(Expr * E)5527     void CalledExpr(Expr *E) { CalledStmt(E); }
5528 
5529     /// Integrate an invoked statement into the collected data.
5530     void CalledStmt(Stmt *S);
5531 
5532     /// Overwrite an EPI's exception specification with this
5533     /// computed exception specification.
getExceptionSpec()5534     FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
5535       FunctionProtoType::ExceptionSpecInfo ESI;
5536       ESI.Type = getExceptionSpecType();
5537       if (ESI.Type == EST_Dynamic) {
5538         ESI.Exceptions = Exceptions;
5539       } else if (ESI.Type == EST_None) {
5540         /// C++11 [except.spec]p14:
5541         ///   The exception-specification is noexcept(false) if the set of
5542         ///   potential exceptions of the special member function contains "any"
5543         ESI.Type = EST_NoexceptFalse;
5544         ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
5545                                                      tok::kw_false).get();
5546       }
5547       return ESI;
5548     }
5549   };
5550 
5551   /// Determine what sort of exception specification a defaulted
5552   /// copy constructor of a class will have.
5553   ImplicitExceptionSpecification
5554   ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
5555                                            CXXMethodDecl *MD);
5556 
5557   /// Determine what sort of exception specification a defaulted
5558   /// default constructor of a class will have, and whether the parameter
5559   /// will be const.
5560   ImplicitExceptionSpecification
5561   ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
5562 
5563   /// Determine what sort of exception specification a defaulted
5564   /// copy assignment operator of a class will have, and whether the
5565   /// parameter will be const.
5566   ImplicitExceptionSpecification
5567   ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
5568 
5569   /// Determine what sort of exception specification a defaulted move
5570   /// constructor of a class will have.
5571   ImplicitExceptionSpecification
5572   ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
5573 
5574   /// Determine what sort of exception specification a defaulted move
5575   /// assignment operator of a class will have.
5576   ImplicitExceptionSpecification
5577   ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
5578 
5579   /// Determine what sort of exception specification a defaulted
5580   /// destructor of a class will have.
5581   ImplicitExceptionSpecification
5582   ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
5583 
5584   /// Determine what sort of exception specification an inheriting
5585   /// constructor of a class will have.
5586   ImplicitExceptionSpecification
5587   ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
5588                                      CXXConstructorDecl *CD);
5589 
5590   /// Evaluate the implicit exception specification for a defaulted
5591   /// special member function.
5592   void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD);
5593 
5594   /// Check the given noexcept-specifier, convert its expression, and compute
5595   /// the appropriate ExceptionSpecificationType.
5596   ExprResult ActOnNoexceptSpec(SourceLocation NoexceptLoc, Expr *NoexceptExpr,
5597                                ExceptionSpecificationType &EST);
5598 
5599   /// Check the given exception-specification and update the
5600   /// exception specification information with the results.
5601   void checkExceptionSpecification(bool IsTopLevel,
5602                                    ExceptionSpecificationType EST,
5603                                    ArrayRef<ParsedType> DynamicExceptions,
5604                                    ArrayRef<SourceRange> DynamicExceptionRanges,
5605                                    Expr *NoexceptExpr,
5606                                    SmallVectorImpl<QualType> &Exceptions,
5607                                    FunctionProtoType::ExceptionSpecInfo &ESI);
5608 
5609   /// Determine if we're in a case where we need to (incorrectly) eagerly
5610   /// parse an exception specification to work around a libstdc++ bug.
5611   bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
5612 
5613   /// Add an exception-specification to the given member function
5614   /// (or member function template). The exception-specification was parsed
5615   /// after the method itself was declared.
5616   void actOnDelayedExceptionSpecification(Decl *Method,
5617          ExceptionSpecificationType EST,
5618          SourceRange SpecificationRange,
5619          ArrayRef<ParsedType> DynamicExceptions,
5620          ArrayRef<SourceRange> DynamicExceptionRanges,
5621          Expr *NoexceptExpr);
5622 
5623   class InheritedConstructorInfo;
5624 
5625   /// Determine if a special member function should have a deleted
5626   /// definition when it is defaulted.
5627   bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5628                                  InheritedConstructorInfo *ICI = nullptr,
5629                                  bool Diagnose = false);
5630 
5631   /// Produce notes explaining why a defaulted function was defined as deleted.
5632   void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD);
5633 
5634   /// Declare the implicit default constructor for the given class.
5635   ///
5636   /// \param ClassDecl The class declaration into which the implicit
5637   /// default constructor will be added.
5638   ///
5639   /// \returns The implicitly-declared default constructor.
5640   CXXConstructorDecl *DeclareImplicitDefaultConstructor(
5641                                                      CXXRecordDecl *ClassDecl);
5642 
5643   /// DefineImplicitDefaultConstructor - Checks for feasibility of
5644   /// defining this constructor as the default constructor.
5645   void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
5646                                         CXXConstructorDecl *Constructor);
5647 
5648   /// Declare the implicit destructor for the given class.
5649   ///
5650   /// \param ClassDecl The class declaration into which the implicit
5651   /// destructor will be added.
5652   ///
5653   /// \returns The implicitly-declared destructor.
5654   CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
5655 
5656   /// DefineImplicitDestructor - Checks for feasibility of
5657   /// defining this destructor as the default destructor.
5658   void DefineImplicitDestructor(SourceLocation CurrentLocation,
5659                                 CXXDestructorDecl *Destructor);
5660 
5661   /// Build an exception spec for destructors that don't have one.
5662   ///
5663   /// C++11 says that user-defined destructors with no exception spec get one
5664   /// that looks as if the destructor was implicitly declared.
5665   void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor);
5666 
5667   /// Define the specified inheriting constructor.
5668   void DefineInheritingConstructor(SourceLocation UseLoc,
5669                                    CXXConstructorDecl *Constructor);
5670 
5671   /// Declare the implicit copy constructor for the given class.
5672   ///
5673   /// \param ClassDecl The class declaration into which the implicit
5674   /// copy constructor will be added.
5675   ///
5676   /// \returns The implicitly-declared copy constructor.
5677   CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
5678 
5679   /// DefineImplicitCopyConstructor - Checks for feasibility of
5680   /// defining this constructor as the copy constructor.
5681   void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5682                                      CXXConstructorDecl *Constructor);
5683 
5684   /// Declare the implicit move constructor for the given class.
5685   ///
5686   /// \param ClassDecl The Class declaration into which the implicit
5687   /// move constructor will be added.
5688   ///
5689   /// \returns The implicitly-declared move constructor, or NULL if it wasn't
5690   /// declared.
5691   CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
5692 
5693   /// DefineImplicitMoveConstructor - Checks for feasibility of
5694   /// defining this constructor as the move constructor.
5695   void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
5696                                      CXXConstructorDecl *Constructor);
5697 
5698   /// Declare the implicit copy assignment operator for the given class.
5699   ///
5700   /// \param ClassDecl The class declaration into which the implicit
5701   /// copy assignment operator will be added.
5702   ///
5703   /// \returns The implicitly-declared copy assignment operator.
5704   CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
5705 
5706   /// Defines an implicitly-declared copy assignment operator.
5707   void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5708                                     CXXMethodDecl *MethodDecl);
5709 
5710   /// Declare the implicit move assignment operator for the given class.
5711   ///
5712   /// \param ClassDecl The Class declaration into which the implicit
5713   /// move assignment operator will be added.
5714   ///
5715   /// \returns The implicitly-declared move assignment operator, or NULL if it
5716   /// wasn't declared.
5717   CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
5718 
5719   /// Defines an implicitly-declared move assignment operator.
5720   void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
5721                                     CXXMethodDecl *MethodDecl);
5722 
5723   /// Force the declaration of any implicitly-declared members of this
5724   /// class.
5725   void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
5726 
5727   /// Check a completed declaration of an implicit special member.
5728   void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
5729 
5730   /// Determine whether the given function is an implicitly-deleted
5731   /// special member function.
5732   bool isImplicitlyDeleted(FunctionDecl *FD);
5733 
5734   /// Check whether 'this' shows up in the type of a static member
5735   /// function after the (naturally empty) cv-qualifier-seq would be.
5736   ///
5737   /// \returns true if an error occurred.
5738   bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
5739 
5740   /// Whether this' shows up in the exception specification of a static
5741   /// member function.
5742   bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
5743 
5744   /// Check whether 'this' shows up in the attributes of the given
5745   /// static member function.
5746   ///
5747   /// \returns true if an error occurred.
5748   bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
5749 
5750   /// MaybeBindToTemporary - If the passed in expression has a record type with
5751   /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
5752   /// it simply returns the passed in expression.
5753   ExprResult MaybeBindToTemporary(Expr *E);
5754 
5755   /// Wrap the expression in a ConstantExpr if it is a potential immediate
5756   /// invocation.
5757   ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl);
5758 
5759   bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
5760                                MultiExprArg ArgsPtr,
5761                                SourceLocation Loc,
5762                                SmallVectorImpl<Expr*> &ConvertedArgs,
5763                                bool AllowExplicit = false,
5764                                bool IsListInitialization = false);
5765 
5766   ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
5767                                           SourceLocation NameLoc,
5768                                           IdentifierInfo &Name);
5769 
5770   ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc,
5771                                 Scope *S, CXXScopeSpec &SS,
5772                                 bool EnteringContext);
5773   ParsedType getDestructorName(SourceLocation TildeLoc,
5774                                IdentifierInfo &II, SourceLocation NameLoc,
5775                                Scope *S, CXXScopeSpec &SS,
5776                                ParsedType ObjectType,
5777                                bool EnteringContext);
5778 
5779   ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
5780                                           ParsedType ObjectType);
5781 
5782   // Checks that reinterpret casts don't have undefined behavior.
5783   void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
5784                                       bool IsDereference, SourceRange Range);
5785 
5786   /// ActOnCXXNamedCast - Parse
5787   /// {dynamic,static,reinterpret,const,addrspace}_cast's.
5788   ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
5789                                tok::TokenKind Kind,
5790                                SourceLocation LAngleBracketLoc,
5791                                Declarator &D,
5792                                SourceLocation RAngleBracketLoc,
5793                                SourceLocation LParenLoc,
5794                                Expr *E,
5795                                SourceLocation RParenLoc);
5796 
5797   ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
5798                                tok::TokenKind Kind,
5799                                TypeSourceInfo *Ty,
5800                                Expr *E,
5801                                SourceRange AngleBrackets,
5802                                SourceRange Parens);
5803 
5804   ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl,
5805                                      ExprResult Operand,
5806                                      SourceLocation RParenLoc);
5807 
5808   ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI,
5809                                      Expr *Operand, SourceLocation RParenLoc);
5810 
5811   ExprResult BuildCXXTypeId(QualType TypeInfoType,
5812                             SourceLocation TypeidLoc,
5813                             TypeSourceInfo *Operand,
5814                             SourceLocation RParenLoc);
5815   ExprResult BuildCXXTypeId(QualType TypeInfoType,
5816                             SourceLocation TypeidLoc,
5817                             Expr *Operand,
5818                             SourceLocation RParenLoc);
5819 
5820   /// ActOnCXXTypeid - Parse typeid( something ).
5821   ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
5822                             SourceLocation LParenLoc, bool isType,
5823                             void *TyOrExpr,
5824                             SourceLocation RParenLoc);
5825 
5826   ExprResult BuildCXXUuidof(QualType TypeInfoType,
5827                             SourceLocation TypeidLoc,
5828                             TypeSourceInfo *Operand,
5829                             SourceLocation RParenLoc);
5830   ExprResult BuildCXXUuidof(QualType TypeInfoType,
5831                             SourceLocation TypeidLoc,
5832                             Expr *Operand,
5833                             SourceLocation RParenLoc);
5834 
5835   /// ActOnCXXUuidof - Parse __uuidof( something ).
5836   ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
5837                             SourceLocation LParenLoc, bool isType,
5838                             void *TyOrExpr,
5839                             SourceLocation RParenLoc);
5840 
5841   /// Handle a C++1z fold-expression: ( expr op ... op expr ).
5842   ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
5843                               tok::TokenKind Operator,
5844                               SourceLocation EllipsisLoc, Expr *RHS,
5845                               SourceLocation RParenLoc);
5846   ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
5847                               BinaryOperatorKind Operator,
5848                               SourceLocation EllipsisLoc, Expr *RHS,
5849                               SourceLocation RParenLoc,
5850                               Optional<unsigned> NumExpansions);
5851   ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
5852                                    BinaryOperatorKind Operator);
5853 
5854   //// ActOnCXXThis -  Parse 'this' pointer.
5855   ExprResult ActOnCXXThis(SourceLocation loc);
5856 
5857   /// Build a CXXThisExpr and mark it referenced in the current context.
5858   Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
5859   void MarkThisReferenced(CXXThisExpr *This);
5860 
5861   /// Try to retrieve the type of the 'this' pointer.
5862   ///
5863   /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
5864   QualType getCurrentThisType();
5865 
5866   /// When non-NULL, the C++ 'this' expression is allowed despite the
5867   /// current context not being a non-static member function. In such cases,
5868   /// this provides the type used for 'this'.
5869   QualType CXXThisTypeOverride;
5870 
5871   /// RAII object used to temporarily allow the C++ 'this' expression
5872   /// to be used, with the given qualifiers on the current class type.
5873   class CXXThisScopeRAII {
5874     Sema &S;
5875     QualType OldCXXThisTypeOverride;
5876     bool Enabled;
5877 
5878   public:
5879     /// Introduce a new scope where 'this' may be allowed (when enabled),
5880     /// using the given declaration (which is either a class template or a
5881     /// class) along with the given qualifiers.
5882     /// along with the qualifiers placed on '*this'.
5883     CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
5884                      bool Enabled = true);
5885 
5886     ~CXXThisScopeRAII();
5887   };
5888 
5889   /// Make sure the value of 'this' is actually available in the current
5890   /// context, if it is a potentially evaluated context.
5891   ///
5892   /// \param Loc The location at which the capture of 'this' occurs.
5893   ///
5894   /// \param Explicit Whether 'this' is explicitly captured in a lambda
5895   /// capture list.
5896   ///
5897   /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
5898   /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
5899   /// This is useful when enclosing lambdas must speculatively capture
5900   /// 'this' that may or may not be used in certain specializations of
5901   /// a nested generic lambda (depending on whether the name resolves to
5902   /// a non-static member function or a static function).
5903   /// \return returns 'true' if failed, 'false' if success.
5904   bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
5905       bool BuildAndDiagnose = true,
5906       const unsigned *const FunctionScopeIndexToStopAt = nullptr,
5907       bool ByCopy = false);
5908 
5909   /// Determine whether the given type is the type of *this that is used
5910   /// outside of the body of a member function for a type that is currently
5911   /// being defined.
5912   bool isThisOutsideMemberFunctionBody(QualType BaseType);
5913 
5914   /// ActOnCXXBoolLiteral - Parse {true,false} literals.
5915   ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
5916 
5917 
5918   /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
5919   ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
5920 
5921   ExprResult
5922   ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
5923                                  SourceLocation AtLoc, SourceLocation RParen);
5924 
5925   /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
5926   ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
5927 
5928   //// ActOnCXXThrow -  Parse throw expressions.
5929   ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
5930   ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
5931                            bool IsThrownVarInScope);
5932   bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
5933 
5934   /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
5935   /// Can be interpreted either as function-style casting ("int(x)")
5936   /// or class type construction ("ClassType(x,y,z)")
5937   /// or creation of a value-initialized type ("int()").
5938   ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
5939                                        SourceLocation LParenOrBraceLoc,
5940                                        MultiExprArg Exprs,
5941                                        SourceLocation RParenOrBraceLoc,
5942                                        bool ListInitialization);
5943 
5944   ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
5945                                        SourceLocation LParenLoc,
5946                                        MultiExprArg Exprs,
5947                                        SourceLocation RParenLoc,
5948                                        bool ListInitialization);
5949 
5950   /// ActOnCXXNew - Parsed a C++ 'new' expression.
5951   ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
5952                          SourceLocation PlacementLParen,
5953                          MultiExprArg PlacementArgs,
5954                          SourceLocation PlacementRParen,
5955                          SourceRange TypeIdParens, Declarator &D,
5956                          Expr *Initializer);
5957   ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
5958                          SourceLocation PlacementLParen,
5959                          MultiExprArg PlacementArgs,
5960                          SourceLocation PlacementRParen,
5961                          SourceRange TypeIdParens,
5962                          QualType AllocType,
5963                          TypeSourceInfo *AllocTypeInfo,
5964                          Optional<Expr *> ArraySize,
5965                          SourceRange DirectInitRange,
5966                          Expr *Initializer);
5967 
5968   /// Determine whether \p FD is an aligned allocation or deallocation
5969   /// function that is unavailable.
5970   bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const;
5971 
5972   /// Produce diagnostics if \p FD is an aligned allocation or deallocation
5973   /// function that is unavailable.
5974   void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
5975                                             SourceLocation Loc);
5976 
5977   bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
5978                           SourceRange R);
5979 
5980   /// The scope in which to find allocation functions.
5981   enum AllocationFunctionScope {
5982     /// Only look for allocation functions in the global scope.
5983     AFS_Global,
5984     /// Only look for allocation functions in the scope of the
5985     /// allocated class.
5986     AFS_Class,
5987     /// Look for allocation functions in both the global scope
5988     /// and in the scope of the allocated class.
5989     AFS_Both
5990   };
5991 
5992   /// Finds the overloads of operator new and delete that are appropriate
5993   /// for the allocation.
5994   bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
5995                                AllocationFunctionScope NewScope,
5996                                AllocationFunctionScope DeleteScope,
5997                                QualType AllocType, bool IsArray,
5998                                bool &PassAlignment, MultiExprArg PlaceArgs,
5999                                FunctionDecl *&OperatorNew,
6000                                FunctionDecl *&OperatorDelete,
6001                                bool Diagnose = true);
6002   void DeclareGlobalNewDelete();
6003   void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
6004                                        ArrayRef<QualType> Params);
6005 
6006   bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
6007                                 DeclarationName Name, FunctionDecl* &Operator,
6008                                 bool Diagnose = true);
6009   FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
6010                                               bool CanProvideSize,
6011                                               bool Overaligned,
6012                                               DeclarationName Name);
6013   FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
6014                                                       CXXRecordDecl *RD);
6015 
6016   /// ActOnCXXDelete - Parsed a C++ 'delete' expression
6017   ExprResult ActOnCXXDelete(SourceLocation StartLoc,
6018                             bool UseGlobal, bool ArrayForm,
6019                             Expr *Operand);
6020   void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
6021                             bool IsDelete, bool CallCanBeVirtual,
6022                             bool WarnOnNonAbstractTypes,
6023                             SourceLocation DtorLoc);
6024 
6025   ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
6026                                Expr *Operand, SourceLocation RParen);
6027   ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
6028                                   SourceLocation RParen);
6029 
6030   /// Parsed one of the type trait support pseudo-functions.
6031   ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
6032                             ArrayRef<ParsedType> Args,
6033                             SourceLocation RParenLoc);
6034   ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
6035                             ArrayRef<TypeSourceInfo *> Args,
6036                             SourceLocation RParenLoc);
6037 
6038   /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
6039   /// pseudo-functions.
6040   ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
6041                                  SourceLocation KWLoc,
6042                                  ParsedType LhsTy,
6043                                  Expr *DimExpr,
6044                                  SourceLocation RParen);
6045 
6046   ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
6047                                  SourceLocation KWLoc,
6048                                  TypeSourceInfo *TSInfo,
6049                                  Expr *DimExpr,
6050                                  SourceLocation RParen);
6051 
6052   /// ActOnExpressionTrait - Parsed one of the unary type trait support
6053   /// pseudo-functions.
6054   ExprResult ActOnExpressionTrait(ExpressionTrait OET,
6055                                   SourceLocation KWLoc,
6056                                   Expr *Queried,
6057                                   SourceLocation RParen);
6058 
6059   ExprResult BuildExpressionTrait(ExpressionTrait OET,
6060                                   SourceLocation KWLoc,
6061                                   Expr *Queried,
6062                                   SourceLocation RParen);
6063 
6064   ExprResult ActOnStartCXXMemberReference(Scope *S,
6065                                           Expr *Base,
6066                                           SourceLocation OpLoc,
6067                                           tok::TokenKind OpKind,
6068                                           ParsedType &ObjectType,
6069                                           bool &MayBePseudoDestructor);
6070 
6071   ExprResult BuildPseudoDestructorExpr(Expr *Base,
6072                                        SourceLocation OpLoc,
6073                                        tok::TokenKind OpKind,
6074                                        const CXXScopeSpec &SS,
6075                                        TypeSourceInfo *ScopeType,
6076                                        SourceLocation CCLoc,
6077                                        SourceLocation TildeLoc,
6078                                      PseudoDestructorTypeStorage DestroyedType);
6079 
6080   ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6081                                        SourceLocation OpLoc,
6082                                        tok::TokenKind OpKind,
6083                                        CXXScopeSpec &SS,
6084                                        UnqualifiedId &FirstTypeName,
6085                                        SourceLocation CCLoc,
6086                                        SourceLocation TildeLoc,
6087                                        UnqualifiedId &SecondTypeName);
6088 
6089   ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6090                                        SourceLocation OpLoc,
6091                                        tok::TokenKind OpKind,
6092                                        SourceLocation TildeLoc,
6093                                        const DeclSpec& DS);
6094 
6095   /// MaybeCreateExprWithCleanups - If the current full-expression
6096   /// requires any cleanups, surround it with a ExprWithCleanups node.
6097   /// Otherwise, just returns the passed-in expression.
6098   Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
6099   Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
6100   ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
6101 
6102   MaterializeTemporaryExpr *
6103   CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
6104                                  bool BoundToLvalueReference);
6105 
ActOnFinishFullExpr(Expr * Expr,bool DiscardedValue)6106   ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
6107     return ActOnFinishFullExpr(
6108         Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
6109   }
6110   ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
6111                                  bool DiscardedValue, bool IsConstexpr = false);
6112   StmtResult ActOnFinishFullStmt(Stmt *Stmt);
6113 
6114   // Marks SS invalid if it represents an incomplete type.
6115   bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
6116 
6117   DeclContext *computeDeclContext(QualType T);
6118   DeclContext *computeDeclContext(const CXXScopeSpec &SS,
6119                                   bool EnteringContext = false);
6120   bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
6121   CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
6122 
6123   /// The parser has parsed a global nested-name-specifier '::'.
6124   ///
6125   /// \param CCLoc The location of the '::'.
6126   ///
6127   /// \param SS The nested-name-specifier, which will be updated in-place
6128   /// to reflect the parsed nested-name-specifier.
6129   ///
6130   /// \returns true if an error occurred, false otherwise.
6131   bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
6132 
6133   /// The parser has parsed a '__super' nested-name-specifier.
6134   ///
6135   /// \param SuperLoc The location of the '__super' keyword.
6136   ///
6137   /// \param ColonColonLoc The location of the '::'.
6138   ///
6139   /// \param SS The nested-name-specifier, which will be updated in-place
6140   /// to reflect the parsed nested-name-specifier.
6141   ///
6142   /// \returns true if an error occurred, false otherwise.
6143   bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
6144                                 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
6145 
6146   bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
6147                                        bool *CanCorrect = nullptr);
6148   NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
6149 
6150   /// Keeps information about an identifier in a nested-name-spec.
6151   ///
6152   struct NestedNameSpecInfo {
6153     /// The type of the object, if we're parsing nested-name-specifier in
6154     /// a member access expression.
6155     ParsedType ObjectType;
6156 
6157     /// The identifier preceding the '::'.
6158     IdentifierInfo *Identifier;
6159 
6160     /// The location of the identifier.
6161     SourceLocation IdentifierLoc;
6162 
6163     /// The location of the '::'.
6164     SourceLocation CCLoc;
6165 
6166     /// Creates info object for the most typical case.
6167     NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
6168              SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
ObjectTypeNestedNameSpecInfo6169       : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
6170         CCLoc(ColonColonLoc) {
6171     }
6172 
NestedNameSpecInfoNestedNameSpecInfo6173     NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
6174                        SourceLocation ColonColonLoc, QualType ObjectType)
6175       : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
6176         IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
6177     }
6178   };
6179 
6180   bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
6181                                     NestedNameSpecInfo &IdInfo);
6182 
6183   bool BuildCXXNestedNameSpecifier(Scope *S,
6184                                    NestedNameSpecInfo &IdInfo,
6185                                    bool EnteringContext,
6186                                    CXXScopeSpec &SS,
6187                                    NamedDecl *ScopeLookupResult,
6188                                    bool ErrorRecoveryLookup,
6189                                    bool *IsCorrectedToColon = nullptr,
6190                                    bool OnlyNamespace = false);
6191 
6192   /// The parser has parsed a nested-name-specifier 'identifier::'.
6193   ///
6194   /// \param S The scope in which this nested-name-specifier occurs.
6195   ///
6196   /// \param IdInfo Parser information about an identifier in the
6197   /// nested-name-spec.
6198   ///
6199   /// \param EnteringContext Whether we're entering the context nominated by
6200   /// this nested-name-specifier.
6201   ///
6202   /// \param SS The nested-name-specifier, which is both an input
6203   /// parameter (the nested-name-specifier before this type) and an
6204   /// output parameter (containing the full nested-name-specifier,
6205   /// including this new type).
6206   ///
6207   /// \param ErrorRecoveryLookup If true, then this method is called to improve
6208   /// error recovery. In this case do not emit error message.
6209   ///
6210   /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
6211   /// are allowed.  The bool value pointed by this parameter is set to 'true'
6212   /// if the identifier is treated as if it was followed by ':', not '::'.
6213   ///
6214   /// \param OnlyNamespace If true, only considers namespaces in lookup.
6215   ///
6216   /// \returns true if an error occurred, false otherwise.
6217   bool ActOnCXXNestedNameSpecifier(Scope *S,
6218                                    NestedNameSpecInfo &IdInfo,
6219                                    bool EnteringContext,
6220                                    CXXScopeSpec &SS,
6221                                    bool ErrorRecoveryLookup = false,
6222                                    bool *IsCorrectedToColon = nullptr,
6223                                    bool OnlyNamespace = false);
6224 
6225   ExprResult ActOnDecltypeExpression(Expr *E);
6226 
6227   bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
6228                                            const DeclSpec &DS,
6229                                            SourceLocation ColonColonLoc);
6230 
6231   bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
6232                                  NestedNameSpecInfo &IdInfo,
6233                                  bool EnteringContext);
6234 
6235   /// The parser has parsed a nested-name-specifier
6236   /// 'template[opt] template-name < template-args >::'.
6237   ///
6238   /// \param S The scope in which this nested-name-specifier occurs.
6239   ///
6240   /// \param SS The nested-name-specifier, which is both an input
6241   /// parameter (the nested-name-specifier before this type) and an
6242   /// output parameter (containing the full nested-name-specifier,
6243   /// including this new type).
6244   ///
6245   /// \param TemplateKWLoc the location of the 'template' keyword, if any.
6246   /// \param TemplateName the template name.
6247   /// \param TemplateNameLoc The location of the template name.
6248   /// \param LAngleLoc The location of the opening angle bracket  ('<').
6249   /// \param TemplateArgs The template arguments.
6250   /// \param RAngleLoc The location of the closing angle bracket  ('>').
6251   /// \param CCLoc The location of the '::'.
6252   ///
6253   /// \param EnteringContext Whether we're entering the context of the
6254   /// nested-name-specifier.
6255   ///
6256   ///
6257   /// \returns true if an error occurred, false otherwise.
6258   bool ActOnCXXNestedNameSpecifier(Scope *S,
6259                                    CXXScopeSpec &SS,
6260                                    SourceLocation TemplateKWLoc,
6261                                    TemplateTy TemplateName,
6262                                    SourceLocation TemplateNameLoc,
6263                                    SourceLocation LAngleLoc,
6264                                    ASTTemplateArgsPtr TemplateArgs,
6265                                    SourceLocation RAngleLoc,
6266                                    SourceLocation CCLoc,
6267                                    bool EnteringContext);
6268 
6269   /// Given a C++ nested-name-specifier, produce an annotation value
6270   /// that the parser can use later to reconstruct the given
6271   /// nested-name-specifier.
6272   ///
6273   /// \param SS A nested-name-specifier.
6274   ///
6275   /// \returns A pointer containing all of the information in the
6276   /// nested-name-specifier \p SS.
6277   void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
6278 
6279   /// Given an annotation pointer for a nested-name-specifier, restore
6280   /// the nested-name-specifier structure.
6281   ///
6282   /// \param Annotation The annotation pointer, produced by
6283   /// \c SaveNestedNameSpecifierAnnotation().
6284   ///
6285   /// \param AnnotationRange The source range corresponding to the annotation.
6286   ///
6287   /// \param SS The nested-name-specifier that will be updated with the contents
6288   /// of the annotation pointer.
6289   void RestoreNestedNameSpecifierAnnotation(void *Annotation,
6290                                             SourceRange AnnotationRange,
6291                                             CXXScopeSpec &SS);
6292 
6293   bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
6294 
6295   /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
6296   /// scope or nested-name-specifier) is parsed, part of a declarator-id.
6297   /// After this method is called, according to [C++ 3.4.3p3], names should be
6298   /// looked up in the declarator-id's scope, until the declarator is parsed and
6299   /// ActOnCXXExitDeclaratorScope is called.
6300   /// The 'SS' should be a non-empty valid CXXScopeSpec.
6301   bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
6302 
6303   /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
6304   /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
6305   /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
6306   /// Used to indicate that names should revert to being looked up in the
6307   /// defining scope.
6308   void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
6309 
6310   /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
6311   /// initializer for the declaration 'Dcl'.
6312   /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6313   /// static data member of class X, names should be looked up in the scope of
6314   /// class X.
6315   void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
6316 
6317   /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
6318   /// initializer for the declaration 'Dcl'.
6319   void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
6320 
6321   /// Create a new lambda closure type.
6322   CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
6323                                          TypeSourceInfo *Info,
6324                                          bool KnownDependent,
6325                                          LambdaCaptureDefault CaptureDefault);
6326 
6327   /// Start the definition of a lambda expression.
6328   CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
6329                                        SourceRange IntroducerRange,
6330                                        TypeSourceInfo *MethodType,
6331                                        SourceLocation EndLoc,
6332                                        ArrayRef<ParmVarDecl *> Params,
6333                                        ConstexprSpecKind ConstexprKind,
6334                                        Expr *TrailingRequiresClause);
6335 
6336   /// Number lambda for linkage purposes if necessary.
6337   void handleLambdaNumbering(
6338       CXXRecordDecl *Class, CXXMethodDecl *Method,
6339       Optional<std::tuple<unsigned, bool, Decl *>> Mangling = None);
6340 
6341   /// Endow the lambda scope info with the relevant properties.
6342   void buildLambdaScope(sema::LambdaScopeInfo *LSI,
6343                         CXXMethodDecl *CallOperator,
6344                         SourceRange IntroducerRange,
6345                         LambdaCaptureDefault CaptureDefault,
6346                         SourceLocation CaptureDefaultLoc,
6347                         bool ExplicitParams,
6348                         bool ExplicitResultType,
6349                         bool Mutable);
6350 
6351   /// Perform initialization analysis of the init-capture and perform
6352   /// any implicit conversions such as an lvalue-to-rvalue conversion if
6353   /// not being used to initialize a reference.
actOnLambdaInitCaptureInitialization(SourceLocation Loc,bool ByRef,SourceLocation EllipsisLoc,IdentifierInfo * Id,LambdaCaptureInitKind InitKind,Expr * & Init)6354   ParsedType actOnLambdaInitCaptureInitialization(
6355       SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
6356       IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
6357     return ParsedType::make(buildLambdaInitCaptureInitialization(
6358         Loc, ByRef, EllipsisLoc, None, Id,
6359         InitKind != LambdaCaptureInitKind::CopyInit, Init));
6360   }
6361   QualType buildLambdaInitCaptureInitialization(
6362       SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
6363       Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit,
6364       Expr *&Init);
6365 
6366   /// Create a dummy variable within the declcontext of the lambda's
6367   ///  call operator, for name lookup purposes for a lambda init capture.
6368   ///
6369   ///  CodeGen handles emission of lambda captures, ignoring these dummy
6370   ///  variables appropriately.
6371   VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
6372                                           QualType InitCaptureType,
6373                                           SourceLocation EllipsisLoc,
6374                                           IdentifierInfo *Id,
6375                                           unsigned InitStyle, Expr *Init);
6376 
6377   /// Add an init-capture to a lambda scope.
6378   void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var);
6379 
6380   /// Note that we have finished the explicit captures for the
6381   /// given lambda.
6382   void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
6383 
6384   /// \brief This is called after parsing the explicit template parameter list
6385   /// on a lambda (if it exists) in C++2a.
6386   void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc,
6387                                                 ArrayRef<NamedDecl *> TParams,
6388                                                 SourceLocation RAngleLoc);
6389 
6390   /// Introduce the lambda parameters into scope.
6391   void addLambdaParameters(
6392       ArrayRef<LambdaIntroducer::LambdaCapture> Captures,
6393       CXXMethodDecl *CallOperator, Scope *CurScope);
6394 
6395   /// Deduce a block or lambda's return type based on the return
6396   /// statements present in the body.
6397   void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
6398 
6399   /// ActOnStartOfLambdaDefinition - This is called just before we start
6400   /// parsing the body of a lambda; it analyzes the explicit captures and
6401   /// arguments, and sets up various data-structures for the body of the
6402   /// lambda.
6403   void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
6404                                     Declarator &ParamInfo, Scope *CurScope);
6405 
6406   /// ActOnLambdaError - If there is an error parsing a lambda, this callback
6407   /// is invoked to pop the information about the lambda.
6408   void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
6409                         bool IsInstantiation = false);
6410 
6411   /// ActOnLambdaExpr - This is called when the body of a lambda expression
6412   /// was successfully completed.
6413   ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
6414                              Scope *CurScope);
6415 
6416   /// Does copying/destroying the captured variable have side effects?
6417   bool CaptureHasSideEffects(const sema::Capture &From);
6418 
6419   /// Diagnose if an explicit lambda capture is unused. Returns true if a
6420   /// diagnostic is emitted.
6421   bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
6422                                    const sema::Capture &From);
6423 
6424   /// Build a FieldDecl suitable to hold the given capture.
6425   FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture);
6426 
6427   /// Initialize the given capture with a suitable expression.
6428   ExprResult BuildCaptureInit(const sema::Capture &Capture,
6429                               SourceLocation ImplicitCaptureLoc,
6430                               bool IsOpenMPMapping = false);
6431 
6432   /// Complete a lambda-expression having processed and attached the
6433   /// lambda body.
6434   ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
6435                              sema::LambdaScopeInfo *LSI);
6436 
6437   /// Get the return type to use for a lambda's conversion function(s) to
6438   /// function pointer type, given the type of the call operator.
6439   QualType
6440   getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType);
6441 
6442   /// Define the "body" of the conversion from a lambda object to a
6443   /// function pointer.
6444   ///
6445   /// This routine doesn't actually define a sensible body; rather, it fills
6446   /// in the initialization expression needed to copy the lambda object into
6447   /// the block, and IR generation actually generates the real body of the
6448   /// block pointer conversion.
6449   void DefineImplicitLambdaToFunctionPointerConversion(
6450          SourceLocation CurrentLoc, CXXConversionDecl *Conv);
6451 
6452   /// Define the "body" of the conversion from a lambda object to a
6453   /// block pointer.
6454   ///
6455   /// This routine doesn't actually define a sensible body; rather, it fills
6456   /// in the initialization expression needed to copy the lambda object into
6457   /// the block, and IR generation actually generates the real body of the
6458   /// block pointer conversion.
6459   void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
6460                                                     CXXConversionDecl *Conv);
6461 
6462   ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
6463                                            SourceLocation ConvLocation,
6464                                            CXXConversionDecl *Conv,
6465                                            Expr *Src);
6466 
6467   /// Check whether the given expression is a valid constraint expression.
6468   /// A diagnostic is emitted if it is not, false is returned, and
6469   /// PossibleNonPrimary will be set to true if the failure might be due to a
6470   /// non-primary expression being used as an atomic constraint.
6471   bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(),
6472                                  bool *PossibleNonPrimary = nullptr,
6473                                  bool IsTrailingRequiresClause = false);
6474 
6475 private:
6476   /// Caches pairs of template-like decls whose associated constraints were
6477   /// checked for subsumption and whether or not the first's constraints did in
6478   /// fact subsume the second's.
6479   llvm::DenseMap<std::pair<NamedDecl *, NamedDecl *>, bool> SubsumptionCache;
6480   /// Caches the normalized associated constraints of declarations (concepts or
6481   /// constrained declarations). If an error occurred while normalizing the
6482   /// associated constraints of the template or concept, nullptr will be cached
6483   /// here.
6484   llvm::DenseMap<NamedDecl *, NormalizedConstraint *>
6485       NormalizationCache;
6486 
6487   llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &>
6488       SatisfactionCache;
6489 
6490 public:
6491   const NormalizedConstraint *
6492   getNormalizedAssociatedConstraints(
6493       NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints);
6494 
6495   /// \brief Check whether the given declaration's associated constraints are
6496   /// at least as constrained than another declaration's according to the
6497   /// partial ordering of constraints.
6498   ///
6499   /// \param Result If no error occurred, receives the result of true if D1 is
6500   /// at least constrained than D2, and false otherwise.
6501   ///
6502   /// \returns true if an error occurred, false otherwise.
6503   bool IsAtLeastAsConstrained(NamedDecl *D1, ArrayRef<const Expr *> AC1,
6504                               NamedDecl *D2, ArrayRef<const Expr *> AC2,
6505                               bool &Result);
6506 
6507   /// If D1 was not at least as constrained as D2, but would've been if a pair
6508   /// of atomic constraints involved had been declared in a concept and not
6509   /// repeated in two separate places in code.
6510   /// \returns true if such a diagnostic was emitted, false otherwise.
6511   bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1,
6512       ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2);
6513 
6514   /// \brief Check whether the given list of constraint expressions are
6515   /// satisfied (as if in a 'conjunction') given template arguments.
6516   /// \param Template the template-like entity that triggered the constraints
6517   /// check (either a concept or a constrained entity).
6518   /// \param ConstraintExprs a list of constraint expressions, treated as if
6519   /// they were 'AND'ed together.
6520   /// \param TemplateArgs the list of template arguments to substitute into the
6521   /// constraint expression.
6522   /// \param TemplateIDRange The source range of the template id that
6523   /// caused the constraints check.
6524   /// \param Satisfaction if true is returned, will contain details of the
6525   /// satisfaction, with enough information to diagnose an unsatisfied
6526   /// expression.
6527   /// \returns true if an error occurred and satisfaction could not be checked,
6528   /// false otherwise.
6529   bool CheckConstraintSatisfaction(
6530       const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs,
6531       ArrayRef<TemplateArgument> TemplateArgs,
6532       SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction);
6533 
6534   /// \brief Check whether the given non-dependent constraint expression is
6535   /// satisfied. Returns false and updates Satisfaction with the satisfaction
6536   /// verdict if successful, emits a diagnostic and returns true if an error
6537   /// occured and satisfaction could not be determined.
6538   ///
6539   /// \returns true if an error occurred, false otherwise.
6540   bool CheckConstraintSatisfaction(const Expr *ConstraintExpr,
6541                                    ConstraintSatisfaction &Satisfaction);
6542 
6543   /// Check whether the given function decl's trailing requires clause is
6544   /// satisfied, if any. Returns false and updates Satisfaction with the
6545   /// satisfaction verdict if successful, emits a diagnostic and returns true if
6546   /// an error occured and satisfaction could not be determined.
6547   ///
6548   /// \returns true if an error occurred, false otherwise.
6549   bool CheckFunctionConstraints(const FunctionDecl *FD,
6550                                 ConstraintSatisfaction &Satisfaction,
6551                                 SourceLocation UsageLoc = SourceLocation());
6552 
6553 
6554   /// \brief Ensure that the given template arguments satisfy the constraints
6555   /// associated with the given template, emitting a diagnostic if they do not.
6556   ///
6557   /// \param Template The template to which the template arguments are being
6558   /// provided.
6559   ///
6560   /// \param TemplateArgs The converted, canonicalized template arguments.
6561   ///
6562   /// \param TemplateIDRange The source range of the template id that
6563   /// caused the constraints check.
6564   ///
6565   /// \returns true if the constrains are not satisfied or could not be checked
6566   /// for satisfaction, false if the constraints are satisfied.
6567   bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template,
6568                                        ArrayRef<TemplateArgument> TemplateArgs,
6569                                              SourceRange TemplateIDRange);
6570 
6571   /// \brief Emit diagnostics explaining why a constraint expression was deemed
6572   /// unsatisfied.
6573   /// \param First whether this is the first time an unsatisfied constraint is
6574   /// diagnosed for this error.
6575   void
6576   DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction,
6577                                 bool First = true);
6578 
6579   /// \brief Emit diagnostics explaining why a constraint expression was deemed
6580   /// unsatisfied.
6581   void
6582   DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction &Satisfaction,
6583                                 bool First = true);
6584 
6585   /// \brief Emit diagnostics explaining why a constraint expression was deemed
6586   /// unsatisfied because it was ill-formed.
6587   void DiagnoseUnsatisfiedIllFormedConstraint(SourceLocation DiagnosticLocation,
6588                                               StringRef Diagnostic);
6589 
6590   void DiagnoseRedeclarationConstraintMismatch(SourceLocation Old,
6591                                                SourceLocation New);
6592 
6593   // ParseObjCStringLiteral - Parse Objective-C string literals.
6594   ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
6595                                     ArrayRef<Expr *> Strings);
6596 
6597   ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
6598 
6599   /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
6600   /// numeric literal expression. Type of the expression will be "NSNumber *"
6601   /// or "id" if NSNumber is unavailable.
6602   ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
6603   ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
6604                                   bool Value);
6605   ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
6606 
6607   /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
6608   /// '@' prefixed parenthesized expression. The type of the expression will
6609   /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
6610   /// of ValueType, which is allowed to be a built-in numeric type, "char *",
6611   /// "const char *" or C structure with attribute 'objc_boxable'.
6612   ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
6613 
6614   ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
6615                                           Expr *IndexExpr,
6616                                           ObjCMethodDecl *getterMethod,
6617                                           ObjCMethodDecl *setterMethod);
6618 
6619   ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
6620                                MutableArrayRef<ObjCDictionaryElement> Elements);
6621 
6622   ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
6623                                   TypeSourceInfo *EncodedTypeInfo,
6624                                   SourceLocation RParenLoc);
6625   ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
6626                                     CXXConversionDecl *Method,
6627                                     bool HadMultipleCandidates);
6628 
6629   ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
6630                                        SourceLocation EncodeLoc,
6631                                        SourceLocation LParenLoc,
6632                                        ParsedType Ty,
6633                                        SourceLocation RParenLoc);
6634 
6635   /// ParseObjCSelectorExpression - Build selector expression for \@selector
6636   ExprResult ParseObjCSelectorExpression(Selector Sel,
6637                                          SourceLocation AtLoc,
6638                                          SourceLocation SelLoc,
6639                                          SourceLocation LParenLoc,
6640                                          SourceLocation RParenLoc,
6641                                          bool WarnMultipleSelectors);
6642 
6643   /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
6644   ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
6645                                          SourceLocation AtLoc,
6646                                          SourceLocation ProtoLoc,
6647                                          SourceLocation LParenLoc,
6648                                          SourceLocation ProtoIdLoc,
6649                                          SourceLocation RParenLoc);
6650 
6651   //===--------------------------------------------------------------------===//
6652   // C++ Declarations
6653   //
6654   Decl *ActOnStartLinkageSpecification(Scope *S,
6655                                        SourceLocation ExternLoc,
6656                                        Expr *LangStr,
6657                                        SourceLocation LBraceLoc);
6658   Decl *ActOnFinishLinkageSpecification(Scope *S,
6659                                         Decl *LinkageSpec,
6660                                         SourceLocation RBraceLoc);
6661 
6662 
6663   //===--------------------------------------------------------------------===//
6664   // C++ Classes
6665   //
6666   CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS);
6667   bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
6668                           const CXXScopeSpec *SS = nullptr);
6669   bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
6670 
6671   bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
6672                             SourceLocation ColonLoc,
6673                             const ParsedAttributesView &Attrs);
6674 
6675   NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
6676                                  Declarator &D,
6677                                  MultiTemplateParamsArg TemplateParameterLists,
6678                                  Expr *BitfieldWidth, const VirtSpecifiers &VS,
6679                                  InClassInitStyle InitStyle);
6680 
6681   void ActOnStartCXXInClassMemberInitializer();
6682   void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
6683                                               SourceLocation EqualLoc,
6684                                               Expr *Init);
6685 
6686   MemInitResult ActOnMemInitializer(Decl *ConstructorD,
6687                                     Scope *S,
6688                                     CXXScopeSpec &SS,
6689                                     IdentifierInfo *MemberOrBase,
6690                                     ParsedType TemplateTypeTy,
6691                                     const DeclSpec &DS,
6692                                     SourceLocation IdLoc,
6693                                     SourceLocation LParenLoc,
6694                                     ArrayRef<Expr *> Args,
6695                                     SourceLocation RParenLoc,
6696                                     SourceLocation EllipsisLoc);
6697 
6698   MemInitResult ActOnMemInitializer(Decl *ConstructorD,
6699                                     Scope *S,
6700                                     CXXScopeSpec &SS,
6701                                     IdentifierInfo *MemberOrBase,
6702                                     ParsedType TemplateTypeTy,
6703                                     const DeclSpec &DS,
6704                                     SourceLocation IdLoc,
6705                                     Expr *InitList,
6706                                     SourceLocation EllipsisLoc);
6707 
6708   MemInitResult BuildMemInitializer(Decl *ConstructorD,
6709                                     Scope *S,
6710                                     CXXScopeSpec &SS,
6711                                     IdentifierInfo *MemberOrBase,
6712                                     ParsedType TemplateTypeTy,
6713                                     const DeclSpec &DS,
6714                                     SourceLocation IdLoc,
6715                                     Expr *Init,
6716                                     SourceLocation EllipsisLoc);
6717 
6718   MemInitResult BuildMemberInitializer(ValueDecl *Member,
6719                                        Expr *Init,
6720                                        SourceLocation IdLoc);
6721 
6722   MemInitResult BuildBaseInitializer(QualType BaseType,
6723                                      TypeSourceInfo *BaseTInfo,
6724                                      Expr *Init,
6725                                      CXXRecordDecl *ClassDecl,
6726                                      SourceLocation EllipsisLoc);
6727 
6728   MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
6729                                            Expr *Init,
6730                                            CXXRecordDecl *ClassDecl);
6731 
6732   bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
6733                                 CXXCtorInitializer *Initializer);
6734 
6735   bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
6736                            ArrayRef<CXXCtorInitializer *> Initializers = None);
6737 
6738   void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
6739 
6740 
6741   /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
6742   /// mark all the non-trivial destructors of its members and bases as
6743   /// referenced.
6744   void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
6745                                               CXXRecordDecl *Record);
6746 
6747   /// Mark destructors of virtual bases of this class referenced. In the Itanium
6748   /// C++ ABI, this is done when emitting a destructor for any non-abstract
6749   /// class. In the Microsoft C++ ABI, this is done any time a class's
6750   /// destructor is referenced.
6751   void MarkVirtualBaseDestructorsReferenced(
6752       SourceLocation Location, CXXRecordDecl *ClassDecl,
6753       llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases = nullptr);
6754 
6755   /// Do semantic checks to allow the complete destructor variant to be emitted
6756   /// when the destructor is defined in another translation unit. In the Itanium
6757   /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they
6758   /// can be emitted in separate TUs. To emit the complete variant, run a subset
6759   /// of the checks performed when emitting a regular destructor.
6760   void CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
6761                                       CXXDestructorDecl *Dtor);
6762 
6763   /// The list of classes whose vtables have been used within
6764   /// this translation unit, and the source locations at which the
6765   /// first use occurred.
6766   typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
6767 
6768   /// The list of vtables that are required but have not yet been
6769   /// materialized.
6770   SmallVector<VTableUse, 16> VTableUses;
6771 
6772   /// The set of classes whose vtables have been used within
6773   /// this translation unit, and a bit that will be true if the vtable is
6774   /// required to be emitted (otherwise, it should be emitted only if needed
6775   /// by code generation).
6776   llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
6777 
6778   /// Load any externally-stored vtable uses.
6779   void LoadExternalVTableUses();
6780 
6781   /// Note that the vtable for the given class was used at the
6782   /// given location.
6783   void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6784                       bool DefinitionRequired = false);
6785 
6786   /// Mark the exception specifications of all virtual member functions
6787   /// in the given class as needed.
6788   void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
6789                                              const CXXRecordDecl *RD);
6790 
6791   /// MarkVirtualMembersReferenced - Will mark all members of the given
6792   /// CXXRecordDecl referenced.
6793   void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD,
6794                                     bool ConstexprOnly = false);
6795 
6796   /// Define all of the vtables that have been used in this
6797   /// translation unit and reference any virtual members used by those
6798   /// vtables.
6799   ///
6800   /// \returns true if any work was done, false otherwise.
6801   bool DefineUsedVTables();
6802 
6803   void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
6804 
6805   void ActOnMemInitializers(Decl *ConstructorDecl,
6806                             SourceLocation ColonLoc,
6807                             ArrayRef<CXXCtorInitializer*> MemInits,
6808                             bool AnyErrors);
6809 
6810   /// Check class-level dllimport/dllexport attribute. The caller must
6811   /// ensure that referenceDLLExportedClassMethods is called some point later
6812   /// when all outer classes of Class are complete.
6813   void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
6814   void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class);
6815 
6816   void referenceDLLExportedClassMethods();
6817 
6818   void propagateDLLAttrToBaseClassTemplate(
6819       CXXRecordDecl *Class, Attr *ClassAttr,
6820       ClassTemplateSpecializationDecl *BaseTemplateSpec,
6821       SourceLocation BaseLoc);
6822 
6823   /// Add gsl::Pointer attribute to std::container::iterator
6824   /// \param ND The declaration that introduces the name
6825   /// std::container::iterator. \param UnderlyingRecord The record named by ND.
6826   void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
6827 
6828   /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
6829   void inferGslOwnerPointerAttribute(CXXRecordDecl *Record);
6830 
6831   /// Add [[gsl::Pointer]] attributes for std:: types.
6832   void inferGslPointerAttribute(TypedefNameDecl *TD);
6833 
6834   void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record);
6835 
6836   /// Check that the C++ class annoated with "trivial_abi" satisfies all the
6837   /// conditions that are needed for the attribute to have an effect.
6838   void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
6839 
6840   void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc,
6841                                          Decl *TagDecl, SourceLocation LBrac,
6842                                          SourceLocation RBrac,
6843                                          const ParsedAttributesView &AttrList);
6844   void ActOnFinishCXXMemberDecls();
6845   void ActOnFinishCXXNonNestedClass();
6846 
6847   void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
6848   unsigned ActOnReenterTemplateScope(Decl *Template,
6849                                      llvm::function_ref<Scope *()> EnterScope);
6850   void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
6851   void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
6852   void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
6853   void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
6854   void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
6855   void ActOnFinishDelayedMemberInitializers(Decl *Record);
6856   void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
6857                                 CachedTokens &Toks);
6858   void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
6859   bool IsInsideALocalClassWithinATemplateFunction();
6860 
6861   Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
6862                                      Expr *AssertExpr,
6863                                      Expr *AssertMessageExpr,
6864                                      SourceLocation RParenLoc);
6865   Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
6866                                      Expr *AssertExpr,
6867                                      StringLiteral *AssertMessageExpr,
6868                                      SourceLocation RParenLoc,
6869                                      bool Failed);
6870 
6871   FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
6872                                   SourceLocation FriendLoc,
6873                                   TypeSourceInfo *TSInfo);
6874   Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
6875                             MultiTemplateParamsArg TemplateParams);
6876   NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
6877                                      MultiTemplateParamsArg TemplateParams);
6878 
6879   QualType CheckConstructorDeclarator(Declarator &D, QualType R,
6880                                       StorageClass& SC);
6881   void CheckConstructor(CXXConstructorDecl *Constructor);
6882   QualType CheckDestructorDeclarator(Declarator &D, QualType R,
6883                                      StorageClass& SC);
6884   bool CheckDestructor(CXXDestructorDecl *Destructor);
6885   void CheckConversionDeclarator(Declarator &D, QualType &R,
6886                                  StorageClass& SC);
6887   Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
6888   void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
6889                                      StorageClass &SC);
6890   void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
6891 
6892   void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD);
6893 
6894   bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
6895                                              CXXSpecialMember CSM);
6896   void CheckDelayedMemberExceptionSpecs();
6897 
6898   bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD,
6899                                           DefaultedComparisonKind DCK);
6900   void DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
6901                                          FunctionDecl *Spaceship);
6902   void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD,
6903                                  DefaultedComparisonKind DCK);
6904 
6905   //===--------------------------------------------------------------------===//
6906   // C++ Derived Classes
6907   //
6908 
6909   /// ActOnBaseSpecifier - Parsed a base specifier
6910   CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
6911                                        SourceRange SpecifierRange,
6912                                        bool Virtual, AccessSpecifier Access,
6913                                        TypeSourceInfo *TInfo,
6914                                        SourceLocation EllipsisLoc);
6915 
6916   BaseResult ActOnBaseSpecifier(Decl *classdecl,
6917                                 SourceRange SpecifierRange,
6918                                 ParsedAttributes &Attrs,
6919                                 bool Virtual, AccessSpecifier Access,
6920                                 ParsedType basetype,
6921                                 SourceLocation BaseLoc,
6922                                 SourceLocation EllipsisLoc);
6923 
6924   bool AttachBaseSpecifiers(CXXRecordDecl *Class,
6925                             MutableArrayRef<CXXBaseSpecifier *> Bases);
6926   void ActOnBaseSpecifiers(Decl *ClassDecl,
6927                            MutableArrayRef<CXXBaseSpecifier *> Bases);
6928 
6929   bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
6930   bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
6931                      CXXBasePaths &Paths);
6932 
6933   // FIXME: I don't like this name.
6934   void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
6935 
6936   bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
6937                                     SourceLocation Loc, SourceRange Range,
6938                                     CXXCastPath *BasePath = nullptr,
6939                                     bool IgnoreAccess = false);
6940   bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
6941                                     unsigned InaccessibleBaseID,
6942                                     unsigned AmbiguousBaseConvID,
6943                                     SourceLocation Loc, SourceRange Range,
6944                                     DeclarationName Name,
6945                                     CXXCastPath *BasePath,
6946                                     bool IgnoreAccess = false);
6947 
6948   std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
6949 
6950   bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
6951                                          const CXXMethodDecl *Old);
6952 
6953   /// CheckOverridingFunctionReturnType - Checks whether the return types are
6954   /// covariant, according to C++ [class.virtual]p5.
6955   bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
6956                                          const CXXMethodDecl *Old);
6957 
6958   /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
6959   /// spec is a subset of base spec.
6960   bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
6961                                             const CXXMethodDecl *Old);
6962 
6963   bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
6964 
6965   /// CheckOverrideControl - Check C++11 override control semantics.
6966   void CheckOverrideControl(NamedDecl *D);
6967 
6968   /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
6969   /// not used in the declaration of an overriding method.
6970   void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent);
6971 
6972   /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
6973   /// overrides a virtual member function marked 'final', according to
6974   /// C++11 [class.virtual]p4.
6975   bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
6976                                               const CXXMethodDecl *Old);
6977 
6978 
6979   //===--------------------------------------------------------------------===//
6980   // C++ Access Control
6981   //
6982 
6983   enum AccessResult {
6984     AR_accessible,
6985     AR_inaccessible,
6986     AR_dependent,
6987     AR_delayed
6988   };
6989 
6990   bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
6991                                 NamedDecl *PrevMemberDecl,
6992                                 AccessSpecifier LexicalAS);
6993 
6994   AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
6995                                            DeclAccessPair FoundDecl);
6996   AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
6997                                            DeclAccessPair FoundDecl);
6998   AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
6999                                      SourceRange PlacementRange,
7000                                      CXXRecordDecl *NamingClass,
7001                                      DeclAccessPair FoundDecl,
7002                                      bool Diagnose = true);
7003   AccessResult CheckConstructorAccess(SourceLocation Loc,
7004                                       CXXConstructorDecl *D,
7005                                       DeclAccessPair FoundDecl,
7006                                       const InitializedEntity &Entity,
7007                                       bool IsCopyBindingRefToTemp = false);
7008   AccessResult CheckConstructorAccess(SourceLocation Loc,
7009                                       CXXConstructorDecl *D,
7010                                       DeclAccessPair FoundDecl,
7011                                       const InitializedEntity &Entity,
7012                                       const PartialDiagnostic &PDiag);
7013   AccessResult CheckDestructorAccess(SourceLocation Loc,
7014                                      CXXDestructorDecl *Dtor,
7015                                      const PartialDiagnostic &PDiag,
7016                                      QualType objectType = QualType());
7017   AccessResult CheckFriendAccess(NamedDecl *D);
7018   AccessResult CheckMemberAccess(SourceLocation UseLoc,
7019                                  CXXRecordDecl *NamingClass,
7020                                  DeclAccessPair Found);
7021   AccessResult
7022   CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
7023                                      CXXRecordDecl *DecomposedClass,
7024                                      DeclAccessPair Field);
7025   AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
7026                                          Expr *ObjectExpr,
7027                                          Expr *ArgExpr,
7028                                          DeclAccessPair FoundDecl);
7029   AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
7030                                           DeclAccessPair FoundDecl);
7031   AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
7032                                     QualType Base, QualType Derived,
7033                                     const CXXBasePath &Path,
7034                                     unsigned DiagID,
7035                                     bool ForceCheck = false,
7036                                     bool ForceUnprivileged = false);
7037   void CheckLookupAccess(const LookupResult &R);
7038   bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
7039                           QualType BaseType);
7040   bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
7041                                      DeclAccessPair Found, QualType ObjectType,
7042                                      SourceLocation Loc,
7043                                      const PartialDiagnostic &Diag);
isMemberAccessibleForDeletion(CXXRecordDecl * NamingClass,DeclAccessPair Found,QualType ObjectType)7044   bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
7045                                      DeclAccessPair Found,
7046                                      QualType ObjectType) {
7047     return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType,
7048                                          SourceLocation(), PDiag());
7049   }
7050 
7051   void HandleDependentAccessCheck(const DependentDiagnostic &DD,
7052                          const MultiLevelTemplateArgumentList &TemplateArgs);
7053   void PerformDependentDiagnostics(const DeclContext *Pattern,
7054                         const MultiLevelTemplateArgumentList &TemplateArgs);
7055 
7056   void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
7057 
7058   /// When true, access checking violations are treated as SFINAE
7059   /// failures rather than hard errors.
7060   bool AccessCheckingSFINAE;
7061 
7062   enum AbstractDiagSelID {
7063     AbstractNone = -1,
7064     AbstractReturnType,
7065     AbstractParamType,
7066     AbstractVariableType,
7067     AbstractFieldType,
7068     AbstractIvarType,
7069     AbstractSynthesizedIvarType,
7070     AbstractArrayType
7071   };
7072 
7073   bool isAbstractType(SourceLocation Loc, QualType T);
7074   bool RequireNonAbstractType(SourceLocation Loc, QualType T,
7075                               TypeDiagnoser &Diagnoser);
7076   template <typename... Ts>
RequireNonAbstractType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)7077   bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
7078                               const Ts &...Args) {
7079     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
7080     return RequireNonAbstractType(Loc, T, Diagnoser);
7081   }
7082 
7083   void DiagnoseAbstractType(const CXXRecordDecl *RD);
7084 
7085   //===--------------------------------------------------------------------===//
7086   // C++ Overloaded Operators [C++ 13.5]
7087   //
7088 
7089   bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
7090 
7091   bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
7092 
7093   //===--------------------------------------------------------------------===//
7094   // C++ Templates [C++ 14]
7095   //
7096   void FilterAcceptableTemplateNames(LookupResult &R,
7097                                      bool AllowFunctionTemplates = true,
7098                                      bool AllowDependent = true);
7099   bool hasAnyAcceptableTemplateNames(LookupResult &R,
7100                                      bool AllowFunctionTemplates = true,
7101                                      bool AllowDependent = true,
7102                                      bool AllowNonTemplateFunctions = false);
7103   /// Try to interpret the lookup result D as a template-name.
7104   ///
7105   /// \param D A declaration found by name lookup.
7106   /// \param AllowFunctionTemplates Whether function templates should be
7107   ///        considered valid results.
7108   /// \param AllowDependent Whether unresolved using declarations (that might
7109   ///        name templates) should be considered valid results.
7110   NamedDecl *getAsTemplateNameDecl(NamedDecl *D,
7111                                    bool AllowFunctionTemplates = true,
7112                                    bool AllowDependent = true);
7113 
7114   enum TemplateNameIsRequiredTag { TemplateNameIsRequired };
7115   /// Whether and why a template name is required in this lookup.
7116   class RequiredTemplateKind {
7117   public:
7118     /// Template name is required if TemplateKWLoc is valid.
7119     RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation())
TemplateKW(TemplateKWLoc)7120         : TemplateKW(TemplateKWLoc) {}
7121     /// Template name is unconditionally required.
RequiredTemplateKind(TemplateNameIsRequiredTag)7122     RequiredTemplateKind(TemplateNameIsRequiredTag) : TemplateKW() {}
7123 
getTemplateKeywordLoc()7124     SourceLocation getTemplateKeywordLoc() const {
7125       return TemplateKW.getValueOr(SourceLocation());
7126     }
hasTemplateKeyword()7127     bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
isRequired()7128     bool isRequired() const { return TemplateKW != SourceLocation(); }
7129     explicit operator bool() const { return isRequired(); }
7130 
7131   private:
7132     llvm::Optional<SourceLocation> TemplateKW;
7133   };
7134 
7135   enum class AssumedTemplateKind {
7136     /// This is not assumed to be a template name.
7137     None,
7138     /// This is assumed to be a template name because lookup found nothing.
7139     FoundNothing,
7140     /// This is assumed to be a template name because lookup found one or more
7141     /// functions (but no function templates).
7142     FoundFunctions,
7143   };
7144   bool LookupTemplateName(
7145       LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType,
7146       bool EnteringContext, bool &MemberOfUnknownSpecialization,
7147       RequiredTemplateKind RequiredTemplate = SourceLocation(),
7148       AssumedTemplateKind *ATK = nullptr, bool AllowTypoCorrection = true);
7149 
7150   TemplateNameKind isTemplateName(Scope *S,
7151                                   CXXScopeSpec &SS,
7152                                   bool hasTemplateKeyword,
7153                                   const UnqualifiedId &Name,
7154                                   ParsedType ObjectType,
7155                                   bool EnteringContext,
7156                                   TemplateTy &Template,
7157                                   bool &MemberOfUnknownSpecialization,
7158                                   bool Disambiguation = false);
7159 
7160   /// Try to resolve an undeclared template name as a type template.
7161   ///
7162   /// Sets II to the identifier corresponding to the template name, and updates
7163   /// Name to a corresponding (typo-corrected) type template name and TNK to
7164   /// the corresponding kind, if possible.
7165   void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name,
7166                                        TemplateNameKind &TNK,
7167                                        SourceLocation NameLoc,
7168                                        IdentifierInfo *&II);
7169 
7170   bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
7171                                         SourceLocation NameLoc,
7172                                         bool Diagnose = true);
7173 
7174   /// Determine whether a particular identifier might be the name in a C++1z
7175   /// deduction-guide declaration.
7176   bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
7177                             SourceLocation NameLoc,
7178                             ParsedTemplateTy *Template = nullptr);
7179 
7180   bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
7181                                    SourceLocation IILoc,
7182                                    Scope *S,
7183                                    const CXXScopeSpec *SS,
7184                                    TemplateTy &SuggestedTemplate,
7185                                    TemplateNameKind &SuggestedKind);
7186 
7187   bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
7188                                       NamedDecl *Instantiation,
7189                                       bool InstantiatedFromMember,
7190                                       const NamedDecl *Pattern,
7191                                       const NamedDecl *PatternDef,
7192                                       TemplateSpecializationKind TSK,
7193                                       bool Complain = true);
7194 
7195   void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
7196   TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
7197 
7198   NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
7199                                 SourceLocation EllipsisLoc,
7200                                 SourceLocation KeyLoc,
7201                                 IdentifierInfo *ParamName,
7202                                 SourceLocation ParamNameLoc,
7203                                 unsigned Depth, unsigned Position,
7204                                 SourceLocation EqualLoc,
7205                                 ParsedType DefaultArg, bool HasTypeConstraint);
7206 
7207   bool ActOnTypeConstraint(const CXXScopeSpec &SS,
7208                            TemplateIdAnnotation *TypeConstraint,
7209                            TemplateTypeParmDecl *ConstrainedParameter,
7210                            SourceLocation EllipsisLoc);
7211 
7212   bool AttachTypeConstraint(NestedNameSpecifierLoc NS,
7213                             DeclarationNameInfo NameInfo,
7214                             ConceptDecl *NamedConcept,
7215                             const TemplateArgumentListInfo *TemplateArgs,
7216                             TemplateTypeParmDecl *ConstrainedParameter,
7217                             SourceLocation EllipsisLoc);
7218 
7219   bool AttachTypeConstraint(AutoTypeLoc TL,
7220                             NonTypeTemplateParmDecl *ConstrainedParameter,
7221                             SourceLocation EllipsisLoc);
7222 
7223   QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
7224                                              SourceLocation Loc);
7225   QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
7226 
7227   NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
7228                                       unsigned Depth,
7229                                       unsigned Position,
7230                                       SourceLocation EqualLoc,
7231                                       Expr *DefaultArg);
7232   NamedDecl *ActOnTemplateTemplateParameter(Scope *S,
7233                                        SourceLocation TmpLoc,
7234                                        TemplateParameterList *Params,
7235                                        SourceLocation EllipsisLoc,
7236                                        IdentifierInfo *ParamName,
7237                                        SourceLocation ParamNameLoc,
7238                                        unsigned Depth,
7239                                        unsigned Position,
7240                                        SourceLocation EqualLoc,
7241                                        ParsedTemplateArgument DefaultArg);
7242 
7243   TemplateParameterList *
7244   ActOnTemplateParameterList(unsigned Depth,
7245                              SourceLocation ExportLoc,
7246                              SourceLocation TemplateLoc,
7247                              SourceLocation LAngleLoc,
7248                              ArrayRef<NamedDecl *> Params,
7249                              SourceLocation RAngleLoc,
7250                              Expr *RequiresClause);
7251 
7252   /// The context in which we are checking a template parameter list.
7253   enum TemplateParamListContext {
7254     TPC_ClassTemplate,
7255     TPC_VarTemplate,
7256     TPC_FunctionTemplate,
7257     TPC_ClassTemplateMember,
7258     TPC_FriendClassTemplate,
7259     TPC_FriendFunctionTemplate,
7260     TPC_FriendFunctionTemplateDefinition,
7261     TPC_TypeAliasTemplate
7262   };
7263 
7264   bool CheckTemplateParameterList(TemplateParameterList *NewParams,
7265                                   TemplateParameterList *OldParams,
7266                                   TemplateParamListContext TPC,
7267                                   SkipBodyInfo *SkipBody = nullptr);
7268   TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
7269       SourceLocation DeclStartLoc, SourceLocation DeclLoc,
7270       const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
7271       ArrayRef<TemplateParameterList *> ParamLists,
7272       bool IsFriend, bool &IsMemberSpecialization, bool &Invalid,
7273       bool SuppressDiagnostic = false);
7274 
7275   DeclResult CheckClassTemplate(
7276       Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7277       CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
7278       const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
7279       AccessSpecifier AS, SourceLocation ModulePrivateLoc,
7280       SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
7281       TemplateParameterList **OuterTemplateParamLists,
7282       SkipBodyInfo *SkipBody = nullptr);
7283 
7284   TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
7285                                                     QualType NTTPType,
7286                                                     SourceLocation Loc);
7287 
7288   /// Get a template argument mapping the given template parameter to itself,
7289   /// e.g. for X in \c template<int X>, this would return an expression template
7290   /// argument referencing X.
7291   TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param,
7292                                                      SourceLocation Location);
7293 
7294   void translateTemplateArguments(const ASTTemplateArgsPtr &In,
7295                                   TemplateArgumentListInfo &Out);
7296 
7297   ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
7298 
7299   void NoteAllFoundTemplates(TemplateName Name);
7300 
7301   QualType CheckTemplateIdType(TemplateName Template,
7302                                SourceLocation TemplateLoc,
7303                               TemplateArgumentListInfo &TemplateArgs);
7304 
7305   TypeResult
7306   ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
7307                       TemplateTy Template, IdentifierInfo *TemplateII,
7308                       SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
7309                       ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
7310                       bool IsCtorOrDtorName = false, bool IsClassName = false);
7311 
7312   /// Parsed an elaborated-type-specifier that refers to a template-id,
7313   /// such as \c class T::template apply<U>.
7314   TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
7315                                     TypeSpecifierType TagSpec,
7316                                     SourceLocation TagLoc,
7317                                     CXXScopeSpec &SS,
7318                                     SourceLocation TemplateKWLoc,
7319                                     TemplateTy TemplateD,
7320                                     SourceLocation TemplateLoc,
7321                                     SourceLocation LAngleLoc,
7322                                     ASTTemplateArgsPtr TemplateArgsIn,
7323                                     SourceLocation RAngleLoc);
7324 
7325   DeclResult ActOnVarTemplateSpecialization(
7326       Scope *S, Declarator &D, TypeSourceInfo *DI,
7327       SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
7328       StorageClass SC, bool IsPartialSpecialization);
7329 
7330   DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
7331                                 SourceLocation TemplateLoc,
7332                                 SourceLocation TemplateNameLoc,
7333                                 const TemplateArgumentListInfo &TemplateArgs);
7334 
7335   ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
7336                                 const DeclarationNameInfo &NameInfo,
7337                                 VarTemplateDecl *Template,
7338                                 SourceLocation TemplateLoc,
7339                                 const TemplateArgumentListInfo *TemplateArgs);
7340 
7341   ExprResult
7342   CheckConceptTemplateId(const CXXScopeSpec &SS,
7343                          SourceLocation TemplateKWLoc,
7344                          const DeclarationNameInfo &ConceptNameInfo,
7345                          NamedDecl *FoundDecl, ConceptDecl *NamedConcept,
7346                          const TemplateArgumentListInfo *TemplateArgs);
7347 
7348   void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc);
7349 
7350   ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
7351                                  SourceLocation TemplateKWLoc,
7352                                  LookupResult &R,
7353                                  bool RequiresADL,
7354                                const TemplateArgumentListInfo *TemplateArgs);
7355 
7356   ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
7357                                           SourceLocation TemplateKWLoc,
7358                                const DeclarationNameInfo &NameInfo,
7359                                const TemplateArgumentListInfo *TemplateArgs);
7360 
7361   TemplateNameKind ActOnTemplateName(
7362       Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
7363       const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
7364       TemplateTy &Template, bool AllowInjectedClassName = false);
7365 
7366   DeclResult ActOnClassTemplateSpecialization(
7367       Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7368       SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
7369       TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
7370       MultiTemplateParamsArg TemplateParameterLists,
7371       SkipBodyInfo *SkipBody = nullptr);
7372 
7373   bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
7374                                               TemplateDecl *PrimaryTemplate,
7375                                               unsigned NumExplicitArgs,
7376                                               ArrayRef<TemplateArgument> Args);
7377   void CheckTemplatePartialSpecialization(
7378       ClassTemplatePartialSpecializationDecl *Partial);
7379   void CheckTemplatePartialSpecialization(
7380       VarTemplatePartialSpecializationDecl *Partial);
7381 
7382   Decl *ActOnTemplateDeclarator(Scope *S,
7383                                 MultiTemplateParamsArg TemplateParameterLists,
7384                                 Declarator &D);
7385 
7386   bool
7387   CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
7388                                          TemplateSpecializationKind NewTSK,
7389                                          NamedDecl *PrevDecl,
7390                                          TemplateSpecializationKind PrevTSK,
7391                                          SourceLocation PrevPtOfInstantiation,
7392                                          bool &SuppressNew);
7393 
7394   bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
7395                     const TemplateArgumentListInfo &ExplicitTemplateArgs,
7396                                                     LookupResult &Previous);
7397 
7398   bool CheckFunctionTemplateSpecialization(
7399       FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
7400       LookupResult &Previous, bool QualifiedFriend = false);
7401   bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
7402   void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
7403 
7404   DeclResult ActOnExplicitInstantiation(
7405       Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
7406       unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
7407       TemplateTy Template, SourceLocation TemplateNameLoc,
7408       SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
7409       SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
7410 
7411   DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
7412                                         SourceLocation TemplateLoc,
7413                                         unsigned TagSpec, SourceLocation KWLoc,
7414                                         CXXScopeSpec &SS, IdentifierInfo *Name,
7415                                         SourceLocation NameLoc,
7416                                         const ParsedAttributesView &Attr);
7417 
7418   DeclResult ActOnExplicitInstantiation(Scope *S,
7419                                         SourceLocation ExternLoc,
7420                                         SourceLocation TemplateLoc,
7421                                         Declarator &D);
7422 
7423   TemplateArgumentLoc
7424   SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
7425                                           SourceLocation TemplateLoc,
7426                                           SourceLocation RAngleLoc,
7427                                           Decl *Param,
7428                                           SmallVectorImpl<TemplateArgument>
7429                                             &Converted,
7430                                           bool &HasDefaultArg);
7431 
7432   /// Specifies the context in which a particular template
7433   /// argument is being checked.
7434   enum CheckTemplateArgumentKind {
7435     /// The template argument was specified in the code or was
7436     /// instantiated with some deduced template arguments.
7437     CTAK_Specified,
7438 
7439     /// The template argument was deduced via template argument
7440     /// deduction.
7441     CTAK_Deduced,
7442 
7443     /// The template argument was deduced from an array bound
7444     /// via template argument deduction.
7445     CTAK_DeducedFromArrayBound
7446   };
7447 
7448   bool CheckTemplateArgument(NamedDecl *Param,
7449                              TemplateArgumentLoc &Arg,
7450                              NamedDecl *Template,
7451                              SourceLocation TemplateLoc,
7452                              SourceLocation RAngleLoc,
7453                              unsigned ArgumentPackIndex,
7454                            SmallVectorImpl<TemplateArgument> &Converted,
7455                              CheckTemplateArgumentKind CTAK = CTAK_Specified);
7456 
7457   /// Check that the given template arguments can be be provided to
7458   /// the given template, converting the arguments along the way.
7459   ///
7460   /// \param Template The template to which the template arguments are being
7461   /// provided.
7462   ///
7463   /// \param TemplateLoc The location of the template name in the source.
7464   ///
7465   /// \param TemplateArgs The list of template arguments. If the template is
7466   /// a template template parameter, this function may extend the set of
7467   /// template arguments to also include substituted, defaulted template
7468   /// arguments.
7469   ///
7470   /// \param PartialTemplateArgs True if the list of template arguments is
7471   /// intentionally partial, e.g., because we're checking just the initial
7472   /// set of template arguments.
7473   ///
7474   /// \param Converted Will receive the converted, canonicalized template
7475   /// arguments.
7476   ///
7477   /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
7478   /// contain the converted forms of the template arguments as written.
7479   /// Otherwise, \p TemplateArgs will not be modified.
7480   ///
7481   /// \param ConstraintsNotSatisfied If provided, and an error occured, will
7482   /// receive true if the cause for the error is the associated constraints of
7483   /// the template not being satisfied by the template arguments.
7484   ///
7485   /// \returns true if an error occurred, false otherwise.
7486   bool CheckTemplateArgumentList(TemplateDecl *Template,
7487                                  SourceLocation TemplateLoc,
7488                                  TemplateArgumentListInfo &TemplateArgs,
7489                                  bool PartialTemplateArgs,
7490                                  SmallVectorImpl<TemplateArgument> &Converted,
7491                                  bool UpdateArgsWithConversions = true,
7492                                  bool *ConstraintsNotSatisfied = nullptr);
7493 
7494   bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
7495                                  TemplateArgumentLoc &Arg,
7496                            SmallVectorImpl<TemplateArgument> &Converted);
7497 
7498   bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
7499                              TypeSourceInfo *Arg);
7500   ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
7501                                    QualType InstantiatedParamType, Expr *Arg,
7502                                    TemplateArgument &Converted,
7503                                CheckTemplateArgumentKind CTAK = CTAK_Specified);
7504   bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
7505                                      TemplateParameterList *Params,
7506                                      TemplateArgumentLoc &Arg);
7507 
7508   ExprResult
7509   BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
7510                                           QualType ParamType,
7511                                           SourceLocation Loc);
7512   ExprResult
7513   BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
7514                                               SourceLocation Loc);
7515 
7516   /// Enumeration describing how template parameter lists are compared
7517   /// for equality.
7518   enum TemplateParameterListEqualKind {
7519     /// We are matching the template parameter lists of two templates
7520     /// that might be redeclarations.
7521     ///
7522     /// \code
7523     /// template<typename T> struct X;
7524     /// template<typename T> struct X;
7525     /// \endcode
7526     TPL_TemplateMatch,
7527 
7528     /// We are matching the template parameter lists of two template
7529     /// template parameters as part of matching the template parameter lists
7530     /// of two templates that might be redeclarations.
7531     ///
7532     /// \code
7533     /// template<template<int I> class TT> struct X;
7534     /// template<template<int Value> class Other> struct X;
7535     /// \endcode
7536     TPL_TemplateTemplateParmMatch,
7537 
7538     /// We are matching the template parameter lists of a template
7539     /// template argument against the template parameter lists of a template
7540     /// template parameter.
7541     ///
7542     /// \code
7543     /// template<template<int Value> class Metafun> struct X;
7544     /// template<int Value> struct integer_c;
7545     /// X<integer_c> xic;
7546     /// \endcode
7547     TPL_TemplateTemplateArgumentMatch
7548   };
7549 
7550   bool TemplateParameterListsAreEqual(TemplateParameterList *New,
7551                                       TemplateParameterList *Old,
7552                                       bool Complain,
7553                                       TemplateParameterListEqualKind Kind,
7554                                       SourceLocation TemplateArgLoc
7555                                         = SourceLocation());
7556 
7557   bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
7558 
7559   /// Called when the parser has parsed a C++ typename
7560   /// specifier, e.g., "typename T::type".
7561   ///
7562   /// \param S The scope in which this typename type occurs.
7563   /// \param TypenameLoc the location of the 'typename' keyword
7564   /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
7565   /// \param II the identifier we're retrieving (e.g., 'type' in the example).
7566   /// \param IdLoc the location of the identifier.
7567   TypeResult
7568   ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
7569                     const CXXScopeSpec &SS, const IdentifierInfo &II,
7570                     SourceLocation IdLoc);
7571 
7572   /// Called when the parser has parsed a C++ typename
7573   /// specifier that ends in a template-id, e.g.,
7574   /// "typename MetaFun::template apply<T1, T2>".
7575   ///
7576   /// \param S The scope in which this typename type occurs.
7577   /// \param TypenameLoc the location of the 'typename' keyword
7578   /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
7579   /// \param TemplateLoc the location of the 'template' keyword, if any.
7580   /// \param TemplateName The template name.
7581   /// \param TemplateII The identifier used to name the template.
7582   /// \param TemplateIILoc The location of the template name.
7583   /// \param LAngleLoc The location of the opening angle bracket  ('<').
7584   /// \param TemplateArgs The template arguments.
7585   /// \param RAngleLoc The location of the closing angle bracket  ('>').
7586   TypeResult
7587   ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
7588                     const CXXScopeSpec &SS,
7589                     SourceLocation TemplateLoc,
7590                     TemplateTy TemplateName,
7591                     IdentifierInfo *TemplateII,
7592                     SourceLocation TemplateIILoc,
7593                     SourceLocation LAngleLoc,
7594                     ASTTemplateArgsPtr TemplateArgs,
7595                     SourceLocation RAngleLoc);
7596 
7597   QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
7598                              SourceLocation KeywordLoc,
7599                              NestedNameSpecifierLoc QualifierLoc,
7600                              const IdentifierInfo &II,
7601                              SourceLocation IILoc,
7602                              TypeSourceInfo **TSI,
7603                              bool DeducedTSTContext);
7604 
7605   QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
7606                              SourceLocation KeywordLoc,
7607                              NestedNameSpecifierLoc QualifierLoc,
7608                              const IdentifierInfo &II,
7609                              SourceLocation IILoc,
7610                              bool DeducedTSTContext = true);
7611 
7612 
7613   TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
7614                                                     SourceLocation Loc,
7615                                                     DeclarationName Name);
7616   bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
7617 
7618   ExprResult RebuildExprInCurrentInstantiation(Expr *E);
7619   bool RebuildTemplateParamsInCurrentInstantiation(
7620                                                 TemplateParameterList *Params);
7621 
7622   std::string
7623   getTemplateArgumentBindingsText(const TemplateParameterList *Params,
7624                                   const TemplateArgumentList &Args);
7625 
7626   std::string
7627   getTemplateArgumentBindingsText(const TemplateParameterList *Params,
7628                                   const TemplateArgument *Args,
7629                                   unsigned NumArgs);
7630 
7631   //===--------------------------------------------------------------------===//
7632   // C++ Concepts
7633   //===--------------------------------------------------------------------===//
7634   Decl *ActOnConceptDefinition(
7635       Scope *S, MultiTemplateParamsArg TemplateParameterLists,
7636       IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr);
7637 
7638   RequiresExprBodyDecl *
7639   ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
7640                          ArrayRef<ParmVarDecl *> LocalParameters,
7641                          Scope *BodyScope);
7642   void ActOnFinishRequiresExpr();
7643   concepts::Requirement *ActOnSimpleRequirement(Expr *E);
7644   concepts::Requirement *ActOnTypeRequirement(
7645       SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc,
7646       IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId);
7647   concepts::Requirement *ActOnCompoundRequirement(Expr *E,
7648                                                   SourceLocation NoexceptLoc);
7649   concepts::Requirement *
7650   ActOnCompoundRequirement(
7651       Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
7652       TemplateIdAnnotation *TypeConstraint, unsigned Depth);
7653   concepts::Requirement *ActOnNestedRequirement(Expr *Constraint);
7654   concepts::ExprRequirement *
7655   BuildExprRequirement(
7656       Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc,
7657       concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
7658   concepts::ExprRequirement *
7659   BuildExprRequirement(
7660       concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag,
7661       bool IsSatisfied, SourceLocation NoexceptLoc,
7662       concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
7663   concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type);
7664   concepts::TypeRequirement *
7665   BuildTypeRequirement(
7666       concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
7667   concepts::NestedRequirement *BuildNestedRequirement(Expr *E);
7668   concepts::NestedRequirement *
7669   BuildNestedRequirement(
7670       concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
7671   ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc,
7672                                RequiresExprBodyDecl *Body,
7673                                ArrayRef<ParmVarDecl *> LocalParameters,
7674                                ArrayRef<concepts::Requirement *> Requirements,
7675                                SourceLocation ClosingBraceLoc);
7676 
7677   //===--------------------------------------------------------------------===//
7678   // C++ Variadic Templates (C++0x [temp.variadic])
7679   //===--------------------------------------------------------------------===//
7680 
7681   /// Determine whether an unexpanded parameter pack might be permitted in this
7682   /// location. Useful for error recovery.
7683   bool isUnexpandedParameterPackPermitted();
7684 
7685   /// The context in which an unexpanded parameter pack is
7686   /// being diagnosed.
7687   ///
7688   /// Note that the values of this enumeration line up with the first
7689   /// argument to the \c err_unexpanded_parameter_pack diagnostic.
7690   enum UnexpandedParameterPackContext {
7691     /// An arbitrary expression.
7692     UPPC_Expression = 0,
7693 
7694     /// The base type of a class type.
7695     UPPC_BaseType,
7696 
7697     /// The type of an arbitrary declaration.
7698     UPPC_DeclarationType,
7699 
7700     /// The type of a data member.
7701     UPPC_DataMemberType,
7702 
7703     /// The size of a bit-field.
7704     UPPC_BitFieldWidth,
7705 
7706     /// The expression in a static assertion.
7707     UPPC_StaticAssertExpression,
7708 
7709     /// The fixed underlying type of an enumeration.
7710     UPPC_FixedUnderlyingType,
7711 
7712     /// The enumerator value.
7713     UPPC_EnumeratorValue,
7714 
7715     /// A using declaration.
7716     UPPC_UsingDeclaration,
7717 
7718     /// A friend declaration.
7719     UPPC_FriendDeclaration,
7720 
7721     /// A declaration qualifier.
7722     UPPC_DeclarationQualifier,
7723 
7724     /// An initializer.
7725     UPPC_Initializer,
7726 
7727     /// A default argument.
7728     UPPC_DefaultArgument,
7729 
7730     /// The type of a non-type template parameter.
7731     UPPC_NonTypeTemplateParameterType,
7732 
7733     /// The type of an exception.
7734     UPPC_ExceptionType,
7735 
7736     /// Partial specialization.
7737     UPPC_PartialSpecialization,
7738 
7739     /// Microsoft __if_exists.
7740     UPPC_IfExists,
7741 
7742     /// Microsoft __if_not_exists.
7743     UPPC_IfNotExists,
7744 
7745     /// Lambda expression.
7746     UPPC_Lambda,
7747 
7748     /// Block expression,
7749     UPPC_Block,
7750 
7751     /// A type constraint,
7752     UPPC_TypeConstraint
7753   };
7754 
7755   /// Diagnose unexpanded parameter packs.
7756   ///
7757   /// \param Loc The location at which we should emit the diagnostic.
7758   ///
7759   /// \param UPPC The context in which we are diagnosing unexpanded
7760   /// parameter packs.
7761   ///
7762   /// \param Unexpanded the set of unexpanded parameter packs.
7763   ///
7764   /// \returns true if an error occurred, false otherwise.
7765   bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
7766                                         UnexpandedParameterPackContext UPPC,
7767                                   ArrayRef<UnexpandedParameterPack> Unexpanded);
7768 
7769   /// If the given type contains an unexpanded parameter pack,
7770   /// diagnose the error.
7771   ///
7772   /// \param Loc The source location where a diagnostc should be emitted.
7773   ///
7774   /// \param T The type that is being checked for unexpanded parameter
7775   /// packs.
7776   ///
7777   /// \returns true if an error occurred, false otherwise.
7778   bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
7779                                        UnexpandedParameterPackContext UPPC);
7780 
7781   /// If the given expression contains an unexpanded parameter
7782   /// pack, diagnose the error.
7783   ///
7784   /// \param E The expression that is being checked for unexpanded
7785   /// parameter packs.
7786   ///
7787   /// \returns true if an error occurred, false otherwise.
7788   bool DiagnoseUnexpandedParameterPack(Expr *E,
7789                        UnexpandedParameterPackContext UPPC = UPPC_Expression);
7790 
7791   /// If the given nested-name-specifier contains an unexpanded
7792   /// parameter pack, diagnose the error.
7793   ///
7794   /// \param SS The nested-name-specifier that is being checked for
7795   /// unexpanded parameter packs.
7796   ///
7797   /// \returns true if an error occurred, false otherwise.
7798   bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
7799                                        UnexpandedParameterPackContext UPPC);
7800 
7801   /// If the given name contains an unexpanded parameter pack,
7802   /// diagnose the error.
7803   ///
7804   /// \param NameInfo The name (with source location information) that
7805   /// is being checked for unexpanded parameter packs.
7806   ///
7807   /// \returns true if an error occurred, false otherwise.
7808   bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
7809                                        UnexpandedParameterPackContext UPPC);
7810 
7811   /// If the given template name contains an unexpanded parameter pack,
7812   /// diagnose the error.
7813   ///
7814   /// \param Loc The location of the template name.
7815   ///
7816   /// \param Template The template name that is being checked for unexpanded
7817   /// parameter packs.
7818   ///
7819   /// \returns true if an error occurred, false otherwise.
7820   bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
7821                                        TemplateName Template,
7822                                        UnexpandedParameterPackContext UPPC);
7823 
7824   /// If the given template argument contains an unexpanded parameter
7825   /// pack, diagnose the error.
7826   ///
7827   /// \param Arg The template argument that is being checked for unexpanded
7828   /// parameter packs.
7829   ///
7830   /// \returns true if an error occurred, false otherwise.
7831   bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
7832                                        UnexpandedParameterPackContext UPPC);
7833 
7834   /// Collect the set of unexpanded parameter packs within the given
7835   /// template argument.
7836   ///
7837   /// \param Arg The template argument that will be traversed to find
7838   /// unexpanded parameter packs.
7839   void collectUnexpandedParameterPacks(TemplateArgument Arg,
7840                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7841 
7842   /// Collect the set of unexpanded parameter packs within the given
7843   /// template argument.
7844   ///
7845   /// \param Arg The template argument that will be traversed to find
7846   /// unexpanded parameter packs.
7847   void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
7848                     SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7849 
7850   /// Collect the set of unexpanded parameter packs within the given
7851   /// type.
7852   ///
7853   /// \param T The type that will be traversed to find
7854   /// unexpanded parameter packs.
7855   void collectUnexpandedParameterPacks(QualType T,
7856                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7857 
7858   /// Collect the set of unexpanded parameter packs within the given
7859   /// type.
7860   ///
7861   /// \param TL The type that will be traversed to find
7862   /// unexpanded parameter packs.
7863   void collectUnexpandedParameterPacks(TypeLoc TL,
7864                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7865 
7866   /// Collect the set of unexpanded parameter packs within the given
7867   /// nested-name-specifier.
7868   ///
7869   /// \param NNS The nested-name-specifier that will be traversed to find
7870   /// unexpanded parameter packs.
7871   void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
7872                          SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7873 
7874   /// Collect the set of unexpanded parameter packs within the given
7875   /// name.
7876   ///
7877   /// \param NameInfo The name that will be traversed to find
7878   /// unexpanded parameter packs.
7879   void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
7880                          SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7881 
7882   /// Invoked when parsing a template argument followed by an
7883   /// ellipsis, which creates a pack expansion.
7884   ///
7885   /// \param Arg The template argument preceding the ellipsis, which
7886   /// may already be invalid.
7887   ///
7888   /// \param EllipsisLoc The location of the ellipsis.
7889   ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
7890                                             SourceLocation EllipsisLoc);
7891 
7892   /// Invoked when parsing a type followed by an ellipsis, which
7893   /// creates a pack expansion.
7894   ///
7895   /// \param Type The type preceding the ellipsis, which will become
7896   /// the pattern of the pack expansion.
7897   ///
7898   /// \param EllipsisLoc The location of the ellipsis.
7899   TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
7900 
7901   /// Construct a pack expansion type from the pattern of the pack
7902   /// expansion.
7903   TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
7904                                      SourceLocation EllipsisLoc,
7905                                      Optional<unsigned> NumExpansions);
7906 
7907   /// Construct a pack expansion type from the pattern of the pack
7908   /// expansion.
7909   QualType CheckPackExpansion(QualType Pattern,
7910                               SourceRange PatternRange,
7911                               SourceLocation EllipsisLoc,
7912                               Optional<unsigned> NumExpansions);
7913 
7914   /// Invoked when parsing an expression followed by an ellipsis, which
7915   /// creates a pack expansion.
7916   ///
7917   /// \param Pattern The expression preceding the ellipsis, which will become
7918   /// the pattern of the pack expansion.
7919   ///
7920   /// \param EllipsisLoc The location of the ellipsis.
7921   ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
7922 
7923   /// Invoked when parsing an expression followed by an ellipsis, which
7924   /// creates a pack expansion.
7925   ///
7926   /// \param Pattern The expression preceding the ellipsis, which will become
7927   /// the pattern of the pack expansion.
7928   ///
7929   /// \param EllipsisLoc The location of the ellipsis.
7930   ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
7931                                 Optional<unsigned> NumExpansions);
7932 
7933   /// Determine whether we could expand a pack expansion with the
7934   /// given set of parameter packs into separate arguments by repeatedly
7935   /// transforming the pattern.
7936   ///
7937   /// \param EllipsisLoc The location of the ellipsis that identifies the
7938   /// pack expansion.
7939   ///
7940   /// \param PatternRange The source range that covers the entire pattern of
7941   /// the pack expansion.
7942   ///
7943   /// \param Unexpanded The set of unexpanded parameter packs within the
7944   /// pattern.
7945   ///
7946   /// \param ShouldExpand Will be set to \c true if the transformer should
7947   /// expand the corresponding pack expansions into separate arguments. When
7948   /// set, \c NumExpansions must also be set.
7949   ///
7950   /// \param RetainExpansion Whether the caller should add an unexpanded
7951   /// pack expansion after all of the expanded arguments. This is used
7952   /// when extending explicitly-specified template argument packs per
7953   /// C++0x [temp.arg.explicit]p9.
7954   ///
7955   /// \param NumExpansions The number of separate arguments that will be in
7956   /// the expanded form of the corresponding pack expansion. This is both an
7957   /// input and an output parameter, which can be set by the caller if the
7958   /// number of expansions is known a priori (e.g., due to a prior substitution)
7959   /// and will be set by the callee when the number of expansions is known.
7960   /// The callee must set this value when \c ShouldExpand is \c true; it may
7961   /// set this value in other cases.
7962   ///
7963   /// \returns true if an error occurred (e.g., because the parameter packs
7964   /// are to be instantiated with arguments of different lengths), false
7965   /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
7966   /// must be set.
7967   bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
7968                                        SourceRange PatternRange,
7969                              ArrayRef<UnexpandedParameterPack> Unexpanded,
7970                              const MultiLevelTemplateArgumentList &TemplateArgs,
7971                                        bool &ShouldExpand,
7972                                        bool &RetainExpansion,
7973                                        Optional<unsigned> &NumExpansions);
7974 
7975   /// Determine the number of arguments in the given pack expansion
7976   /// type.
7977   ///
7978   /// This routine assumes that the number of arguments in the expansion is
7979   /// consistent across all of the unexpanded parameter packs in its pattern.
7980   ///
7981   /// Returns an empty Optional if the type can't be expanded.
7982   Optional<unsigned> getNumArgumentsInExpansion(QualType T,
7983       const MultiLevelTemplateArgumentList &TemplateArgs);
7984 
7985   /// Determine whether the given declarator contains any unexpanded
7986   /// parameter packs.
7987   ///
7988   /// This routine is used by the parser to disambiguate function declarators
7989   /// with an ellipsis prior to the ')', e.g.,
7990   ///
7991   /// \code
7992   ///   void f(T...);
7993   /// \endcode
7994   ///
7995   /// To determine whether we have an (unnamed) function parameter pack or
7996   /// a variadic function.
7997   ///
7998   /// \returns true if the declarator contains any unexpanded parameter packs,
7999   /// false otherwise.
8000   bool containsUnexpandedParameterPacks(Declarator &D);
8001 
8002   /// Returns the pattern of the pack expansion for a template argument.
8003   ///
8004   /// \param OrigLoc The template argument to expand.
8005   ///
8006   /// \param Ellipsis Will be set to the location of the ellipsis.
8007   ///
8008   /// \param NumExpansions Will be set to the number of expansions that will
8009   /// be generated from this pack expansion, if known a priori.
8010   TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
8011       TemplateArgumentLoc OrigLoc,
8012       SourceLocation &Ellipsis,
8013       Optional<unsigned> &NumExpansions) const;
8014 
8015   /// Given a template argument that contains an unexpanded parameter pack, but
8016   /// which has already been substituted, attempt to determine the number of
8017   /// elements that will be produced once this argument is fully-expanded.
8018   ///
8019   /// This is intended for use when transforming 'sizeof...(Arg)' in order to
8020   /// avoid actually expanding the pack where possible.
8021   Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
8022 
8023   //===--------------------------------------------------------------------===//
8024   // C++ Template Argument Deduction (C++ [temp.deduct])
8025   //===--------------------------------------------------------------------===//
8026 
8027   /// Adjust the type \p ArgFunctionType to match the calling convention,
8028   /// noreturn, and optionally the exception specification of \p FunctionType.
8029   /// Deduction often wants to ignore these properties when matching function
8030   /// types.
8031   QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
8032                                bool AdjustExceptionSpec = false);
8033 
8034   /// Describes the result of template argument deduction.
8035   ///
8036   /// The TemplateDeductionResult enumeration describes the result of
8037   /// template argument deduction, as returned from
8038   /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
8039   /// structure provides additional information about the results of
8040   /// template argument deduction, e.g., the deduced template argument
8041   /// list (if successful) or the specific template parameters or
8042   /// deduced arguments that were involved in the failure.
8043   enum TemplateDeductionResult {
8044     /// Template argument deduction was successful.
8045     TDK_Success = 0,
8046     /// The declaration was invalid; do nothing.
8047     TDK_Invalid,
8048     /// Template argument deduction exceeded the maximum template
8049     /// instantiation depth (which has already been diagnosed).
8050     TDK_InstantiationDepth,
8051     /// Template argument deduction did not deduce a value
8052     /// for every template parameter.
8053     TDK_Incomplete,
8054     /// Template argument deduction did not deduce a value for every
8055     /// expansion of an expanded template parameter pack.
8056     TDK_IncompletePack,
8057     /// Template argument deduction produced inconsistent
8058     /// deduced values for the given template parameter.
8059     TDK_Inconsistent,
8060     /// Template argument deduction failed due to inconsistent
8061     /// cv-qualifiers on a template parameter type that would
8062     /// otherwise be deduced, e.g., we tried to deduce T in "const T"
8063     /// but were given a non-const "X".
8064     TDK_Underqualified,
8065     /// Substitution of the deduced template argument values
8066     /// resulted in an error.
8067     TDK_SubstitutionFailure,
8068     /// After substituting deduced template arguments, a dependent
8069     /// parameter type did not match the corresponding argument.
8070     TDK_DeducedMismatch,
8071     /// After substituting deduced template arguments, an element of
8072     /// a dependent parameter type did not match the corresponding element
8073     /// of the corresponding argument (when deducing from an initializer list).
8074     TDK_DeducedMismatchNested,
8075     /// A non-depnedent component of the parameter did not match the
8076     /// corresponding component of the argument.
8077     TDK_NonDeducedMismatch,
8078     /// When performing template argument deduction for a function
8079     /// template, there were too many call arguments.
8080     TDK_TooManyArguments,
8081     /// When performing template argument deduction for a function
8082     /// template, there were too few call arguments.
8083     TDK_TooFewArguments,
8084     /// The explicitly-specified template arguments were not valid
8085     /// template arguments for the given template.
8086     TDK_InvalidExplicitArguments,
8087     /// Checking non-dependent argument conversions failed.
8088     TDK_NonDependentConversionFailure,
8089     /// The deduced arguments did not satisfy the constraints associated
8090     /// with the template.
8091     TDK_ConstraintsNotSatisfied,
8092     /// Deduction failed; that's all we know.
8093     TDK_MiscellaneousDeductionFailure,
8094     /// CUDA Target attributes do not match.
8095     TDK_CUDATargetMismatch
8096   };
8097 
8098   TemplateDeductionResult
8099   DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
8100                           const TemplateArgumentList &TemplateArgs,
8101                           sema::TemplateDeductionInfo &Info);
8102 
8103   TemplateDeductionResult
8104   DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
8105                           const TemplateArgumentList &TemplateArgs,
8106                           sema::TemplateDeductionInfo &Info);
8107 
8108   TemplateDeductionResult SubstituteExplicitTemplateArguments(
8109       FunctionTemplateDecl *FunctionTemplate,
8110       TemplateArgumentListInfo &ExplicitTemplateArgs,
8111       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
8112       SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
8113       sema::TemplateDeductionInfo &Info);
8114 
8115   /// brief A function argument from which we performed template argument
8116   // deduction for a call.
8117   struct OriginalCallArg {
OriginalCallArgOriginalCallArg8118     OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
8119                     unsigned ArgIdx, QualType OriginalArgType)
8120         : OriginalParamType(OriginalParamType),
8121           DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
8122           OriginalArgType(OriginalArgType) {}
8123 
8124     QualType OriginalParamType;
8125     bool DecomposedParam;
8126     unsigned ArgIdx;
8127     QualType OriginalArgType;
8128   };
8129 
8130   TemplateDeductionResult FinishTemplateArgumentDeduction(
8131       FunctionTemplateDecl *FunctionTemplate,
8132       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
8133       unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
8134       sema::TemplateDeductionInfo &Info,
8135       SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
8136       bool PartialOverloading = false,
8137       llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
8138 
8139   TemplateDeductionResult DeduceTemplateArguments(
8140       FunctionTemplateDecl *FunctionTemplate,
8141       TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8142       FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
8143       bool PartialOverloading,
8144       llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
8145 
8146   TemplateDeductionResult
8147   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
8148                           TemplateArgumentListInfo *ExplicitTemplateArgs,
8149                           QualType ArgFunctionType,
8150                           FunctionDecl *&Specialization,
8151                           sema::TemplateDeductionInfo &Info,
8152                           bool IsAddressOfFunction = false);
8153 
8154   TemplateDeductionResult
8155   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
8156                           QualType ToType,
8157                           CXXConversionDecl *&Specialization,
8158                           sema::TemplateDeductionInfo &Info);
8159 
8160   TemplateDeductionResult
8161   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
8162                           TemplateArgumentListInfo *ExplicitTemplateArgs,
8163                           FunctionDecl *&Specialization,
8164                           sema::TemplateDeductionInfo &Info,
8165                           bool IsAddressOfFunction = false);
8166 
8167   /// Substitute Replacement for \p auto in \p TypeWithAuto
8168   QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
8169   /// Substitute Replacement for auto in TypeWithAuto
8170   TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
8171                                           QualType Replacement);
8172   /// Completely replace the \c auto in \p TypeWithAuto by
8173   /// \p Replacement. This does not retain any \c auto type sugar.
8174   QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
8175 
8176   /// Result type of DeduceAutoType.
8177   enum DeduceAutoResult {
8178     DAR_Succeeded,
8179     DAR_Failed,
8180     DAR_FailedAlreadyDiagnosed
8181   };
8182 
8183   DeduceAutoResult
8184   DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
8185                  Optional<unsigned> DependentDeductionDepth = None,
8186                  bool IgnoreConstraints = false);
8187   DeduceAutoResult
8188   DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
8189                  Optional<unsigned> DependentDeductionDepth = None,
8190                  bool IgnoreConstraints = false);
8191   void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
8192   bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
8193                         bool Diagnose = true);
8194 
8195   /// Declare implicit deduction guides for a class template if we've
8196   /// not already done so.
8197   void DeclareImplicitDeductionGuides(TemplateDecl *Template,
8198                                       SourceLocation Loc);
8199 
8200   QualType DeduceTemplateSpecializationFromInitializer(
8201       TypeSourceInfo *TInfo, const InitializedEntity &Entity,
8202       const InitializationKind &Kind, MultiExprArg Init);
8203 
8204   QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
8205                                         QualType Type, TypeSourceInfo *TSI,
8206                                         SourceRange Range, bool DirectInit,
8207                                         Expr *Init);
8208 
8209   TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
8210 
8211   bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
8212                                         SourceLocation ReturnLoc,
8213                                         Expr *&RetExpr, AutoType *AT);
8214 
8215   FunctionTemplateDecl *getMoreSpecializedTemplate(
8216       FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc,
8217       TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
8218       unsigned NumCallArguments2, bool Reversed = false);
8219   UnresolvedSetIterator
8220   getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
8221                      TemplateSpecCandidateSet &FailedCandidates,
8222                      SourceLocation Loc,
8223                      const PartialDiagnostic &NoneDiag,
8224                      const PartialDiagnostic &AmbigDiag,
8225                      const PartialDiagnostic &CandidateDiag,
8226                      bool Complain = true, QualType TargetType = QualType());
8227 
8228   ClassTemplatePartialSpecializationDecl *
8229   getMoreSpecializedPartialSpecialization(
8230                                   ClassTemplatePartialSpecializationDecl *PS1,
8231                                   ClassTemplatePartialSpecializationDecl *PS2,
8232                                   SourceLocation Loc);
8233 
8234   bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
8235                                     sema::TemplateDeductionInfo &Info);
8236 
8237   VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
8238       VarTemplatePartialSpecializationDecl *PS1,
8239       VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
8240 
8241   bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
8242                                     sema::TemplateDeductionInfo &Info);
8243 
8244   bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
8245       TemplateParameterList *PParam, TemplateDecl *AArg, SourceLocation Loc);
8246 
8247   void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
8248                                   unsigned Depth, llvm::SmallBitVector &Used);
8249 
8250   void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
8251                                   bool OnlyDeduced,
8252                                   unsigned Depth,
8253                                   llvm::SmallBitVector &Used);
MarkDeducedTemplateParameters(const FunctionTemplateDecl * FunctionTemplate,llvm::SmallBitVector & Deduced)8254   void MarkDeducedTemplateParameters(
8255                                   const FunctionTemplateDecl *FunctionTemplate,
8256                                   llvm::SmallBitVector &Deduced) {
8257     return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
8258   }
8259   static void MarkDeducedTemplateParameters(ASTContext &Ctx,
8260                                   const FunctionTemplateDecl *FunctionTemplate,
8261                                   llvm::SmallBitVector &Deduced);
8262 
8263   //===--------------------------------------------------------------------===//
8264   // C++ Template Instantiation
8265   //
8266 
8267   MultiLevelTemplateArgumentList
8268   getTemplateInstantiationArgs(NamedDecl *D,
8269                                const TemplateArgumentList *Innermost = nullptr,
8270                                bool RelativeToPrimary = false,
8271                                const FunctionDecl *Pattern = nullptr);
8272 
8273   /// A context in which code is being synthesized (where a source location
8274   /// alone is not sufficient to identify the context). This covers template
8275   /// instantiation and various forms of implicitly-generated functions.
8276   struct CodeSynthesisContext {
8277     /// The kind of template instantiation we are performing
8278     enum SynthesisKind {
8279       /// We are instantiating a template declaration. The entity is
8280       /// the declaration we're instantiating (e.g., a CXXRecordDecl).
8281       TemplateInstantiation,
8282 
8283       /// We are instantiating a default argument for a template
8284       /// parameter. The Entity is the template parameter whose argument is
8285       /// being instantiated, the Template is the template, and the
8286       /// TemplateArgs/NumTemplateArguments provide the template arguments as
8287       /// specified.
8288       DefaultTemplateArgumentInstantiation,
8289 
8290       /// We are instantiating a default argument for a function.
8291       /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
8292       /// provides the template arguments as specified.
8293       DefaultFunctionArgumentInstantiation,
8294 
8295       /// We are substituting explicit template arguments provided for
8296       /// a function template. The entity is a FunctionTemplateDecl.
8297       ExplicitTemplateArgumentSubstitution,
8298 
8299       /// We are substituting template argument determined as part of
8300       /// template argument deduction for either a class template
8301       /// partial specialization or a function template. The
8302       /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
8303       /// a TemplateDecl.
8304       DeducedTemplateArgumentSubstitution,
8305 
8306       /// We are substituting prior template arguments into a new
8307       /// template parameter. The template parameter itself is either a
8308       /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
8309       PriorTemplateArgumentSubstitution,
8310 
8311       /// We are checking the validity of a default template argument that
8312       /// has been used when naming a template-id.
8313       DefaultTemplateArgumentChecking,
8314 
8315       /// We are computing the exception specification for a defaulted special
8316       /// member function.
8317       ExceptionSpecEvaluation,
8318 
8319       /// We are instantiating the exception specification for a function
8320       /// template which was deferred until it was needed.
8321       ExceptionSpecInstantiation,
8322 
8323       /// We are instantiating a requirement of a requires expression.
8324       RequirementInstantiation,
8325 
8326       /// We are checking the satisfaction of a nested requirement of a requires
8327       /// expression.
8328       NestedRequirementConstraintsCheck,
8329 
8330       /// We are declaring an implicit special member function.
8331       DeclaringSpecialMember,
8332 
8333       /// We are declaring an implicit 'operator==' for a defaulted
8334       /// 'operator<=>'.
8335       DeclaringImplicitEqualityComparison,
8336 
8337       /// We are defining a synthesized function (such as a defaulted special
8338       /// member).
8339       DefiningSynthesizedFunction,
8340 
8341       // We are checking the constraints associated with a constrained entity or
8342       // the constraint expression of a concept. This includes the checks that
8343       // atomic constraints have the type 'bool' and that they can be constant
8344       // evaluated.
8345       ConstraintsCheck,
8346 
8347       // We are substituting template arguments into a constraint expression.
8348       ConstraintSubstitution,
8349 
8350       // We are normalizing a constraint expression.
8351       ConstraintNormalization,
8352 
8353       // We are substituting into the parameter mapping of an atomic constraint
8354       // during normalization.
8355       ParameterMappingSubstitution,
8356 
8357       /// We are rewriting a comparison operator in terms of an operator<=>.
8358       RewritingOperatorAsSpaceship,
8359 
8360       /// We are initializing a structured binding.
8361       InitializingStructuredBinding,
8362 
8363       /// We are marking a class as __dllexport.
8364       MarkingClassDllexported,
8365 
8366       /// Added for Template instantiation observation.
8367       /// Memoization means we are _not_ instantiating a template because
8368       /// it is already instantiated (but we entered a context where we
8369       /// would have had to if it was not already instantiated).
8370       Memoization
8371     } Kind;
8372 
8373     /// Was the enclosing context a non-instantiation SFINAE context?
8374     bool SavedInNonInstantiationSFINAEContext;
8375 
8376     /// The point of instantiation or synthesis within the source code.
8377     SourceLocation PointOfInstantiation;
8378 
8379     /// The entity that is being synthesized.
8380     Decl *Entity;
8381 
8382     /// The template (or partial specialization) in which we are
8383     /// performing the instantiation, for substitutions of prior template
8384     /// arguments.
8385     NamedDecl *Template;
8386 
8387     /// The list of template arguments we are substituting, if they
8388     /// are not part of the entity.
8389     const TemplateArgument *TemplateArgs;
8390 
8391     // FIXME: Wrap this union around more members, or perhaps store the
8392     // kind-specific members in the RAII object owning the context.
8393     union {
8394       /// The number of template arguments in TemplateArgs.
8395       unsigned NumTemplateArgs;
8396 
8397       /// The special member being declared or defined.
8398       CXXSpecialMember SpecialMember;
8399     };
8400 
template_argumentsCodeSynthesisContext8401     ArrayRef<TemplateArgument> template_arguments() const {
8402       assert(Kind != DeclaringSpecialMember);
8403       return {TemplateArgs, NumTemplateArgs};
8404     }
8405 
8406     /// The template deduction info object associated with the
8407     /// substitution or checking of explicit or deduced template arguments.
8408     sema::TemplateDeductionInfo *DeductionInfo;
8409 
8410     /// The source range that covers the construct that cause
8411     /// the instantiation, e.g., the template-id that causes a class
8412     /// template instantiation.
8413     SourceRange InstantiationRange;
8414 
CodeSynthesisContextCodeSynthesisContext8415     CodeSynthesisContext()
8416         : Kind(TemplateInstantiation),
8417           SavedInNonInstantiationSFINAEContext(false), Entity(nullptr),
8418           Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0),
8419           DeductionInfo(nullptr) {}
8420 
8421     /// Determines whether this template is an actual instantiation
8422     /// that should be counted toward the maximum instantiation depth.
8423     bool isInstantiationRecord() const;
8424   };
8425 
8426   /// List of active code synthesis contexts.
8427   ///
8428   /// This vector is treated as a stack. As synthesis of one entity requires
8429   /// synthesis of another, additional contexts are pushed onto the stack.
8430   SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
8431 
8432   /// Specializations whose definitions are currently being instantiated.
8433   llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
8434 
8435   /// Non-dependent types used in templates that have already been instantiated
8436   /// by some template instantiation.
8437   llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
8438 
8439   /// Extra modules inspected when performing a lookup during a template
8440   /// instantiation. Computed lazily.
8441   SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
8442 
8443   /// Cache of additional modules that should be used for name lookup
8444   /// within the current template instantiation. Computed lazily; use
8445   /// getLookupModules() to get a complete set.
8446   llvm::DenseSet<Module*> LookupModulesCache;
8447 
8448   /// Get the set of additional modules that should be checked during
8449   /// name lookup. A module and its imports become visible when instanting a
8450   /// template defined within it.
8451   llvm::DenseSet<Module*> &getLookupModules();
8452 
8453   /// Map from the most recent declaration of a namespace to the most
8454   /// recent visible declaration of that namespace.
8455   llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
8456 
8457   /// Whether we are in a SFINAE context that is not associated with
8458   /// template instantiation.
8459   ///
8460   /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
8461   /// of a template instantiation or template argument deduction.
8462   bool InNonInstantiationSFINAEContext;
8463 
8464   /// The number of \p CodeSynthesisContexts that are not template
8465   /// instantiations and, therefore, should not be counted as part of the
8466   /// instantiation depth.
8467   ///
8468   /// When the instantiation depth reaches the user-configurable limit
8469   /// \p LangOptions::InstantiationDepth we will abort instantiation.
8470   // FIXME: Should we have a similar limit for other forms of synthesis?
8471   unsigned NonInstantiationEntries;
8472 
8473   /// The depth of the context stack at the point when the most recent
8474   /// error or warning was produced.
8475   ///
8476   /// This value is used to suppress printing of redundant context stacks
8477   /// when there are multiple errors or warnings in the same instantiation.
8478   // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
8479   unsigned LastEmittedCodeSynthesisContextDepth = 0;
8480 
8481   /// The template instantiation callbacks to trace or track
8482   /// instantiations (objects can be chained).
8483   ///
8484   /// This callbacks is used to print, trace or track template
8485   /// instantiations as they are being constructed.
8486   std::vector<std::unique_ptr<TemplateInstantiationCallback>>
8487       TemplateInstCallbacks;
8488 
8489   /// The current index into pack expansion arguments that will be
8490   /// used for substitution of parameter packs.
8491   ///
8492   /// The pack expansion index will be -1 to indicate that parameter packs
8493   /// should be instantiated as themselves. Otherwise, the index specifies
8494   /// which argument within the parameter pack will be used for substitution.
8495   int ArgumentPackSubstitutionIndex;
8496 
8497   /// RAII object used to change the argument pack substitution index
8498   /// within a \c Sema object.
8499   ///
8500   /// See \c ArgumentPackSubstitutionIndex for more information.
8501   class ArgumentPackSubstitutionIndexRAII {
8502     Sema &Self;
8503     int OldSubstitutionIndex;
8504 
8505   public:
ArgumentPackSubstitutionIndexRAII(Sema & Self,int NewSubstitutionIndex)8506     ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
8507       : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
8508       Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
8509     }
8510 
~ArgumentPackSubstitutionIndexRAII()8511     ~ArgumentPackSubstitutionIndexRAII() {
8512       Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
8513     }
8514   };
8515 
8516   friend class ArgumentPackSubstitutionRAII;
8517 
8518   /// For each declaration that involved template argument deduction, the
8519   /// set of diagnostics that were suppressed during that template argument
8520   /// deduction.
8521   ///
8522   /// FIXME: Serialize this structure to the AST file.
8523   typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
8524     SuppressedDiagnosticsMap;
8525   SuppressedDiagnosticsMap SuppressedDiagnostics;
8526 
8527   /// A stack object to be created when performing template
8528   /// instantiation.
8529   ///
8530   /// Construction of an object of type \c InstantiatingTemplate
8531   /// pushes the current instantiation onto the stack of active
8532   /// instantiations. If the size of this stack exceeds the maximum
8533   /// number of recursive template instantiations, construction
8534   /// produces an error and evaluates true.
8535   ///
8536   /// Destruction of this object will pop the named instantiation off
8537   /// the stack.
8538   struct InstantiatingTemplate {
8539     /// Note that we are instantiating a class template,
8540     /// function template, variable template, alias template,
8541     /// or a member thereof.
8542     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8543                           Decl *Entity,
8544                           SourceRange InstantiationRange = SourceRange());
8545 
8546     struct ExceptionSpecification {};
8547     /// Note that we are instantiating an exception specification
8548     /// of a function template.
8549     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8550                           FunctionDecl *Entity, ExceptionSpecification,
8551                           SourceRange InstantiationRange = SourceRange());
8552 
8553     /// Note that we are instantiating a default argument in a
8554     /// template-id.
8555     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8556                           TemplateParameter Param, TemplateDecl *Template,
8557                           ArrayRef<TemplateArgument> TemplateArgs,
8558                           SourceRange InstantiationRange = SourceRange());
8559 
8560     /// Note that we are substituting either explicitly-specified or
8561     /// deduced template arguments during function template argument deduction.
8562     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8563                           FunctionTemplateDecl *FunctionTemplate,
8564                           ArrayRef<TemplateArgument> TemplateArgs,
8565                           CodeSynthesisContext::SynthesisKind Kind,
8566                           sema::TemplateDeductionInfo &DeductionInfo,
8567                           SourceRange InstantiationRange = SourceRange());
8568 
8569     /// Note that we are instantiating as part of template
8570     /// argument deduction for a class template declaration.
8571     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8572                           TemplateDecl *Template,
8573                           ArrayRef<TemplateArgument> TemplateArgs,
8574                           sema::TemplateDeductionInfo &DeductionInfo,
8575                           SourceRange InstantiationRange = SourceRange());
8576 
8577     /// Note that we are instantiating as part of template
8578     /// argument deduction for a class template partial
8579     /// specialization.
8580     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8581                           ClassTemplatePartialSpecializationDecl *PartialSpec,
8582                           ArrayRef<TemplateArgument> TemplateArgs,
8583                           sema::TemplateDeductionInfo &DeductionInfo,
8584                           SourceRange InstantiationRange = SourceRange());
8585 
8586     /// Note that we are instantiating as part of template
8587     /// argument deduction for a variable template partial
8588     /// specialization.
8589     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8590                           VarTemplatePartialSpecializationDecl *PartialSpec,
8591                           ArrayRef<TemplateArgument> TemplateArgs,
8592                           sema::TemplateDeductionInfo &DeductionInfo,
8593                           SourceRange InstantiationRange = SourceRange());
8594 
8595     /// Note that we are instantiating a default argument for a function
8596     /// parameter.
8597     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8598                           ParmVarDecl *Param,
8599                           ArrayRef<TemplateArgument> TemplateArgs,
8600                           SourceRange InstantiationRange = SourceRange());
8601 
8602     /// Note that we are substituting prior template arguments into a
8603     /// non-type parameter.
8604     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8605                           NamedDecl *Template,
8606                           NonTypeTemplateParmDecl *Param,
8607                           ArrayRef<TemplateArgument> TemplateArgs,
8608                           SourceRange InstantiationRange);
8609 
8610     /// Note that we are substituting prior template arguments into a
8611     /// template template parameter.
8612     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8613                           NamedDecl *Template,
8614                           TemplateTemplateParmDecl *Param,
8615                           ArrayRef<TemplateArgument> TemplateArgs,
8616                           SourceRange InstantiationRange);
8617 
8618     /// Note that we are checking the default template argument
8619     /// against the template parameter for a given template-id.
8620     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8621                           TemplateDecl *Template,
8622                           NamedDecl *Param,
8623                           ArrayRef<TemplateArgument> TemplateArgs,
8624                           SourceRange InstantiationRange);
8625 
8626     struct ConstraintsCheck {};
8627     /// \brief Note that we are checking the constraints associated with some
8628     /// constrained entity (a concept declaration or a template with associated
8629     /// constraints).
8630     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8631                           ConstraintsCheck, NamedDecl *Template,
8632                           ArrayRef<TemplateArgument> TemplateArgs,
8633                           SourceRange InstantiationRange);
8634 
8635     struct ConstraintSubstitution {};
8636     /// \brief Note that we are checking a constraint expression associated
8637     /// with a template declaration or as part of the satisfaction check of a
8638     /// concept.
8639     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8640                           ConstraintSubstitution, NamedDecl *Template,
8641                           sema::TemplateDeductionInfo &DeductionInfo,
8642                           SourceRange InstantiationRange);
8643 
8644     struct ConstraintNormalization {};
8645     /// \brief Note that we are normalizing a constraint expression.
8646     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8647                           ConstraintNormalization, NamedDecl *Template,
8648                           SourceRange InstantiationRange);
8649 
8650     struct ParameterMappingSubstitution {};
8651     /// \brief Note that we are subtituting into the parameter mapping of an
8652     /// atomic constraint during constraint normalization.
8653     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8654                           ParameterMappingSubstitution, NamedDecl *Template,
8655                           SourceRange InstantiationRange);
8656 
8657     /// \brief Note that we are substituting template arguments into a part of
8658     /// a requirement of a requires expression.
8659     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8660                           concepts::Requirement *Req,
8661                           sema::TemplateDeductionInfo &DeductionInfo,
8662                           SourceRange InstantiationRange = SourceRange());
8663 
8664     /// \brief Note that we are checking the satisfaction of the constraint
8665     /// expression inside of a nested requirement.
8666     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8667                           concepts::NestedRequirement *Req, ConstraintsCheck,
8668                           SourceRange InstantiationRange = SourceRange());
8669 
8670     /// Note that we have finished instantiating this template.
8671     void Clear();
8672 
~InstantiatingTemplateInstantiatingTemplate8673     ~InstantiatingTemplate() { Clear(); }
8674 
8675     /// Determines whether we have exceeded the maximum
8676     /// recursive template instantiations.
isInvalidInstantiatingTemplate8677     bool isInvalid() const { return Invalid; }
8678 
8679     /// Determine whether we are already instantiating this
8680     /// specialization in some surrounding active instantiation.
isAlreadyInstantiatingInstantiatingTemplate8681     bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
8682 
8683   private:
8684     Sema &SemaRef;
8685     bool Invalid;
8686     bool AlreadyInstantiating;
8687     bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
8688                                  SourceRange InstantiationRange);
8689 
8690     InstantiatingTemplate(
8691         Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
8692         SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
8693         Decl *Entity, NamedDecl *Template = nullptr,
8694         ArrayRef<TemplateArgument> TemplateArgs = None,
8695         sema::TemplateDeductionInfo *DeductionInfo = nullptr);
8696 
8697     InstantiatingTemplate(const InstantiatingTemplate&) = delete;
8698 
8699     InstantiatingTemplate&
8700     operator=(const InstantiatingTemplate&) = delete;
8701   };
8702 
8703   void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
8704   void popCodeSynthesisContext();
8705 
8706   /// Determine whether we are currently performing template instantiation.
inTemplateInstantiation()8707   bool inTemplateInstantiation() const {
8708     return CodeSynthesisContexts.size() > NonInstantiationEntries;
8709   }
8710 
PrintContextStack()8711   void PrintContextStack() {
8712     if (!CodeSynthesisContexts.empty() &&
8713         CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
8714       PrintInstantiationStack();
8715       LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
8716     }
8717     if (PragmaAttributeCurrentTargetDecl)
8718       PrintPragmaAttributeInstantiationPoint();
8719   }
8720   void PrintInstantiationStack();
8721 
8722   void PrintPragmaAttributeInstantiationPoint();
8723 
8724   /// Determines whether we are currently in a context where
8725   /// template argument substitution failures are not considered
8726   /// errors.
8727   ///
8728   /// \returns An empty \c Optional if we're not in a SFINAE context.
8729   /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
8730   /// template-deduction context object, which can be used to capture
8731   /// diagnostics that will be suppressed.
8732   Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
8733 
8734   /// Determines whether we are currently in a context that
8735   /// is not evaluated as per C++ [expr] p5.
isUnevaluatedContext()8736   bool isUnevaluatedContext() const {
8737     assert(!ExprEvalContexts.empty() &&
8738            "Must be in an expression evaluation context");
8739     return ExprEvalContexts.back().isUnevaluated();
8740   }
8741 
8742   /// RAII class used to determine whether SFINAE has
8743   /// trapped any errors that occur during template argument
8744   /// deduction.
8745   class SFINAETrap {
8746     Sema &SemaRef;
8747     unsigned PrevSFINAEErrors;
8748     bool PrevInNonInstantiationSFINAEContext;
8749     bool PrevAccessCheckingSFINAE;
8750     bool PrevLastDiagnosticIgnored;
8751 
8752   public:
8753     explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
SemaRef(SemaRef)8754       : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
8755         PrevInNonInstantiationSFINAEContext(
8756                                       SemaRef.InNonInstantiationSFINAEContext),
8757         PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE),
8758         PrevLastDiagnosticIgnored(
8759             SemaRef.getDiagnostics().isLastDiagnosticIgnored())
8760     {
8761       if (!SemaRef.isSFINAEContext())
8762         SemaRef.InNonInstantiationSFINAEContext = true;
8763       SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
8764     }
8765 
~SFINAETrap()8766     ~SFINAETrap() {
8767       SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
8768       SemaRef.InNonInstantiationSFINAEContext
8769         = PrevInNonInstantiationSFINAEContext;
8770       SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
8771       SemaRef.getDiagnostics().setLastDiagnosticIgnored(
8772           PrevLastDiagnosticIgnored);
8773     }
8774 
8775     /// Determine whether any SFINAE errors have been trapped.
hasErrorOccurred()8776     bool hasErrorOccurred() const {
8777       return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
8778     }
8779   };
8780 
8781   /// RAII class used to indicate that we are performing provisional
8782   /// semantic analysis to determine the validity of a construct, so
8783   /// typo-correction and diagnostics in the immediate context (not within
8784   /// implicitly-instantiated templates) should be suppressed.
8785   class TentativeAnalysisScope {
8786     Sema &SemaRef;
8787     // FIXME: Using a SFINAETrap for this is a hack.
8788     SFINAETrap Trap;
8789     bool PrevDisableTypoCorrection;
8790   public:
TentativeAnalysisScope(Sema & SemaRef)8791     explicit TentativeAnalysisScope(Sema &SemaRef)
8792         : SemaRef(SemaRef), Trap(SemaRef, true),
8793           PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
8794       SemaRef.DisableTypoCorrection = true;
8795     }
~TentativeAnalysisScope()8796     ~TentativeAnalysisScope() {
8797       SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
8798     }
8799   };
8800 
8801   /// The current instantiation scope used to store local
8802   /// variables.
8803   LocalInstantiationScope *CurrentInstantiationScope;
8804 
8805   /// Tracks whether we are in a context where typo correction is
8806   /// disabled.
8807   bool DisableTypoCorrection;
8808 
8809   /// The number of typos corrected by CorrectTypo.
8810   unsigned TyposCorrected;
8811 
8812   typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
8813   typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
8814 
8815   /// A cache containing identifiers for which typo correction failed and
8816   /// their locations, so that repeated attempts to correct an identifier in a
8817   /// given location are ignored if typo correction already failed for it.
8818   IdentifierSourceLocations TypoCorrectionFailures;
8819 
8820   /// Worker object for performing CFG-based warnings.
8821   sema::AnalysisBasedWarnings AnalysisWarnings;
8822   threadSafety::BeforeSet *ThreadSafetyDeclCache;
8823 
8824   /// An entity for which implicit template instantiation is required.
8825   ///
8826   /// The source location associated with the declaration is the first place in
8827   /// the source code where the declaration was "used". It is not necessarily
8828   /// the point of instantiation (which will be either before or after the
8829   /// namespace-scope declaration that triggered this implicit instantiation),
8830   /// However, it is the location that diagnostics should generally refer to,
8831   /// because users will need to know what code triggered the instantiation.
8832   typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
8833 
8834   /// The queue of implicit template instantiations that are required
8835   /// but have not yet been performed.
8836   std::deque<PendingImplicitInstantiation> PendingInstantiations;
8837 
8838   /// Queue of implicit template instantiations that cannot be performed
8839   /// eagerly.
8840   SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations;
8841 
8842   class GlobalEagerInstantiationScope {
8843   public:
GlobalEagerInstantiationScope(Sema & S,bool Enabled)8844     GlobalEagerInstantiationScope(Sema &S, bool Enabled)
8845         : S(S), Enabled(Enabled) {
8846       if (!Enabled) return;
8847 
8848       SavedPendingInstantiations.swap(S.PendingInstantiations);
8849       SavedVTableUses.swap(S.VTableUses);
8850     }
8851 
perform()8852     void perform() {
8853       if (Enabled) {
8854         S.DefineUsedVTables();
8855         S.PerformPendingInstantiations();
8856       }
8857     }
8858 
~GlobalEagerInstantiationScope()8859     ~GlobalEagerInstantiationScope() {
8860       if (!Enabled) return;
8861 
8862       // Restore the set of pending vtables.
8863       assert(S.VTableUses.empty() &&
8864              "VTableUses should be empty before it is discarded.");
8865       S.VTableUses.swap(SavedVTableUses);
8866 
8867       // Restore the set of pending implicit instantiations.
8868       if (S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) {
8869         assert(S.PendingInstantiations.empty() &&
8870                "PendingInstantiations should be empty before it is discarded.");
8871         S.PendingInstantiations.swap(SavedPendingInstantiations);
8872       } else {
8873         // Template instantiations in the PCH may be delayed until the TU.
8874         S.PendingInstantiations.swap(SavedPendingInstantiations);
8875         S.PendingInstantiations.insert(S.PendingInstantiations.end(),
8876                                        SavedPendingInstantiations.begin(),
8877                                        SavedPendingInstantiations.end());
8878       }
8879     }
8880 
8881   private:
8882     Sema &S;
8883     SmallVector<VTableUse, 16> SavedVTableUses;
8884     std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
8885     bool Enabled;
8886   };
8887 
8888   /// The queue of implicit template instantiations that are required
8889   /// and must be performed within the current local scope.
8890   ///
8891   /// This queue is only used for member functions of local classes in
8892   /// templates, which must be instantiated in the same scope as their
8893   /// enclosing function, so that they can reference function-local
8894   /// types, static variables, enumerators, etc.
8895   std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
8896 
8897   class LocalEagerInstantiationScope {
8898   public:
LocalEagerInstantiationScope(Sema & S)8899     LocalEagerInstantiationScope(Sema &S) : S(S) {
8900       SavedPendingLocalImplicitInstantiations.swap(
8901           S.PendingLocalImplicitInstantiations);
8902     }
8903 
perform()8904     void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); }
8905 
~LocalEagerInstantiationScope()8906     ~LocalEagerInstantiationScope() {
8907       assert(S.PendingLocalImplicitInstantiations.empty() &&
8908              "there shouldn't be any pending local implicit instantiations");
8909       SavedPendingLocalImplicitInstantiations.swap(
8910           S.PendingLocalImplicitInstantiations);
8911     }
8912 
8913   private:
8914     Sema &S;
8915     std::deque<PendingImplicitInstantiation>
8916         SavedPendingLocalImplicitInstantiations;
8917   };
8918 
8919   /// A helper class for building up ExtParameterInfos.
8920   class ExtParameterInfoBuilder {
8921     SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
8922     bool HasInteresting = false;
8923 
8924   public:
8925     /// Set the ExtParameterInfo for the parameter at the given index,
8926     ///
set(unsigned index,FunctionProtoType::ExtParameterInfo info)8927     void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
8928       assert(Infos.size() <= index);
8929       Infos.resize(index);
8930       Infos.push_back(info);
8931 
8932       if (!HasInteresting)
8933         HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
8934     }
8935 
8936     /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
8937     /// ExtParameterInfo array we've built up.
8938     const FunctionProtoType::ExtParameterInfo *
getPointerOrNull(unsigned numParams)8939     getPointerOrNull(unsigned numParams) {
8940       if (!HasInteresting) return nullptr;
8941       Infos.resize(numParams);
8942       return Infos.data();
8943     }
8944   };
8945 
8946   void PerformPendingInstantiations(bool LocalOnly = false);
8947 
8948   TypeSourceInfo *SubstType(TypeSourceInfo *T,
8949                             const MultiLevelTemplateArgumentList &TemplateArgs,
8950                             SourceLocation Loc, DeclarationName Entity,
8951                             bool AllowDeducedTST = false);
8952 
8953   QualType SubstType(QualType T,
8954                      const MultiLevelTemplateArgumentList &TemplateArgs,
8955                      SourceLocation Loc, DeclarationName Entity);
8956 
8957   TypeSourceInfo *SubstType(TypeLoc TL,
8958                             const MultiLevelTemplateArgumentList &TemplateArgs,
8959                             SourceLocation Loc, DeclarationName Entity);
8960 
8961   TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
8962                             const MultiLevelTemplateArgumentList &TemplateArgs,
8963                                         SourceLocation Loc,
8964                                         DeclarationName Entity,
8965                                         CXXRecordDecl *ThisContext,
8966                                         Qualifiers ThisTypeQuals);
8967   void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
8968                           const MultiLevelTemplateArgumentList &Args);
8969   bool SubstExceptionSpec(SourceLocation Loc,
8970                           FunctionProtoType::ExceptionSpecInfo &ESI,
8971                           SmallVectorImpl<QualType> &ExceptionStorage,
8972                           const MultiLevelTemplateArgumentList &Args);
8973   ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
8974                             const MultiLevelTemplateArgumentList &TemplateArgs,
8975                                 int indexAdjustment,
8976                                 Optional<unsigned> NumExpansions,
8977                                 bool ExpectParameterPack);
8978   bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
8979                       const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
8980                       const MultiLevelTemplateArgumentList &TemplateArgs,
8981                       SmallVectorImpl<QualType> &ParamTypes,
8982                       SmallVectorImpl<ParmVarDecl *> *OutParams,
8983                       ExtParameterInfoBuilder &ParamInfos);
8984   ExprResult SubstExpr(Expr *E,
8985                        const MultiLevelTemplateArgumentList &TemplateArgs);
8986 
8987   /// Substitute the given template arguments into a list of
8988   /// expressions, expanding pack expansions if required.
8989   ///
8990   /// \param Exprs The list of expressions to substitute into.
8991   ///
8992   /// \param IsCall Whether this is some form of call, in which case
8993   /// default arguments will be dropped.
8994   ///
8995   /// \param TemplateArgs The set of template arguments to substitute.
8996   ///
8997   /// \param Outputs Will receive all of the substituted arguments.
8998   ///
8999   /// \returns true if an error occurred, false otherwise.
9000   bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
9001                   const MultiLevelTemplateArgumentList &TemplateArgs,
9002                   SmallVectorImpl<Expr *> &Outputs);
9003 
9004   StmtResult SubstStmt(Stmt *S,
9005                        const MultiLevelTemplateArgumentList &TemplateArgs);
9006 
9007   TemplateParameterList *
9008   SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
9009                       const MultiLevelTemplateArgumentList &TemplateArgs);
9010 
9011   bool
9012   SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
9013                          const MultiLevelTemplateArgumentList &TemplateArgs,
9014                          TemplateArgumentListInfo &Outputs);
9015 
9016 
9017   Decl *SubstDecl(Decl *D, DeclContext *Owner,
9018                   const MultiLevelTemplateArgumentList &TemplateArgs);
9019 
9020   /// Substitute the name and return type of a defaulted 'operator<=>' to form
9021   /// an implicit 'operator=='.
9022   FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
9023                                            FunctionDecl *Spaceship);
9024 
9025   ExprResult SubstInitializer(Expr *E,
9026                        const MultiLevelTemplateArgumentList &TemplateArgs,
9027                        bool CXXDirectInit);
9028 
9029   bool
9030   SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
9031                       CXXRecordDecl *Pattern,
9032                       const MultiLevelTemplateArgumentList &TemplateArgs);
9033 
9034   bool
9035   InstantiateClass(SourceLocation PointOfInstantiation,
9036                    CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
9037                    const MultiLevelTemplateArgumentList &TemplateArgs,
9038                    TemplateSpecializationKind TSK,
9039                    bool Complain = true);
9040 
9041   bool InstantiateEnum(SourceLocation PointOfInstantiation,
9042                        EnumDecl *Instantiation, EnumDecl *Pattern,
9043                        const MultiLevelTemplateArgumentList &TemplateArgs,
9044                        TemplateSpecializationKind TSK);
9045 
9046   bool InstantiateInClassInitializer(
9047       SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
9048       FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
9049 
9050   struct LateInstantiatedAttribute {
9051     const Attr *TmplAttr;
9052     LocalInstantiationScope *Scope;
9053     Decl *NewDecl;
9054 
LateInstantiatedAttributeLateInstantiatedAttribute9055     LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
9056                               Decl *D)
9057       : TmplAttr(A), Scope(S), NewDecl(D)
9058     { }
9059   };
9060   typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
9061 
9062   void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
9063                         const Decl *Pattern, Decl *Inst,
9064                         LateInstantiatedAttrVec *LateAttrs = nullptr,
9065                         LocalInstantiationScope *OuterMostScope = nullptr);
9066 
9067   void
9068   InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
9069                           const Decl *Pattern, Decl *Inst,
9070                           LateInstantiatedAttrVec *LateAttrs = nullptr,
9071                           LocalInstantiationScope *OuterMostScope = nullptr);
9072 
9073   bool usesPartialOrExplicitSpecialization(
9074       SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
9075 
9076   bool
9077   InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
9078                            ClassTemplateSpecializationDecl *ClassTemplateSpec,
9079                            TemplateSpecializationKind TSK,
9080                            bool Complain = true);
9081 
9082   void InstantiateClassMembers(SourceLocation PointOfInstantiation,
9083                                CXXRecordDecl *Instantiation,
9084                             const MultiLevelTemplateArgumentList &TemplateArgs,
9085                                TemplateSpecializationKind TSK);
9086 
9087   void InstantiateClassTemplateSpecializationMembers(
9088                                           SourceLocation PointOfInstantiation,
9089                            ClassTemplateSpecializationDecl *ClassTemplateSpec,
9090                                                 TemplateSpecializationKind TSK);
9091 
9092   NestedNameSpecifierLoc
9093   SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
9094                            const MultiLevelTemplateArgumentList &TemplateArgs);
9095 
9096   DeclarationNameInfo
9097   SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
9098                            const MultiLevelTemplateArgumentList &TemplateArgs);
9099   TemplateName
9100   SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
9101                     SourceLocation Loc,
9102                     const MultiLevelTemplateArgumentList &TemplateArgs);
9103   bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
9104              TemplateArgumentListInfo &Result,
9105              const MultiLevelTemplateArgumentList &TemplateArgs);
9106 
9107   bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
9108                                   ParmVarDecl *Param);
9109   void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
9110                                 FunctionDecl *Function);
9111   bool CheckInstantiatedFunctionTemplateConstraints(
9112       SourceLocation PointOfInstantiation, FunctionDecl *Decl,
9113       ArrayRef<TemplateArgument> TemplateArgs,
9114       ConstraintSatisfaction &Satisfaction);
9115   FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
9116                                                const TemplateArgumentList *Args,
9117                                                SourceLocation Loc);
9118   void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
9119                                      FunctionDecl *Function,
9120                                      bool Recursive = false,
9121                                      bool DefinitionRequired = false,
9122                                      bool AtEndOfTU = false);
9123   VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
9124       VarTemplateDecl *VarTemplate, VarDecl *FromVar,
9125       const TemplateArgumentList &TemplateArgList,
9126       const TemplateArgumentListInfo &TemplateArgsInfo,
9127       SmallVectorImpl<TemplateArgument> &Converted,
9128       SourceLocation PointOfInstantiation, void *InsertPos,
9129       LateInstantiatedAttrVec *LateAttrs = nullptr,
9130       LocalInstantiationScope *StartingScope = nullptr);
9131   VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
9132       VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
9133       const MultiLevelTemplateArgumentList &TemplateArgs);
9134   void
9135   BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
9136                              const MultiLevelTemplateArgumentList &TemplateArgs,
9137                              LateInstantiatedAttrVec *LateAttrs,
9138                              DeclContext *Owner,
9139                              LocalInstantiationScope *StartingScope,
9140                              bool InstantiatingVarTemplate = false,
9141                              VarTemplateSpecializationDecl *PrevVTSD = nullptr);
9142 
9143   VarDecl *getVarTemplateSpecialization(
9144       VarTemplateDecl *VarTempl, const TemplateArgumentListInfo *TemplateArgs,
9145       const DeclarationNameInfo &MemberNameInfo, SourceLocation TemplateKWLoc);
9146 
9147   void InstantiateVariableInitializer(
9148       VarDecl *Var, VarDecl *OldVar,
9149       const MultiLevelTemplateArgumentList &TemplateArgs);
9150   void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
9151                                      VarDecl *Var, bool Recursive = false,
9152                                      bool DefinitionRequired = false,
9153                                      bool AtEndOfTU = false);
9154 
9155   void InstantiateMemInitializers(CXXConstructorDecl *New,
9156                                   const CXXConstructorDecl *Tmpl,
9157                             const MultiLevelTemplateArgumentList &TemplateArgs);
9158 
9159   NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
9160                           const MultiLevelTemplateArgumentList &TemplateArgs,
9161                           bool FindingInstantiatedContext = false);
9162   DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
9163                           const MultiLevelTemplateArgumentList &TemplateArgs);
9164 
9165   // Objective-C declarations.
9166   enum ObjCContainerKind {
9167     OCK_None = -1,
9168     OCK_Interface = 0,
9169     OCK_Protocol,
9170     OCK_Category,
9171     OCK_ClassExtension,
9172     OCK_Implementation,
9173     OCK_CategoryImplementation
9174   };
9175   ObjCContainerKind getObjCContainerKind() const;
9176 
9177   DeclResult actOnObjCTypeParam(Scope *S,
9178                                 ObjCTypeParamVariance variance,
9179                                 SourceLocation varianceLoc,
9180                                 unsigned index,
9181                                 IdentifierInfo *paramName,
9182                                 SourceLocation paramLoc,
9183                                 SourceLocation colonLoc,
9184                                 ParsedType typeBound);
9185 
9186   ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
9187                                             ArrayRef<Decl *> typeParams,
9188                                             SourceLocation rAngleLoc);
9189   void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
9190 
9191   Decl *ActOnStartClassInterface(
9192       Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
9193       SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
9194       IdentifierInfo *SuperName, SourceLocation SuperLoc,
9195       ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange,
9196       Decl *const *ProtoRefs, unsigned NumProtoRefs,
9197       const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
9198       const ParsedAttributesView &AttrList);
9199 
9200   void ActOnSuperClassOfClassInterface(Scope *S,
9201                                        SourceLocation AtInterfaceLoc,
9202                                        ObjCInterfaceDecl *IDecl,
9203                                        IdentifierInfo *ClassName,
9204                                        SourceLocation ClassLoc,
9205                                        IdentifierInfo *SuperName,
9206                                        SourceLocation SuperLoc,
9207                                        ArrayRef<ParsedType> SuperTypeArgs,
9208                                        SourceRange SuperTypeArgsRange);
9209 
9210   void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
9211                                SmallVectorImpl<SourceLocation> &ProtocolLocs,
9212                                IdentifierInfo *SuperName,
9213                                SourceLocation SuperLoc);
9214 
9215   Decl *ActOnCompatibilityAlias(
9216                     SourceLocation AtCompatibilityAliasLoc,
9217                     IdentifierInfo *AliasName,  SourceLocation AliasLocation,
9218                     IdentifierInfo *ClassName, SourceLocation ClassLocation);
9219 
9220   bool CheckForwardProtocolDeclarationForCircularDependency(
9221     IdentifierInfo *PName,
9222     SourceLocation &PLoc, SourceLocation PrevLoc,
9223     const ObjCList<ObjCProtocolDecl> &PList);
9224 
9225   Decl *ActOnStartProtocolInterface(
9226       SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
9227       SourceLocation ProtocolLoc, Decl *const *ProtoRefNames,
9228       unsigned NumProtoRefs, const SourceLocation *ProtoLocs,
9229       SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList);
9230 
9231   Decl *ActOnStartCategoryInterface(
9232       SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
9233       SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
9234       IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
9235       Decl *const *ProtoRefs, unsigned NumProtoRefs,
9236       const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
9237       const ParsedAttributesView &AttrList);
9238 
9239   Decl *ActOnStartClassImplementation(SourceLocation AtClassImplLoc,
9240                                       IdentifierInfo *ClassName,
9241                                       SourceLocation ClassLoc,
9242                                       IdentifierInfo *SuperClassname,
9243                                       SourceLocation SuperClassLoc,
9244                                       const ParsedAttributesView &AttrList);
9245 
9246   Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
9247                                          IdentifierInfo *ClassName,
9248                                          SourceLocation ClassLoc,
9249                                          IdentifierInfo *CatName,
9250                                          SourceLocation CatLoc,
9251                                          const ParsedAttributesView &AttrList);
9252 
9253   DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
9254                                                ArrayRef<Decl *> Decls);
9255 
9256   DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
9257                    IdentifierInfo **IdentList,
9258                    SourceLocation *IdentLocs,
9259                    ArrayRef<ObjCTypeParamList *> TypeParamLists,
9260                    unsigned NumElts);
9261 
9262   DeclGroupPtrTy
9263   ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
9264                                   ArrayRef<IdentifierLocPair> IdentList,
9265                                   const ParsedAttributesView &attrList);
9266 
9267   void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
9268                                ArrayRef<IdentifierLocPair> ProtocolId,
9269                                SmallVectorImpl<Decl *> &Protocols);
9270 
9271   void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
9272                                     SourceLocation ProtocolLoc,
9273                                     IdentifierInfo *TypeArgId,
9274                                     SourceLocation TypeArgLoc,
9275                                     bool SelectProtocolFirst = false);
9276 
9277   /// Given a list of identifiers (and their locations), resolve the
9278   /// names to either Objective-C protocol qualifiers or type
9279   /// arguments, as appropriate.
9280   void actOnObjCTypeArgsOrProtocolQualifiers(
9281          Scope *S,
9282          ParsedType baseType,
9283          SourceLocation lAngleLoc,
9284          ArrayRef<IdentifierInfo *> identifiers,
9285          ArrayRef<SourceLocation> identifierLocs,
9286          SourceLocation rAngleLoc,
9287          SourceLocation &typeArgsLAngleLoc,
9288          SmallVectorImpl<ParsedType> &typeArgs,
9289          SourceLocation &typeArgsRAngleLoc,
9290          SourceLocation &protocolLAngleLoc,
9291          SmallVectorImpl<Decl *> &protocols,
9292          SourceLocation &protocolRAngleLoc,
9293          bool warnOnIncompleteProtocols);
9294 
9295   /// Build a an Objective-C protocol-qualified 'id' type where no
9296   /// base type was specified.
9297   TypeResult actOnObjCProtocolQualifierType(
9298                SourceLocation lAngleLoc,
9299                ArrayRef<Decl *> protocols,
9300                ArrayRef<SourceLocation> protocolLocs,
9301                SourceLocation rAngleLoc);
9302 
9303   /// Build a specialized and/or protocol-qualified Objective-C type.
9304   TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
9305                Scope *S,
9306                SourceLocation Loc,
9307                ParsedType BaseType,
9308                SourceLocation TypeArgsLAngleLoc,
9309                ArrayRef<ParsedType> TypeArgs,
9310                SourceLocation TypeArgsRAngleLoc,
9311                SourceLocation ProtocolLAngleLoc,
9312                ArrayRef<Decl *> Protocols,
9313                ArrayRef<SourceLocation> ProtocolLocs,
9314                SourceLocation ProtocolRAngleLoc);
9315 
9316   /// Build an Objective-C type parameter type.
9317   QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
9318                                   SourceLocation ProtocolLAngleLoc,
9319                                   ArrayRef<ObjCProtocolDecl *> Protocols,
9320                                   ArrayRef<SourceLocation> ProtocolLocs,
9321                                   SourceLocation ProtocolRAngleLoc,
9322                                   bool FailOnError = false);
9323 
9324   /// Build an Objective-C object pointer type.
9325   QualType BuildObjCObjectType(QualType BaseType,
9326                                SourceLocation Loc,
9327                                SourceLocation TypeArgsLAngleLoc,
9328                                ArrayRef<TypeSourceInfo *> TypeArgs,
9329                                SourceLocation TypeArgsRAngleLoc,
9330                                SourceLocation ProtocolLAngleLoc,
9331                                ArrayRef<ObjCProtocolDecl *> Protocols,
9332                                ArrayRef<SourceLocation> ProtocolLocs,
9333                                SourceLocation ProtocolRAngleLoc,
9334                                bool FailOnError = false);
9335 
9336   /// Ensure attributes are consistent with type.
9337   /// \param [in, out] Attributes The attributes to check; they will
9338   /// be modified to be consistent with \p PropertyTy.
9339   void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
9340                                    SourceLocation Loc,
9341                                    unsigned &Attributes,
9342                                    bool propertyInPrimaryClass);
9343 
9344   /// Process the specified property declaration and create decls for the
9345   /// setters and getters as needed.
9346   /// \param property The property declaration being processed
9347   void ProcessPropertyDecl(ObjCPropertyDecl *property);
9348 
9349 
9350   void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
9351                                 ObjCPropertyDecl *SuperProperty,
9352                                 const IdentifierInfo *Name,
9353                                 bool OverridingProtocolProperty);
9354 
9355   void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
9356                                         ObjCInterfaceDecl *ID);
9357 
9358   Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
9359                    ArrayRef<Decl *> allMethods = None,
9360                    ArrayRef<DeclGroupPtrTy> allTUVars = None);
9361 
9362   Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
9363                       SourceLocation LParenLoc,
9364                       FieldDeclarator &FD, ObjCDeclSpec &ODS,
9365                       Selector GetterSel, Selector SetterSel,
9366                       tok::ObjCKeywordKind MethodImplKind,
9367                       DeclContext *lexicalDC = nullptr);
9368 
9369   Decl *ActOnPropertyImplDecl(Scope *S,
9370                               SourceLocation AtLoc,
9371                               SourceLocation PropertyLoc,
9372                               bool ImplKind,
9373                               IdentifierInfo *PropertyId,
9374                               IdentifierInfo *PropertyIvar,
9375                               SourceLocation PropertyIvarLoc,
9376                               ObjCPropertyQueryKind QueryKind);
9377 
9378   enum ObjCSpecialMethodKind {
9379     OSMK_None,
9380     OSMK_Alloc,
9381     OSMK_New,
9382     OSMK_Copy,
9383     OSMK_RetainingInit,
9384     OSMK_NonRetainingInit
9385   };
9386 
9387   struct ObjCArgInfo {
9388     IdentifierInfo *Name;
9389     SourceLocation NameLoc;
9390     // The Type is null if no type was specified, and the DeclSpec is invalid
9391     // in this case.
9392     ParsedType Type;
9393     ObjCDeclSpec DeclSpec;
9394 
9395     /// ArgAttrs - Attribute list for this argument.
9396     ParsedAttributesView ArgAttrs;
9397   };
9398 
9399   Decl *ActOnMethodDeclaration(
9400       Scope *S,
9401       SourceLocation BeginLoc, // location of the + or -.
9402       SourceLocation EndLoc,   // location of the ; or {.
9403       tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
9404       ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
9405       // optional arguments. The number of types/arguments is obtained
9406       // from the Sel.getNumArgs().
9407       ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
9408       unsigned CNumArgs, // c-style args
9409       const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind,
9410       bool isVariadic, bool MethodDefinition);
9411 
9412   ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
9413                                               const ObjCObjectPointerType *OPT,
9414                                               bool IsInstance);
9415   ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
9416                                            bool IsInstance);
9417 
9418   bool CheckARCMethodDecl(ObjCMethodDecl *method);
9419   bool inferObjCARCLifetime(ValueDecl *decl);
9420 
9421   void deduceOpenCLAddressSpace(ValueDecl *decl);
9422 
9423   ExprResult
9424   HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
9425                             Expr *BaseExpr,
9426                             SourceLocation OpLoc,
9427                             DeclarationName MemberName,
9428                             SourceLocation MemberLoc,
9429                             SourceLocation SuperLoc, QualType SuperType,
9430                             bool Super);
9431 
9432   ExprResult
9433   ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
9434                             IdentifierInfo &propertyName,
9435                             SourceLocation receiverNameLoc,
9436                             SourceLocation propertyNameLoc);
9437 
9438   ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
9439 
9440   /// Describes the kind of message expression indicated by a message
9441   /// send that starts with an identifier.
9442   enum ObjCMessageKind {
9443     /// The message is sent to 'super'.
9444     ObjCSuperMessage,
9445     /// The message is an instance message.
9446     ObjCInstanceMessage,
9447     /// The message is a class message, and the identifier is a type
9448     /// name.
9449     ObjCClassMessage
9450   };
9451 
9452   ObjCMessageKind getObjCMessageKind(Scope *S,
9453                                      IdentifierInfo *Name,
9454                                      SourceLocation NameLoc,
9455                                      bool IsSuper,
9456                                      bool HasTrailingDot,
9457                                      ParsedType &ReceiverType);
9458 
9459   ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
9460                                Selector Sel,
9461                                SourceLocation LBracLoc,
9462                                ArrayRef<SourceLocation> SelectorLocs,
9463                                SourceLocation RBracLoc,
9464                                MultiExprArg Args);
9465 
9466   ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
9467                                QualType ReceiverType,
9468                                SourceLocation SuperLoc,
9469                                Selector Sel,
9470                                ObjCMethodDecl *Method,
9471                                SourceLocation LBracLoc,
9472                                ArrayRef<SourceLocation> SelectorLocs,
9473                                SourceLocation RBracLoc,
9474                                MultiExprArg Args,
9475                                bool isImplicit = false);
9476 
9477   ExprResult BuildClassMessageImplicit(QualType ReceiverType,
9478                                        bool isSuperReceiver,
9479                                        SourceLocation Loc,
9480                                        Selector Sel,
9481                                        ObjCMethodDecl *Method,
9482                                        MultiExprArg Args);
9483 
9484   ExprResult ActOnClassMessage(Scope *S,
9485                                ParsedType Receiver,
9486                                Selector Sel,
9487                                SourceLocation LBracLoc,
9488                                ArrayRef<SourceLocation> SelectorLocs,
9489                                SourceLocation RBracLoc,
9490                                MultiExprArg Args);
9491 
9492   ExprResult BuildInstanceMessage(Expr *Receiver,
9493                                   QualType ReceiverType,
9494                                   SourceLocation SuperLoc,
9495                                   Selector Sel,
9496                                   ObjCMethodDecl *Method,
9497                                   SourceLocation LBracLoc,
9498                                   ArrayRef<SourceLocation> SelectorLocs,
9499                                   SourceLocation RBracLoc,
9500                                   MultiExprArg Args,
9501                                   bool isImplicit = false);
9502 
9503   ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
9504                                           QualType ReceiverType,
9505                                           SourceLocation Loc,
9506                                           Selector Sel,
9507                                           ObjCMethodDecl *Method,
9508                                           MultiExprArg Args);
9509 
9510   ExprResult ActOnInstanceMessage(Scope *S,
9511                                   Expr *Receiver,
9512                                   Selector Sel,
9513                                   SourceLocation LBracLoc,
9514                                   ArrayRef<SourceLocation> SelectorLocs,
9515                                   SourceLocation RBracLoc,
9516                                   MultiExprArg Args);
9517 
9518   ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
9519                                   ObjCBridgeCastKind Kind,
9520                                   SourceLocation BridgeKeywordLoc,
9521                                   TypeSourceInfo *TSInfo,
9522                                   Expr *SubExpr);
9523 
9524   ExprResult ActOnObjCBridgedCast(Scope *S,
9525                                   SourceLocation LParenLoc,
9526                                   ObjCBridgeCastKind Kind,
9527                                   SourceLocation BridgeKeywordLoc,
9528                                   ParsedType Type,
9529                                   SourceLocation RParenLoc,
9530                                   Expr *SubExpr);
9531 
9532   void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
9533 
9534   void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
9535 
9536   bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
9537                                      CastKind &Kind);
9538 
9539   bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
9540                                         QualType DestType, QualType SrcType,
9541                                         ObjCInterfaceDecl *&RelatedClass,
9542                                         ObjCMethodDecl *&ClassMethod,
9543                                         ObjCMethodDecl *&InstanceMethod,
9544                                         TypedefNameDecl *&TDNDecl,
9545                                         bool CfToNs, bool Diagnose = true);
9546 
9547   bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
9548                                          QualType DestType, QualType SrcType,
9549                                          Expr *&SrcExpr, bool Diagnose = true);
9550 
9551   bool CheckConversionToObjCLiteral(QualType DstType, Expr *&SrcExpr,
9552                                     bool Diagnose = true);
9553 
9554   bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
9555 
9556   /// Check whether the given new method is a valid override of the
9557   /// given overridden method, and set any properties that should be inherited.
9558   void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
9559                                const ObjCMethodDecl *Overridden);
9560 
9561   /// Describes the compatibility of a result type with its method.
9562   enum ResultTypeCompatibilityKind {
9563     RTC_Compatible,
9564     RTC_Incompatible,
9565     RTC_Unknown
9566   };
9567 
9568   void CheckObjCMethodDirectOverrides(ObjCMethodDecl *method,
9569                                       ObjCMethodDecl *overridden);
9570 
9571   void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
9572                                 ObjCInterfaceDecl *CurrentClass,
9573                                 ResultTypeCompatibilityKind RTC);
9574 
9575   enum PragmaOptionsAlignKind {
9576     POAK_Native,  // #pragma options align=native
9577     POAK_Natural, // #pragma options align=natural
9578     POAK_Packed,  // #pragma options align=packed
9579     POAK_Power,   // #pragma options align=power
9580     POAK_Mac68k,  // #pragma options align=mac68k
9581     POAK_Reset    // #pragma options align=reset
9582   };
9583 
9584   /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
9585   void ActOnPragmaClangSection(SourceLocation PragmaLoc,
9586                                PragmaClangSectionAction Action,
9587                                PragmaClangSectionKind SecKind, StringRef SecName);
9588 
9589   /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
9590   void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
9591                                SourceLocation PragmaLoc);
9592 
9593   /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
9594   void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
9595                        StringRef SlotLabel, Expr *Alignment);
9596 
9597   enum class PragmaPackDiagnoseKind {
9598     NonDefaultStateAtInclude,
9599     ChangedStateAtExit
9600   };
9601 
9602   void DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind,
9603                                     SourceLocation IncludeLoc);
9604   void DiagnoseUnterminatedPragmaPack();
9605 
9606   /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
9607   void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
9608 
9609   /// ActOnPragmaMSComment - Called on well formed
9610   /// \#pragma comment(kind, "arg").
9611   void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
9612                             StringRef Arg);
9613 
9614   /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
9615   /// pointers_to_members(representation method[, general purpose
9616   /// representation]).
9617   void ActOnPragmaMSPointersToMembers(
9618       LangOptions::PragmaMSPointersToMembersKind Kind,
9619       SourceLocation PragmaLoc);
9620 
9621   /// Called on well formed \#pragma vtordisp().
9622   void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
9623                              SourceLocation PragmaLoc,
9624                              MSVtorDispMode Value);
9625 
9626   enum PragmaSectionKind {
9627     PSK_DataSeg,
9628     PSK_BSSSeg,
9629     PSK_ConstSeg,
9630     PSK_CodeSeg,
9631   };
9632 
9633   bool UnifySection(StringRef SectionName,
9634                     int SectionFlags,
9635                     DeclaratorDecl *TheDecl);
9636   bool UnifySection(StringRef SectionName,
9637                     int SectionFlags,
9638                     SourceLocation PragmaSectionLocation);
9639 
9640   /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
9641   void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
9642                         PragmaMsStackAction Action,
9643                         llvm::StringRef StackSlotLabel,
9644                         StringLiteral *SegmentName,
9645                         llvm::StringRef PragmaName);
9646 
9647   /// Called on well formed \#pragma section().
9648   void ActOnPragmaMSSection(SourceLocation PragmaLocation,
9649                             int SectionFlags, StringLiteral *SegmentName);
9650 
9651   /// Called on well-formed \#pragma init_seg().
9652   void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
9653                             StringLiteral *SegmentName);
9654 
9655   /// Called on #pragma clang __debug dump II
9656   void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
9657 
9658   /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
9659   void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
9660                                  StringRef Value);
9661 
9662   /// Are precise floating point semantics currently enabled?
isPreciseFPEnabled()9663   bool isPreciseFPEnabled() {
9664     return !CurFPFeatures.getAllowFPReassociate() &&
9665            !CurFPFeatures.getNoSignedZero() &&
9666            !CurFPFeatures.getAllowReciprocal() &&
9667            !CurFPFeatures.getAllowApproxFunc();
9668   }
9669 
9670   /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control
9671   void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action,
9672                                PragmaFloatControlKind Value);
9673 
9674   /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
9675   void ActOnPragmaUnused(const Token &Identifier,
9676                          Scope *curScope,
9677                          SourceLocation PragmaLoc);
9678 
9679   /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
9680   void ActOnPragmaVisibility(const IdentifierInfo* VisType,
9681                              SourceLocation PragmaLoc);
9682 
9683   NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
9684                                  SourceLocation Loc);
9685   void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
9686 
9687   /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
9688   void ActOnPragmaWeakID(IdentifierInfo* WeakName,
9689                          SourceLocation PragmaLoc,
9690                          SourceLocation WeakNameLoc);
9691 
9692   /// ActOnPragmaRedefineExtname - Called on well formed
9693   /// \#pragma redefine_extname oldname newname.
9694   void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
9695                                   IdentifierInfo* AliasName,
9696                                   SourceLocation PragmaLoc,
9697                                   SourceLocation WeakNameLoc,
9698                                   SourceLocation AliasNameLoc);
9699 
9700   /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
9701   void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
9702                             IdentifierInfo* AliasName,
9703                             SourceLocation PragmaLoc,
9704                             SourceLocation WeakNameLoc,
9705                             SourceLocation AliasNameLoc);
9706 
9707   /// ActOnPragmaFPContract - Called on well formed
9708   /// \#pragma {STDC,OPENCL} FP_CONTRACT and
9709   /// \#pragma clang fp contract
9710   void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC);
9711 
9712   /// Called on well formed
9713   /// \#pragma clang fp reassociate
9714   void ActOnPragmaFPReassociate(SourceLocation Loc, bool IsEnabled);
9715 
9716   /// ActOnPragmaFenvAccess - Called on well formed
9717   /// \#pragma STDC FENV_ACCESS
9718   void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled);
9719 
9720   /// Called to set rounding mode for floating point operations.
9721   void setRoundingMode(SourceLocation Loc, llvm::RoundingMode);
9722 
9723   /// Called to set exception behavior for floating point operations.
9724   void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind);
9725 
9726   /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
9727   /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
9728   void AddAlignmentAttributesForRecord(RecordDecl *RD);
9729 
9730   /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
9731   void AddMsStructLayoutForRecord(RecordDecl *RD);
9732 
9733   /// FreePackedContext - Deallocate and null out PackContext.
9734   void FreePackedContext();
9735 
9736   /// PushNamespaceVisibilityAttr - Note that we've entered a
9737   /// namespace with a visibility attribute.
9738   void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
9739                                    SourceLocation Loc);
9740 
9741   /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
9742   /// add an appropriate visibility attribute.
9743   void AddPushedVisibilityAttribute(Decl *RD);
9744 
9745   /// PopPragmaVisibility - Pop the top element of the visibility stack; used
9746   /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
9747   void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
9748 
9749   /// FreeVisContext - Deallocate and null out VisContext.
9750   void FreeVisContext();
9751 
9752   /// AddCFAuditedAttribute - Check whether we're currently within
9753   /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
9754   /// the appropriate attribute.
9755   void AddCFAuditedAttribute(Decl *D);
9756 
9757   void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute,
9758                                      SourceLocation PragmaLoc,
9759                                      attr::ParsedSubjectMatchRuleSet Rules);
9760   void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
9761                                      const IdentifierInfo *Namespace);
9762 
9763   /// Called on well-formed '\#pragma clang attribute pop'.
9764   void ActOnPragmaAttributePop(SourceLocation PragmaLoc,
9765                                const IdentifierInfo *Namespace);
9766 
9767   /// Adds the attributes that have been specified using the
9768   /// '\#pragma clang attribute push' directives to the given declaration.
9769   void AddPragmaAttributes(Scope *S, Decl *D);
9770 
9771   void DiagnoseUnterminatedPragmaAttribute();
9772 
9773   /// Called on well formed \#pragma clang optimize.
9774   void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
9775 
9776   /// Get the location for the currently active "\#pragma clang optimize
9777   /// off". If this location is invalid, then the state of the pragma is "on".
getOptimizeOffPragmaLocation()9778   SourceLocation getOptimizeOffPragmaLocation() const {
9779     return OptimizeOffPragmaLocation;
9780   }
9781 
9782   /// Only called on function definitions; if there is a pragma in scope
9783   /// with the effect of a range-based optnone, consider marking the function
9784   /// with attribute optnone.
9785   void AddRangeBasedOptnone(FunctionDecl *FD);
9786 
9787   /// Adds the 'optnone' attribute to the function declaration if there
9788   /// are no conflicts; Loc represents the location causing the 'optnone'
9789   /// attribute to be added (usually because of a pragma).
9790   void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
9791 
9792   /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
9793   void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
9794                       bool IsPackExpansion);
9795   void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T,
9796                       bool IsPackExpansion);
9797 
9798   /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
9799   /// declaration.
9800   void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
9801                             Expr *OE);
9802 
9803   /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
9804   /// declaration.
9805   void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
9806                          Expr *ParamExpr);
9807 
9808   /// AddAlignValueAttr - Adds an align_value attribute to a particular
9809   /// declaration.
9810   void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
9811 
9812   /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
9813   /// declaration.
9814   void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
9815                            Expr *MaxThreads, Expr *MinBlocks);
9816 
9817   /// AddModeAttr - Adds a mode attribute to a particular declaration.
9818   void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name,
9819                    bool InInstantiation = false);
9820 
9821   void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI,
9822                            ParameterABI ABI);
9823 
9824   enum class RetainOwnershipKind {NS, CF, OS};
9825   void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI,
9826                         RetainOwnershipKind K, bool IsTemplateInstantiation);
9827 
9828   /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size
9829   /// attribute to a particular declaration.
9830   void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI,
9831                                       Expr *Min, Expr *Max);
9832 
9833   /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a
9834   /// particular declaration.
9835   void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI,
9836                                Expr *Min, Expr *Max);
9837 
9838   bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type);
9839 
9840   //===--------------------------------------------------------------------===//
9841   // C++ Coroutines TS
9842   //
9843   bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
9844                                StringRef Keyword);
9845   ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
9846   ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
9847   StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
9848 
9849   ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
9850                                       bool IsImplicit = false);
9851   ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
9852                                         UnresolvedLookupExpr* Lookup);
9853   ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
9854   StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
9855                                bool IsImplicit = false);
9856   StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
9857   bool buildCoroutineParameterMoves(SourceLocation Loc);
9858   VarDecl *buildCoroutinePromise(SourceLocation Loc);
9859   void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
9860   ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
9861                                            SourceLocation FuncLoc);
9862   /// Check that the expression co_await promise.final_suspend() shall not be
9863   /// potentially-throwing.
9864   bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend);
9865 
9866   //===--------------------------------------------------------------------===//
9867   // OpenCL extensions.
9868   //
9869 private:
9870   std::string CurrOpenCLExtension;
9871   /// Extensions required by an OpenCL type.
9872   llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap;
9873   /// Extensions required by an OpenCL declaration.
9874   llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap;
9875 public:
getCurrentOpenCLExtension()9876   llvm::StringRef getCurrentOpenCLExtension() const {
9877     return CurrOpenCLExtension;
9878   }
9879 
9880   /// Check if a function declaration \p FD associates with any
9881   /// extensions present in OpenCLDeclExtMap and if so return the
9882   /// extension(s) name(s).
9883   std::string getOpenCLExtensionsFromDeclExtMap(FunctionDecl *FD);
9884 
9885   /// Check if a function type \p FT associates with any
9886   /// extensions present in OpenCLTypeExtMap and if so return the
9887   /// extension(s) name(s).
9888   std::string getOpenCLExtensionsFromTypeExtMap(FunctionType *FT);
9889 
9890   /// Find an extension in an appropriate extension map and return its name
9891   template<typename T, typename MapT>
9892   std::string getOpenCLExtensionsFromExtMap(T* FT, MapT &Map);
9893 
setCurrentOpenCLExtension(llvm::StringRef Ext)9894   void setCurrentOpenCLExtension(llvm::StringRef Ext) {
9895     CurrOpenCLExtension = std::string(Ext);
9896   }
9897 
9898   /// Set OpenCL extensions for a type which can only be used when these
9899   /// OpenCL extensions are enabled. If \p Exts is empty, do nothing.
9900   /// \param Exts A space separated list of OpenCL extensions.
9901   void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts);
9902 
9903   /// Set OpenCL extensions for a declaration which can only be
9904   /// used when these OpenCL extensions are enabled. If \p Exts is empty, do
9905   /// nothing.
9906   /// \param Exts A space separated list of OpenCL extensions.
9907   void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts);
9908 
9909   /// Set current OpenCL extensions for a type which can only be used
9910   /// when these OpenCL extensions are enabled. If current OpenCL extension is
9911   /// empty, do nothing.
9912   void setCurrentOpenCLExtensionForType(QualType T);
9913 
9914   /// Set current OpenCL extensions for a declaration which
9915   /// can only be used when these OpenCL extensions are enabled. If current
9916   /// OpenCL extension is empty, do nothing.
9917   void setCurrentOpenCLExtensionForDecl(Decl *FD);
9918 
9919   bool isOpenCLDisabledDecl(Decl *FD);
9920 
9921   /// Check if type \p T corresponding to declaration specifier \p DS
9922   /// is disabled due to required OpenCL extensions being disabled. If so,
9923   /// emit diagnostics.
9924   /// \return true if type is disabled.
9925   bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T);
9926 
9927   /// Check if declaration \p D used by expression \p E
9928   /// is disabled due to required OpenCL extensions being disabled. If so,
9929   /// emit diagnostics.
9930   /// \return true if type is disabled.
9931   bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E);
9932 
9933   //===--------------------------------------------------------------------===//
9934   // OpenMP directives and clauses.
9935   //
9936 private:
9937   void *VarDataSharingAttributesStack;
9938   /// Number of nested '#pragma omp declare target' directives.
9939   unsigned DeclareTargetNestingLevel = 0;
9940   /// Initialization of data-sharing attributes stack.
9941   void InitDataSharingAttributesStack();
9942   void DestroyDataSharingAttributesStack();
9943   ExprResult
9944   VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
9945                                         bool StrictlyPositive = true);
9946   /// Returns OpenMP nesting level for current directive.
9947   unsigned getOpenMPNestingLevel() const;
9948 
9949   /// Adjusts the function scopes index for the target-based regions.
9950   void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
9951                                     unsigned Level) const;
9952 
9953   /// Returns the number of scopes associated with the construct on the given
9954   /// OpenMP level.
9955   int getNumberOfConstructScopes(unsigned Level) const;
9956 
9957   /// Push new OpenMP function region for non-capturing function.
9958   void pushOpenMPFunctionRegion();
9959 
9960   /// Pop OpenMP function region for non-capturing function.
9961   void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI);
9962 
9963   /// Checks if a type or a declaration is disabled due to the owning extension
9964   /// being disabled, and emits diagnostic messages if it is disabled.
9965   /// \param D type or declaration to be checked.
9966   /// \param DiagLoc source location for the diagnostic message.
9967   /// \param DiagInfo information to be emitted for the diagnostic message.
9968   /// \param SrcRange source range of the declaration.
9969   /// \param Map maps type or declaration to the extensions.
9970   /// \param Selector selects diagnostic message: 0 for type and 1 for
9971   ///        declaration.
9972   /// \return true if the type or declaration is disabled.
9973   template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
9974   bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo,
9975                                      MapT &Map, unsigned Selector = 0,
9976                                      SourceRange SrcRange = SourceRange());
9977 
9978   /// Helper to keep information about the current `omp begin/end declare
9979   /// variant` nesting.
9980   struct OMPDeclareVariantScope {
9981     /// The associated OpenMP context selector.
9982     OMPTraitInfo *TI;
9983 
9984     /// The associated OpenMP context selector mangling.
9985     std::string NameSuffix;
9986 
9987     OMPDeclareVariantScope(OMPTraitInfo &TI);
9988   };
9989 
9990   /// The current `omp begin/end declare variant` scopes.
9991   SmallVector<OMPDeclareVariantScope, 4> OMPDeclareVariantScopes;
9992 
9993   /// The declarator \p D defines a function in the scope \p S which is nested
9994   /// in an `omp begin/end declare variant` scope. In this method we create a
9995   /// declaration for \p D and rename \p D according to the OpenMP context
9996   /// selector of the surrounding scope.
9997   FunctionDecl *
9998   ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(Scope *S,
9999                                                             Declarator &D);
10000 
10001   /// Register \p FD as specialization of \p BaseFD in the current `omp
10002   /// begin/end declare variant` scope.
10003   void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
10004       FunctionDecl *FD, FunctionDecl *BaseFD);
10005 
10006 public:
10007 
10008   /// Can we exit a scope at the moment.
isInOpenMPDeclareVariantScope()10009   bool isInOpenMPDeclareVariantScope() {
10010     return !OMPDeclareVariantScopes.empty();
10011   }
10012 
10013   /// Given the potential call expression \p Call, determine if there is a
10014   /// specialization via the OpenMP declare variant mechanism available. If
10015   /// there is, return the specialized call expression, otherwise return the
10016   /// original \p Call.
10017   ExprResult ActOnOpenMPCall(ExprResult Call, Scope *Scope,
10018                              SourceLocation LParenLoc, MultiExprArg ArgExprs,
10019                              SourceLocation RParenLoc, Expr *ExecConfig);
10020 
10021   /// Handle a `omp begin declare variant`.
10022   void ActOnOpenMPBeginDeclareVariant(SourceLocation Loc, OMPTraitInfo &TI);
10023 
10024   /// Handle a `omp end declare variant`.
10025   void ActOnOpenMPEndDeclareVariant();
10026 
10027   /// Checks if the variant/multiversion functions are compatible.
10028   bool areMultiversionVariantFunctionsCompatible(
10029       const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10030       const PartialDiagnostic &NoProtoDiagID,
10031       const PartialDiagnosticAt &NoteCausedDiagIDAt,
10032       const PartialDiagnosticAt &NoSupportDiagIDAt,
10033       const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10034       bool ConstexprSupported, bool CLinkageMayDiffer);
10035 
10036   /// Function tries to capture lambda's captured variables in the OpenMP region
10037   /// before the original lambda is captured.
10038   void tryCaptureOpenMPLambdas(ValueDecl *V);
10039 
10040   /// Return true if the provided declaration \a VD should be captured by
10041   /// reference.
10042   /// \param Level Relative level of nested OpenMP construct for that the check
10043   /// is performed.
10044   /// \param OpenMPCaptureLevel Capture level within an OpenMP construct.
10045   bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
10046                              unsigned OpenMPCaptureLevel) const;
10047 
10048   /// Check if the specified variable is used in one of the private
10049   /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
10050   /// constructs.
10051   VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false,
10052                                 unsigned StopAt = 0);
10053   ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
10054                                    ExprObjectKind OK, SourceLocation Loc);
10055 
10056   /// If the current region is a loop-based region, mark the start of the loop
10057   /// construct.
10058   void startOpenMPLoop();
10059 
10060   /// If the current region is a range loop-based region, mark the start of the
10061   /// loop construct.
10062   void startOpenMPCXXRangeFor();
10063 
10064   /// Check if the specified variable is used in 'private' clause.
10065   /// \param Level Relative level of nested OpenMP construct for that the check
10066   /// is performed.
10067   OpenMPClauseKind isOpenMPPrivateDecl(ValueDecl *D, unsigned Level,
10068                                        unsigned CapLevel) const;
10069 
10070   /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.)
10071   /// for \p FD based on DSA for the provided corresponding captured declaration
10072   /// \p D.
10073   void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level);
10074 
10075   /// Check if the specified variable is captured  by 'target' directive.
10076   /// \param Level Relative level of nested OpenMP construct for that the check
10077   /// is performed.
10078   bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level,
10079                                   unsigned CaptureLevel) const;
10080 
10081   /// Check if the specified global variable must be captured  by outer capture
10082   /// regions.
10083   /// \param Level Relative level of nested OpenMP construct for that
10084   /// the check is performed.
10085   bool isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level,
10086                                   unsigned CaptureLevel) const;
10087 
10088   ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
10089                                                     Expr *Op);
10090   /// Called on start of new data sharing attribute block.
10091   void StartOpenMPDSABlock(OpenMPDirectiveKind K,
10092                            const DeclarationNameInfo &DirName, Scope *CurScope,
10093                            SourceLocation Loc);
10094   /// Start analysis of clauses.
10095   void StartOpenMPClause(OpenMPClauseKind K);
10096   /// End analysis of clauses.
10097   void EndOpenMPClause();
10098   /// Called on end of data sharing attribute block.
10099   void EndOpenMPDSABlock(Stmt *CurDirective);
10100 
10101   /// Check if the current region is an OpenMP loop region and if it is,
10102   /// mark loop control variable, used in \p Init for loop initialization, as
10103   /// private by default.
10104   /// \param Init First part of the for loop.
10105   void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
10106 
10107   // OpenMP directives and clauses.
10108   /// Called on correct id-expression from the '#pragma omp
10109   /// threadprivate'.
10110   ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec,
10111                                      const DeclarationNameInfo &Id,
10112                                      OpenMPDirectiveKind Kind);
10113   /// Called on well-formed '#pragma omp threadprivate'.
10114   DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
10115                                      SourceLocation Loc,
10116                                      ArrayRef<Expr *> VarList);
10117   /// Builds a new OpenMPThreadPrivateDecl and checks its correctness.
10118   OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc,
10119                                                   ArrayRef<Expr *> VarList);
10120   /// Called on well-formed '#pragma omp allocate'.
10121   DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc,
10122                                               ArrayRef<Expr *> VarList,
10123                                               ArrayRef<OMPClause *> Clauses,
10124                                               DeclContext *Owner = nullptr);
10125   /// Called on well-formed '#pragma omp requires'.
10126   DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc,
10127                                               ArrayRef<OMPClause *> ClauseList);
10128   /// Check restrictions on Requires directive
10129   OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc,
10130                                         ArrayRef<OMPClause *> Clauses);
10131   /// Check if the specified type is allowed to be used in 'omp declare
10132   /// reduction' construct.
10133   QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
10134                                            TypeResult ParsedType);
10135   /// Called on start of '#pragma omp declare reduction'.
10136   DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
10137       Scope *S, DeclContext *DC, DeclarationName Name,
10138       ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10139       AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
10140   /// Initialize declare reduction construct initializer.
10141   void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
10142   /// Finish current declare reduction construct initializer.
10143   void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
10144   /// Initialize declare reduction construct initializer.
10145   /// \return omp_priv variable.
10146   VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
10147   /// Finish current declare reduction construct initializer.
10148   void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
10149                                                  VarDecl *OmpPrivParm);
10150   /// Called at the end of '#pragma omp declare reduction'.
10151   DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
10152       Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
10153 
10154   /// Check variable declaration in 'omp declare mapper' construct.
10155   TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D);
10156   /// Check if the specified type is allowed to be used in 'omp declare
10157   /// mapper' construct.
10158   QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
10159                                         TypeResult ParsedType);
10160   /// Called on start of '#pragma omp declare mapper'.
10161   OMPDeclareMapperDecl *ActOnOpenMPDeclareMapperDirectiveStart(
10162       Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
10163       SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
10164       Decl *PrevDeclInScope = nullptr);
10165   /// Build the mapper variable of '#pragma omp declare mapper'.
10166   void ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
10167                                                 Scope *S, QualType MapperType,
10168                                                 SourceLocation StartLoc,
10169                                                 DeclarationName VN);
10170   /// Called at the end of '#pragma omp declare mapper'.
10171   DeclGroupPtrTy
10172   ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
10173                                        ArrayRef<OMPClause *> ClauseList);
10174 
10175   /// Called on the start of target region i.e. '#pragma omp declare target'.
10176   bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc);
10177   /// Called at the end of target region i.e. '#pragme omp end declare target'.
10178   void ActOnFinishOpenMPDeclareTargetDirective();
10179   /// Searches for the provided declaration name for OpenMP declare target
10180   /// directive.
10181   NamedDecl *
10182   lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
10183                                 const DeclarationNameInfo &Id,
10184                                 NamedDeclSetType &SameDirectiveDecls);
10185   /// Called on correct id-expression from the '#pragma omp declare target'.
10186   void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc,
10187                                     OMPDeclareTargetDeclAttr::MapTypeTy MT,
10188                                     OMPDeclareTargetDeclAttr::DevTypeTy DT);
10189   /// Check declaration inside target region.
10190   void
10191   checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
10192                                    SourceLocation IdLoc = SourceLocation());
10193   /// Finishes analysis of the deferred functions calls that may be declared as
10194   /// host/nohost during device/host compilation.
10195   void finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller,
10196                                      const FunctionDecl *Callee,
10197                                      SourceLocation Loc);
10198   /// Return true inside OpenMP declare target region.
isInOpenMPDeclareTargetContext()10199   bool isInOpenMPDeclareTargetContext() const {
10200     return DeclareTargetNestingLevel > 0;
10201   }
10202   /// Return true inside OpenMP target region.
10203   bool isInOpenMPTargetExecutionDirective() const;
10204 
10205   /// Return the number of captured regions created for an OpenMP directive.
10206   static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
10207 
10208   /// Initialization of captured region for OpenMP region.
10209   void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
10210   /// End of OpenMP region.
10211   ///
10212   /// \param S Statement associated with the current OpenMP region.
10213   /// \param Clauses List of clauses for the current OpenMP region.
10214   ///
10215   /// \returns Statement for finished OpenMP region.
10216   StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
10217   StmtResult ActOnOpenMPExecutableDirective(
10218       OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
10219       OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
10220       Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
10221   /// Called on well-formed '\#pragma omp parallel' after parsing
10222   /// of the  associated statement.
10223   StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
10224                                           Stmt *AStmt,
10225                                           SourceLocation StartLoc,
10226                                           SourceLocation EndLoc);
10227   using VarsWithInheritedDSAType =
10228       llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>;
10229   /// Called on well-formed '\#pragma omp simd' after parsing
10230   /// of the associated statement.
10231   StmtResult
10232   ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10233                            SourceLocation StartLoc, SourceLocation EndLoc,
10234                            VarsWithInheritedDSAType &VarsWithImplicitDSA);
10235   /// Called on well-formed '\#pragma omp for' after parsing
10236   /// of the associated statement.
10237   StmtResult
10238   ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10239                           SourceLocation StartLoc, SourceLocation EndLoc,
10240                           VarsWithInheritedDSAType &VarsWithImplicitDSA);
10241   /// Called on well-formed '\#pragma omp for simd' after parsing
10242   /// of the associated statement.
10243   StmtResult
10244   ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10245                               SourceLocation StartLoc, SourceLocation EndLoc,
10246                               VarsWithInheritedDSAType &VarsWithImplicitDSA);
10247   /// Called on well-formed '\#pragma omp sections' after parsing
10248   /// of the associated statement.
10249   StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
10250                                           Stmt *AStmt, SourceLocation StartLoc,
10251                                           SourceLocation EndLoc);
10252   /// Called on well-formed '\#pragma omp section' after parsing of the
10253   /// associated statement.
10254   StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
10255                                          SourceLocation EndLoc);
10256   /// Called on well-formed '\#pragma omp single' after parsing of the
10257   /// associated statement.
10258   StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
10259                                         Stmt *AStmt, SourceLocation StartLoc,
10260                                         SourceLocation EndLoc);
10261   /// Called on well-formed '\#pragma omp master' after parsing of the
10262   /// associated statement.
10263   StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
10264                                         SourceLocation EndLoc);
10265   /// Called on well-formed '\#pragma omp critical' after parsing of the
10266   /// associated statement.
10267   StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
10268                                           ArrayRef<OMPClause *> Clauses,
10269                                           Stmt *AStmt, SourceLocation StartLoc,
10270                                           SourceLocation EndLoc);
10271   /// Called on well-formed '\#pragma omp parallel for' after parsing
10272   /// of the  associated statement.
10273   StmtResult ActOnOpenMPParallelForDirective(
10274       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10275       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10276   /// Called on well-formed '\#pragma omp parallel for simd' after
10277   /// parsing of the  associated statement.
10278   StmtResult ActOnOpenMPParallelForSimdDirective(
10279       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10280       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10281   /// Called on well-formed '\#pragma omp parallel master' after
10282   /// parsing of the  associated statement.
10283   StmtResult ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
10284                                                 Stmt *AStmt,
10285                                                 SourceLocation StartLoc,
10286                                                 SourceLocation EndLoc);
10287   /// Called on well-formed '\#pragma omp parallel sections' after
10288   /// parsing of the  associated statement.
10289   StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
10290                                                   Stmt *AStmt,
10291                                                   SourceLocation StartLoc,
10292                                                   SourceLocation EndLoc);
10293   /// Called on well-formed '\#pragma omp task' after parsing of the
10294   /// associated statement.
10295   StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
10296                                       Stmt *AStmt, SourceLocation StartLoc,
10297                                       SourceLocation EndLoc);
10298   /// Called on well-formed '\#pragma omp taskyield'.
10299   StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
10300                                            SourceLocation EndLoc);
10301   /// Called on well-formed '\#pragma omp barrier'.
10302   StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
10303                                          SourceLocation EndLoc);
10304   /// Called on well-formed '\#pragma omp taskwait'.
10305   StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
10306                                           SourceLocation EndLoc);
10307   /// Called on well-formed '\#pragma omp taskgroup'.
10308   StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
10309                                            Stmt *AStmt, SourceLocation StartLoc,
10310                                            SourceLocation EndLoc);
10311   /// Called on well-formed '\#pragma omp flush'.
10312   StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
10313                                        SourceLocation StartLoc,
10314                                        SourceLocation EndLoc);
10315   /// Called on well-formed '\#pragma omp depobj'.
10316   StmtResult ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses,
10317                                         SourceLocation StartLoc,
10318                                         SourceLocation EndLoc);
10319   /// Called on well-formed '\#pragma omp scan'.
10320   StmtResult ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses,
10321                                       SourceLocation StartLoc,
10322                                       SourceLocation EndLoc);
10323   /// Called on well-formed '\#pragma omp ordered' after parsing of the
10324   /// associated statement.
10325   StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
10326                                          Stmt *AStmt, SourceLocation StartLoc,
10327                                          SourceLocation EndLoc);
10328   /// Called on well-formed '\#pragma omp atomic' after parsing of the
10329   /// associated statement.
10330   StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
10331                                         Stmt *AStmt, SourceLocation StartLoc,
10332                                         SourceLocation EndLoc);
10333   /// Called on well-formed '\#pragma omp target' after parsing of the
10334   /// associated statement.
10335   StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
10336                                         Stmt *AStmt, SourceLocation StartLoc,
10337                                         SourceLocation EndLoc);
10338   /// Called on well-formed '\#pragma omp target data' after parsing of
10339   /// the associated statement.
10340   StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
10341                                             Stmt *AStmt, SourceLocation StartLoc,
10342                                             SourceLocation EndLoc);
10343   /// Called on well-formed '\#pragma omp target enter data' after
10344   /// parsing of the associated statement.
10345   StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
10346                                                  SourceLocation StartLoc,
10347                                                  SourceLocation EndLoc,
10348                                                  Stmt *AStmt);
10349   /// Called on well-formed '\#pragma omp target exit data' after
10350   /// parsing of the associated statement.
10351   StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
10352                                                 SourceLocation StartLoc,
10353                                                 SourceLocation EndLoc,
10354                                                 Stmt *AStmt);
10355   /// Called on well-formed '\#pragma omp target parallel' after
10356   /// parsing of the associated statement.
10357   StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
10358                                                 Stmt *AStmt,
10359                                                 SourceLocation StartLoc,
10360                                                 SourceLocation EndLoc);
10361   /// Called on well-formed '\#pragma omp target parallel for' after
10362   /// parsing of the  associated statement.
10363   StmtResult ActOnOpenMPTargetParallelForDirective(
10364       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10365       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10366   /// Called on well-formed '\#pragma omp teams' after parsing of the
10367   /// associated statement.
10368   StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
10369                                        Stmt *AStmt, SourceLocation StartLoc,
10370                                        SourceLocation EndLoc);
10371   /// Called on well-formed '\#pragma omp cancellation point'.
10372   StmtResult
10373   ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
10374                                         SourceLocation EndLoc,
10375                                         OpenMPDirectiveKind CancelRegion);
10376   /// Called on well-formed '\#pragma omp cancel'.
10377   StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
10378                                         SourceLocation StartLoc,
10379                                         SourceLocation EndLoc,
10380                                         OpenMPDirectiveKind CancelRegion);
10381   /// Called on well-formed '\#pragma omp taskloop' after parsing of the
10382   /// associated statement.
10383   StmtResult
10384   ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10385                                SourceLocation StartLoc, SourceLocation EndLoc,
10386                                VarsWithInheritedDSAType &VarsWithImplicitDSA);
10387   /// Called on well-formed '\#pragma omp taskloop simd' after parsing of
10388   /// the associated statement.
10389   StmtResult ActOnOpenMPTaskLoopSimdDirective(
10390       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10391       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10392   /// Called on well-formed '\#pragma omp master taskloop' after parsing of the
10393   /// associated statement.
10394   StmtResult ActOnOpenMPMasterTaskLoopDirective(
10395       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10396       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10397   /// Called on well-formed '\#pragma omp master taskloop simd' after parsing of
10398   /// the associated statement.
10399   StmtResult ActOnOpenMPMasterTaskLoopSimdDirective(
10400       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10401       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10402   /// Called on well-formed '\#pragma omp parallel master taskloop' after
10403   /// parsing of the associated statement.
10404   StmtResult ActOnOpenMPParallelMasterTaskLoopDirective(
10405       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10406       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10407   /// Called on well-formed '\#pragma omp parallel master taskloop simd' after
10408   /// parsing of the associated statement.
10409   StmtResult ActOnOpenMPParallelMasterTaskLoopSimdDirective(
10410       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10411       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10412   /// Called on well-formed '\#pragma omp distribute' after parsing
10413   /// of the associated statement.
10414   StmtResult
10415   ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10416                                  SourceLocation StartLoc, SourceLocation EndLoc,
10417                                  VarsWithInheritedDSAType &VarsWithImplicitDSA);
10418   /// Called on well-formed '\#pragma omp target update'.
10419   StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
10420                                               SourceLocation StartLoc,
10421                                               SourceLocation EndLoc,
10422                                               Stmt *AStmt);
10423   /// Called on well-formed '\#pragma omp distribute parallel for' after
10424   /// parsing of the associated statement.
10425   StmtResult ActOnOpenMPDistributeParallelForDirective(
10426       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10427       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10428   /// Called on well-formed '\#pragma omp distribute parallel for simd'
10429   /// after parsing of the associated statement.
10430   StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
10431       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10432       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10433   /// Called on well-formed '\#pragma omp distribute simd' after
10434   /// parsing of the associated statement.
10435   StmtResult ActOnOpenMPDistributeSimdDirective(
10436       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10437       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10438   /// Called on well-formed '\#pragma omp target parallel for simd' after
10439   /// parsing of the associated statement.
10440   StmtResult ActOnOpenMPTargetParallelForSimdDirective(
10441       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10442       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10443   /// Called on well-formed '\#pragma omp target simd' after parsing of
10444   /// the associated statement.
10445   StmtResult
10446   ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10447                                  SourceLocation StartLoc, SourceLocation EndLoc,
10448                                  VarsWithInheritedDSAType &VarsWithImplicitDSA);
10449   /// Called on well-formed '\#pragma omp teams distribute' after parsing of
10450   /// the associated statement.
10451   StmtResult ActOnOpenMPTeamsDistributeDirective(
10452       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10453       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10454   /// Called on well-formed '\#pragma omp teams distribute simd' after parsing
10455   /// of the associated statement.
10456   StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
10457       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10458       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10459   /// Called on well-formed '\#pragma omp teams distribute parallel for simd'
10460   /// after parsing of the associated statement.
10461   StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
10462       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10463       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10464   /// Called on well-formed '\#pragma omp teams distribute parallel for'
10465   /// after parsing of the associated statement.
10466   StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
10467       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10468       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10469   /// Called on well-formed '\#pragma omp target teams' after parsing of the
10470   /// associated statement.
10471   StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
10472                                              Stmt *AStmt,
10473                                              SourceLocation StartLoc,
10474                                              SourceLocation EndLoc);
10475   /// Called on well-formed '\#pragma omp target teams distribute' after parsing
10476   /// of the associated statement.
10477   StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
10478       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10479       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10480   /// Called on well-formed '\#pragma omp target teams distribute parallel for'
10481   /// after parsing of the associated statement.
10482   StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
10483       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10484       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10485   /// Called on well-formed '\#pragma omp target teams distribute parallel for
10486   /// simd' after parsing of the associated statement.
10487   StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
10488       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10489       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10490   /// Called on well-formed '\#pragma omp target teams distribute simd' after
10491   /// parsing of the associated statement.
10492   StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
10493       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10494       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10495 
10496   /// Checks correctness of linear modifiers.
10497   bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
10498                                  SourceLocation LinLoc);
10499   /// Checks that the specified declaration matches requirements for the linear
10500   /// decls.
10501   bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
10502                              OpenMPLinearClauseKind LinKind, QualType Type,
10503                              bool IsDeclareSimd = false);
10504 
10505   /// Called on well-formed '\#pragma omp declare simd' after parsing of
10506   /// the associated method/function.
10507   DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
10508       DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
10509       Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
10510       ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
10511       ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
10512 
10513   /// Checks '\#pragma omp declare variant' variant function and original
10514   /// functions after parsing of the associated method/function.
10515   /// \param DG Function declaration to which declare variant directive is
10516   /// applied to.
10517   /// \param VariantRef Expression that references the variant function, which
10518   /// must be used instead of the original one, specified in \p DG.
10519   /// \param TI The trait info object representing the match clause.
10520   /// \returns None, if the function/variant function are not compatible with
10521   /// the pragma, pair of original function/variant ref expression otherwise.
10522   Optional<std::pair<FunctionDecl *, Expr *>>
10523   checkOpenMPDeclareVariantFunction(DeclGroupPtrTy DG, Expr *VariantRef,
10524                                     OMPTraitInfo &TI, SourceRange SR);
10525 
10526   /// Called on well-formed '\#pragma omp declare variant' after parsing of
10527   /// the associated method/function.
10528   /// \param FD Function declaration to which declare variant directive is
10529   /// applied to.
10530   /// \param VariantRef Expression that references the variant function, which
10531   /// must be used instead of the original one, specified in \p DG.
10532   /// \param TI The context traits associated with the function variant.
10533   void ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD, Expr *VariantRef,
10534                                           OMPTraitInfo &TI, SourceRange SR);
10535 
10536   OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
10537                                          Expr *Expr,
10538                                          SourceLocation StartLoc,
10539                                          SourceLocation LParenLoc,
10540                                          SourceLocation EndLoc);
10541   /// Called on well-formed 'allocator' clause.
10542   OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator,
10543                                         SourceLocation StartLoc,
10544                                         SourceLocation LParenLoc,
10545                                         SourceLocation EndLoc);
10546   /// Called on well-formed 'if' clause.
10547   OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
10548                                  Expr *Condition, SourceLocation StartLoc,
10549                                  SourceLocation LParenLoc,
10550                                  SourceLocation NameModifierLoc,
10551                                  SourceLocation ColonLoc,
10552                                  SourceLocation EndLoc);
10553   /// Called on well-formed 'final' clause.
10554   OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
10555                                     SourceLocation LParenLoc,
10556                                     SourceLocation EndLoc);
10557   /// Called on well-formed 'num_threads' clause.
10558   OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
10559                                          SourceLocation StartLoc,
10560                                          SourceLocation LParenLoc,
10561                                          SourceLocation EndLoc);
10562   /// Called on well-formed 'safelen' clause.
10563   OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
10564                                       SourceLocation StartLoc,
10565                                       SourceLocation LParenLoc,
10566                                       SourceLocation EndLoc);
10567   /// Called on well-formed 'simdlen' clause.
10568   OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
10569                                       SourceLocation LParenLoc,
10570                                       SourceLocation EndLoc);
10571   /// Called on well-formed 'collapse' clause.
10572   OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
10573                                        SourceLocation StartLoc,
10574                                        SourceLocation LParenLoc,
10575                                        SourceLocation EndLoc);
10576   /// Called on well-formed 'ordered' clause.
10577   OMPClause *
10578   ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
10579                            SourceLocation LParenLoc = SourceLocation(),
10580                            Expr *NumForLoops = nullptr);
10581   /// Called on well-formed 'grainsize' clause.
10582   OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
10583                                         SourceLocation LParenLoc,
10584                                         SourceLocation EndLoc);
10585   /// Called on well-formed 'num_tasks' clause.
10586   OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
10587                                        SourceLocation LParenLoc,
10588                                        SourceLocation EndLoc);
10589   /// Called on well-formed 'hint' clause.
10590   OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
10591                                    SourceLocation LParenLoc,
10592                                    SourceLocation EndLoc);
10593   /// Called on well-formed 'detach' clause.
10594   OMPClause *ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc,
10595                                      SourceLocation LParenLoc,
10596                                      SourceLocation EndLoc);
10597 
10598   OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
10599                                      unsigned Argument,
10600                                      SourceLocation ArgumentLoc,
10601                                      SourceLocation StartLoc,
10602                                      SourceLocation LParenLoc,
10603                                      SourceLocation EndLoc);
10604   /// Called on well-formed 'default' clause.
10605   OMPClause *ActOnOpenMPDefaultClause(llvm::omp::DefaultKind Kind,
10606                                       SourceLocation KindLoc,
10607                                       SourceLocation StartLoc,
10608                                       SourceLocation LParenLoc,
10609                                       SourceLocation EndLoc);
10610   /// Called on well-formed 'proc_bind' clause.
10611   OMPClause *ActOnOpenMPProcBindClause(llvm::omp::ProcBindKind Kind,
10612                                        SourceLocation KindLoc,
10613                                        SourceLocation StartLoc,
10614                                        SourceLocation LParenLoc,
10615                                        SourceLocation EndLoc);
10616   /// Called on well-formed 'order' clause.
10617   OMPClause *ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind,
10618                                     SourceLocation KindLoc,
10619                                     SourceLocation StartLoc,
10620                                     SourceLocation LParenLoc,
10621                                     SourceLocation EndLoc);
10622   /// Called on well-formed 'update' clause.
10623   OMPClause *ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind,
10624                                      SourceLocation KindLoc,
10625                                      SourceLocation StartLoc,
10626                                      SourceLocation LParenLoc,
10627                                      SourceLocation EndLoc);
10628 
10629   OMPClause *ActOnOpenMPSingleExprWithArgClause(
10630       OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
10631       SourceLocation StartLoc, SourceLocation LParenLoc,
10632       ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
10633       SourceLocation EndLoc);
10634   /// Called on well-formed 'schedule' clause.
10635   OMPClause *ActOnOpenMPScheduleClause(
10636       OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
10637       OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
10638       SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
10639       SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
10640 
10641   OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
10642                                SourceLocation EndLoc);
10643   /// Called on well-formed 'nowait' clause.
10644   OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
10645                                      SourceLocation EndLoc);
10646   /// Called on well-formed 'untied' clause.
10647   OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
10648                                      SourceLocation EndLoc);
10649   /// Called on well-formed 'mergeable' clause.
10650   OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
10651                                         SourceLocation EndLoc);
10652   /// Called on well-formed 'read' clause.
10653   OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
10654                                    SourceLocation EndLoc);
10655   /// Called on well-formed 'write' clause.
10656   OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
10657                                     SourceLocation EndLoc);
10658   /// Called on well-formed 'update' clause.
10659   OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
10660                                      SourceLocation EndLoc);
10661   /// Called on well-formed 'capture' clause.
10662   OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
10663                                       SourceLocation EndLoc);
10664   /// Called on well-formed 'seq_cst' clause.
10665   OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
10666                                      SourceLocation EndLoc);
10667   /// Called on well-formed 'acq_rel' clause.
10668   OMPClause *ActOnOpenMPAcqRelClause(SourceLocation StartLoc,
10669                                      SourceLocation EndLoc);
10670   /// Called on well-formed 'acquire' clause.
10671   OMPClause *ActOnOpenMPAcquireClause(SourceLocation StartLoc,
10672                                       SourceLocation EndLoc);
10673   /// Called on well-formed 'release' clause.
10674   OMPClause *ActOnOpenMPReleaseClause(SourceLocation StartLoc,
10675                                       SourceLocation EndLoc);
10676   /// Called on well-formed 'relaxed' clause.
10677   OMPClause *ActOnOpenMPRelaxedClause(SourceLocation StartLoc,
10678                                       SourceLocation EndLoc);
10679   /// Called on well-formed 'destroy' clause.
10680   OMPClause *ActOnOpenMPDestroyClause(SourceLocation StartLoc,
10681                                       SourceLocation EndLoc);
10682   /// Called on well-formed 'threads' clause.
10683   OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
10684                                       SourceLocation EndLoc);
10685   /// Called on well-formed 'simd' clause.
10686   OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
10687                                    SourceLocation EndLoc);
10688   /// Called on well-formed 'nogroup' clause.
10689   OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
10690                                       SourceLocation EndLoc);
10691   /// Called on well-formed 'unified_address' clause.
10692   OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
10693                                              SourceLocation EndLoc);
10694 
10695   /// Called on well-formed 'unified_address' clause.
10696   OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
10697                                                   SourceLocation EndLoc);
10698 
10699   /// Called on well-formed 'reverse_offload' clause.
10700   OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
10701                                              SourceLocation EndLoc);
10702 
10703   /// Called on well-formed 'dynamic_allocators' clause.
10704   OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
10705                                                 SourceLocation EndLoc);
10706 
10707   /// Called on well-formed 'atomic_default_mem_order' clause.
10708   OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause(
10709       OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc,
10710       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
10711 
10712   OMPClause *ActOnOpenMPVarListClause(
10713       OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *DepModOrTailExpr,
10714       const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
10715       CXXScopeSpec &ReductionOrMapperIdScopeSpec,
10716       DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier,
10717       ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
10718       ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit,
10719       SourceLocation ExtraModifierLoc);
10720   /// Called on well-formed 'inclusive' clause.
10721   OMPClause *ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList,
10722                                         SourceLocation StartLoc,
10723                                         SourceLocation LParenLoc,
10724                                         SourceLocation EndLoc);
10725   /// Called on well-formed 'exclusive' clause.
10726   OMPClause *ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList,
10727                                         SourceLocation StartLoc,
10728                                         SourceLocation LParenLoc,
10729                                         SourceLocation EndLoc);
10730   /// Called on well-formed 'allocate' clause.
10731   OMPClause *
10732   ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList,
10733                             SourceLocation StartLoc, SourceLocation ColonLoc,
10734                             SourceLocation LParenLoc, SourceLocation EndLoc);
10735   /// Called on well-formed 'private' clause.
10736   OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
10737                                       SourceLocation StartLoc,
10738                                       SourceLocation LParenLoc,
10739                                       SourceLocation EndLoc);
10740   /// Called on well-formed 'firstprivate' clause.
10741   OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
10742                                            SourceLocation StartLoc,
10743                                            SourceLocation LParenLoc,
10744                                            SourceLocation EndLoc);
10745   /// Called on well-formed 'lastprivate' clause.
10746   OMPClause *ActOnOpenMPLastprivateClause(
10747       ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
10748       SourceLocation LPKindLoc, SourceLocation ColonLoc,
10749       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
10750   /// Called on well-formed 'shared' clause.
10751   OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
10752                                      SourceLocation StartLoc,
10753                                      SourceLocation LParenLoc,
10754                                      SourceLocation EndLoc);
10755   /// Called on well-formed 'reduction' clause.
10756   OMPClause *ActOnOpenMPReductionClause(
10757       ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
10758       SourceLocation StartLoc, SourceLocation LParenLoc,
10759       SourceLocation ModifierLoc, SourceLocation ColonLoc,
10760       SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
10761       const DeclarationNameInfo &ReductionId,
10762       ArrayRef<Expr *> UnresolvedReductions = llvm::None);
10763   /// Called on well-formed 'task_reduction' clause.
10764   OMPClause *ActOnOpenMPTaskReductionClause(
10765       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10766       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
10767       CXXScopeSpec &ReductionIdScopeSpec,
10768       const DeclarationNameInfo &ReductionId,
10769       ArrayRef<Expr *> UnresolvedReductions = llvm::None);
10770   /// Called on well-formed 'in_reduction' clause.
10771   OMPClause *ActOnOpenMPInReductionClause(
10772       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10773       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
10774       CXXScopeSpec &ReductionIdScopeSpec,
10775       const DeclarationNameInfo &ReductionId,
10776       ArrayRef<Expr *> UnresolvedReductions = llvm::None);
10777   /// Called on well-formed 'linear' clause.
10778   OMPClause *
10779   ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
10780                           SourceLocation StartLoc, SourceLocation LParenLoc,
10781                           OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
10782                           SourceLocation ColonLoc, SourceLocation EndLoc);
10783   /// Called on well-formed 'aligned' clause.
10784   OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
10785                                       Expr *Alignment,
10786                                       SourceLocation StartLoc,
10787                                       SourceLocation LParenLoc,
10788                                       SourceLocation ColonLoc,
10789                                       SourceLocation EndLoc);
10790   /// Called on well-formed 'copyin' clause.
10791   OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
10792                                      SourceLocation StartLoc,
10793                                      SourceLocation LParenLoc,
10794                                      SourceLocation EndLoc);
10795   /// Called on well-formed 'copyprivate' clause.
10796   OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
10797                                           SourceLocation StartLoc,
10798                                           SourceLocation LParenLoc,
10799                                           SourceLocation EndLoc);
10800   /// Called on well-formed 'flush' pseudo clause.
10801   OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
10802                                     SourceLocation StartLoc,
10803                                     SourceLocation LParenLoc,
10804                                     SourceLocation EndLoc);
10805   /// Called on well-formed 'depobj' pseudo clause.
10806   OMPClause *ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
10807                                      SourceLocation LParenLoc,
10808                                      SourceLocation EndLoc);
10809   /// Called on well-formed 'depend' clause.
10810   OMPClause *
10811   ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind,
10812                           SourceLocation DepLoc, SourceLocation ColonLoc,
10813                           ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10814                           SourceLocation LParenLoc, SourceLocation EndLoc);
10815   /// Called on well-formed 'device' clause.
10816   OMPClause *ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
10817                                      Expr *Device, SourceLocation StartLoc,
10818                                      SourceLocation LParenLoc,
10819                                      SourceLocation ModifierLoc,
10820                                      SourceLocation EndLoc);
10821   /// Called on well-formed 'map' clause.
10822   OMPClause *
10823   ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
10824                        ArrayRef<SourceLocation> MapTypeModifiersLoc,
10825                        CXXScopeSpec &MapperIdScopeSpec,
10826                        DeclarationNameInfo &MapperId,
10827                        OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
10828                        SourceLocation MapLoc, SourceLocation ColonLoc,
10829                        ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
10830                        ArrayRef<Expr *> UnresolvedMappers = llvm::None);
10831   /// Called on well-formed 'num_teams' clause.
10832   OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
10833                                        SourceLocation LParenLoc,
10834                                        SourceLocation EndLoc);
10835   /// Called on well-formed 'thread_limit' clause.
10836   OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
10837                                           SourceLocation StartLoc,
10838                                           SourceLocation LParenLoc,
10839                                           SourceLocation EndLoc);
10840   /// Called on well-formed 'priority' clause.
10841   OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
10842                                        SourceLocation LParenLoc,
10843                                        SourceLocation EndLoc);
10844   /// Called on well-formed 'dist_schedule' clause.
10845   OMPClause *ActOnOpenMPDistScheduleClause(
10846       OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
10847       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
10848       SourceLocation CommaLoc, SourceLocation EndLoc);
10849   /// Called on well-formed 'defaultmap' clause.
10850   OMPClause *ActOnOpenMPDefaultmapClause(
10851       OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
10852       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
10853       SourceLocation KindLoc, SourceLocation EndLoc);
10854   /// Called on well-formed 'to' clause.
10855   OMPClause *
10856   ActOnOpenMPToClause(ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec,
10857                       DeclarationNameInfo &MapperId,
10858                       const OMPVarListLocTy &Locs,
10859                       ArrayRef<Expr *> UnresolvedMappers = llvm::None);
10860   /// Called on well-formed 'from' clause.
10861   OMPClause *ActOnOpenMPFromClause(
10862       ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec,
10863       DeclarationNameInfo &MapperId, const OMPVarListLocTy &Locs,
10864       ArrayRef<Expr *> UnresolvedMappers = llvm::None);
10865   /// Called on well-formed 'use_device_ptr' clause.
10866   OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
10867                                            const OMPVarListLocTy &Locs);
10868   /// Called on well-formed 'use_device_addr' clause.
10869   OMPClause *ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
10870                                             const OMPVarListLocTy &Locs);
10871   /// Called on well-formed 'is_device_ptr' clause.
10872   OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
10873                                           const OMPVarListLocTy &Locs);
10874   /// Called on well-formed 'nontemporal' clause.
10875   OMPClause *ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
10876                                           SourceLocation StartLoc,
10877                                           SourceLocation LParenLoc,
10878                                           SourceLocation EndLoc);
10879 
10880   /// Data for list of allocators.
10881   struct UsesAllocatorsData {
10882     /// Allocator.
10883     Expr *Allocator = nullptr;
10884     /// Allocator traits.
10885     Expr *AllocatorTraits = nullptr;
10886     /// Locations of '(' and ')' symbols.
10887     SourceLocation LParenLoc, RParenLoc;
10888   };
10889   /// Called on well-formed 'uses_allocators' clause.
10890   OMPClause *ActOnOpenMPUsesAllocatorClause(SourceLocation StartLoc,
10891                                             SourceLocation LParenLoc,
10892                                             SourceLocation EndLoc,
10893                                             ArrayRef<UsesAllocatorsData> Data);
10894   /// Called on well-formed 'affinity' clause.
10895   OMPClause *ActOnOpenMPAffinityClause(SourceLocation StartLoc,
10896                                        SourceLocation LParenLoc,
10897                                        SourceLocation ColonLoc,
10898                                        SourceLocation EndLoc, Expr *Modifier,
10899                                        ArrayRef<Expr *> Locators);
10900 
10901   /// The kind of conversion being performed.
10902   enum CheckedConversionKind {
10903     /// An implicit conversion.
10904     CCK_ImplicitConversion,
10905     /// A C-style cast.
10906     CCK_CStyleCast,
10907     /// A functional-style cast.
10908     CCK_FunctionalCast,
10909     /// A cast other than a C-style cast.
10910     CCK_OtherCast,
10911     /// A conversion for an operand of a builtin overloaded operator.
10912     CCK_ForBuiltinOverloadedOp
10913   };
10914 
isCast(CheckedConversionKind CCK)10915   static bool isCast(CheckedConversionKind CCK) {
10916     return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast ||
10917            CCK == CCK_OtherCast;
10918   }
10919 
10920   /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
10921   /// cast.  If there is already an implicit cast, merge into the existing one.
10922   /// If isLvalue, the result of the cast is an lvalue.
10923   ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
10924                                ExprValueKind VK = VK_RValue,
10925                                const CXXCastPath *BasePath = nullptr,
10926                                CheckedConversionKind CCK
10927                                   = CCK_ImplicitConversion);
10928 
10929   /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
10930   /// to the conversion from scalar type ScalarTy to the Boolean type.
10931   static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
10932 
10933   /// IgnoredValueConversions - Given that an expression's result is
10934   /// syntactically ignored, perform any conversions that are
10935   /// required.
10936   ExprResult IgnoredValueConversions(Expr *E);
10937 
10938   // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
10939   // functions and arrays to their respective pointers (C99 6.3.2.1).
10940   ExprResult UsualUnaryConversions(Expr *E);
10941 
10942   /// CallExprUnaryConversions - a special case of an unary conversion
10943   /// performed on a function designator of a call expression.
10944   ExprResult CallExprUnaryConversions(Expr *E);
10945 
10946   // DefaultFunctionArrayConversion - converts functions and arrays
10947   // to their respective pointers (C99 6.3.2.1).
10948   ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
10949 
10950   // DefaultFunctionArrayLvalueConversion - converts functions and
10951   // arrays to their respective pointers and performs the
10952   // lvalue-to-rvalue conversion.
10953   ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
10954                                                   bool Diagnose = true);
10955 
10956   // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
10957   // the operand. This function is a no-op if the operand has a function type
10958   // or an array type.
10959   ExprResult DefaultLvalueConversion(Expr *E);
10960 
10961   // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
10962   // do not have a prototype. Integer promotions are performed on each
10963   // argument, and arguments that have type float are promoted to double.
10964   ExprResult DefaultArgumentPromotion(Expr *E);
10965 
10966   /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
10967   /// it as an xvalue. In C++98, the result will still be a prvalue, because
10968   /// we don't have xvalues there.
10969   ExprResult TemporaryMaterializationConversion(Expr *E);
10970 
10971   // Used for emitting the right warning by DefaultVariadicArgumentPromotion
10972   enum VariadicCallType {
10973     VariadicFunction,
10974     VariadicBlock,
10975     VariadicMethod,
10976     VariadicConstructor,
10977     VariadicDoesNotApply
10978   };
10979 
10980   VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
10981                                        const FunctionProtoType *Proto,
10982                                        Expr *Fn);
10983 
10984   // Used for determining in which context a type is allowed to be passed to a
10985   // vararg function.
10986   enum VarArgKind {
10987     VAK_Valid,
10988     VAK_ValidInCXX11,
10989     VAK_Undefined,
10990     VAK_MSVCUndefined,
10991     VAK_Invalid
10992   };
10993 
10994   // Determines which VarArgKind fits an expression.
10995   VarArgKind isValidVarArgType(const QualType &Ty);
10996 
10997   /// Check to see if the given expression is a valid argument to a variadic
10998   /// function, issuing a diagnostic if not.
10999   void checkVariadicArgument(const Expr *E, VariadicCallType CT);
11000 
11001   /// Check to see if a given expression could have '.c_str()' called on it.
11002   bool hasCStrMethod(const Expr *E);
11003 
11004   /// GatherArgumentsForCall - Collector argument expressions for various
11005   /// form of call prototypes.
11006   bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
11007                               const FunctionProtoType *Proto,
11008                               unsigned FirstParam, ArrayRef<Expr *> Args,
11009                               SmallVectorImpl<Expr *> &AllArgs,
11010                               VariadicCallType CallType = VariadicDoesNotApply,
11011                               bool AllowExplicit = false,
11012                               bool IsListInitialization = false);
11013 
11014   // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
11015   // will create a runtime trap if the resulting type is not a POD type.
11016   ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
11017                                               FunctionDecl *FDecl);
11018 
11019   /// Context in which we're performing a usual arithmetic conversion.
11020   enum ArithConvKind {
11021     /// An arithmetic operation.
11022     ACK_Arithmetic,
11023     /// A bitwise operation.
11024     ACK_BitwiseOp,
11025     /// A comparison.
11026     ACK_Comparison,
11027     /// A conditional (?:) operator.
11028     ACK_Conditional,
11029     /// A compound assignment expression.
11030     ACK_CompAssign,
11031   };
11032 
11033   // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
11034   // operands and then handles various conversions that are common to binary
11035   // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
11036   // routine returns the first non-arithmetic type found. The client is
11037   // responsible for emitting appropriate error diagnostics.
11038   QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
11039                                       SourceLocation Loc, ArithConvKind ACK);
11040 
11041   /// AssignConvertType - All of the 'assignment' semantic checks return this
11042   /// enum to indicate whether the assignment was allowed.  These checks are
11043   /// done for simple assignments, as well as initialization, return from
11044   /// function, argument passing, etc.  The query is phrased in terms of a
11045   /// source and destination type.
11046   enum AssignConvertType {
11047     /// Compatible - the types are compatible according to the standard.
11048     Compatible,
11049 
11050     /// PointerToInt - The assignment converts a pointer to an int, which we
11051     /// accept as an extension.
11052     PointerToInt,
11053 
11054     /// IntToPointer - The assignment converts an int to a pointer, which we
11055     /// accept as an extension.
11056     IntToPointer,
11057 
11058     /// FunctionVoidPointer - The assignment is between a function pointer and
11059     /// void*, which the standard doesn't allow, but we accept as an extension.
11060     FunctionVoidPointer,
11061 
11062     /// IncompatiblePointer - The assignment is between two pointers types that
11063     /// are not compatible, but we accept them as an extension.
11064     IncompatiblePointer,
11065 
11066     /// IncompatibleFunctionPointer - The assignment is between two function
11067     /// pointers types that are not compatible, but we accept them as an
11068     /// extension.
11069     IncompatibleFunctionPointer,
11070 
11071     /// IncompatiblePointerSign - The assignment is between two pointers types
11072     /// which point to integers which have a different sign, but are otherwise
11073     /// identical. This is a subset of the above, but broken out because it's by
11074     /// far the most common case of incompatible pointers.
11075     IncompatiblePointerSign,
11076 
11077     /// CompatiblePointerDiscardsQualifiers - The assignment discards
11078     /// c/v/r qualifiers, which we accept as an extension.
11079     CompatiblePointerDiscardsQualifiers,
11080 
11081     /// IncompatiblePointerDiscardsQualifiers - The assignment
11082     /// discards qualifiers that we don't permit to be discarded,
11083     /// like address spaces.
11084     IncompatiblePointerDiscardsQualifiers,
11085 
11086     /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment
11087     /// changes address spaces in nested pointer types which is not allowed.
11088     /// For instance, converting __private int ** to __generic int ** is
11089     /// illegal even though __private could be converted to __generic.
11090     IncompatibleNestedPointerAddressSpaceMismatch,
11091 
11092     /// IncompatibleNestedPointerQualifiers - The assignment is between two
11093     /// nested pointer types, and the qualifiers other than the first two
11094     /// levels differ e.g. char ** -> const char **, but we accept them as an
11095     /// extension.
11096     IncompatibleNestedPointerQualifiers,
11097 
11098     /// IncompatibleVectors - The assignment is between two vector types that
11099     /// have the same size, which we accept as an extension.
11100     IncompatibleVectors,
11101 
11102     /// IntToBlockPointer - The assignment converts an int to a block
11103     /// pointer. We disallow this.
11104     IntToBlockPointer,
11105 
11106     /// IncompatibleBlockPointer - The assignment is between two block
11107     /// pointers types that are not compatible.
11108     IncompatibleBlockPointer,
11109 
11110     /// IncompatibleObjCQualifiedId - The assignment is between a qualified
11111     /// id type and something else (that is incompatible with it). For example,
11112     /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
11113     IncompatibleObjCQualifiedId,
11114 
11115     /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
11116     /// object with __weak qualifier.
11117     IncompatibleObjCWeakRef,
11118 
11119     /// Incompatible - We reject this conversion outright, it is invalid to
11120     /// represent it in the AST.
11121     Incompatible
11122   };
11123 
11124   /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
11125   /// assignment conversion type specified by ConvTy.  This returns true if the
11126   /// conversion was invalid or false if the conversion was accepted.
11127   bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
11128                                 SourceLocation Loc,
11129                                 QualType DstType, QualType SrcType,
11130                                 Expr *SrcExpr, AssignmentAction Action,
11131                                 bool *Complained = nullptr);
11132 
11133   /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
11134   /// enum. If AllowMask is true, then we also allow the complement of a valid
11135   /// value, to be used as a mask.
11136   bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
11137                          bool AllowMask) const;
11138 
11139   /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
11140   /// integer not in the range of enum values.
11141   void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
11142                               Expr *SrcExpr);
11143 
11144   /// CheckAssignmentConstraints - Perform type checking for assignment,
11145   /// argument passing, variable initialization, and function return values.
11146   /// C99 6.5.16.
11147   AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
11148                                                QualType LHSType,
11149                                                QualType RHSType);
11150 
11151   /// Check assignment constraints and optionally prepare for a conversion of
11152   /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
11153   /// is true.
11154   AssignConvertType CheckAssignmentConstraints(QualType LHSType,
11155                                                ExprResult &RHS,
11156                                                CastKind &Kind,
11157                                                bool ConvertRHS = true);
11158 
11159   /// Check assignment constraints for an assignment of RHS to LHSType.
11160   ///
11161   /// \param LHSType The destination type for the assignment.
11162   /// \param RHS The source expression for the assignment.
11163   /// \param Diagnose If \c true, diagnostics may be produced when checking
11164   ///        for assignability. If a diagnostic is produced, \p RHS will be
11165   ///        set to ExprError(). Note that this function may still return
11166   ///        without producing a diagnostic, even for an invalid assignment.
11167   /// \param DiagnoseCFAudited If \c true, the target is a function parameter
11168   ///        in an audited Core Foundation API and does not need to be checked
11169   ///        for ARC retain issues.
11170   /// \param ConvertRHS If \c true, \p RHS will be updated to model the
11171   ///        conversions necessary to perform the assignment. If \c false,
11172   ///        \p Diagnose must also be \c false.
11173   AssignConvertType CheckSingleAssignmentConstraints(
11174       QualType LHSType, ExprResult &RHS, bool Diagnose = true,
11175       bool DiagnoseCFAudited = false, bool ConvertRHS = true);
11176 
11177   // If the lhs type is a transparent union, check whether we
11178   // can initialize the transparent union with the given expression.
11179   AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
11180                                                              ExprResult &RHS);
11181 
11182   bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
11183 
11184   bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
11185 
11186   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
11187                                        AssignmentAction Action,
11188                                        bool AllowExplicit = false);
11189   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
11190                                        AssignmentAction Action,
11191                                        bool AllowExplicit,
11192                                        ImplicitConversionSequence& ICS);
11193   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
11194                                        const ImplicitConversionSequence& ICS,
11195                                        AssignmentAction Action,
11196                                        CheckedConversionKind CCK
11197                                           = CCK_ImplicitConversion);
11198   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
11199                                        const StandardConversionSequence& SCS,
11200                                        AssignmentAction Action,
11201                                        CheckedConversionKind CCK);
11202 
11203   ExprResult PerformQualificationConversion(
11204       Expr *E, QualType Ty, ExprValueKind VK = VK_RValue,
11205       CheckedConversionKind CCK = CCK_ImplicitConversion);
11206 
11207   /// the following "Check" methods will return a valid/converted QualType
11208   /// or a null QualType (indicating an error diagnostic was issued).
11209 
11210   /// type checking binary operators (subroutines of CreateBuiltinBinOp).
11211   QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
11212                            ExprResult &RHS);
11213   QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
11214                                  ExprResult &RHS);
11215   QualType CheckPointerToMemberOperands( // C++ 5.5
11216     ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
11217     SourceLocation OpLoc, bool isIndirect);
11218   QualType CheckMultiplyDivideOperands( // C99 6.5.5
11219     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
11220     bool IsDivide);
11221   QualType CheckRemainderOperands( // C99 6.5.5
11222     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11223     bool IsCompAssign = false);
11224   QualType CheckAdditionOperands( // C99 6.5.6
11225     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11226     BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
11227   QualType CheckSubtractionOperands( // C99 6.5.6
11228     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11229     QualType* CompLHSTy = nullptr);
11230   QualType CheckShiftOperands( // C99 6.5.7
11231     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11232     BinaryOperatorKind Opc, bool IsCompAssign = false);
11233   void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE);
11234   QualType CheckCompareOperands( // C99 6.5.8/9
11235       ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11236       BinaryOperatorKind Opc);
11237   QualType CheckBitwiseOperands( // C99 6.5.[10...12]
11238       ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11239       BinaryOperatorKind Opc);
11240   QualType CheckLogicalOperands( // C99 6.5.[13,14]
11241     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11242     BinaryOperatorKind Opc);
11243   // CheckAssignmentOperands is used for both simple and compound assignment.
11244   // For simple assignment, pass both expressions and a null converted type.
11245   // For compound assignment, pass both expressions and the converted type.
11246   QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
11247     Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
11248 
11249   ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
11250                                      UnaryOperatorKind Opcode, Expr *Op);
11251   ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
11252                                          BinaryOperatorKind Opcode,
11253                                          Expr *LHS, Expr *RHS);
11254   ExprResult checkPseudoObjectRValue(Expr *E);
11255   Expr *recreateSyntacticForm(PseudoObjectExpr *E);
11256 
11257   QualType CheckConditionalOperands( // C99 6.5.15
11258     ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
11259     ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
11260   QualType CXXCheckConditionalOperands( // C++ 5.16
11261     ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
11262     ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
11263   QualType CheckGNUVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
11264                                           ExprResult &RHS,
11265                                           SourceLocation QuestionLoc);
11266   QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
11267                                     bool ConvertArgs = true);
11268   QualType FindCompositePointerType(SourceLocation Loc,
11269                                     ExprResult &E1, ExprResult &E2,
11270                                     bool ConvertArgs = true) {
11271     Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
11272     QualType Composite =
11273         FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
11274     E1 = E1Tmp;
11275     E2 = E2Tmp;
11276     return Composite;
11277   }
11278 
11279   QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
11280                                         SourceLocation QuestionLoc);
11281 
11282   bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
11283                                   SourceLocation QuestionLoc);
11284 
11285   void DiagnoseAlwaysNonNullPointer(Expr *E,
11286                                     Expr::NullPointerConstantKind NullType,
11287                                     bool IsEqual, SourceRange Range);
11288 
11289   /// type checking for vector binary operators.
11290   QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
11291                                SourceLocation Loc, bool IsCompAssign,
11292                                bool AllowBothBool, bool AllowBoolConversion);
11293   QualType GetSignedVectorType(QualType V);
11294   QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
11295                                       SourceLocation Loc,
11296                                       BinaryOperatorKind Opc);
11297   QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11298                                       SourceLocation Loc);
11299 
11300   /// Type checking for matrix binary operators.
11301   QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
11302                                           SourceLocation Loc,
11303                                           bool IsCompAssign);
11304   QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
11305                                        SourceLocation Loc, bool IsCompAssign);
11306 
11307   bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
11308   bool isLaxVectorConversion(QualType srcType, QualType destType);
11309 
11310   /// type checking declaration initializers (C99 6.7.8)
11311   bool CheckForConstantInitializer(Expr *e, QualType t);
11312 
11313   // type checking C++ declaration initializers (C++ [dcl.init]).
11314 
11315   /// ReferenceCompareResult - Expresses the result of comparing two
11316   /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
11317   /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
11318   enum ReferenceCompareResult {
11319     /// Ref_Incompatible - The two types are incompatible, so direct
11320     /// reference binding is not possible.
11321     Ref_Incompatible = 0,
11322     /// Ref_Related - The two types are reference-related, which means
11323     /// that their unqualified forms (T1 and T2) are either the same
11324     /// or T1 is a base class of T2.
11325     Ref_Related,
11326     /// Ref_Compatible - The two types are reference-compatible.
11327     Ref_Compatible
11328   };
11329 
11330   // Fake up a scoped enumeration that still contextually converts to bool.
11331   struct ReferenceConversionsScope {
11332     /// The conversions that would be performed on an lvalue of type T2 when
11333     /// binding a reference of type T1 to it, as determined when evaluating
11334     /// whether T1 is reference-compatible with T2.
11335     enum ReferenceConversions {
11336       Qualification = 0x1,
11337       NestedQualification = 0x2,
11338       Function = 0x4,
11339       DerivedToBase = 0x8,
11340       ObjC = 0x10,
11341       ObjCLifetime = 0x20,
11342 
11343       LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime)
11344     };
11345   };
11346   using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions;
11347 
11348   ReferenceCompareResult
11349   CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2,
11350                                ReferenceConversions *Conv = nullptr);
11351 
11352   ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11353                                  Expr *CastExpr, CastKind &CastKind,
11354                                  ExprValueKind &VK, CXXCastPath &Path);
11355 
11356   /// Force an expression with unknown-type to an expression of the
11357   /// given type.
11358   ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
11359 
11360   /// Type-check an expression that's being passed to an
11361   /// __unknown_anytype parameter.
11362   ExprResult checkUnknownAnyArg(SourceLocation callLoc,
11363                                 Expr *result, QualType &paramType);
11364 
11365   // CheckVectorCast - check type constraints for vectors.
11366   // Since vectors are an extension, there are no C standard reference for this.
11367   // We allow casting between vectors and integer datatypes of the same size.
11368   // returns true if the cast is invalid
11369   bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
11370                        CastKind &Kind);
11371 
11372   /// Prepare `SplattedExpr` for a vector splat operation, adding
11373   /// implicit casts if necessary.
11374   ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
11375 
11376   // CheckExtVectorCast - check type constraints for extended vectors.
11377   // Since vectors are an extension, there are no C standard reference for this.
11378   // We allow casting between vectors and integer datatypes of the same size,
11379   // or vectors and the element type of that vector.
11380   // returns the cast expr
11381   ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
11382                                 CastKind &Kind);
11383 
11384   ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
11385                                         SourceLocation LParenLoc,
11386                                         Expr *CastExpr,
11387                                         SourceLocation RParenLoc);
11388 
11389   enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
11390 
11391   /// Checks for invalid conversions and casts between
11392   /// retainable pointers and other pointer kinds for ARC and Weak.
11393   ARCConversionResult CheckObjCConversion(SourceRange castRange,
11394                                           QualType castType, Expr *&op,
11395                                           CheckedConversionKind CCK,
11396                                           bool Diagnose = true,
11397                                           bool DiagnoseCFAudited = false,
11398                                           BinaryOperatorKind Opc = BO_PtrMemD
11399                                           );
11400 
11401   Expr *stripARCUnbridgedCast(Expr *e);
11402   void diagnoseARCUnbridgedCast(Expr *e);
11403 
11404   bool CheckObjCARCUnavailableWeakConversion(QualType castType,
11405                                              QualType ExprType);
11406 
11407   /// checkRetainCycles - Check whether an Objective-C message send
11408   /// might create an obvious retain cycle.
11409   void checkRetainCycles(ObjCMessageExpr *msg);
11410   void checkRetainCycles(Expr *receiver, Expr *argument);
11411   void checkRetainCycles(VarDecl *Var, Expr *Init);
11412 
11413   /// checkUnsafeAssigns - Check whether +1 expr is being assigned
11414   /// to weak/__unsafe_unretained type.
11415   bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
11416 
11417   /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
11418   /// to weak/__unsafe_unretained expression.
11419   void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
11420 
11421   /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
11422   /// \param Method - May be null.
11423   /// \param [out] ReturnType - The return type of the send.
11424   /// \return true iff there were any incompatible types.
11425   bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType,
11426                                  MultiExprArg Args, Selector Sel,
11427                                  ArrayRef<SourceLocation> SelectorLocs,
11428                                  ObjCMethodDecl *Method, bool isClassMessage,
11429                                  bool isSuperMessage, SourceLocation lbrac,
11430                                  SourceLocation rbrac, SourceRange RecRange,
11431                                  QualType &ReturnType, ExprValueKind &VK);
11432 
11433   /// Determine the result of a message send expression based on
11434   /// the type of the receiver, the method expected to receive the message,
11435   /// and the form of the message send.
11436   QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType,
11437                                     ObjCMethodDecl *Method, bool isClassMessage,
11438                                     bool isSuperMessage);
11439 
11440   /// If the given expression involves a message send to a method
11441   /// with a related result type, emit a note describing what happened.
11442   void EmitRelatedResultTypeNote(const Expr *E);
11443 
11444   /// Given that we had incompatible pointer types in a return
11445   /// statement, check whether we're in a method with a related result
11446   /// type, and if so, emit a note describing what happened.
11447   void EmitRelatedResultTypeNoteForReturn(QualType destType);
11448 
11449   class ConditionResult {
11450     Decl *ConditionVar;
11451     FullExprArg Condition;
11452     bool Invalid;
11453     bool HasKnownValue;
11454     bool KnownValue;
11455 
11456     friend class Sema;
ConditionResult(Sema & S,Decl * ConditionVar,FullExprArg Condition,bool IsConstexpr)11457     ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
11458                     bool IsConstexpr)
11459         : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
11460           HasKnownValue(IsConstexpr && Condition.get() &&
11461                         !Condition.get()->isValueDependent()),
11462           KnownValue(HasKnownValue &&
11463                      !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
ConditionResult(bool Invalid)11464     explicit ConditionResult(bool Invalid)
11465         : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
11466           HasKnownValue(false), KnownValue(false) {}
11467 
11468   public:
ConditionResult()11469     ConditionResult() : ConditionResult(false) {}
isInvalid()11470     bool isInvalid() const { return Invalid; }
get()11471     std::pair<VarDecl *, Expr *> get() const {
11472       return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
11473                             Condition.get());
11474     }
getKnownValue()11475     llvm::Optional<bool> getKnownValue() const {
11476       if (!HasKnownValue)
11477         return None;
11478       return KnownValue;
11479     }
11480   };
ConditionError()11481   static ConditionResult ConditionError() { return ConditionResult(true); }
11482 
11483   enum class ConditionKind {
11484     Boolean,     ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
11485     ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
11486     Switch       ///< An integral condition for a 'switch' statement.
11487   };
11488 
11489   ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
11490                                  Expr *SubExpr, ConditionKind CK);
11491 
11492   ConditionResult ActOnConditionVariable(Decl *ConditionVar,
11493                                          SourceLocation StmtLoc,
11494                                          ConditionKind CK);
11495 
11496   DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
11497 
11498   ExprResult CheckConditionVariable(VarDecl *ConditionVar,
11499                                     SourceLocation StmtLoc,
11500                                     ConditionKind CK);
11501   ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
11502 
11503   /// CheckBooleanCondition - Diagnose problems involving the use of
11504   /// the given expression as a boolean condition (e.g. in an if
11505   /// statement).  Also performs the standard function and array
11506   /// decays, possibly changing the input variable.
11507   ///
11508   /// \param Loc - A location associated with the condition, e.g. the
11509   /// 'if' keyword.
11510   /// \return true iff there were any errors
11511   ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
11512                                    bool IsConstexpr = false);
11513 
11514   /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression
11515   /// found in an explicit(bool) specifier.
11516   ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E);
11517 
11518   /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
11519   /// Returns true if the explicit specifier is now resolved.
11520   bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec);
11521 
11522   /// DiagnoseAssignmentAsCondition - Given that an expression is
11523   /// being used as a boolean condition, warn if it's an assignment.
11524   void DiagnoseAssignmentAsCondition(Expr *E);
11525 
11526   /// Redundant parentheses over an equality comparison can indicate
11527   /// that the user intended an assignment used as condition.
11528   void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
11529 
11530   /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
11531   ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
11532 
11533   /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
11534   /// the specified width and sign.  If an overflow occurs, detect it and emit
11535   /// the specified diagnostic.
11536   void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
11537                                           unsigned NewWidth, bool NewSign,
11538                                           SourceLocation Loc, unsigned DiagID);
11539 
11540   /// Checks that the Objective-C declaration is declared in the global scope.
11541   /// Emits an error and marks the declaration as invalid if it's not declared
11542   /// in the global scope.
11543   bool CheckObjCDeclScope(Decl *D);
11544 
11545   /// Abstract base class used for diagnosing integer constant
11546   /// expression violations.
11547   class VerifyICEDiagnoser {
11548   public:
11549     bool Suppress;
11550 
Suppress(Suppress)11551     VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
11552 
11553     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
11554     virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
~VerifyICEDiagnoser()11555     virtual ~VerifyICEDiagnoser() { }
11556   };
11557 
11558   /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
11559   /// and reports the appropriate diagnostics. Returns false on success.
11560   /// Can optionally return the value of the expression.
11561   ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
11562                                              VerifyICEDiagnoser &Diagnoser,
11563                                              bool AllowFold = true);
11564   ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
11565                                              unsigned DiagID,
11566                                              bool AllowFold = true);
11567   ExprResult VerifyIntegerConstantExpression(Expr *E,
11568                                              llvm::APSInt *Result = nullptr);
11569 
11570   /// VerifyBitField - verifies that a bit field expression is an ICE and has
11571   /// the correct width, and that the field type is valid.
11572   /// Returns false on success.
11573   /// Can optionally return whether the bit-field is of width 0
11574   ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
11575                             QualType FieldTy, bool IsMsStruct,
11576                             Expr *BitWidth, bool *ZeroWidth = nullptr);
11577 
11578 private:
11579   unsigned ForceCUDAHostDeviceDepth = 0;
11580 
11581 public:
11582   /// Increments our count of the number of times we've seen a pragma forcing
11583   /// functions to be __host__ __device__.  So long as this count is greater
11584   /// than zero, all functions encountered will be __host__ __device__.
11585   void PushForceCUDAHostDevice();
11586 
11587   /// Decrements our count of the number of times we've seen a pragma forcing
11588   /// functions to be __host__ __device__.  Returns false if the count is 0
11589   /// before incrementing, so you can emit an error.
11590   bool PopForceCUDAHostDevice();
11591 
11592   /// Diagnostics that are emitted only if we discover that the given function
11593   /// must be codegen'ed.  Because handling these correctly adds overhead to
11594   /// compilation, this is currently only enabled for CUDA compilations.
11595   llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
11596                  std::vector<PartialDiagnosticAt>>
11597       DeviceDeferredDiags;
11598 
11599   /// A pair of a canonical FunctionDecl and a SourceLocation.  When used as the
11600   /// key in a hashtable, both the FD and location are hashed.
11601   struct FunctionDeclAndLoc {
11602     CanonicalDeclPtr<FunctionDecl> FD;
11603     SourceLocation Loc;
11604   };
11605 
11606   /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
11607   /// (maybe deferred) "bad call" diagnostic.  We use this to avoid emitting the
11608   /// same deferred diag twice.
11609   llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
11610 
11611   /// An inverse call graph, mapping known-emitted functions to one of their
11612   /// known-emitted callers (plus the location of the call).
11613   ///
11614   /// Functions that we can tell a priori must be emitted aren't added to this
11615   /// map.
11616   llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
11617                  /* Caller = */ FunctionDeclAndLoc>
11618       DeviceKnownEmittedFns;
11619 
11620   /// Diagnostic builder for CUDA/OpenMP devices errors which may or may not be
11621   /// deferred.
11622   ///
11623   /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
11624   /// which are not allowed to appear inside __device__ functions and are
11625   /// allowed to appear in __host__ __device__ functions only if the host+device
11626   /// function is never codegen'ed.
11627   ///
11628   /// To handle this, we use the notion of "deferred diagnostics", where we
11629   /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
11630   ///
11631   /// This class lets you emit either a regular diagnostic, a deferred
11632   /// diagnostic, or no diagnostic at all, according to an argument you pass to
11633   /// its constructor, thus simplifying the process of creating these "maybe
11634   /// deferred" diagnostics.
11635   class DeviceDiagBuilder {
11636   public:
11637     enum Kind {
11638       /// Emit no diagnostics.
11639       K_Nop,
11640       /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
11641       K_Immediate,
11642       /// Emit the diagnostic immediately, and, if it's a warning or error, also
11643       /// emit a call stack showing how this function can be reached by an a
11644       /// priori known-emitted function.
11645       K_ImmediateWithCallStack,
11646       /// Create a deferred diagnostic, which is emitted only if the function
11647       /// it's attached to is codegen'ed.  Also emit a call stack as with
11648       /// K_ImmediateWithCallStack.
11649       K_Deferred
11650     };
11651 
11652     DeviceDiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
11653                       FunctionDecl *Fn, Sema &S);
11654     DeviceDiagBuilder(DeviceDiagBuilder &&D);
11655     DeviceDiagBuilder(const DeviceDiagBuilder &) = default;
11656     ~DeviceDiagBuilder();
11657 
11658     /// Convertible to bool: True if we immediately emitted an error, false if
11659     /// we didn't emit an error or we created a deferred error.
11660     ///
11661     /// Example usage:
11662     ///
11663     ///   if (DeviceDiagBuilder(...) << foo << bar)
11664     ///     return ExprError();
11665     ///
11666     /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
11667     /// want to use these instead of creating a DeviceDiagBuilder yourself.
11668     operator bool() const { return ImmediateDiag.hasValue(); }
11669 
11670     template <typename T>
11671     friend const DeviceDiagBuilder &operator<<(const DeviceDiagBuilder &Diag,
11672                                                const T &Value) {
11673       if (Diag.ImmediateDiag.hasValue())
11674         *Diag.ImmediateDiag << Value;
11675       else if (Diag.PartialDiagId.hasValue())
11676         Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
11677             << Value;
11678       return Diag;
11679     }
11680 
11681   private:
11682     Sema &S;
11683     SourceLocation Loc;
11684     unsigned DiagID;
11685     FunctionDecl *Fn;
11686     bool ShowCallStack;
11687 
11688     // Invariant: At most one of these Optionals has a value.
11689     // FIXME: Switch these to a Variant once that exists.
11690     llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag;
11691     llvm::Optional<unsigned> PartialDiagId;
11692   };
11693 
11694   /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context
11695   /// is "used as device code".
11696   ///
11697   /// - If CurContext is a __host__ function, does not emit any diagnostics.
11698   /// - If CurContext is a __device__ or __global__ function, emits the
11699   ///   diagnostics immediately.
11700   /// - If CurContext is a __host__ __device__ function and we are compiling for
11701   ///   the device, creates a diagnostic which is emitted if and when we realize
11702   ///   that the function will be codegen'ed.
11703   ///
11704   /// Example usage:
11705   ///
11706   ///  // Variable-length arrays are not allowed in CUDA device code.
11707   ///  if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
11708   ///    return ExprError();
11709   ///  // Otherwise, continue parsing as normal.
11710   DeviceDiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID);
11711 
11712   /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context
11713   /// is "used as host code".
11714   ///
11715   /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
11716   DeviceDiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
11717 
11718   /// Creates a DeviceDiagBuilder that emits the diagnostic if the current
11719   /// context is "used as device code".
11720   ///
11721   /// - If CurContext is a `declare target` function or it is known that the
11722   /// function is emitted for the device, emits the diagnostics immediately.
11723   /// - If CurContext is a non-`declare target` function and we are compiling
11724   ///   for the device, creates a diagnostic which is emitted if and when we
11725   ///   realize that the function will be codegen'ed.
11726   ///
11727   /// Example usage:
11728   ///
11729   ///  // Variable-length arrays are not allowed in NVPTX device code.
11730   ///  if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported))
11731   ///    return ExprError();
11732   ///  // Otherwise, continue parsing as normal.
11733   DeviceDiagBuilder diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID);
11734 
11735   /// Creates a DeviceDiagBuilder that emits the diagnostic if the current
11736   /// context is "used as host code".
11737   ///
11738   /// - If CurContext is a `declare target` function or it is known that the
11739   /// function is emitted for the host, emits the diagnostics immediately.
11740   /// - If CurContext is a non-host function, just ignore it.
11741   ///
11742   /// Example usage:
11743   ///
11744   ///  // Variable-length arrays are not allowed in NVPTX device code.
11745   ///  if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported))
11746   ///    return ExprError();
11747   ///  // Otherwise, continue parsing as normal.
11748   DeviceDiagBuilder diagIfOpenMPHostCode(SourceLocation Loc, unsigned DiagID);
11749 
11750   DeviceDiagBuilder targetDiag(SourceLocation Loc, unsigned DiagID);
11751 
11752   /// Check if the expression is allowed to be used in expressions for the
11753   /// offloading devices.
11754   void checkDeviceDecl(const ValueDecl *D, SourceLocation Loc);
11755 
11756   enum CUDAFunctionTarget {
11757     CFT_Device,
11758     CFT_Global,
11759     CFT_Host,
11760     CFT_HostDevice,
11761     CFT_InvalidTarget
11762   };
11763 
11764   /// Determines whether the given function is a CUDA device/host/kernel/etc.
11765   /// function.
11766   ///
11767   /// Use this rather than examining the function's attributes yourself -- you
11768   /// will get it wrong.  Returns CFT_Host if D is null.
11769   CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
11770                                         bool IgnoreImplicitHDAttr = false);
11771   CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs);
11772 
11773   /// Gets the CUDA target for the current context.
CurrentCUDATarget()11774   CUDAFunctionTarget CurrentCUDATarget() {
11775     return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
11776   }
11777 
11778   static bool isCUDAImplicitHostDeviceFunction(const FunctionDecl *D);
11779 
11780   // CUDA function call preference. Must be ordered numerically from
11781   // worst to best.
11782   enum CUDAFunctionPreference {
11783     CFP_Never,      // Invalid caller/callee combination.
11784     CFP_WrongSide,  // Calls from host-device to host or device
11785                     // function that do not match current compilation
11786                     // mode.
11787     CFP_HostDevice, // Any calls to host/device functions.
11788     CFP_SameSide,   // Calls from host-device to host or device
11789                     // function matching current compilation mode.
11790     CFP_Native,     // host-to-host or device-to-device calls.
11791   };
11792 
11793   /// Identifies relative preference of a given Caller/Callee
11794   /// combination, based on their host/device attributes.
11795   /// \param Caller function which needs address of \p Callee.
11796   ///               nullptr in case of global context.
11797   /// \param Callee target function
11798   ///
11799   /// \returns preference value for particular Caller/Callee combination.
11800   CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
11801                                                 const FunctionDecl *Callee);
11802 
11803   /// Determines whether Caller may invoke Callee, based on their CUDA
11804   /// host/device attributes.  Returns false if the call is not allowed.
11805   ///
11806   /// Note: Will return true for CFP_WrongSide calls.  These may appear in
11807   /// semantically correct CUDA programs, but only if they're never codegen'ed.
IsAllowedCUDACall(const FunctionDecl * Caller,const FunctionDecl * Callee)11808   bool IsAllowedCUDACall(const FunctionDecl *Caller,
11809                          const FunctionDecl *Callee) {
11810     return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
11811   }
11812 
11813   /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
11814   /// depending on FD and the current compilation settings.
11815   void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
11816                                    const LookupResult &Previous);
11817 
11818   /// May add implicit CUDAConstantAttr attribute to VD, depending on VD
11819   /// and current compilation settings.
11820   void MaybeAddCUDAConstantAttr(VarDecl *VD);
11821 
11822 public:
11823   /// Check whether we're allowed to call Callee from the current context.
11824   ///
11825   /// - If the call is never allowed in a semantically-correct program
11826   ///   (CFP_Never), emits an error and returns false.
11827   ///
11828   /// - If the call is allowed in semantically-correct programs, but only if
11829   ///   it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
11830   ///   be emitted if and when the caller is codegen'ed, and returns true.
11831   ///
11832   ///   Will only create deferred diagnostics for a given SourceLocation once,
11833   ///   so you can safely call this multiple times without generating duplicate
11834   ///   deferred errors.
11835   ///
11836   /// - Otherwise, returns true without emitting any diagnostics.
11837   bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
11838 
11839   void CUDACheckLambdaCapture(CXXMethodDecl *D, const sema::Capture &Capture);
11840 
11841   /// Set __device__ or __host__ __device__ attributes on the given lambda
11842   /// operator() method.
11843   ///
11844   /// CUDA lambdas by default is host device function unless it has explicit
11845   /// host or device attribute.
11846   void CUDASetLambdaAttrs(CXXMethodDecl *Method);
11847 
11848   /// Finds a function in \p Matches with highest calling priority
11849   /// from \p Caller context and erases all functions with lower
11850   /// calling priority.
11851   void EraseUnwantedCUDAMatches(
11852       const FunctionDecl *Caller,
11853       SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
11854 
11855   /// Given a implicit special member, infer its CUDA target from the
11856   /// calls it needs to make to underlying base/field special members.
11857   /// \param ClassDecl the class for which the member is being created.
11858   /// \param CSM the kind of special member.
11859   /// \param MemberDecl the special member itself.
11860   /// \param ConstRHS true if this is a copy operation with a const object on
11861   ///        its RHS.
11862   /// \param Diagnose true if this call should emit diagnostics.
11863   /// \return true if there was an error inferring.
11864   /// The result of this call is implicit CUDA target attribute(s) attached to
11865   /// the member declaration.
11866   bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
11867                                                CXXSpecialMember CSM,
11868                                                CXXMethodDecl *MemberDecl,
11869                                                bool ConstRHS,
11870                                                bool Diagnose);
11871 
11872   /// \return true if \p CD can be considered empty according to CUDA
11873   /// (E.2.3.1 in CUDA 7.5 Programming guide).
11874   bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
11875   bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
11876 
11877   // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In
11878   // case of error emits appropriate diagnostic and invalidates \p Var.
11879   //
11880   // \details CUDA allows only empty constructors as initializers for global
11881   // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all
11882   // __shared__ variables whether they are local or not (they all are implicitly
11883   // static in CUDA). One exception is that CUDA allows constant initializers
11884   // for __constant__ and __device__ variables.
11885   void checkAllowedCUDAInitializer(VarDecl *VD);
11886 
11887   /// Check whether NewFD is a valid overload for CUDA. Emits
11888   /// diagnostics and invalidates NewFD if not.
11889   void checkCUDATargetOverload(FunctionDecl *NewFD,
11890                                const LookupResult &Previous);
11891   /// Copies target attributes from the template TD to the function FD.
11892   void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
11893 
11894   /// Returns the name of the launch configuration function.  This is the name
11895   /// of the function that will be called to configure kernel call, with the
11896   /// parameters specified via <<<>>>.
11897   std::string getCudaConfigureFuncName() const;
11898 
11899   /// \name Code completion
11900   //@{
11901   /// Describes the context in which code completion occurs.
11902   enum ParserCompletionContext {
11903     /// Code completion occurs at top-level or namespace context.
11904     PCC_Namespace,
11905     /// Code completion occurs within a class, struct, or union.
11906     PCC_Class,
11907     /// Code completion occurs within an Objective-C interface, protocol,
11908     /// or category.
11909     PCC_ObjCInterface,
11910     /// Code completion occurs within an Objective-C implementation or
11911     /// category implementation
11912     PCC_ObjCImplementation,
11913     /// Code completion occurs within the list of instance variables
11914     /// in an Objective-C interface, protocol, category, or implementation.
11915     PCC_ObjCInstanceVariableList,
11916     /// Code completion occurs following one or more template
11917     /// headers.
11918     PCC_Template,
11919     /// Code completion occurs following one or more template
11920     /// headers within a class.
11921     PCC_MemberTemplate,
11922     /// Code completion occurs within an expression.
11923     PCC_Expression,
11924     /// Code completion occurs within a statement, which may
11925     /// also be an expression or a declaration.
11926     PCC_Statement,
11927     /// Code completion occurs at the beginning of the
11928     /// initialization statement (or expression) in a for loop.
11929     PCC_ForInit,
11930     /// Code completion occurs within the condition of an if,
11931     /// while, switch, or for statement.
11932     PCC_Condition,
11933     /// Code completion occurs within the body of a function on a
11934     /// recovery path, where we do not have a specific handle on our position
11935     /// in the grammar.
11936     PCC_RecoveryInFunction,
11937     /// Code completion occurs where only a type is permitted.
11938     PCC_Type,
11939     /// Code completion occurs in a parenthesized expression, which
11940     /// might also be a type cast.
11941     PCC_ParenthesizedExpression,
11942     /// Code completion occurs within a sequence of declaration
11943     /// specifiers within a function, method, or block.
11944     PCC_LocalDeclarationSpecifiers
11945   };
11946 
11947   void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
11948   void CodeCompleteOrdinaryName(Scope *S,
11949                                 ParserCompletionContext CompletionContext);
11950   void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
11951                             bool AllowNonIdentifiers,
11952                             bool AllowNestedNameSpecifiers);
11953 
11954   struct CodeCompleteExpressionData;
11955   void CodeCompleteExpression(Scope *S,
11956                               const CodeCompleteExpressionData &Data);
11957   void CodeCompleteExpression(Scope *S, QualType PreferredType,
11958                               bool IsParenthesized = false);
11959   void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase,
11960                                        SourceLocation OpLoc, bool IsArrow,
11961                                        bool IsBaseExprStatement,
11962                                        QualType PreferredType);
11963   void CodeCompletePostfixExpression(Scope *S, ExprResult LHS,
11964                                      QualType PreferredType);
11965   void CodeCompleteTag(Scope *S, unsigned TagSpec);
11966   void CodeCompleteTypeQualifiers(DeclSpec &DS);
11967   void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
11968                                       const VirtSpecifiers *VS = nullptr);
11969   void CodeCompleteBracketDeclarator(Scope *S);
11970   void CodeCompleteCase(Scope *S);
11971   /// Reports signatures for a call to CodeCompleteConsumer and returns the
11972   /// preferred type for the current argument. Returned type can be null.
11973   QualType ProduceCallSignatureHelp(Scope *S, Expr *Fn, ArrayRef<Expr *> Args,
11974                                     SourceLocation OpenParLoc);
11975   QualType ProduceConstructorSignatureHelp(Scope *S, QualType Type,
11976                                            SourceLocation Loc,
11977                                            ArrayRef<Expr *> Args,
11978                                            SourceLocation OpenParLoc);
11979   QualType ProduceCtorInitMemberSignatureHelp(Scope *S, Decl *ConstructorDecl,
11980                                               CXXScopeSpec SS,
11981                                               ParsedType TemplateTypeTy,
11982                                               ArrayRef<Expr *> ArgExprs,
11983                                               IdentifierInfo *II,
11984                                               SourceLocation OpenParLoc);
11985   void CodeCompleteInitializer(Scope *S, Decl *D);
11986   /// Trigger code completion for a record of \p BaseType. \p InitExprs are
11987   /// expressions in the initializer list seen so far and \p D is the current
11988   /// Designation being parsed.
11989   void CodeCompleteDesignator(const QualType BaseType,
11990                               llvm::ArrayRef<Expr *> InitExprs,
11991                               const Designation &D);
11992   void CodeCompleteAfterIf(Scope *S, bool IsBracedThen);
11993 
11994   void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext,
11995                                bool IsUsingDeclaration, QualType BaseType,
11996                                QualType PreferredType);
11997   void CodeCompleteUsing(Scope *S);
11998   void CodeCompleteUsingDirective(Scope *S);
11999   void CodeCompleteNamespaceDecl(Scope *S);
12000   void CodeCompleteNamespaceAliasDecl(Scope *S);
12001   void CodeCompleteOperatorName(Scope *S);
12002   void CodeCompleteConstructorInitializer(
12003                                 Decl *Constructor,
12004                                 ArrayRef<CXXCtorInitializer *> Initializers);
12005 
12006   void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
12007                                     bool AfterAmpersand);
12008   void CodeCompleteAfterFunctionEquals(Declarator &D);
12009 
12010   void CodeCompleteObjCAtDirective(Scope *S);
12011   void CodeCompleteObjCAtVisibility(Scope *S);
12012   void CodeCompleteObjCAtStatement(Scope *S);
12013   void CodeCompleteObjCAtExpression(Scope *S);
12014   void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
12015   void CodeCompleteObjCPropertyGetter(Scope *S);
12016   void CodeCompleteObjCPropertySetter(Scope *S);
12017   void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
12018                                    bool IsParameter);
12019   void CodeCompleteObjCMessageReceiver(Scope *S);
12020   void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
12021                                     ArrayRef<IdentifierInfo *> SelIdents,
12022                                     bool AtArgumentExpression);
12023   void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
12024                                     ArrayRef<IdentifierInfo *> SelIdents,
12025                                     bool AtArgumentExpression,
12026                                     bool IsSuper = false);
12027   void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
12028                                        ArrayRef<IdentifierInfo *> SelIdents,
12029                                        bool AtArgumentExpression,
12030                                        ObjCInterfaceDecl *Super = nullptr);
12031   void CodeCompleteObjCForCollection(Scope *S,
12032                                      DeclGroupPtrTy IterationVar);
12033   void CodeCompleteObjCSelector(Scope *S,
12034                                 ArrayRef<IdentifierInfo *> SelIdents);
12035   void CodeCompleteObjCProtocolReferences(
12036                                          ArrayRef<IdentifierLocPair> Protocols);
12037   void CodeCompleteObjCProtocolDecl(Scope *S);
12038   void CodeCompleteObjCInterfaceDecl(Scope *S);
12039   void CodeCompleteObjCSuperclass(Scope *S,
12040                                   IdentifierInfo *ClassName,
12041                                   SourceLocation ClassNameLoc);
12042   void CodeCompleteObjCImplementationDecl(Scope *S);
12043   void CodeCompleteObjCInterfaceCategory(Scope *S,
12044                                          IdentifierInfo *ClassName,
12045                                          SourceLocation ClassNameLoc);
12046   void CodeCompleteObjCImplementationCategory(Scope *S,
12047                                               IdentifierInfo *ClassName,
12048                                               SourceLocation ClassNameLoc);
12049   void CodeCompleteObjCPropertyDefinition(Scope *S);
12050   void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
12051                                               IdentifierInfo *PropertyName);
12052   void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod,
12053                                   ParsedType ReturnType);
12054   void CodeCompleteObjCMethodDeclSelector(Scope *S,
12055                                           bool IsInstanceMethod,
12056                                           bool AtParameterName,
12057                                           ParsedType ReturnType,
12058                                           ArrayRef<IdentifierInfo *> SelIdents);
12059   void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
12060                                             SourceLocation ClassNameLoc,
12061                                             bool IsBaseExprStatement);
12062   void CodeCompletePreprocessorDirective(bool InConditional);
12063   void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
12064   void CodeCompletePreprocessorMacroName(bool IsDefinition);
12065   void CodeCompletePreprocessorExpression();
12066   void CodeCompletePreprocessorMacroArgument(Scope *S,
12067                                              IdentifierInfo *Macro,
12068                                              MacroInfo *MacroInfo,
12069                                              unsigned Argument);
12070   void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled);
12071   void CodeCompleteNaturalLanguage();
12072   void CodeCompleteAvailabilityPlatformName();
12073   void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
12074                                    CodeCompletionTUInfo &CCTUInfo,
12075                   SmallVectorImpl<CodeCompletionResult> &Results);
12076   //@}
12077 
12078   //===--------------------------------------------------------------------===//
12079   // Extra semantic analysis beyond the C type system
12080 
12081 public:
12082   SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
12083                                                 unsigned ByteNo) const;
12084 
12085 private:
12086   void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
12087                         const ArraySubscriptExpr *ASE=nullptr,
12088                         bool AllowOnePastEnd=true, bool IndexNegated=false);
12089   void CheckArrayAccess(const Expr *E);
12090   // Used to grab the relevant information from a FormatAttr and a
12091   // FunctionDeclaration.
12092   struct FormatStringInfo {
12093     unsigned FormatIdx;
12094     unsigned FirstDataArg;
12095     bool HasVAListArg;
12096   };
12097 
12098   static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
12099                                   FormatStringInfo *FSI);
12100   bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
12101                          const FunctionProtoType *Proto);
12102   bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
12103                            ArrayRef<const Expr *> Args);
12104   bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
12105                         const FunctionProtoType *Proto);
12106   bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
12107   void CheckConstructorCall(FunctionDecl *FDecl,
12108                             ArrayRef<const Expr *> Args,
12109                             const FunctionProtoType *Proto,
12110                             SourceLocation Loc);
12111 
12112   void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
12113                  const Expr *ThisArg, ArrayRef<const Expr *> Args,
12114                  bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
12115                  VariadicCallType CallType);
12116 
12117   bool CheckObjCString(Expr *Arg);
12118   ExprResult CheckOSLogFormatStringArg(Expr *Arg);
12119 
12120   ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
12121                                       unsigned BuiltinID, CallExpr *TheCall);
12122 
12123   bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12124                                   CallExpr *TheCall);
12125 
12126   void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
12127 
12128   bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
12129                                     unsigned MaxWidth);
12130   bool CheckNeonBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12131                                     CallExpr *TheCall);
12132   bool CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12133   bool CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12134   bool CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12135                                    CallExpr *TheCall);
12136   bool CheckARMCoprocessorImmediate(const TargetInfo &TI, const Expr *CoprocArg,
12137                                     bool WantCDE);
12138   bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12139                                    CallExpr *TheCall);
12140 
12141   bool CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12142                                        CallExpr *TheCall);
12143   bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12144   bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12145   bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
12146   bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12147                                     CallExpr *TheCall);
12148   bool CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
12149                            CallExpr *TheCall);
12150   bool CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
12151   bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12152   bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
12153   bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
12154   bool CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall);
12155   bool CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
12156                                          ArrayRef<int> ArgNums);
12157   bool CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, int ArgNum);
12158   bool CheckX86BuiltinTileDuplicate(CallExpr *TheCall, ArrayRef<int> ArgNums);
12159   bool CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
12160                                             ArrayRef<int> ArgNums);
12161   bool CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12162                                    CallExpr *TheCall);
12163   bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12164                                    CallExpr *TheCall);
12165   bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12166 
12167   bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
12168   bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call);
12169   bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
12170   bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
12171   bool SemaBuiltinVSX(CallExpr *TheCall);
12172   bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
12173 
12174 public:
12175   // Used by C++ template instantiation.
12176   ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
12177   ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
12178                                    SourceLocation BuiltinLoc,
12179                                    SourceLocation RParenLoc);
12180 
12181 private:
12182   bool SemaBuiltinPrefetch(CallExpr *TheCall);
12183   bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
12184   bool SemaBuiltinAssume(CallExpr *TheCall);
12185   bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
12186   bool SemaBuiltinLongjmp(CallExpr *TheCall);
12187   bool SemaBuiltinSetjmp(CallExpr *TheCall);
12188   ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
12189   ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
12190   ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
12191                                      AtomicExpr::AtomicOp Op);
12192   ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
12193                                                     bool IsDelete);
12194   bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
12195                               llvm::APSInt &Result);
12196   bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low,
12197                                    int High, bool RangeIsError = true);
12198   bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
12199                                       unsigned Multiple);
12200   bool SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum);
12201   bool SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
12202                                          unsigned ArgBits);
12203   bool SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum,
12204                                                unsigned ArgBits);
12205   bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
12206                                 int ArgNum, unsigned ExpectedFieldNum,
12207                                 bool AllowName);
12208   bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall);
12209 
12210   // Matrix builtin handling.
12211   ExprResult SemaBuiltinMatrixTranspose(CallExpr *TheCall,
12212                                         ExprResult CallResult);
12213   ExprResult SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
12214                                               ExprResult CallResult);
12215   ExprResult SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
12216                                                ExprResult CallResult);
12217 
12218 public:
12219   enum FormatStringType {
12220     FST_Scanf,
12221     FST_Printf,
12222     FST_NSString,
12223     FST_Strftime,
12224     FST_Strfmon,
12225     FST_Kprintf,
12226     FST_FreeBSDKPrintf,
12227     FST_OSTrace,
12228     FST_OSLog,
12229     FST_Unknown
12230   };
12231   static FormatStringType GetFormatStringType(const FormatAttr *Format);
12232 
12233   bool FormatStringHasSArg(const StringLiteral *FExpr);
12234 
12235   static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
12236 
12237 private:
12238   bool CheckFormatArguments(const FormatAttr *Format,
12239                             ArrayRef<const Expr *> Args,
12240                             bool IsCXXMember,
12241                             VariadicCallType CallType,
12242                             SourceLocation Loc, SourceRange Range,
12243                             llvm::SmallBitVector &CheckedVarArgs);
12244   bool CheckFormatArguments(ArrayRef<const Expr *> Args,
12245                             bool HasVAListArg, unsigned format_idx,
12246                             unsigned firstDataArg, FormatStringType Type,
12247                             VariadicCallType CallType,
12248                             SourceLocation Loc, SourceRange range,
12249                             llvm::SmallBitVector &CheckedVarArgs);
12250 
12251   void CheckAbsoluteValueFunction(const CallExpr *Call,
12252                                   const FunctionDecl *FDecl);
12253 
12254   void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
12255 
12256   void CheckMemaccessArguments(const CallExpr *Call,
12257                                unsigned BId,
12258                                IdentifierInfo *FnName);
12259 
12260   void CheckStrlcpycatArguments(const CallExpr *Call,
12261                                 IdentifierInfo *FnName);
12262 
12263   void CheckStrncatArguments(const CallExpr *Call,
12264                              IdentifierInfo *FnName);
12265 
12266   void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
12267                           SourceLocation ReturnLoc,
12268                           bool isObjCMethod = false,
12269                           const AttrVec *Attrs = nullptr,
12270                           const FunctionDecl *FD = nullptr);
12271 
12272 public:
12273   void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS);
12274 
12275 private:
12276   void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
12277   void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
12278   void CheckForIntOverflow(Expr *E);
12279   void CheckUnsequencedOperations(const Expr *E);
12280 
12281   /// Perform semantic checks on a completed expression. This will either
12282   /// be a full-expression or a default argument expression.
12283   void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
12284                           bool IsConstexpr = false);
12285 
12286   void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
12287                                    Expr *Init);
12288 
12289   /// Check if there is a field shadowing.
12290   void CheckShadowInheritedFields(const SourceLocation &Loc,
12291                                   DeclarationName FieldName,
12292                                   const CXXRecordDecl *RD,
12293                                   bool DeclIsField = true);
12294 
12295   /// Check if the given expression contains 'break' or 'continue'
12296   /// statement that produces control flow different from GCC.
12297   void CheckBreakContinueBinding(Expr *E);
12298 
12299   /// Check whether receiver is mutable ObjC container which
12300   /// attempts to add itself into the container
12301   void CheckObjCCircularContainer(ObjCMessageExpr *Message);
12302 
12303   void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
12304   void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
12305                                  bool DeleteWasArrayForm);
12306 public:
12307   /// Register a magic integral constant to be used as a type tag.
12308   void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12309                                   uint64_t MagicValue, QualType Type,
12310                                   bool LayoutCompatible, bool MustBeNull);
12311 
12312   struct TypeTagData {
TypeTagDataTypeTagData12313     TypeTagData() {}
12314 
TypeTagDataTypeTagData12315     TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
12316         Type(Type), LayoutCompatible(LayoutCompatible),
12317         MustBeNull(MustBeNull)
12318     {}
12319 
12320     QualType Type;
12321 
12322     /// If true, \c Type should be compared with other expression's types for
12323     /// layout-compatibility.
12324     unsigned LayoutCompatible : 1;
12325     unsigned MustBeNull : 1;
12326   };
12327 
12328   /// A pair of ArgumentKind identifier and magic value.  This uniquely
12329   /// identifies the magic value.
12330   typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
12331 
12332 private:
12333   /// A map from magic value to type information.
12334   std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
12335       TypeTagForDatatypeMagicValues;
12336 
12337   /// Peform checks on a call of a function with argument_with_type_tag
12338   /// or pointer_with_type_tag attributes.
12339   void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
12340                                 const ArrayRef<const Expr *> ExprArgs,
12341                                 SourceLocation CallSiteLoc);
12342 
12343   /// Check if we are taking the address of a packed field
12344   /// as this may be a problem if the pointer value is dereferenced.
12345   void CheckAddressOfPackedMember(Expr *rhs);
12346 
12347   /// The parser's current scope.
12348   ///
12349   /// The parser maintains this state here.
12350   Scope *CurScope;
12351 
12352   mutable IdentifierInfo *Ident_super;
12353   mutable IdentifierInfo *Ident___float128;
12354 
12355   /// Nullability type specifiers.
12356   IdentifierInfo *Ident__Nonnull = nullptr;
12357   IdentifierInfo *Ident__Nullable = nullptr;
12358   IdentifierInfo *Ident__Null_unspecified = nullptr;
12359 
12360   IdentifierInfo *Ident_NSError = nullptr;
12361 
12362   /// The handler for the FileChanged preprocessor events.
12363   ///
12364   /// Used for diagnostics that implement custom semantic analysis for #include
12365   /// directives, like -Wpragma-pack.
12366   sema::SemaPPCallbacks *SemaPPCallbackHandler;
12367 
12368 protected:
12369   friend class Parser;
12370   friend class InitializationSequence;
12371   friend class ASTReader;
12372   friend class ASTDeclReader;
12373   friend class ASTWriter;
12374 
12375 public:
12376   /// Retrieve the keyword associated
12377   IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
12378 
12379   /// The struct behind the CFErrorRef pointer.
12380   RecordDecl *CFError = nullptr;
12381 
12382   /// Retrieve the identifier "NSError".
12383   IdentifierInfo *getNSErrorIdent();
12384 
12385   /// Retrieve the parser's current scope.
12386   ///
12387   /// This routine must only be used when it is certain that semantic analysis
12388   /// and the parser are in precisely the same context, which is not the case
12389   /// when, e.g., we are performing any kind of template instantiation.
12390   /// Therefore, the only safe places to use this scope are in the parser
12391   /// itself and in routines directly invoked from the parser and *never* from
12392   /// template substitution or instantiation.
getCurScope()12393   Scope *getCurScope() const { return CurScope; }
12394 
incrementMSManglingNumber()12395   void incrementMSManglingNumber() const {
12396     return CurScope->incrementMSManglingNumber();
12397   }
12398 
12399   IdentifierInfo *getSuperIdentifier() const;
12400   IdentifierInfo *getFloat128Identifier() const;
12401 
12402   Decl *getObjCDeclContext() const;
12403 
getCurLexicalContext()12404   DeclContext *getCurLexicalContext() const {
12405     return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
12406   }
12407 
getCurObjCLexicalContext()12408   const DeclContext *getCurObjCLexicalContext() const {
12409     const DeclContext *DC = getCurLexicalContext();
12410     // A category implicitly has the attribute of the interface.
12411     if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
12412       DC = CatD->getClassInterface();
12413     return DC;
12414   }
12415 
12416   /// Determine the number of levels of enclosing template parameters. This is
12417   /// only usable while parsing. Note that this does not include dependent
12418   /// contexts in which no template parameters have yet been declared, such as
12419   /// in a terse function template or generic lambda before the first 'auto' is
12420   /// encountered.
12421   unsigned getTemplateDepth(Scope *S) const;
12422 
12423   /// To be used for checking whether the arguments being passed to
12424   /// function exceeds the number of parameters expected for it.
12425   static bool TooManyArguments(size_t NumParams, size_t NumArgs,
12426                                bool PartialOverloading = false) {
12427     // We check whether we're just after a comma in code-completion.
12428     if (NumArgs > 0 && PartialOverloading)
12429       return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
12430     return NumArgs > NumParams;
12431   }
12432 
12433   // Emitting members of dllexported classes is delayed until the class
12434   // (including field initializers) is fully parsed.
12435   SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
12436   SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions;
12437 
12438 private:
12439   int ParsingClassDepth = 0;
12440 
12441   class SavePendingParsedClassStateRAII {
12442   public:
SavePendingParsedClassStateRAII(Sema & S)12443     SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
12444 
~SavePendingParsedClassStateRAII()12445     ~SavePendingParsedClassStateRAII() {
12446       assert(S.DelayedOverridingExceptionSpecChecks.empty() &&
12447              "there shouldn't be any pending delayed exception spec checks");
12448       assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&
12449              "there shouldn't be any pending delayed exception spec checks");
12450       swapSavedState();
12451     }
12452 
12453   private:
12454     Sema &S;
12455     decltype(DelayedOverridingExceptionSpecChecks)
12456         SavedOverridingExceptionSpecChecks;
12457     decltype(DelayedEquivalentExceptionSpecChecks)
12458         SavedEquivalentExceptionSpecChecks;
12459 
swapSavedState()12460     void swapSavedState() {
12461       SavedOverridingExceptionSpecChecks.swap(
12462           S.DelayedOverridingExceptionSpecChecks);
12463       SavedEquivalentExceptionSpecChecks.swap(
12464           S.DelayedEquivalentExceptionSpecChecks);
12465     }
12466   };
12467 
12468   /// Helper class that collects misaligned member designations and
12469   /// their location info for delayed diagnostics.
12470   struct MisalignedMember {
12471     Expr *E;
12472     RecordDecl *RD;
12473     ValueDecl *MD;
12474     CharUnits Alignment;
12475 
MisalignedMemberMisalignedMember12476     MisalignedMember() : E(), RD(), MD(), Alignment() {}
MisalignedMemberMisalignedMember12477     MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
12478                      CharUnits Alignment)
12479         : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
MisalignedMemberMisalignedMember12480     explicit MisalignedMember(Expr *E)
12481         : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
12482 
12483     bool operator==(const MisalignedMember &m) { return this->E == m.E; }
12484   };
12485   /// Small set of gathered accesses to potentially misaligned members
12486   /// due to the packed attribute.
12487   SmallVector<MisalignedMember, 4> MisalignedMembers;
12488 
12489   /// Adds an expression to the set of gathered misaligned members.
12490   void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12491                                      CharUnits Alignment);
12492 
12493 public:
12494   /// Diagnoses the current set of gathered accesses. This typically
12495   /// happens at full expression level. The set is cleared after emitting the
12496   /// diagnostics.
12497   void DiagnoseMisalignedMembers();
12498 
12499   /// This function checks if the expression is in the sef of potentially
12500   /// misaligned members and it is converted to some pointer type T with lower
12501   /// or equal alignment requirements. If so it removes it. This is used when
12502   /// we do not want to diagnose such misaligned access (e.g. in conversions to
12503   /// void*).
12504   void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
12505 
12506   /// This function calls Action when it determines that E designates a
12507   /// misaligned member due to the packed attribute. This is used to emit
12508   /// local diagnostics like in reference binding.
12509   void RefersToMemberWithReducedAlignment(
12510       Expr *E,
12511       llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12512           Action);
12513 
12514   /// Describes the reason a calling convention specification was ignored, used
12515   /// for diagnostics.
12516   enum class CallingConventionIgnoredReason {
12517     ForThisTarget = 0,
12518     VariadicFunction,
12519     ConstructorDestructor,
12520     BuiltinFunction
12521   };
12522   /// Creates a DeviceDiagBuilder that emits the diagnostic if the current
12523   /// context is "used as device code".
12524   ///
12525   /// - If CurLexicalContext is a kernel function or it is known that the
12526   ///   function will be emitted for the device, emits the diagnostics
12527   ///   immediately.
12528   /// - If CurLexicalContext is a function and we are compiling
12529   ///   for the device, but we don't know that this function will be codegen'ed
12530   ///   for devive yet, creates a diagnostic which is emitted if and when we
12531   ///   realize that the function will be codegen'ed.
12532   ///
12533   /// Example usage:
12534   ///
12535   /// Diagnose __float128 type usage only from SYCL device code if the current
12536   /// target doesn't support it
12537   /// if (!S.Context.getTargetInfo().hasFloat128Type() &&
12538   ///     S.getLangOpts().SYCLIsDevice)
12539   ///   SYCLDiagIfDeviceCode(Loc, diag::err_type_unsupported) << "__float128";
12540   DeviceDiagBuilder SYCLDiagIfDeviceCode(SourceLocation Loc, unsigned DiagID);
12541 
12542   /// Check whether we're allowed to call Callee from the current context.
12543   ///
12544   /// - If the call is never allowed in a semantically-correct program
12545   ///   emits an error and returns false.
12546   ///
12547   /// - If the call is allowed in semantically-correct programs, but only if
12548   ///   it's never codegen'ed, creates a deferred diagnostic to be emitted if
12549   ///   and when the caller is codegen'ed, and returns true.
12550   ///
12551   /// - Otherwise, returns true without emitting any diagnostics.
12552   ///
12553   /// Adds Callee to DeviceCallGraph if we don't know if its caller will be
12554   /// codegen'ed yet.
12555   bool checkSYCLDeviceFunction(SourceLocation Loc, FunctionDecl *Callee);
12556 };
12557 
12558 /// RAII object that enters a new expression evaluation context.
12559 class EnterExpressionEvaluationContext {
12560   Sema &Actions;
12561   bool Entered = true;
12562 
12563 public:
12564   EnterExpressionEvaluationContext(
12565       Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
12566       Decl *LambdaContextDecl = nullptr,
12567       Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
12568           Sema::ExpressionEvaluationContextRecord::EK_Other,
12569       bool ShouldEnter = true)
Actions(Actions)12570       : Actions(Actions), Entered(ShouldEnter) {
12571     if (Entered)
12572       Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
12573                                               ExprContext);
12574   }
12575   EnterExpressionEvaluationContext(
12576       Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
12577       Sema::ReuseLambdaContextDecl_t,
12578       Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
12579           Sema::ExpressionEvaluationContextRecord::EK_Other)
Actions(Actions)12580       : Actions(Actions) {
12581     Actions.PushExpressionEvaluationContext(
12582         NewContext, Sema::ReuseLambdaContextDecl, ExprContext);
12583   }
12584 
12585   enum InitListTag { InitList };
12586   EnterExpressionEvaluationContext(Sema &Actions, InitListTag,
12587                                    bool ShouldEnter = true)
Actions(Actions)12588       : Actions(Actions), Entered(false) {
12589     // In C++11 onwards, narrowing checks are performed on the contents of
12590     // braced-init-lists, even when they occur within unevaluated operands.
12591     // Therefore we still need to instantiate constexpr functions used in such
12592     // a context.
12593     if (ShouldEnter && Actions.isUnevaluatedContext() &&
12594         Actions.getLangOpts().CPlusPlus11) {
12595       Actions.PushExpressionEvaluationContext(
12596           Sema::ExpressionEvaluationContext::UnevaluatedList);
12597       Entered = true;
12598     }
12599   }
12600 
~EnterExpressionEvaluationContext()12601   ~EnterExpressionEvaluationContext() {
12602     if (Entered)
12603       Actions.PopExpressionEvaluationContext();
12604   }
12605 };
12606 
12607 DeductionFailureInfo
12608 MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
12609                          sema::TemplateDeductionInfo &Info);
12610 
12611 /// Contains a late templated function.
12612 /// Will be parsed at the end of the translation unit, used by Sema & Parser.
12613 struct LateParsedTemplate {
12614   CachedTokens Toks;
12615   /// The template function declaration to be late parsed.
12616   Decl *D;
12617 };
12618 } // end namespace clang
12619 
12620 namespace llvm {
12621 // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
12622 // SourceLocation.
12623 template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
12624   using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
12625   using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
12626 
12627   static FunctionDeclAndLoc getEmptyKey() {
12628     return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
12629   }
12630 
12631   static FunctionDeclAndLoc getTombstoneKey() {
12632     return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
12633   }
12634 
12635   static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
12636     return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
12637                         FDL.Loc.getRawEncoding());
12638   }
12639 
12640   static bool isEqual(const FunctionDeclAndLoc &LHS,
12641                       const FunctionDeclAndLoc &RHS) {
12642     return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
12643   }
12644 };
12645 } // namespace llvm
12646 
12647 #endif
12648