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