xref: /freebsd/contrib/llvm-project/clang/lib/Sema/DeclSpec.cpp (revision 6ba2210ee039f2f12878c217bcf058e9c8b26b29)
1 //===--- DeclSpec.cpp - Declaration Specifier Semantic Analysis -----------===//
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 implements semantic analysis for declaration specifiers.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/Sema/DeclSpec.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/DeclCXX.h"
16 #include "clang/AST/Expr.h"
17 #include "clang/AST/LocInfoType.h"
18 #include "clang/AST/TypeLoc.h"
19 #include "clang/Basic/LangOptions.h"
20 #include "clang/Basic/SourceManager.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "clang/Sema/ParsedTemplate.h"
23 #include "clang/Sema/Sema.h"
24 #include "clang/Sema/SemaDiagnostic.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallString.h"
27 #include <cstring>
28 using namespace clang;
29 
30 
31 void UnqualifiedId::setTemplateId(TemplateIdAnnotation *TemplateId) {
32   assert(TemplateId && "NULL template-id annotation?");
33   assert(!TemplateId->isInvalid() &&
34          "should not convert invalid template-ids to unqualified-ids");
35 
36   Kind = UnqualifiedIdKind::IK_TemplateId;
37   this->TemplateId = TemplateId;
38   StartLocation = TemplateId->TemplateNameLoc;
39   EndLocation = TemplateId->RAngleLoc;
40 }
41 
42 void UnqualifiedId::setConstructorTemplateId(TemplateIdAnnotation *TemplateId) {
43   assert(TemplateId && "NULL template-id annotation?");
44   assert(!TemplateId->isInvalid() &&
45          "should not convert invalid template-ids to unqualified-ids");
46 
47   Kind = UnqualifiedIdKind::IK_ConstructorTemplateId;
48   this->TemplateId = TemplateId;
49   StartLocation = TemplateId->TemplateNameLoc;
50   EndLocation = TemplateId->RAngleLoc;
51 }
52 
53 void CXXScopeSpec::Extend(ASTContext &Context, SourceLocation TemplateKWLoc,
54                           TypeLoc TL, SourceLocation ColonColonLoc) {
55   Builder.Extend(Context, TemplateKWLoc, TL, ColonColonLoc);
56   if (Range.getBegin().isInvalid())
57     Range.setBegin(TL.getBeginLoc());
58   Range.setEnd(ColonColonLoc);
59 
60   assert(Range == Builder.getSourceRange() &&
61          "NestedNameSpecifierLoc range computation incorrect");
62 }
63 
64 void CXXScopeSpec::Extend(ASTContext &Context, IdentifierInfo *Identifier,
65                           SourceLocation IdentifierLoc,
66                           SourceLocation ColonColonLoc) {
67   Builder.Extend(Context, Identifier, IdentifierLoc, ColonColonLoc);
68 
69   if (Range.getBegin().isInvalid())
70     Range.setBegin(IdentifierLoc);
71   Range.setEnd(ColonColonLoc);
72 
73   assert(Range == Builder.getSourceRange() &&
74          "NestedNameSpecifierLoc range computation incorrect");
75 }
76 
77 void CXXScopeSpec::Extend(ASTContext &Context, NamespaceDecl *Namespace,
78                           SourceLocation NamespaceLoc,
79                           SourceLocation ColonColonLoc) {
80   Builder.Extend(Context, Namespace, NamespaceLoc, ColonColonLoc);
81 
82   if (Range.getBegin().isInvalid())
83     Range.setBegin(NamespaceLoc);
84   Range.setEnd(ColonColonLoc);
85 
86   assert(Range == Builder.getSourceRange() &&
87          "NestedNameSpecifierLoc range computation incorrect");
88 }
89 
90 void CXXScopeSpec::Extend(ASTContext &Context, NamespaceAliasDecl *Alias,
91                           SourceLocation AliasLoc,
92                           SourceLocation ColonColonLoc) {
93   Builder.Extend(Context, Alias, AliasLoc, ColonColonLoc);
94 
95   if (Range.getBegin().isInvalid())
96     Range.setBegin(AliasLoc);
97   Range.setEnd(ColonColonLoc);
98 
99   assert(Range == Builder.getSourceRange() &&
100          "NestedNameSpecifierLoc range computation incorrect");
101 }
102 
103 void CXXScopeSpec::MakeGlobal(ASTContext &Context,
104                               SourceLocation ColonColonLoc) {
105   Builder.MakeGlobal(Context, ColonColonLoc);
106 
107   Range = SourceRange(ColonColonLoc);
108 
109   assert(Range == Builder.getSourceRange() &&
110          "NestedNameSpecifierLoc range computation incorrect");
111 }
112 
113 void CXXScopeSpec::MakeSuper(ASTContext &Context, CXXRecordDecl *RD,
114                              SourceLocation SuperLoc,
115                              SourceLocation ColonColonLoc) {
116   Builder.MakeSuper(Context, RD, SuperLoc, ColonColonLoc);
117 
118   Range.setBegin(SuperLoc);
119   Range.setEnd(ColonColonLoc);
120 
121   assert(Range == Builder.getSourceRange() &&
122   "NestedNameSpecifierLoc range computation incorrect");
123 }
124 
125 void CXXScopeSpec::MakeTrivial(ASTContext &Context,
126                                NestedNameSpecifier *Qualifier, SourceRange R) {
127   Builder.MakeTrivial(Context, Qualifier, R);
128   Range = R;
129 }
130 
131 void CXXScopeSpec::Adopt(NestedNameSpecifierLoc Other) {
132   if (!Other) {
133     Range = SourceRange();
134     Builder.Clear();
135     return;
136   }
137 
138   Range = Other.getSourceRange();
139   Builder.Adopt(Other);
140   assert(Range == Builder.getSourceRange() &&
141          "NestedNameSpecifierLoc range computation incorrect");
142 }
143 
144 SourceLocation CXXScopeSpec::getLastQualifierNameLoc() const {
145   if (!Builder.getRepresentation())
146     return SourceLocation();
147   return Builder.getTemporary().getLocalBeginLoc();
148 }
149 
150 NestedNameSpecifierLoc
151 CXXScopeSpec::getWithLocInContext(ASTContext &Context) const {
152   if (!Builder.getRepresentation())
153     return NestedNameSpecifierLoc();
154 
155   return Builder.getWithLocInContext(Context);
156 }
157 
158 /// DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
159 /// "TheDeclarator" is the declarator that this will be added to.
160 DeclaratorChunk DeclaratorChunk::getFunction(bool hasProto,
161                                              bool isAmbiguous,
162                                              SourceLocation LParenLoc,
163                                              ParamInfo *Params,
164                                              unsigned NumParams,
165                                              SourceLocation EllipsisLoc,
166                                              SourceLocation RParenLoc,
167                                              bool RefQualifierIsLvalueRef,
168                                              SourceLocation RefQualifierLoc,
169                                              SourceLocation MutableLoc,
170                                              ExceptionSpecificationType
171                                                  ESpecType,
172                                              SourceRange ESpecRange,
173                                              ParsedType *Exceptions,
174                                              SourceRange *ExceptionRanges,
175                                              unsigned NumExceptions,
176                                              Expr *NoexceptExpr,
177                                              CachedTokens *ExceptionSpecTokens,
178                                              ArrayRef<NamedDecl*>
179                                                  DeclsInPrototype,
180                                              SourceLocation LocalRangeBegin,
181                                              SourceLocation LocalRangeEnd,
182                                              Declarator &TheDeclarator,
183                                              TypeResult TrailingReturnType,
184                                              SourceLocation
185                                                  TrailingReturnTypeLoc,
186                                              DeclSpec *MethodQualifiers) {
187   assert(!(MethodQualifiers && MethodQualifiers->getTypeQualifiers() & DeclSpec::TQ_atomic) &&
188          "function cannot have _Atomic qualifier");
189 
190   DeclaratorChunk I;
191   I.Kind                        = Function;
192   I.Loc                         = LocalRangeBegin;
193   I.EndLoc                      = LocalRangeEnd;
194   new (&I.Fun) FunctionTypeInfo;
195   I.Fun.hasPrototype            = hasProto;
196   I.Fun.isVariadic              = EllipsisLoc.isValid();
197   I.Fun.isAmbiguous             = isAmbiguous;
198   I.Fun.LParenLoc               = LParenLoc;
199   I.Fun.EllipsisLoc             = EllipsisLoc;
200   I.Fun.RParenLoc               = RParenLoc;
201   I.Fun.DeleteParams            = false;
202   I.Fun.NumParams               = NumParams;
203   I.Fun.Params                  = nullptr;
204   I.Fun.RefQualifierIsLValueRef = RefQualifierIsLvalueRef;
205   I.Fun.RefQualifierLoc         = RefQualifierLoc;
206   I.Fun.MutableLoc              = MutableLoc;
207   I.Fun.ExceptionSpecType       = ESpecType;
208   I.Fun.ExceptionSpecLocBeg     = ESpecRange.getBegin();
209   I.Fun.ExceptionSpecLocEnd     = ESpecRange.getEnd();
210   I.Fun.NumExceptionsOrDecls    = 0;
211   I.Fun.Exceptions              = nullptr;
212   I.Fun.NoexceptExpr            = nullptr;
213   I.Fun.HasTrailingReturnType   = TrailingReturnType.isUsable() ||
214                                   TrailingReturnType.isInvalid();
215   I.Fun.TrailingReturnType      = TrailingReturnType.get();
216   I.Fun.TrailingReturnTypeLoc   = TrailingReturnTypeLoc;
217   I.Fun.MethodQualifiers        = nullptr;
218   I.Fun.QualAttrFactory         = nullptr;
219 
220   if (MethodQualifiers && (MethodQualifiers->getTypeQualifiers() ||
221                            MethodQualifiers->getAttributes().size())) {
222     auto &attrs = MethodQualifiers->getAttributes();
223     I.Fun.MethodQualifiers = new DeclSpec(attrs.getPool().getFactory());
224     MethodQualifiers->forEachCVRUQualifier(
225         [&](DeclSpec::TQ TypeQual, StringRef PrintName, SourceLocation SL) {
226           I.Fun.MethodQualifiers->SetTypeQual(TypeQual, SL);
227         });
228     I.Fun.MethodQualifiers->getAttributes().takeAllFrom(attrs);
229     I.Fun.MethodQualifiers->getAttributePool().takeAllFrom(attrs.getPool());
230   }
231 
232   assert(I.Fun.ExceptionSpecType == ESpecType && "bitfield overflow");
233 
234   // new[] a parameter array if needed.
235   if (NumParams) {
236     // If the 'InlineParams' in Declarator is unused and big enough, put our
237     // parameter list there (in an effort to avoid new/delete traffic).  If it
238     // is already used (consider a function returning a function pointer) or too
239     // small (function with too many parameters), go to the heap.
240     if (!TheDeclarator.InlineStorageUsed &&
241         NumParams <= llvm::array_lengthof(TheDeclarator.InlineParams)) {
242       I.Fun.Params = TheDeclarator.InlineParams;
243       new (I.Fun.Params) ParamInfo[NumParams];
244       I.Fun.DeleteParams = false;
245       TheDeclarator.InlineStorageUsed = true;
246     } else {
247       I.Fun.Params = new DeclaratorChunk::ParamInfo[NumParams];
248       I.Fun.DeleteParams = true;
249     }
250     for (unsigned i = 0; i < NumParams; i++)
251       I.Fun.Params[i] = std::move(Params[i]);
252   }
253 
254   // Check what exception specification information we should actually store.
255   switch (ESpecType) {
256   default: break; // By default, save nothing.
257   case EST_Dynamic:
258     // new[] an exception array if needed
259     if (NumExceptions) {
260       I.Fun.NumExceptionsOrDecls = NumExceptions;
261       I.Fun.Exceptions = new DeclaratorChunk::TypeAndRange[NumExceptions];
262       for (unsigned i = 0; i != NumExceptions; ++i) {
263         I.Fun.Exceptions[i].Ty = Exceptions[i];
264         I.Fun.Exceptions[i].Range = ExceptionRanges[i];
265       }
266     }
267     break;
268 
269   case EST_DependentNoexcept:
270   case EST_NoexceptFalse:
271   case EST_NoexceptTrue:
272     I.Fun.NoexceptExpr = NoexceptExpr;
273     break;
274 
275   case EST_Unparsed:
276     I.Fun.ExceptionSpecTokens = ExceptionSpecTokens;
277     break;
278   }
279 
280   if (!DeclsInPrototype.empty()) {
281     assert(ESpecType == EST_None && NumExceptions == 0 &&
282            "cannot have exception specifiers and decls in prototype");
283     I.Fun.NumExceptionsOrDecls = DeclsInPrototype.size();
284     // Copy the array of decls into stable heap storage.
285     I.Fun.DeclsInPrototype = new NamedDecl *[DeclsInPrototype.size()];
286     for (size_t J = 0; J < DeclsInPrototype.size(); ++J)
287       I.Fun.DeclsInPrototype[J] = DeclsInPrototype[J];
288   }
289 
290   return I;
291 }
292 
293 void Declarator::setDecompositionBindings(
294     SourceLocation LSquareLoc,
295     ArrayRef<DecompositionDeclarator::Binding> Bindings,
296     SourceLocation RSquareLoc) {
297   assert(!hasName() && "declarator given multiple names!");
298 
299   BindingGroup.LSquareLoc = LSquareLoc;
300   BindingGroup.RSquareLoc = RSquareLoc;
301   BindingGroup.NumBindings = Bindings.size();
302   Range.setEnd(RSquareLoc);
303 
304   // We're now past the identifier.
305   SetIdentifier(nullptr, LSquareLoc);
306   Name.EndLocation = RSquareLoc;
307 
308   // Allocate storage for bindings and stash them away.
309   if (Bindings.size()) {
310     if (!InlineStorageUsed &&
311         Bindings.size() <= llvm::array_lengthof(InlineBindings)) {
312       BindingGroup.Bindings = InlineBindings;
313       BindingGroup.DeleteBindings = false;
314       InlineStorageUsed = true;
315     } else {
316       BindingGroup.Bindings =
317           new DecompositionDeclarator::Binding[Bindings.size()];
318       BindingGroup.DeleteBindings = true;
319     }
320     std::uninitialized_copy(Bindings.begin(), Bindings.end(),
321                             BindingGroup.Bindings);
322   }
323 }
324 
325 bool Declarator::isDeclarationOfFunction() const {
326   for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
327     switch (DeclTypeInfo[i].Kind) {
328     case DeclaratorChunk::Function:
329       return true;
330     case DeclaratorChunk::Paren:
331       continue;
332     case DeclaratorChunk::Pointer:
333     case DeclaratorChunk::Reference:
334     case DeclaratorChunk::Array:
335     case DeclaratorChunk::BlockPointer:
336     case DeclaratorChunk::MemberPointer:
337     case DeclaratorChunk::Pipe:
338       return false;
339     }
340     llvm_unreachable("Invalid type chunk");
341   }
342 
343   switch (DS.getTypeSpecType()) {
344     case TST_atomic:
345     case TST_auto:
346     case TST_auto_type:
347     case TST_bool:
348     case TST_char:
349     case TST_char8:
350     case TST_char16:
351     case TST_char32:
352     case TST_class:
353     case TST_decimal128:
354     case TST_decimal32:
355     case TST_decimal64:
356     case TST_double:
357     case TST_Accum:
358     case TST_Fract:
359     case TST_Float16:
360     case TST_float128:
361     case TST_enum:
362     case TST_error:
363     case TST_float:
364     case TST_half:
365     case TST_int:
366     case TST_int128:
367     case TST_extint:
368     case TST_struct:
369     case TST_interface:
370     case TST_union:
371     case TST_unknown_anytype:
372     case TST_unspecified:
373     case TST_void:
374     case TST_wchar:
375     case TST_BFloat16:
376 #define GENERIC_IMAGE_TYPE(ImgType, Id) case TST_##ImgType##_t:
377 #include "clang/Basic/OpenCLImageTypes.def"
378       return false;
379 
380     case TST_decltype_auto:
381       // This must have an initializer, so can't be a function declaration,
382       // even if the initializer has function type.
383       return false;
384 
385     case TST_decltype:
386     case TST_typeofExpr:
387       if (Expr *E = DS.getRepAsExpr())
388         return E->getType()->isFunctionType();
389       return false;
390 
391     case TST_underlyingType:
392     case TST_typename:
393     case TST_typeofType: {
394       QualType QT = DS.getRepAsType().get();
395       if (QT.isNull())
396         return false;
397 
398       if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT))
399         QT = LIT->getType();
400 
401       if (QT.isNull())
402         return false;
403 
404       return QT->isFunctionType();
405     }
406   }
407 
408   llvm_unreachable("Invalid TypeSpecType!");
409 }
410 
411 bool Declarator::isStaticMember() {
412   assert(getContext() == DeclaratorContext::Member);
413   return getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
414          (getName().Kind == UnqualifiedIdKind::IK_OperatorFunctionId &&
415           CXXMethodDecl::isStaticOverloadedOperator(
416               getName().OperatorFunctionId.Operator));
417 }
418 
419 bool Declarator::isCtorOrDtor() {
420   return (getName().getKind() == UnqualifiedIdKind::IK_ConstructorName) ||
421          (getName().getKind() == UnqualifiedIdKind::IK_DestructorName);
422 }
423 
424 void DeclSpec::forEachCVRUQualifier(
425     llvm::function_ref<void(TQ, StringRef, SourceLocation)> Handle) {
426   if (TypeQualifiers & TQ_const)
427     Handle(TQ_const, "const", TQ_constLoc);
428   if (TypeQualifiers & TQ_volatile)
429     Handle(TQ_volatile, "volatile", TQ_volatileLoc);
430   if (TypeQualifiers & TQ_restrict)
431     Handle(TQ_restrict, "restrict", TQ_restrictLoc);
432   if (TypeQualifiers & TQ_unaligned)
433     Handle(TQ_unaligned, "unaligned", TQ_unalignedLoc);
434 }
435 
436 void DeclSpec::forEachQualifier(
437     llvm::function_ref<void(TQ, StringRef, SourceLocation)> Handle) {
438   forEachCVRUQualifier(Handle);
439   // FIXME: Add code below to iterate through the attributes and call Handle.
440 }
441 
442 bool DeclSpec::hasTagDefinition() const {
443   if (!TypeSpecOwned)
444     return false;
445   return cast<TagDecl>(getRepAsDecl())->isCompleteDefinition();
446 }
447 
448 /// getParsedSpecifiers - Return a bitmask of which flavors of specifiers this
449 /// declaration specifier includes.
450 ///
451 unsigned DeclSpec::getParsedSpecifiers() const {
452   unsigned Res = 0;
453   if (StorageClassSpec != SCS_unspecified ||
454       ThreadStorageClassSpec != TSCS_unspecified)
455     Res |= PQ_StorageClassSpecifier;
456 
457   if (TypeQualifiers != TQ_unspecified)
458     Res |= PQ_TypeQualifier;
459 
460   if (hasTypeSpecifier())
461     Res |= PQ_TypeSpecifier;
462 
463   if (FS_inline_specified || FS_virtual_specified || hasExplicitSpecifier() ||
464       FS_noreturn_specified || FS_forceinline_specified)
465     Res |= PQ_FunctionSpecifier;
466   return Res;
467 }
468 
469 template <class T> static bool BadSpecifier(T TNew, T TPrev,
470                                             const char *&PrevSpec,
471                                             unsigned &DiagID,
472                                             bool IsExtension = true) {
473   PrevSpec = DeclSpec::getSpecifierName(TPrev);
474   if (TNew != TPrev)
475     DiagID = diag::err_invalid_decl_spec_combination;
476   else
477     DiagID = IsExtension ? diag::ext_warn_duplicate_declspec :
478                            diag::warn_duplicate_declspec;
479   return true;
480 }
481 
482 const char *DeclSpec::getSpecifierName(DeclSpec::SCS S) {
483   switch (S) {
484   case DeclSpec::SCS_unspecified: return "unspecified";
485   case DeclSpec::SCS_typedef:     return "typedef";
486   case DeclSpec::SCS_extern:      return "extern";
487   case DeclSpec::SCS_static:      return "static";
488   case DeclSpec::SCS_auto:        return "auto";
489   case DeclSpec::SCS_register:    return "register";
490   case DeclSpec::SCS_private_extern: return "__private_extern__";
491   case DeclSpec::SCS_mutable:     return "mutable";
492   }
493   llvm_unreachable("Unknown typespec!");
494 }
495 
496 const char *DeclSpec::getSpecifierName(DeclSpec::TSCS S) {
497   switch (S) {
498   case DeclSpec::TSCS_unspecified:   return "unspecified";
499   case DeclSpec::TSCS___thread:      return "__thread";
500   case DeclSpec::TSCS_thread_local:  return "thread_local";
501   case DeclSpec::TSCS__Thread_local: return "_Thread_local";
502   }
503   llvm_unreachable("Unknown typespec!");
504 }
505 
506 const char *DeclSpec::getSpecifierName(TypeSpecifierWidth W) {
507   switch (W) {
508   case TypeSpecifierWidth::Unspecified:
509     return "unspecified";
510   case TypeSpecifierWidth::Short:
511     return "short";
512   case TypeSpecifierWidth::Long:
513     return "long";
514   case TypeSpecifierWidth::LongLong:
515     return "long long";
516   }
517   llvm_unreachable("Unknown typespec!");
518 }
519 
520 const char *DeclSpec::getSpecifierName(TSC C) {
521   switch (C) {
522   case TSC_unspecified: return "unspecified";
523   case TSC_imaginary:   return "imaginary";
524   case TSC_complex:     return "complex";
525   }
526   llvm_unreachable("Unknown typespec!");
527 }
528 
529 const char *DeclSpec::getSpecifierName(TypeSpecifierSign S) {
530   switch (S) {
531   case TypeSpecifierSign::Unspecified:
532     return "unspecified";
533   case TypeSpecifierSign::Signed:
534     return "signed";
535   case TypeSpecifierSign::Unsigned:
536     return "unsigned";
537   }
538   llvm_unreachable("Unknown typespec!");
539 }
540 
541 const char *DeclSpec::getSpecifierName(DeclSpec::TST T,
542                                        const PrintingPolicy &Policy) {
543   switch (T) {
544   case DeclSpec::TST_unspecified: return "unspecified";
545   case DeclSpec::TST_void:        return "void";
546   case DeclSpec::TST_char:        return "char";
547   case DeclSpec::TST_wchar:       return Policy.MSWChar ? "__wchar_t" : "wchar_t";
548   case DeclSpec::TST_char8:       return "char8_t";
549   case DeclSpec::TST_char16:      return "char16_t";
550   case DeclSpec::TST_char32:      return "char32_t";
551   case DeclSpec::TST_int:         return "int";
552   case DeclSpec::TST_int128:      return "__int128";
553   case DeclSpec::TST_extint:      return "_ExtInt";
554   case DeclSpec::TST_half:        return "half";
555   case DeclSpec::TST_float:       return "float";
556   case DeclSpec::TST_double:      return "double";
557   case DeclSpec::TST_accum:       return "_Accum";
558   case DeclSpec::TST_fract:       return "_Fract";
559   case DeclSpec::TST_float16:     return "_Float16";
560   case DeclSpec::TST_float128:    return "__float128";
561   case DeclSpec::TST_bool:        return Policy.Bool ? "bool" : "_Bool";
562   case DeclSpec::TST_decimal32:   return "_Decimal32";
563   case DeclSpec::TST_decimal64:   return "_Decimal64";
564   case DeclSpec::TST_decimal128:  return "_Decimal128";
565   case DeclSpec::TST_enum:        return "enum";
566   case DeclSpec::TST_class:       return "class";
567   case DeclSpec::TST_union:       return "union";
568   case DeclSpec::TST_struct:      return "struct";
569   case DeclSpec::TST_interface:   return "__interface";
570   case DeclSpec::TST_typename:    return "type-name";
571   case DeclSpec::TST_typeofType:
572   case DeclSpec::TST_typeofExpr:  return "typeof";
573   case DeclSpec::TST_auto:        return "auto";
574   case DeclSpec::TST_auto_type:   return "__auto_type";
575   case DeclSpec::TST_decltype:    return "(decltype)";
576   case DeclSpec::TST_decltype_auto: return "decltype(auto)";
577   case DeclSpec::TST_underlyingType: return "__underlying_type";
578   case DeclSpec::TST_unknown_anytype: return "__unknown_anytype";
579   case DeclSpec::TST_atomic: return "_Atomic";
580   case DeclSpec::TST_BFloat16: return "__bf16";
581 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
582   case DeclSpec::TST_##ImgType##_t: \
583     return #ImgType "_t";
584 #include "clang/Basic/OpenCLImageTypes.def"
585   case DeclSpec::TST_error:       return "(error)";
586   }
587   llvm_unreachable("Unknown typespec!");
588 }
589 
590 const char *DeclSpec::getSpecifierName(ConstexprSpecKind C) {
591   switch (C) {
592   case ConstexprSpecKind::Unspecified:
593     return "unspecified";
594   case ConstexprSpecKind::Constexpr:
595     return "constexpr";
596   case ConstexprSpecKind::Consteval:
597     return "consteval";
598   case ConstexprSpecKind::Constinit:
599     return "constinit";
600   }
601   llvm_unreachable("Unknown ConstexprSpecKind");
602 }
603 
604 const char *DeclSpec::getSpecifierName(TQ T) {
605   switch (T) {
606   case DeclSpec::TQ_unspecified: return "unspecified";
607   case DeclSpec::TQ_const:       return "const";
608   case DeclSpec::TQ_restrict:    return "restrict";
609   case DeclSpec::TQ_volatile:    return "volatile";
610   case DeclSpec::TQ_atomic:      return "_Atomic";
611   case DeclSpec::TQ_unaligned:   return "__unaligned";
612   }
613   llvm_unreachable("Unknown typespec!");
614 }
615 
616 bool DeclSpec::SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc,
617                                    const char *&PrevSpec,
618                                    unsigned &DiagID,
619                                    const PrintingPolicy &Policy) {
620   // OpenCL v1.1 s6.8g: "The extern, static, auto and register storage-class
621   // specifiers are not supported.
622   // It seems sensible to prohibit private_extern too
623   // The cl_clang_storage_class_specifiers extension enables support for
624   // these storage-class specifiers.
625   // OpenCL v1.2 s6.8 changes this to "The auto and register storage-class
626   // specifiers are not supported."
627   if (S.getLangOpts().OpenCL &&
628       !S.getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers")) {
629     switch (SC) {
630     case SCS_extern:
631     case SCS_private_extern:
632     case SCS_static:
633       if (S.getLangOpts().OpenCLVersion < 120 &&
634           !S.getLangOpts().OpenCLCPlusPlus) {
635         DiagID = diag::err_opencl_unknown_type_specifier;
636         PrevSpec = getSpecifierName(SC);
637         return true;
638       }
639       break;
640     case SCS_auto:
641     case SCS_register:
642       DiagID   = diag::err_opencl_unknown_type_specifier;
643       PrevSpec = getSpecifierName(SC);
644       return true;
645     default:
646       break;
647     }
648   }
649 
650   if (StorageClassSpec != SCS_unspecified) {
651     // Maybe this is an attempt to use C++11 'auto' outside of C++11 mode.
652     bool isInvalid = true;
653     if (TypeSpecType == TST_unspecified && S.getLangOpts().CPlusPlus) {
654       if (SC == SCS_auto)
655         return SetTypeSpecType(TST_auto, Loc, PrevSpec, DiagID, Policy);
656       if (StorageClassSpec == SCS_auto) {
657         isInvalid = SetTypeSpecType(TST_auto, StorageClassSpecLoc,
658                                     PrevSpec, DiagID, Policy);
659         assert(!isInvalid && "auto SCS -> TST recovery failed");
660       }
661     }
662 
663     // Changing storage class is allowed only if the previous one
664     // was the 'extern' that is part of a linkage specification and
665     // the new storage class is 'typedef'.
666     if (isInvalid &&
667         !(SCS_extern_in_linkage_spec &&
668           StorageClassSpec == SCS_extern &&
669           SC == SCS_typedef))
670       return BadSpecifier(SC, (SCS)StorageClassSpec, PrevSpec, DiagID);
671   }
672   StorageClassSpec = SC;
673   StorageClassSpecLoc = Loc;
674   assert((unsigned)SC == StorageClassSpec && "SCS constants overflow bitfield");
675   return false;
676 }
677 
678 bool DeclSpec::SetStorageClassSpecThread(TSCS TSC, SourceLocation Loc,
679                                          const char *&PrevSpec,
680                                          unsigned &DiagID) {
681   if (ThreadStorageClassSpec != TSCS_unspecified)
682     return BadSpecifier(TSC, (TSCS)ThreadStorageClassSpec, PrevSpec, DiagID);
683 
684   ThreadStorageClassSpec = TSC;
685   ThreadStorageClassSpecLoc = Loc;
686   return false;
687 }
688 
689 /// These methods set the specified attribute of the DeclSpec, but return true
690 /// and ignore the request if invalid (e.g. "extern" then "auto" is
691 /// specified).
692 bool DeclSpec::SetTypeSpecWidth(TypeSpecifierWidth W, SourceLocation Loc,
693                                 const char *&PrevSpec, unsigned &DiagID,
694                                 const PrintingPolicy &Policy) {
695   // Overwrite TSWRange.Begin only if TypeSpecWidth was unspecified, so that
696   // for 'long long' we will keep the source location of the first 'long'.
697   if (getTypeSpecWidth() == TypeSpecifierWidth::Unspecified)
698     TSWRange.setBegin(Loc);
699   // Allow turning long -> long long.
700   else if (W != TypeSpecifierWidth::LongLong ||
701            getTypeSpecWidth() != TypeSpecifierWidth::Long)
702     return BadSpecifier(W, getTypeSpecWidth(), PrevSpec, DiagID);
703   TypeSpecWidth = static_cast<unsigned>(W);
704   // Remember location of the last 'long'
705   TSWRange.setEnd(Loc);
706   return false;
707 }
708 
709 bool DeclSpec::SetTypeSpecComplex(TSC C, SourceLocation Loc,
710                                   const char *&PrevSpec,
711                                   unsigned &DiagID) {
712   if (TypeSpecComplex != TSC_unspecified)
713     return BadSpecifier(C, (TSC)TypeSpecComplex, PrevSpec, DiagID);
714   TypeSpecComplex = C;
715   TSCLoc = Loc;
716   return false;
717 }
718 
719 bool DeclSpec::SetTypeSpecSign(TypeSpecifierSign S, SourceLocation Loc,
720                                const char *&PrevSpec, unsigned &DiagID) {
721   if (getTypeSpecSign() != TypeSpecifierSign::Unspecified)
722     return BadSpecifier(S, getTypeSpecSign(), PrevSpec, DiagID);
723   TypeSpecSign = static_cast<unsigned>(S);
724   TSSLoc = Loc;
725   return false;
726 }
727 
728 bool DeclSpec::SetTypeSpecType(TST T, SourceLocation Loc,
729                                const char *&PrevSpec,
730                                unsigned &DiagID,
731                                ParsedType Rep,
732                                const PrintingPolicy &Policy) {
733   return SetTypeSpecType(T, Loc, Loc, PrevSpec, DiagID, Rep, Policy);
734 }
735 
736 bool DeclSpec::SetTypeSpecType(TST T, SourceLocation TagKwLoc,
737                                SourceLocation TagNameLoc,
738                                const char *&PrevSpec,
739                                unsigned &DiagID,
740                                ParsedType Rep,
741                                const PrintingPolicy &Policy) {
742   assert(isTypeRep(T) && "T does not store a type");
743   assert(Rep && "no type provided!");
744   if (TypeSpecType == TST_error)
745     return false;
746   if (TypeSpecType != TST_unspecified) {
747     PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType, Policy);
748     DiagID = diag::err_invalid_decl_spec_combination;
749     return true;
750   }
751   TypeSpecType = T;
752   TypeRep = Rep;
753   TSTLoc = TagKwLoc;
754   TSTNameLoc = TagNameLoc;
755   TypeSpecOwned = false;
756   return false;
757 }
758 
759 bool DeclSpec::SetTypeSpecType(TST T, SourceLocation Loc,
760                                const char *&PrevSpec,
761                                unsigned &DiagID,
762                                Expr *Rep,
763                                const PrintingPolicy &Policy) {
764   assert(isExprRep(T) && "T does not store an expr");
765   assert(Rep && "no expression provided!");
766   if (TypeSpecType == TST_error)
767     return false;
768   if (TypeSpecType != TST_unspecified) {
769     PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType, Policy);
770     DiagID = diag::err_invalid_decl_spec_combination;
771     return true;
772   }
773   TypeSpecType = T;
774   ExprRep = Rep;
775   TSTLoc = Loc;
776   TSTNameLoc = Loc;
777   TypeSpecOwned = false;
778   return false;
779 }
780 
781 bool DeclSpec::SetTypeSpecType(TST T, SourceLocation Loc,
782                                const char *&PrevSpec,
783                                unsigned &DiagID,
784                                Decl *Rep, bool Owned,
785                                const PrintingPolicy &Policy) {
786   return SetTypeSpecType(T, Loc, Loc, PrevSpec, DiagID, Rep, Owned, Policy);
787 }
788 
789 bool DeclSpec::SetTypeSpecType(TST T, SourceLocation TagKwLoc,
790                                SourceLocation TagNameLoc,
791                                const char *&PrevSpec,
792                                unsigned &DiagID,
793                                Decl *Rep, bool Owned,
794                                const PrintingPolicy &Policy) {
795   assert(isDeclRep(T) && "T does not store a decl");
796   // Unlike the other cases, we don't assert that we actually get a decl.
797 
798   if (TypeSpecType == TST_error)
799     return false;
800   if (TypeSpecType != TST_unspecified) {
801     PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType, Policy);
802     DiagID = diag::err_invalid_decl_spec_combination;
803     return true;
804   }
805   TypeSpecType = T;
806   DeclRep = Rep;
807   TSTLoc = TagKwLoc;
808   TSTNameLoc = TagNameLoc;
809   TypeSpecOwned = Owned && Rep != nullptr;
810   return false;
811 }
812 
813 bool DeclSpec::SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
814                                unsigned &DiagID, TemplateIdAnnotation *Rep,
815                                const PrintingPolicy &Policy) {
816   assert(T == TST_auto || T == TST_decltype_auto);
817   ConstrainedAuto = true;
818   TemplateIdRep = Rep;
819   return SetTypeSpecType(T, Loc, PrevSpec, DiagID, Policy);
820 }
821 
822 bool DeclSpec::SetTypeSpecType(TST T, SourceLocation Loc,
823                                const char *&PrevSpec,
824                                unsigned &DiagID,
825                                const PrintingPolicy &Policy) {
826   assert(!isDeclRep(T) && !isTypeRep(T) && !isExprRep(T) &&
827          "rep required for these type-spec kinds!");
828   if (TypeSpecType == TST_error)
829     return false;
830   if (TypeSpecType != TST_unspecified) {
831     PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType, Policy);
832     DiagID = diag::err_invalid_decl_spec_combination;
833     return true;
834   }
835   TSTLoc = Loc;
836   TSTNameLoc = Loc;
837   if (TypeAltiVecVector && (T == TST_bool) && !TypeAltiVecBool) {
838     TypeAltiVecBool = true;
839     return false;
840   }
841   TypeSpecType = T;
842   TypeSpecOwned = false;
843   return false;
844 }
845 
846 bool DeclSpec::SetTypeSpecSat(SourceLocation Loc, const char *&PrevSpec,
847                               unsigned &DiagID) {
848   // Cannot set twice
849   if (TypeSpecSat) {
850     DiagID = diag::warn_duplicate_declspec;
851     PrevSpec = "_Sat";
852     return true;
853   }
854   TypeSpecSat = true;
855   TSSatLoc = Loc;
856   return false;
857 }
858 
859 bool DeclSpec::SetTypeAltiVecVector(bool isAltiVecVector, SourceLocation Loc,
860                           const char *&PrevSpec, unsigned &DiagID,
861                           const PrintingPolicy &Policy) {
862   if (TypeSpecType == TST_error)
863     return false;
864   if (TypeSpecType != TST_unspecified) {
865     PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType, Policy);
866     DiagID = diag::err_invalid_vector_decl_spec_combination;
867     return true;
868   }
869   TypeAltiVecVector = isAltiVecVector;
870   AltiVecLoc = Loc;
871   return false;
872 }
873 
874 bool DeclSpec::SetTypePipe(bool isPipe, SourceLocation Loc,
875                            const char *&PrevSpec, unsigned &DiagID,
876                            const PrintingPolicy &Policy) {
877   if (TypeSpecType == TST_error)
878     return false;
879   if (TypeSpecType != TST_unspecified) {
880     PrevSpec = DeclSpec::getSpecifierName((TST)TypeSpecType, Policy);
881     DiagID = diag::err_invalid_decl_spec_combination;
882     return true;
883   }
884 
885   if (isPipe) {
886     TypeSpecPipe = static_cast<unsigned>(TypeSpecifiersPipe::Pipe);
887   }
888   return false;
889 }
890 
891 bool DeclSpec::SetTypeAltiVecPixel(bool isAltiVecPixel, SourceLocation Loc,
892                           const char *&PrevSpec, unsigned &DiagID,
893                           const PrintingPolicy &Policy) {
894   if (TypeSpecType == TST_error)
895     return false;
896   if (!TypeAltiVecVector || TypeAltiVecPixel ||
897       (TypeSpecType != TST_unspecified)) {
898     PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType, Policy);
899     DiagID = diag::err_invalid_pixel_decl_spec_combination;
900     return true;
901   }
902   TypeAltiVecPixel = isAltiVecPixel;
903   TSTLoc = Loc;
904   TSTNameLoc = Loc;
905   return false;
906 }
907 
908 bool DeclSpec::SetTypeAltiVecBool(bool isAltiVecBool, SourceLocation Loc,
909                                   const char *&PrevSpec, unsigned &DiagID,
910                                   const PrintingPolicy &Policy) {
911   if (TypeSpecType == TST_error)
912     return false;
913   if (!TypeAltiVecVector || TypeAltiVecBool ||
914       (TypeSpecType != TST_unspecified)) {
915     PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType, Policy);
916     DiagID = diag::err_invalid_vector_bool_decl_spec;
917     return true;
918   }
919   TypeAltiVecBool = isAltiVecBool;
920   TSTLoc = Loc;
921   TSTNameLoc = Loc;
922   return false;
923 }
924 
925 bool DeclSpec::SetTypeSpecError() {
926   TypeSpecType = TST_error;
927   TypeSpecOwned = false;
928   TSTLoc = SourceLocation();
929   TSTNameLoc = SourceLocation();
930   return false;
931 }
932 
933 bool DeclSpec::SetExtIntType(SourceLocation KWLoc, Expr *BitsExpr,
934                              const char *&PrevSpec, unsigned &DiagID,
935                              const PrintingPolicy &Policy) {
936   assert(BitsExpr && "no expression provided!");
937   if (TypeSpecType == TST_error)
938     return false;
939 
940   if (TypeSpecType != TST_unspecified) {
941     PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType, Policy);
942     DiagID = diag::err_invalid_decl_spec_combination;
943     return true;
944   }
945 
946   TypeSpecType = TST_extint;
947   ExprRep = BitsExpr;
948   TSTLoc = KWLoc;
949   TSTNameLoc = KWLoc;
950   TypeSpecOwned = false;
951   return false;
952 }
953 
954 bool DeclSpec::SetTypeQual(TQ T, SourceLocation Loc, const char *&PrevSpec,
955                            unsigned &DiagID, const LangOptions &Lang) {
956   // Duplicates are permitted in C99 onwards, but are not permitted in C89 or
957   // C++.  However, since this is likely not what the user intended, we will
958   // always warn.  We do not need to set the qualifier's location since we
959   // already have it.
960   if (TypeQualifiers & T) {
961     bool IsExtension = true;
962     if (Lang.C99)
963       IsExtension = false;
964     return BadSpecifier(T, T, PrevSpec, DiagID, IsExtension);
965   }
966 
967   return SetTypeQual(T, Loc);
968 }
969 
970 bool DeclSpec::SetTypeQual(TQ T, SourceLocation Loc) {
971   TypeQualifiers |= T;
972 
973   switch (T) {
974   case TQ_unspecified: break;
975   case TQ_const:    TQ_constLoc = Loc; return false;
976   case TQ_restrict: TQ_restrictLoc = Loc; return false;
977   case TQ_volatile: TQ_volatileLoc = Loc; return false;
978   case TQ_unaligned: TQ_unalignedLoc = Loc; return false;
979   case TQ_atomic:   TQ_atomicLoc = Loc; return false;
980   }
981 
982   llvm_unreachable("Unknown type qualifier!");
983 }
984 
985 bool DeclSpec::setFunctionSpecInline(SourceLocation Loc, const char *&PrevSpec,
986                                      unsigned &DiagID) {
987   // 'inline inline' is ok.  However, since this is likely not what the user
988   // intended, we will always warn, similar to duplicates of type qualifiers.
989   if (FS_inline_specified) {
990     DiagID = diag::warn_duplicate_declspec;
991     PrevSpec = "inline";
992     return true;
993   }
994   FS_inline_specified = true;
995   FS_inlineLoc = Loc;
996   return false;
997 }
998 
999 bool DeclSpec::setFunctionSpecForceInline(SourceLocation Loc, const char *&PrevSpec,
1000                                           unsigned &DiagID) {
1001   if (FS_forceinline_specified) {
1002     DiagID = diag::warn_duplicate_declspec;
1003     PrevSpec = "__forceinline";
1004     return true;
1005   }
1006   FS_forceinline_specified = true;
1007   FS_forceinlineLoc = Loc;
1008   return false;
1009 }
1010 
1011 bool DeclSpec::setFunctionSpecVirtual(SourceLocation Loc,
1012                                       const char *&PrevSpec,
1013                                       unsigned &DiagID) {
1014   // 'virtual virtual' is ok, but warn as this is likely not what the user
1015   // intended.
1016   if (FS_virtual_specified) {
1017     DiagID = diag::warn_duplicate_declspec;
1018     PrevSpec = "virtual";
1019     return true;
1020   }
1021   FS_virtual_specified = true;
1022   FS_virtualLoc = Loc;
1023   return false;
1024 }
1025 
1026 bool DeclSpec::setFunctionSpecExplicit(SourceLocation Loc,
1027                                        const char *&PrevSpec, unsigned &DiagID,
1028                                        ExplicitSpecifier ExplicitSpec,
1029                                        SourceLocation CloseParenLoc) {
1030   // 'explicit explicit' is ok, but warn as this is likely not what the user
1031   // intended.
1032   if (hasExplicitSpecifier()) {
1033     DiagID = (ExplicitSpec.getExpr() || FS_explicit_specifier.getExpr())
1034                  ? diag::err_duplicate_declspec
1035                  : diag::ext_warn_duplicate_declspec;
1036     PrevSpec = "explicit";
1037     return true;
1038   }
1039   FS_explicit_specifier = ExplicitSpec;
1040   FS_explicitLoc = Loc;
1041   FS_explicitCloseParenLoc = CloseParenLoc;
1042   return false;
1043 }
1044 
1045 bool DeclSpec::setFunctionSpecNoreturn(SourceLocation Loc,
1046                                        const char *&PrevSpec,
1047                                        unsigned &DiagID) {
1048   // '_Noreturn _Noreturn' is ok, but warn as this is likely not what the user
1049   // intended.
1050   if (FS_noreturn_specified) {
1051     DiagID = diag::warn_duplicate_declspec;
1052     PrevSpec = "_Noreturn";
1053     return true;
1054   }
1055   FS_noreturn_specified = true;
1056   FS_noreturnLoc = Loc;
1057   return false;
1058 }
1059 
1060 bool DeclSpec::SetFriendSpec(SourceLocation Loc, const char *&PrevSpec,
1061                              unsigned &DiagID) {
1062   if (Friend_specified) {
1063     PrevSpec = "friend";
1064     // Keep the later location, so that we can later diagnose ill-formed
1065     // declarations like 'friend class X friend;'. Per [class.friend]p3,
1066     // 'friend' must be the first token in a friend declaration that is
1067     // not a function declaration.
1068     FriendLoc = Loc;
1069     DiagID = diag::warn_duplicate_declspec;
1070     return true;
1071   }
1072 
1073   Friend_specified = true;
1074   FriendLoc = Loc;
1075   return false;
1076 }
1077 
1078 bool DeclSpec::setModulePrivateSpec(SourceLocation Loc, const char *&PrevSpec,
1079                                     unsigned &DiagID) {
1080   if (isModulePrivateSpecified()) {
1081     PrevSpec = "__module_private__";
1082     DiagID = diag::ext_warn_duplicate_declspec;
1083     return true;
1084   }
1085 
1086   ModulePrivateLoc = Loc;
1087   return false;
1088 }
1089 
1090 bool DeclSpec::SetConstexprSpec(ConstexprSpecKind ConstexprKind,
1091                                 SourceLocation Loc, const char *&PrevSpec,
1092                                 unsigned &DiagID) {
1093   if (getConstexprSpecifier() != ConstexprSpecKind::Unspecified)
1094     return BadSpecifier(ConstexprKind, getConstexprSpecifier(), PrevSpec,
1095                         DiagID);
1096   ConstexprSpecifier = static_cast<unsigned>(ConstexprKind);
1097   ConstexprLoc = Loc;
1098   return false;
1099 }
1100 
1101 void DeclSpec::SaveWrittenBuiltinSpecs() {
1102   writtenBS.Sign = static_cast<int>(getTypeSpecSign());
1103   writtenBS.Width = static_cast<int>(getTypeSpecWidth());
1104   writtenBS.Type = getTypeSpecType();
1105   // Search the list of attributes for the presence of a mode attribute.
1106   writtenBS.ModeAttr = getAttributes().hasAttribute(ParsedAttr::AT_Mode);
1107 }
1108 
1109 /// Finish - This does final analysis of the declspec, rejecting things like
1110 /// "_Imaginary" (lacking an FP type).  This returns a diagnostic to issue or
1111 /// diag::NUM_DIAGNOSTICS if there is no error.  After calling this method,
1112 /// DeclSpec is guaranteed self-consistent, even if an error occurred.
1113 void DeclSpec::Finish(Sema &S, const PrintingPolicy &Policy) {
1114   // Before possibly changing their values, save specs as written.
1115   SaveWrittenBuiltinSpecs();
1116 
1117   // Check the type specifier components first. No checking for an invalid
1118   // type.
1119   if (TypeSpecType == TST_error)
1120     return;
1121 
1122   // If decltype(auto) is used, no other type specifiers are permitted.
1123   if (TypeSpecType == TST_decltype_auto &&
1124       (getTypeSpecWidth() != TypeSpecifierWidth::Unspecified ||
1125        TypeSpecComplex != TSC_unspecified ||
1126        getTypeSpecSign() != TypeSpecifierSign::Unspecified ||
1127        TypeAltiVecVector || TypeAltiVecPixel || TypeAltiVecBool ||
1128        TypeQualifiers)) {
1129     const unsigned NumLocs = 9;
1130     SourceLocation ExtraLocs[NumLocs] = {
1131         TSWRange.getBegin(), TSCLoc,       TSSLoc,
1132         AltiVecLoc,          TQ_constLoc,  TQ_restrictLoc,
1133         TQ_volatileLoc,      TQ_atomicLoc, TQ_unalignedLoc};
1134     FixItHint Hints[NumLocs];
1135     SourceLocation FirstLoc;
1136     for (unsigned I = 0; I != NumLocs; ++I) {
1137       if (ExtraLocs[I].isValid()) {
1138         if (FirstLoc.isInvalid() ||
1139             S.getSourceManager().isBeforeInTranslationUnit(ExtraLocs[I],
1140                                                            FirstLoc))
1141           FirstLoc = ExtraLocs[I];
1142         Hints[I] = FixItHint::CreateRemoval(ExtraLocs[I]);
1143       }
1144     }
1145     TypeSpecWidth = static_cast<unsigned>(TypeSpecifierWidth::Unspecified);
1146     TypeSpecComplex = TSC_unspecified;
1147     TypeSpecSign = static_cast<unsigned>(TypeSpecifierSign::Unspecified);
1148     TypeAltiVecVector = TypeAltiVecPixel = TypeAltiVecBool = false;
1149     TypeQualifiers = 0;
1150     S.Diag(TSTLoc, diag::err_decltype_auto_cannot_be_combined)
1151       << Hints[0] << Hints[1] << Hints[2] << Hints[3]
1152       << Hints[4] << Hints[5] << Hints[6] << Hints[7];
1153   }
1154 
1155   // Validate and finalize AltiVec vector declspec.
1156   if (TypeAltiVecVector) {
1157     if (TypeAltiVecBool) {
1158       // Sign specifiers are not allowed with vector bool. (PIM 2.1)
1159       if (getTypeSpecSign() != TypeSpecifierSign::Unspecified) {
1160         S.Diag(TSSLoc, diag::err_invalid_vector_bool_decl_spec)
1161             << getSpecifierName(getTypeSpecSign());
1162       }
1163       // Only char/int are valid with vector bool prior to Power10.
1164       // Power10 adds instructions that produce vector bool data
1165       // for quadwords as well so allow vector bool __int128.
1166       if (((TypeSpecType != TST_unspecified) && (TypeSpecType != TST_char) &&
1167            (TypeSpecType != TST_int) && (TypeSpecType != TST_int128)) ||
1168           TypeAltiVecPixel) {
1169         S.Diag(TSTLoc, diag::err_invalid_vector_bool_decl_spec)
1170           << (TypeAltiVecPixel ? "__pixel" :
1171                                  getSpecifierName((TST)TypeSpecType, Policy));
1172       }
1173       // vector bool __int128 requires Power10.
1174       if ((TypeSpecType == TST_int128) &&
1175           (!S.Context.getTargetInfo().hasFeature("power10-vector")))
1176         S.Diag(TSTLoc, diag::err_invalid_vector_bool_int128_decl_spec);
1177 
1178       // Only 'short' and 'long long' are valid with vector bool. (PIM 2.1)
1179       if ((getTypeSpecWidth() != TypeSpecifierWidth::Unspecified) &&
1180           (getTypeSpecWidth() != TypeSpecifierWidth::Short) &&
1181           (getTypeSpecWidth() != TypeSpecifierWidth::LongLong))
1182         S.Diag(TSWRange.getBegin(), diag::err_invalid_vector_bool_decl_spec)
1183             << getSpecifierName(getTypeSpecWidth());
1184 
1185       // vector bool long long requires VSX support or ZVector.
1186       if ((getTypeSpecWidth() == TypeSpecifierWidth::LongLong) &&
1187           (!S.Context.getTargetInfo().hasFeature("vsx")) &&
1188           (!S.Context.getTargetInfo().hasFeature("power8-vector")) &&
1189           !S.getLangOpts().ZVector)
1190         S.Diag(TSTLoc, diag::err_invalid_vector_long_long_decl_spec);
1191 
1192       // Elements of vector bool are interpreted as unsigned. (PIM 2.1)
1193       if ((TypeSpecType == TST_char) || (TypeSpecType == TST_int) ||
1194           (TypeSpecType == TST_int128) ||
1195           (getTypeSpecWidth() != TypeSpecifierWidth::Unspecified))
1196         TypeSpecSign = static_cast<unsigned>(TypeSpecifierSign::Unsigned);
1197     } else if (TypeSpecType == TST_double) {
1198       // vector long double and vector long long double are never allowed.
1199       // vector double is OK for Power7 and later, and ZVector.
1200       if (getTypeSpecWidth() == TypeSpecifierWidth::Long ||
1201           getTypeSpecWidth() == TypeSpecifierWidth::LongLong)
1202         S.Diag(TSWRange.getBegin(),
1203                diag::err_invalid_vector_long_double_decl_spec);
1204       else if (!S.Context.getTargetInfo().hasFeature("vsx") &&
1205                !S.getLangOpts().ZVector)
1206         S.Diag(TSTLoc, diag::err_invalid_vector_double_decl_spec);
1207     } else if (TypeSpecType == TST_float) {
1208       // vector float is unsupported for ZVector unless we have the
1209       // vector-enhancements facility 1 (ISA revision 12).
1210       if (S.getLangOpts().ZVector &&
1211           !S.Context.getTargetInfo().hasFeature("arch12"))
1212         S.Diag(TSTLoc, diag::err_invalid_vector_float_decl_spec);
1213     } else if (getTypeSpecWidth() == TypeSpecifierWidth::Long) {
1214       // vector long is unsupported for ZVector and deprecated for AltiVec.
1215       // It has also been historically deprecated on AIX (as an alias for
1216       // "vector int" in both 32-bit and 64-bit modes). It was then made
1217       // unsupported in the Clang-based XL compiler since the deprecated type
1218       // has a number of conflicting semantics and continuing to support it
1219       // is a disservice to users.
1220       if (S.getLangOpts().ZVector ||
1221           S.Context.getTargetInfo().getTriple().isOSAIX())
1222         S.Diag(TSWRange.getBegin(), diag::err_invalid_vector_long_decl_spec);
1223       else
1224         S.Diag(TSWRange.getBegin(),
1225                diag::warn_vector_long_decl_spec_combination)
1226             << getSpecifierName((TST)TypeSpecType, Policy);
1227     }
1228 
1229     if (TypeAltiVecPixel) {
1230       //TODO: perform validation
1231       TypeSpecType = TST_int;
1232       TypeSpecSign = static_cast<unsigned>(TypeSpecifierSign::Unsigned);
1233       TypeSpecWidth = static_cast<unsigned>(TypeSpecifierWidth::Short);
1234       TypeSpecOwned = false;
1235     }
1236   }
1237 
1238   bool IsFixedPointType =
1239       TypeSpecType == TST_accum || TypeSpecType == TST_fract;
1240 
1241   // signed/unsigned are only valid with int/char/wchar_t/_Accum.
1242   if (getTypeSpecSign() != TypeSpecifierSign::Unspecified) {
1243     if (TypeSpecType == TST_unspecified)
1244       TypeSpecType = TST_int; // unsigned -> unsigned int, signed -> signed int.
1245     else if (TypeSpecType != TST_int && TypeSpecType != TST_int128 &&
1246              TypeSpecType != TST_char && TypeSpecType != TST_wchar &&
1247              !IsFixedPointType && TypeSpecType != TST_extint) {
1248       S.Diag(TSSLoc, diag::err_invalid_sign_spec)
1249         << getSpecifierName((TST)TypeSpecType, Policy);
1250       // signed double -> double.
1251       TypeSpecSign = static_cast<unsigned>(TypeSpecifierSign::Unspecified);
1252     }
1253   }
1254 
1255   // Validate the width of the type.
1256   switch (getTypeSpecWidth()) {
1257   case TypeSpecifierWidth::Unspecified:
1258     break;
1259   case TypeSpecifierWidth::Short:    // short int
1260   case TypeSpecifierWidth::LongLong: // long long int
1261     if (TypeSpecType == TST_unspecified)
1262       TypeSpecType = TST_int; // short -> short int, long long -> long long int.
1263     else if (!(TypeSpecType == TST_int ||
1264                (IsFixedPointType &&
1265                 getTypeSpecWidth() != TypeSpecifierWidth::LongLong))) {
1266       S.Diag(TSWRange.getBegin(), diag::err_invalid_width_spec)
1267           << (int)TypeSpecWidth << getSpecifierName((TST)TypeSpecType, Policy);
1268       TypeSpecType = TST_int;
1269       TypeSpecSat = false;
1270       TypeSpecOwned = false;
1271     }
1272     break;
1273   case TypeSpecifierWidth::Long: // long double, long int
1274     if (TypeSpecType == TST_unspecified)
1275       TypeSpecType = TST_int;  // long -> long int.
1276     else if (TypeSpecType != TST_int && TypeSpecType != TST_double &&
1277              !IsFixedPointType) {
1278       S.Diag(TSWRange.getBegin(), diag::err_invalid_width_spec)
1279           << (int)TypeSpecWidth << getSpecifierName((TST)TypeSpecType, Policy);
1280       TypeSpecType = TST_int;
1281       TypeSpecSat = false;
1282       TypeSpecOwned = false;
1283     }
1284     break;
1285   }
1286 
1287   // TODO: if the implementation does not implement _Complex or _Imaginary,
1288   // disallow their use.  Need information about the backend.
1289   if (TypeSpecComplex != TSC_unspecified) {
1290     if (TypeSpecType == TST_unspecified) {
1291       S.Diag(TSCLoc, diag::ext_plain_complex)
1292         << FixItHint::CreateInsertion(
1293                               S.getLocForEndOfToken(getTypeSpecComplexLoc()),
1294                                                  " double");
1295       TypeSpecType = TST_double;   // _Complex -> _Complex double.
1296     } else if (TypeSpecType == TST_int || TypeSpecType == TST_char ||
1297                TypeSpecType == TST_extint) {
1298       // Note that this intentionally doesn't include _Complex _Bool.
1299       if (!S.getLangOpts().CPlusPlus)
1300         S.Diag(TSTLoc, diag::ext_integer_complex);
1301     } else if (TypeSpecType != TST_float && TypeSpecType != TST_double &&
1302                TypeSpecType != TST_float128) {
1303       // FIXME: _Float16, __fp16?
1304       S.Diag(TSCLoc, diag::err_invalid_complex_spec)
1305         << getSpecifierName((TST)TypeSpecType, Policy);
1306       TypeSpecComplex = TSC_unspecified;
1307     }
1308   }
1309 
1310   // C11 6.7.1/3, C++11 [dcl.stc]p1, GNU TLS: __thread, thread_local and
1311   // _Thread_local can only appear with the 'static' and 'extern' storage class
1312   // specifiers. We also allow __private_extern__ as an extension.
1313   if (ThreadStorageClassSpec != TSCS_unspecified) {
1314     switch (StorageClassSpec) {
1315     case SCS_unspecified:
1316     case SCS_extern:
1317     case SCS_private_extern:
1318     case SCS_static:
1319       break;
1320     default:
1321       if (S.getSourceManager().isBeforeInTranslationUnit(
1322             getThreadStorageClassSpecLoc(), getStorageClassSpecLoc()))
1323         S.Diag(getStorageClassSpecLoc(),
1324              diag::err_invalid_decl_spec_combination)
1325           << DeclSpec::getSpecifierName(getThreadStorageClassSpec())
1326           << SourceRange(getThreadStorageClassSpecLoc());
1327       else
1328         S.Diag(getThreadStorageClassSpecLoc(),
1329              diag::err_invalid_decl_spec_combination)
1330           << DeclSpec::getSpecifierName(getStorageClassSpec())
1331           << SourceRange(getStorageClassSpecLoc());
1332       // Discard the thread storage class specifier to recover.
1333       ThreadStorageClassSpec = TSCS_unspecified;
1334       ThreadStorageClassSpecLoc = SourceLocation();
1335     }
1336   }
1337 
1338   // If no type specifier was provided and we're parsing a language where
1339   // the type specifier is not optional, but we got 'auto' as a storage
1340   // class specifier, then assume this is an attempt to use C++0x's 'auto'
1341   // type specifier.
1342   if (S.getLangOpts().CPlusPlus &&
1343       TypeSpecType == TST_unspecified && StorageClassSpec == SCS_auto) {
1344     TypeSpecType = TST_auto;
1345     StorageClassSpec = SCS_unspecified;
1346     TSTLoc = TSTNameLoc = StorageClassSpecLoc;
1347     StorageClassSpecLoc = SourceLocation();
1348   }
1349   // Diagnose if we've recovered from an ill-formed 'auto' storage class
1350   // specifier in a pre-C++11 dialect of C++.
1351   if (!S.getLangOpts().CPlusPlus11 && TypeSpecType == TST_auto)
1352     S.Diag(TSTLoc, diag::ext_auto_type_specifier);
1353   if (S.getLangOpts().CPlusPlus && !S.getLangOpts().CPlusPlus11 &&
1354       StorageClassSpec == SCS_auto)
1355     S.Diag(StorageClassSpecLoc, diag::warn_auto_storage_class)
1356       << FixItHint::CreateRemoval(StorageClassSpecLoc);
1357   if (TypeSpecType == TST_char8)
1358     S.Diag(TSTLoc, diag::warn_cxx17_compat_unicode_type);
1359   else if (TypeSpecType == TST_char16 || TypeSpecType == TST_char32)
1360     S.Diag(TSTLoc, diag::warn_cxx98_compat_unicode_type)
1361       << (TypeSpecType == TST_char16 ? "char16_t" : "char32_t");
1362   if (getConstexprSpecifier() == ConstexprSpecKind::Constexpr)
1363     S.Diag(ConstexprLoc, diag::warn_cxx98_compat_constexpr);
1364   else if (getConstexprSpecifier() == ConstexprSpecKind::Consteval)
1365     S.Diag(ConstexprLoc, diag::warn_cxx20_compat_consteval);
1366   else if (getConstexprSpecifier() == ConstexprSpecKind::Constinit)
1367     S.Diag(ConstexprLoc, diag::warn_cxx20_compat_constinit);
1368   // C++ [class.friend]p6:
1369   //   No storage-class-specifier shall appear in the decl-specifier-seq
1370   //   of a friend declaration.
1371   if (isFriendSpecified() &&
1372       (getStorageClassSpec() || getThreadStorageClassSpec())) {
1373     SmallString<32> SpecName;
1374     SourceLocation SCLoc;
1375     FixItHint StorageHint, ThreadHint;
1376 
1377     if (DeclSpec::SCS SC = getStorageClassSpec()) {
1378       SpecName = getSpecifierName(SC);
1379       SCLoc = getStorageClassSpecLoc();
1380       StorageHint = FixItHint::CreateRemoval(SCLoc);
1381     }
1382 
1383     if (DeclSpec::TSCS TSC = getThreadStorageClassSpec()) {
1384       if (!SpecName.empty()) SpecName += " ";
1385       SpecName += getSpecifierName(TSC);
1386       SCLoc = getThreadStorageClassSpecLoc();
1387       ThreadHint = FixItHint::CreateRemoval(SCLoc);
1388     }
1389 
1390     S.Diag(SCLoc, diag::err_friend_decl_spec)
1391       << SpecName << StorageHint << ThreadHint;
1392 
1393     ClearStorageClassSpecs();
1394   }
1395 
1396   // C++11 [dcl.fct.spec]p5:
1397   //   The virtual specifier shall be used only in the initial
1398   //   declaration of a non-static class member function;
1399   // C++11 [dcl.fct.spec]p6:
1400   //   The explicit specifier shall be used only in the declaration of
1401   //   a constructor or conversion function within its class
1402   //   definition;
1403   if (isFriendSpecified() && (isVirtualSpecified() || hasExplicitSpecifier())) {
1404     StringRef Keyword;
1405     FixItHint Hint;
1406     SourceLocation SCLoc;
1407 
1408     if (isVirtualSpecified()) {
1409       Keyword = "virtual";
1410       SCLoc = getVirtualSpecLoc();
1411       Hint = FixItHint::CreateRemoval(SCLoc);
1412     } else {
1413       Keyword = "explicit";
1414       SCLoc = getExplicitSpecLoc();
1415       Hint = FixItHint::CreateRemoval(getExplicitSpecRange());
1416     }
1417 
1418     S.Diag(SCLoc, diag::err_friend_decl_spec)
1419       << Keyword << Hint;
1420 
1421     FS_virtual_specified = false;
1422     FS_explicit_specifier = ExplicitSpecifier();
1423     FS_virtualLoc = FS_explicitLoc = SourceLocation();
1424   }
1425 
1426   assert(!TypeSpecOwned || isDeclRep((TST) TypeSpecType));
1427 
1428   // Okay, now we can infer the real type.
1429 
1430   // TODO: return "auto function" and other bad things based on the real type.
1431 
1432   // 'data definition has no type or storage class'?
1433 }
1434 
1435 bool DeclSpec::isMissingDeclaratorOk() {
1436   TST tst = getTypeSpecType();
1437   return isDeclRep(tst) && getRepAsDecl() != nullptr &&
1438     StorageClassSpec != DeclSpec::SCS_typedef;
1439 }
1440 
1441 void UnqualifiedId::setOperatorFunctionId(SourceLocation OperatorLoc,
1442                                           OverloadedOperatorKind Op,
1443                                           SourceLocation SymbolLocations[3]) {
1444   Kind = UnqualifiedIdKind::IK_OperatorFunctionId;
1445   StartLocation = OperatorLoc;
1446   EndLocation = OperatorLoc;
1447   new (&OperatorFunctionId) struct OFI;
1448   OperatorFunctionId.Operator = Op;
1449   for (unsigned I = 0; I != 3; ++I) {
1450     OperatorFunctionId.SymbolLocations[I] = SymbolLocations[I];
1451 
1452     if (SymbolLocations[I].isValid())
1453       EndLocation = SymbolLocations[I];
1454   }
1455 }
1456 
1457 bool VirtSpecifiers::SetSpecifier(Specifier VS, SourceLocation Loc,
1458                                   const char *&PrevSpec) {
1459   if (!FirstLocation.isValid())
1460     FirstLocation = Loc;
1461   LastLocation = Loc;
1462   LastSpecifier = VS;
1463 
1464   if (Specifiers & VS) {
1465     PrevSpec = getSpecifierName(VS);
1466     return true;
1467   }
1468 
1469   Specifiers |= VS;
1470 
1471   switch (VS) {
1472   default: llvm_unreachable("Unknown specifier!");
1473   case VS_Override: VS_overrideLoc = Loc; break;
1474   case VS_GNU_Final:
1475   case VS_Sealed:
1476   case VS_Final:    VS_finalLoc = Loc; break;
1477   }
1478 
1479   return false;
1480 }
1481 
1482 const char *VirtSpecifiers::getSpecifierName(Specifier VS) {
1483   switch (VS) {
1484   default: llvm_unreachable("Unknown specifier");
1485   case VS_Override: return "override";
1486   case VS_Final: return "final";
1487   case VS_GNU_Final: return "__final";
1488   case VS_Sealed: return "sealed";
1489   }
1490 }
1491