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 return false;
778}
779
780bool DeclSpec::SetTypeSpecType(TST T, SourceLocation Loc,
781 const char *&PrevSpec,
782 unsigned &DiagID,
783 Expr *Rep,
784 const PrintingPolicy &Policy) {
785 assert(isExprRep(T) && "T does not store an expr");
786 assert(Rep && "no expression provided!");
787 if (TypeSpecType == TST_error)
788 return false;
789 if (TypeSpecType != TST_unspecified) {
790 PrevSpec = DeclSpec::getSpecifierName(T: (TST) TypeSpecType, Policy);
791 DiagID = diag::err_invalid_decl_spec_combination;
792 return true;
793 }
794 TypeSpecType = T;
795 ExprRep = Rep;
796 TSTLoc = Loc;
797 TSTNameLoc = Loc;
798 TypeSpecOwned = false;
799 return false;
800}
801
802bool DeclSpec::SetTypeSpecType(TST T, SourceLocation Loc,
803 const char *&PrevSpec,
804 unsigned &DiagID,
805 Decl *Rep, bool Owned,
806 const PrintingPolicy &Policy) {
807 return SetTypeSpecType(T, TagKwLoc: Loc, TagNameLoc: Loc, PrevSpec, DiagID, Rep, Owned, Policy);
808}
809
810bool DeclSpec::SetTypeSpecType(TST T, SourceLocation TagKwLoc,
811 SourceLocation TagNameLoc,
812 const char *&PrevSpec,
813 unsigned &DiagID,
814 Decl *Rep, bool Owned,
815 const PrintingPolicy &Policy) {
816 assert(isDeclRep(T) && "T does not store a decl");
817 // Unlike the other cases, we don't assert that we actually get a decl.
818
819 if (TypeSpecType == TST_error)
820 return false;
821 if (TypeSpecType != TST_unspecified) {
822 PrevSpec = DeclSpec::getSpecifierName(T: (TST) TypeSpecType, Policy);
823 DiagID = diag::err_invalid_decl_spec_combination;
824 return true;
825 }
826 TypeSpecType = T;
827 DeclRep = Rep;
828 TSTLoc = TagKwLoc;
829 TSTNameLoc = TagNameLoc;
830 TypeSpecOwned = Owned && Rep != nullptr;
831 return false;
832}
833
834bool DeclSpec::SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
835 unsigned &DiagID, TemplateIdAnnotation *Rep,
836 const PrintingPolicy &Policy) {
837 assert(T == TST_auto || T == TST_decltype_auto);
838 ConstrainedAuto = true;
839 TemplateIdRep = Rep;
840 return SetTypeSpecType(T, Loc, PrevSpec, DiagID, Policy);
841}
842
843bool DeclSpec::SetTypeSpecType(TST T, SourceLocation Loc,
844 const char *&PrevSpec,
845 unsigned &DiagID,
846 const PrintingPolicy &Policy) {
847 assert(!isDeclRep(T) && !isTypeRep(T) && !isExprRep(T) &&
848 "rep required for these type-spec kinds!");
849 if (TypeSpecType == TST_error)
850 return false;
851 if (TypeSpecType != TST_unspecified) {
852 PrevSpec = DeclSpec::getSpecifierName(T: (TST) TypeSpecType, Policy);
853 DiagID = diag::err_invalid_decl_spec_combination;
854 return true;
855 }
856 TSTLoc = Loc;
857 TSTNameLoc = Loc;
858 if (TypeAltiVecVector && (T == TST_bool) && !TypeAltiVecBool) {
859 TypeAltiVecBool = true;
860 return false;
861 }
862 TypeSpecType = T;
863 TypeSpecOwned = false;
864 return false;
865}
866
867bool DeclSpec::SetTypeSpecSat(SourceLocation Loc, const char *&PrevSpec,
868 unsigned &DiagID) {
869 // Cannot set twice
870 if (TypeSpecSat) {
871 DiagID = diag::warn_duplicate_declspec;
872 PrevSpec = "_Sat";
873 return true;
874 }
875 TypeSpecSat = true;
876 TSSatLoc = Loc;
877 return false;
878}
879
880bool DeclSpec::SetTypeAltiVecVector(bool isAltiVecVector, SourceLocation Loc,
881 const char *&PrevSpec, unsigned &DiagID,
882 const PrintingPolicy &Policy) {
883 if (TypeSpecType == TST_error)
884 return false;
885 if (TypeSpecType != TST_unspecified) {
886 PrevSpec = DeclSpec::getSpecifierName(T: (TST) TypeSpecType, Policy);
887 DiagID = diag::err_invalid_vector_decl_spec_combination;
888 return true;
889 }
890 TypeAltiVecVector = isAltiVecVector;
891 AltiVecLoc = Loc;
892 return false;
893}
894
895bool DeclSpec::SetTypePipe(bool isPipe, SourceLocation Loc,
896 const char *&PrevSpec, unsigned &DiagID,
897 const PrintingPolicy &Policy) {
898 if (TypeSpecType == TST_error)
899 return false;
900 if (TypeSpecType != TST_unspecified) {
901 PrevSpec = DeclSpec::getSpecifierName(T: (TST)TypeSpecType, Policy);
902 DiagID = diag::err_invalid_decl_spec_combination;
903 return true;
904 }
905
906 if (isPipe) {
907 TypeSpecPipe = static_cast<unsigned>(TypeSpecifiersPipe::Pipe);
908 TQ_pipeLoc = Loc;
909 }
910 return false;
911}
912
913bool DeclSpec::SetTypeAltiVecPixel(bool isAltiVecPixel, SourceLocation Loc,
914 const char *&PrevSpec, unsigned &DiagID,
915 const PrintingPolicy &Policy) {
916 if (TypeSpecType == TST_error)
917 return false;
918 if (!TypeAltiVecVector || TypeAltiVecPixel ||
919 (TypeSpecType != TST_unspecified)) {
920 PrevSpec = DeclSpec::getSpecifierName(T: (TST) TypeSpecType, Policy);
921 DiagID = diag::err_invalid_pixel_decl_spec_combination;
922 return true;
923 }
924 TypeAltiVecPixel = isAltiVecPixel;
925 TSTLoc = Loc;
926 TSTNameLoc = Loc;
927 return false;
928}
929
930bool DeclSpec::SetTypeAltiVecBool(bool isAltiVecBool, SourceLocation Loc,
931 const char *&PrevSpec, unsigned &DiagID,
932 const PrintingPolicy &Policy) {
933 if (TypeSpecType == TST_error)
934 return false;
935 if (!TypeAltiVecVector || TypeAltiVecBool ||
936 (TypeSpecType != TST_unspecified)) {
937 PrevSpec = DeclSpec::getSpecifierName(T: (TST) TypeSpecType, Policy);
938 DiagID = diag::err_invalid_vector_bool_decl_spec;
939 return true;
940 }
941 TypeAltiVecBool = isAltiVecBool;
942 TSTLoc = Loc;
943 TSTNameLoc = Loc;
944 return false;
945}
946
947bool DeclSpec::SetTypeSpecError() {
948 TypeSpecType = TST_error;
949 TypeSpecOwned = false;
950 TSTLoc = SourceLocation();
951 TSTNameLoc = SourceLocation();
952 return false;
953}
954
955bool DeclSpec::SetBitIntType(SourceLocation KWLoc, Expr *BitsExpr,
956 const char *&PrevSpec, unsigned &DiagID,
957 const PrintingPolicy &Policy) {
958 assert(BitsExpr && "no expression provided!");
959 if (TypeSpecType == TST_error)
960 return false;
961
962 if (TypeSpecType != TST_unspecified) {
963 PrevSpec = DeclSpec::getSpecifierName(T: (TST) TypeSpecType, Policy);
964 DiagID = diag::err_invalid_decl_spec_combination;
965 return true;
966 }
967
968 TypeSpecType = TST_bitint;
969 ExprRep = BitsExpr;
970 TSTLoc = KWLoc;
971 TSTNameLoc = KWLoc;
972 TypeSpecOwned = false;
973 return false;
974}
975
976void DeclSpec::SetPackIndexingExpr(SourceLocation EllipsisLoc,
977 Expr *IndexingExpr) {
978 assert(TypeSpecType == TST_typename &&
979 "pack indexing can only be applied to typename");
980 TypeSpecType = TST_typename_pack_indexing;
981 PackIndexingExpr = IndexingExpr;
982 this->EllipsisLoc = EllipsisLoc;
983}
984
985bool DeclSpec::SetTypeQual(TQ T, SourceLocation Loc, const char *&PrevSpec,
986 unsigned &DiagID, const LangOptions &Lang) {
987 // Duplicates are permitted in C99 onwards, but are not permitted in C89 or
988 // C++. However, since this is likely not what the user intended, we will
989 // always warn. We do not need to set the qualifier's location since we
990 // already have it.
991 if (TypeQualifiers & T) {
992 bool IsExtension = true;
993 if (Lang.C99)
994 IsExtension = false;
995 return BadSpecifier(TNew: T, TPrev: T, PrevSpec, DiagID, IsExtension);
996 }
997
998 return SetTypeQual(T, Loc);
999}
1000
1001bool DeclSpec::SetTypeQual(TQ T, SourceLocation Loc) {
1002 TypeQualifiers |= T;
1003
1004 switch (T) {
1005 case TQ_unspecified: break;
1006 case TQ_const: TQ_constLoc = Loc; return false;
1007 case TQ_restrict: TQ_restrictLoc = Loc; return false;
1008 case TQ_volatile: TQ_volatileLoc = Loc; return false;
1009 case TQ_unaligned: TQ_unalignedLoc = Loc; return false;
1010 case TQ_atomic: TQ_atomicLoc = Loc; return false;
1011 }
1012
1013 llvm_unreachable("Unknown type qualifier!");
1014}
1015
1016bool DeclSpec::SetOverflowBehavior(
1017 OverflowBehaviorType::OverflowBehaviorKind Kind, SourceLocation Loc,
1018 const char *&PrevSpec, unsigned &DiagID) {
1019 OverflowBehaviorState NewState =
1020 (Kind == OverflowBehaviorType::OverflowBehaviorKind::Wrap)
1021 ? OverflowBehaviorState::Wrap
1022 : OverflowBehaviorState::Trap;
1023
1024 OverflowBehaviorState CurrentState = getOverflowBehaviorState();
1025
1026 if (CurrentState != OverflowBehaviorState::Unspecified) {
1027 return BadSpecifier(TNew: NewState, TPrev: CurrentState, PrevSpec, DiagID);
1028 }
1029
1030 OB_state = static_cast<unsigned>(NewState);
1031 OB_Loc = Loc;
1032 return false;
1033}
1034
1035bool DeclSpec::setFunctionSpecInline(SourceLocation Loc, const char *&PrevSpec,
1036 unsigned &DiagID) {
1037 // 'inline inline' is ok. However, since this is likely not what the user
1038 // intended, we will always warn, similar to duplicates of type qualifiers.
1039 if (FS_inline_specified) {
1040 DiagID = diag::warn_duplicate_declspec;
1041 PrevSpec = "inline";
1042 return true;
1043 }
1044 FS_inline_specified = true;
1045 FS_inlineLoc = Loc;
1046 return false;
1047}
1048
1049bool DeclSpec::setFunctionSpecForceInline(SourceLocation Loc, const char *&PrevSpec,
1050 unsigned &DiagID) {
1051 if (FS_forceinline_specified) {
1052 DiagID = diag::warn_duplicate_declspec;
1053 PrevSpec = "__forceinline";
1054 return true;
1055 }
1056 FS_forceinline_specified = true;
1057 FS_forceinlineLoc = Loc;
1058 return false;
1059}
1060
1061bool DeclSpec::setFunctionSpecVirtual(SourceLocation Loc,
1062 const char *&PrevSpec,
1063 unsigned &DiagID) {
1064 // 'virtual virtual' is ok, but warn as this is likely not what the user
1065 // intended.
1066 if (FS_virtual_specified) {
1067 DiagID = diag::warn_duplicate_declspec;
1068 PrevSpec = "virtual";
1069 return true;
1070 }
1071 FS_virtual_specified = true;
1072 FS_virtualLoc = Loc;
1073 return false;
1074}
1075
1076bool DeclSpec::setFunctionSpecExplicit(SourceLocation Loc,
1077 const char *&PrevSpec, unsigned &DiagID,
1078 ExplicitSpecifier ExplicitSpec,
1079 SourceLocation CloseParenLoc) {
1080 // 'explicit explicit' is ok, but warn as this is likely not what the user
1081 // intended.
1082 if (hasExplicitSpecifier()) {
1083 DiagID = (ExplicitSpec.getExpr() || FS_explicit_specifier.getExpr())
1084 ? diag::err_duplicate_declspec
1085 : diag::ext_warn_duplicate_declspec;
1086 PrevSpec = "explicit";
1087 return true;
1088 }
1089 FS_explicit_specifier = ExplicitSpec;
1090 FS_explicitLoc = Loc;
1091 FS_explicitCloseParenLoc = CloseParenLoc;
1092 return false;
1093}
1094
1095bool DeclSpec::setFunctionSpecNoreturn(SourceLocation Loc,
1096 const char *&PrevSpec,
1097 unsigned &DiagID) {
1098 // '_Noreturn _Noreturn' is ok, but warn as this is likely not what the user
1099 // intended.
1100 if (FS_noreturn_specified) {
1101 DiagID = diag::warn_duplicate_declspec;
1102 PrevSpec = "_Noreturn";
1103 return true;
1104 }
1105 FS_noreturn_specified = true;
1106 FS_noreturnLoc = Loc;
1107 return false;
1108}
1109
1110bool DeclSpec::SetFriendSpec(SourceLocation Loc, const char *&PrevSpec,
1111 unsigned &DiagID) {
1112 if (isFriendSpecified()) {
1113 PrevSpec = "friend";
1114 DiagID = diag::warn_duplicate_declspec;
1115 return true;
1116 }
1117
1118 FriendSpecifiedFirst = isEmpty();
1119 FriendLoc = Loc;
1120 return false;
1121}
1122
1123bool DeclSpec::setModulePrivateSpec(SourceLocation Loc, const char *&PrevSpec,
1124 unsigned &DiagID) {
1125 if (isModulePrivateSpecified()) {
1126 PrevSpec = "__module_private__";
1127 DiagID = diag::ext_warn_duplicate_declspec;
1128 return true;
1129 }
1130
1131 ModulePrivateLoc = Loc;
1132 return false;
1133}
1134
1135bool DeclSpec::SetConstexprSpec(ConstexprSpecKind ConstexprKind,
1136 SourceLocation Loc, const char *&PrevSpec,
1137 unsigned &DiagID) {
1138 if (getConstexprSpecifier() != ConstexprSpecKind::Unspecified)
1139 return BadSpecifier(TNew: ConstexprKind, TPrev: getConstexprSpecifier(), PrevSpec,
1140 DiagID);
1141 ConstexprSpecifier = static_cast<unsigned>(ConstexprKind);
1142 ConstexprLoc = Loc;
1143 return false;
1144}
1145
1146void DeclSpec::SaveWrittenBuiltinSpecs() {
1147 writtenBS.Sign = static_cast<int>(getTypeSpecSign());
1148 writtenBS.Width = static_cast<int>(getTypeSpecWidth());
1149 writtenBS.Type = getTypeSpecType();
1150 // Search the list of attributes for the presence of a mode attribute.
1151 writtenBS.ModeAttr = getAttributes().hasAttribute(K: ParsedAttr::AT_Mode);
1152}
1153
1154/// Finish - This does final analysis of the declspec, rejecting things like
1155/// "_Complex" (lacking an FP type). After calling this method, DeclSpec is
1156/// guaranteed to be self-consistent, even if an error occurred.
1157void DeclSpec::Finish(Sema &S, const PrintingPolicy &Policy) {
1158 // Before possibly changing their values, save specs as written.
1159 SaveWrittenBuiltinSpecs();
1160
1161 // Check the type specifier components first. No checking for an invalid
1162 // type.
1163 CheckTypeSpec(S, Policy);
1164
1165 CheckFriendSpec(S, Policy);
1166
1167 assert(!TypeSpecOwned || isDeclRep((TST)TypeSpecType));
1168
1169 // Okay, now we can infer the real type.
1170
1171 // TODO: return "auto function" and other bad things based on the real type.
1172
1173 // 'data definition has no type or storage class'?
1174}
1175
1176void DeclSpec::CheckTypeSpec(Sema &S, const PrintingPolicy &Policy) {
1177 if (TypeSpecType == TST_error)
1178 return;
1179
1180 // If decltype(auto) is used, no other type specifiers are permitted.
1181 if (TypeSpecType == TST_decltype_auto &&
1182 (getTypeSpecWidth() != TypeSpecifierWidth::Unspecified ||
1183 TypeSpecComplex != TSC_unspecified ||
1184 getTypeSpecSign() != TypeSpecifierSign::Unspecified ||
1185 TypeAltiVecVector || TypeAltiVecPixel || TypeAltiVecBool ||
1186 TypeQualifiers)) {
1187 const unsigned NumLocs = 9;
1188 SourceLocation ExtraLocs[NumLocs] = {
1189 TSWRange.getBegin(), TSCLoc, TSSLoc,
1190 AltiVecLoc, TQ_constLoc, TQ_restrictLoc,
1191 TQ_volatileLoc, TQ_atomicLoc, TQ_unalignedLoc};
1192 FixItHint Hints[NumLocs];
1193 SourceLocation FirstLoc;
1194 for (unsigned I = 0; I != NumLocs; ++I) {
1195 if (ExtraLocs[I].isValid()) {
1196 if (FirstLoc.isInvalid() ||
1197 S.getSourceManager().isBeforeInTranslationUnit(LHS: ExtraLocs[I],
1198 RHS: FirstLoc))
1199 FirstLoc = ExtraLocs[I];
1200 Hints[I] = FixItHint::CreateRemoval(RemoveRange: ExtraLocs[I]);
1201 }
1202 }
1203 TypeSpecWidth = static_cast<unsigned>(TypeSpecifierWidth::Unspecified);
1204 TypeSpecComplex = TSC_unspecified;
1205 TypeSpecSign = static_cast<unsigned>(TypeSpecifierSign::Unspecified);
1206 TypeAltiVecVector = TypeAltiVecPixel = TypeAltiVecBool = false;
1207 TypeQualifiers = 0;
1208 S.Diag(Loc: TSTLoc, DiagID: diag::err_decltype_auto_cannot_be_combined)
1209 << Hints[0] << Hints[1] << Hints[2] << Hints[3]
1210 << Hints[4] << Hints[5] << Hints[6] << Hints[7];
1211 }
1212
1213 // Validate and finalize AltiVec vector declspec.
1214 if (TypeAltiVecVector) {
1215 // No vector long long without VSX (or ZVector).
1216 if ((getTypeSpecWidth() == TypeSpecifierWidth::LongLong) &&
1217 !S.Context.getTargetInfo().hasFeature(Feature: "vsx") &&
1218 !S.getLangOpts().ZVector)
1219 S.Diag(Loc: TSWRange.getBegin(), DiagID: diag::err_invalid_vector_long_long_decl_spec);
1220
1221 // No vector __int128 prior to Power8 (or ZVector).
1222 if ((TypeSpecType == TST_int128) &&
1223 !S.Context.getTargetInfo().hasFeature(Feature: "power8-vector") &&
1224 !S.getLangOpts().ZVector)
1225 S.Diag(Loc: TSTLoc, DiagID: diag::err_invalid_vector_int128_decl_spec);
1226
1227 // Complex vector types are not supported.
1228 if (TypeSpecComplex != TSC_unspecified)
1229 S.Diag(Loc: TSCLoc, DiagID: diag::err_invalid_vector_complex_decl_spec);
1230 else if (TypeAltiVecBool) {
1231 // Sign specifiers are not allowed with vector bool. (PIM 2.1)
1232 if (getTypeSpecSign() != TypeSpecifierSign::Unspecified) {
1233 S.Diag(Loc: TSSLoc, DiagID: diag::err_invalid_vector_bool_decl_spec)
1234 << getSpecifierName(S: getTypeSpecSign());
1235 }
1236 // Only char/int are valid with vector bool prior to Power10.
1237 // Power10 adds instructions that produce vector bool data
1238 // for quadwords as well so allow vector bool __int128.
1239 if (((TypeSpecType != TST_unspecified) && (TypeSpecType != TST_char) &&
1240 (TypeSpecType != TST_int) && (TypeSpecType != TST_int128)) ||
1241 TypeAltiVecPixel) {
1242 S.Diag(Loc: TSTLoc, DiagID: diag::err_invalid_vector_bool_decl_spec)
1243 << (TypeAltiVecPixel ? "__pixel" :
1244 getSpecifierName(T: (TST)TypeSpecType, Policy));
1245 }
1246 // vector bool __int128 requires Power10 (or ZVector).
1247 if ((TypeSpecType == TST_int128) &&
1248 (!S.Context.getTargetInfo().hasFeature(Feature: "power10-vector") &&
1249 !S.getLangOpts().ZVector))
1250 S.Diag(Loc: TSTLoc, DiagID: diag::err_invalid_vector_bool_int128_decl_spec);
1251
1252 // Only 'short' and 'long long' are valid with vector bool. (PIM 2.1)
1253 if ((getTypeSpecWidth() != TypeSpecifierWidth::Unspecified) &&
1254 (getTypeSpecWidth() != TypeSpecifierWidth::Short) &&
1255 (getTypeSpecWidth() != TypeSpecifierWidth::LongLong))
1256 S.Diag(Loc: TSWRange.getBegin(), DiagID: diag::err_invalid_vector_bool_decl_spec)
1257 << getSpecifierName(W: getTypeSpecWidth());
1258
1259 // Elements of vector bool are interpreted as unsigned. (PIM 2.1)
1260 if ((TypeSpecType == TST_char) || (TypeSpecType == TST_int) ||
1261 (TypeSpecType == TST_int128) ||
1262 (getTypeSpecWidth() != TypeSpecifierWidth::Unspecified))
1263 TypeSpecSign = static_cast<unsigned>(TypeSpecifierSign::Unsigned);
1264 } else if (TypeSpecType == TST_double) {
1265 // vector long double and vector long long double are never allowed.
1266 // vector double is OK for Power7 and later, and ZVector.
1267 if (getTypeSpecWidth() == TypeSpecifierWidth::Long ||
1268 getTypeSpecWidth() == TypeSpecifierWidth::LongLong)
1269 S.Diag(Loc: TSWRange.getBegin(),
1270 DiagID: diag::err_invalid_vector_long_double_decl_spec);
1271 else if (!S.Context.getTargetInfo().hasFeature(Feature: "vsx") &&
1272 !S.getLangOpts().ZVector)
1273 S.Diag(Loc: TSTLoc, DiagID: diag::err_invalid_vector_double_decl_spec);
1274 } else if (TypeSpecType == TST_float) {
1275 // vector float is unsupported for ZVector unless we have the
1276 // vector-enhancements facility 1 (ISA revision 12).
1277 if (S.getLangOpts().ZVector &&
1278 !S.Context.getTargetInfo().hasFeature(Feature: "arch12"))
1279 S.Diag(Loc: TSTLoc, DiagID: diag::err_invalid_vector_float_decl_spec);
1280 } else if (getTypeSpecWidth() == TypeSpecifierWidth::Long) {
1281 // Vector long is unsupported for ZVector, or without VSX, and deprecated
1282 // for AltiVec.
1283 // It has also been historically deprecated on AIX (as an alias for
1284 // "vector int" in both 32-bit and 64-bit modes). It was then made
1285 // unsupported in the Clang-based XL compiler since the deprecated type
1286 // has a number of conflicting semantics and continuing to support it
1287 // is a disservice to users.
1288 if (S.getLangOpts().ZVector ||
1289 !S.Context.getTargetInfo().hasFeature(Feature: "vsx") ||
1290 S.Context.getTargetInfo().getTriple().isOSAIX())
1291 S.Diag(Loc: TSWRange.getBegin(), DiagID: diag::err_invalid_vector_long_decl_spec);
1292 else
1293 S.Diag(Loc: TSWRange.getBegin(),
1294 DiagID: diag::warn_vector_long_decl_spec_combination)
1295 << getSpecifierName(T: (TST)TypeSpecType, Policy);
1296 }
1297
1298 if (TypeAltiVecPixel) {
1299 //TODO: perform validation
1300 TypeSpecType = TST_int;
1301 TypeSpecSign = static_cast<unsigned>(TypeSpecifierSign::Unsigned);
1302 TypeSpecWidth = static_cast<unsigned>(TypeSpecifierWidth::Short);
1303 TypeSpecOwned = false;
1304 }
1305 }
1306
1307 bool IsFixedPointType =
1308 TypeSpecType == TST_accum || TypeSpecType == TST_fract;
1309
1310 // signed/unsigned are only valid with int/char/wchar_t/_Accum.
1311 if (getTypeSpecSign() != TypeSpecifierSign::Unspecified) {
1312 if (TypeSpecType == TST_unspecified)
1313 TypeSpecType = TST_int; // unsigned -> unsigned int, signed -> signed int.
1314 else if (TypeSpecType != TST_int && TypeSpecType != TST_int128 &&
1315 TypeSpecType != TST_char && TypeSpecType != TST_wchar &&
1316 !IsFixedPointType && TypeSpecType != TST_bitint) {
1317 S.Diag(Loc: TSSLoc, DiagID: diag::err_invalid_sign_spec)
1318 << getSpecifierName(T: (TST)TypeSpecType, Policy);
1319 // signed double -> double.
1320 TypeSpecSign = static_cast<unsigned>(TypeSpecifierSign::Unspecified);
1321 }
1322 }
1323
1324 // Validate the width of the type.
1325 switch (getTypeSpecWidth()) {
1326 case TypeSpecifierWidth::Unspecified:
1327 break;
1328 case TypeSpecifierWidth::Short: // short int
1329 case TypeSpecifierWidth::LongLong: // long long int
1330 if (TypeSpecType == TST_unspecified)
1331 TypeSpecType = TST_int; // short -> short int, long long -> long long int.
1332 else if (!(TypeSpecType == TST_int ||
1333 (IsFixedPointType &&
1334 getTypeSpecWidth() != TypeSpecifierWidth::LongLong))) {
1335 S.Diag(Loc: TSWRange.getBegin(), DiagID: diag::err_invalid_width_spec)
1336 << (int)TypeSpecWidth << getSpecifierName(T: (TST)TypeSpecType, Policy);
1337 TypeSpecType = TST_int;
1338 TypeSpecSat = false;
1339 TypeSpecOwned = false;
1340 }
1341 break;
1342 case TypeSpecifierWidth::Long: // long double, long int
1343 if (TypeSpecType == TST_unspecified)
1344 TypeSpecType = TST_int; // long -> long int.
1345 else if (TypeSpecType != TST_int && TypeSpecType != TST_double &&
1346 !IsFixedPointType) {
1347 S.Diag(Loc: TSWRange.getBegin(), DiagID: diag::err_invalid_width_spec)
1348 << (int)TypeSpecWidth << getSpecifierName(T: (TST)TypeSpecType, Policy);
1349 TypeSpecType = TST_int;
1350 TypeSpecSat = false;
1351 TypeSpecOwned = false;
1352 }
1353 break;
1354 }
1355
1356 // TODO: if the implementation does not implement _Complex, disallow their
1357 // use. Need information about the backend.
1358 if (TypeSpecComplex != TSC_unspecified) {
1359 if (TypeSpecType == TST_unspecified) {
1360 S.Diag(Loc: TSCLoc, DiagID: diag::ext_plain_complex)
1361 << FixItHint::CreateInsertion(
1362 InsertionLoc: S.getLocForEndOfToken(Loc: getTypeSpecComplexLoc()),
1363 Code: " double");
1364 TypeSpecType = TST_double; // _Complex -> _Complex double.
1365 } else if (TypeSpecType == TST_int || TypeSpecType == TST_char) {
1366 // Note that this intentionally doesn't include _Complex _Bool.
1367 if (!S.getLangOpts().CPlusPlus)
1368 S.Diag(Loc: TSTLoc, DiagID: diag::ext_integer_complex);
1369 } else if (TypeSpecType != TST_float && TypeSpecType != TST_double &&
1370 TypeSpecType != TST_float128 && TypeSpecType != TST_float16 &&
1371 TypeSpecType != TST_ibm128) {
1372 // FIXME: __fp16?
1373 S.Diag(Loc: TSCLoc, DiagID: diag::err_invalid_complex_spec)
1374 << getSpecifierName(T: (TST)TypeSpecType, Policy);
1375 TypeSpecComplex = TSC_unspecified;
1376 }
1377 }
1378
1379 // C11 6.7.1/3, C++11 [dcl.stc]p1, GNU TLS: __thread, thread_local and
1380 // _Thread_local can only appear with the 'static' and 'extern' storage class
1381 // specifiers. We also allow __private_extern__ as an extension.
1382 if (ThreadStorageClassSpec != TSCS_unspecified) {
1383 if (S.getLangOpts().C23 &&
1384 getConstexprSpecifier() == ConstexprSpecKind::Constexpr) {
1385 S.Diag(Loc: ConstexprLoc, DiagID: diag::err_invalid_decl_spec_combination)
1386 << DeclSpec::getSpecifierName(S: getThreadStorageClassSpec())
1387 << SourceRange(getThreadStorageClassSpecLoc());
1388 }
1389
1390 switch (StorageClassSpec) {
1391 case SCS_unspecified:
1392 case SCS_extern:
1393 case SCS_private_extern:
1394 case SCS_static:
1395 break;
1396 default:
1397 if (S.getSourceManager().isBeforeInTranslationUnit(
1398 LHS: getThreadStorageClassSpecLoc(), RHS: getStorageClassSpecLoc()))
1399 S.Diag(Loc: getStorageClassSpecLoc(),
1400 DiagID: diag::err_invalid_decl_spec_combination)
1401 << DeclSpec::getSpecifierName(S: getThreadStorageClassSpec())
1402 << SourceRange(getThreadStorageClassSpecLoc());
1403 else
1404 S.Diag(Loc: getThreadStorageClassSpecLoc(),
1405 DiagID: diag::err_invalid_decl_spec_combination)
1406 << DeclSpec::getSpecifierName(S: getStorageClassSpec())
1407 << SourceRange(getStorageClassSpecLoc());
1408 // Discard the thread storage class specifier to recover.
1409 ThreadStorageClassSpec = TSCS_unspecified;
1410 ThreadStorageClassSpecLoc = SourceLocation();
1411 }
1412 }
1413
1414 if (S.getLangOpts().C23 && getTypeSpecType() != DeclSpec::TST_unspecified &&
1415 getConstexprSpecifier() == ConstexprSpecKind::Constexpr &&
1416 (StorageClassSpec == SCS_extern || StorageClassSpec == SCS_auto)) {
1417 S.Diag(Loc: getStorageClassSpecLoc(), DiagID: diag::err_invalid_decl_spec_combination)
1418 << DeclSpec::getSpecifierName(C: getConstexprSpecifier())
1419 << SourceRange(getConstexprSpecLoc());
1420 }
1421
1422 // If no type specifier was provided and we're parsing a language where
1423 // the type specifier is not optional, but we got 'auto' as a storage
1424 // class specifier, then assume this is an attempt to use C++0x's 'auto'
1425 // type specifier.
1426 if (S.getLangOpts().CPlusPlus &&
1427 TypeSpecType == TST_unspecified && StorageClassSpec == SCS_auto) {
1428 TypeSpecType = TST_auto;
1429 StorageClassSpec = SCS_unspecified;
1430 TSTLoc = TSTNameLoc = StorageClassSpecLoc;
1431 StorageClassSpecLoc = SourceLocation();
1432 }
1433 // Diagnose if we've recovered from an ill-formed 'auto' storage class
1434 // specifier in a pre-C++11 dialect of C++ or in a pre-C23 dialect of C.
1435 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().C23 &&
1436 TypeSpecType == TST_auto)
1437 S.Diag(Loc: TSTLoc, DiagID: diag::ext_auto_type_specifier) << /*C++*/ 0;
1438 if (S.getLangOpts().HLSL &&
1439 S.getLangOpts().getHLSLVersion() < LangOptions::HLSL_202x &&
1440 TypeSpecType == TST_auto)
1441 S.Diag(Loc: TSTLoc, DiagID: diag::ext_hlsl_auto_type_specifier) << /*HLSL*/ 1;
1442 if (S.getLangOpts().CPlusPlus && !S.getLangOpts().CPlusPlus11 &&
1443 StorageClassSpec == SCS_auto)
1444 S.Diag(Loc: StorageClassSpecLoc, DiagID: diag::warn_auto_storage_class)
1445 << FixItHint::CreateRemoval(RemoveRange: StorageClassSpecLoc);
1446 if (TypeSpecType == TST_char8)
1447 S.Diag(Loc: TSTLoc, DiagID: diag::warn_cxx17_compat_unicode_type);
1448 else if (TypeSpecType == TST_char16 || TypeSpecType == TST_char32)
1449 S.Diag(Loc: TSTLoc, DiagID: diag::warn_cxx98_compat_unicode_type)
1450 << (TypeSpecType == TST_char16 ? "char16_t" : "char32_t");
1451 if (getConstexprSpecifier() == ConstexprSpecKind::Constexpr)
1452 S.Diag(Loc: ConstexprLoc, DiagID: diag::warn_cxx98_compat_constexpr);
1453 else if (getConstexprSpecifier() == ConstexprSpecKind::Consteval)
1454 S.Diag(Loc: ConstexprLoc, DiagID: diag::warn_cxx20_compat_consteval);
1455 else if (getConstexprSpecifier() == ConstexprSpecKind::Constinit)
1456 S.Diag(Loc: ConstexprLoc, DiagID: diag::warn_cxx20_compat_constinit);
1457}
1458
1459void DeclSpec::CheckFriendSpec(Sema &S, const PrintingPolicy &Policy) {
1460 // C++ [class.friend]p6:
1461 // No storage-class-specifier shall appear in the decl-specifier-seq
1462 // of a friend declaration.
1463 if (isFriendSpecified() &&
1464 (getStorageClassSpec() || getThreadStorageClassSpec())) {
1465 SmallString<32> SpecName;
1466 SourceLocation SCLoc;
1467 FixItHint StorageHint, ThreadHint;
1468
1469 if (DeclSpec::SCS SC = getStorageClassSpec()) {
1470 SpecName = getSpecifierName(S: SC);
1471 SCLoc = getStorageClassSpecLoc();
1472 StorageHint = FixItHint::CreateRemoval(RemoveRange: SCLoc);
1473 }
1474
1475 if (DeclSpec::TSCS TSC = getThreadStorageClassSpec()) {
1476 if (!SpecName.empty()) SpecName += " ";
1477 SpecName += getSpecifierName(S: TSC);
1478 SCLoc = getThreadStorageClassSpecLoc();
1479 ThreadHint = FixItHint::CreateRemoval(RemoveRange: SCLoc);
1480 }
1481
1482 S.Diag(Loc: SCLoc, DiagID: diag::err_friend_decl_spec)
1483 << SpecName << StorageHint << ThreadHint;
1484
1485 ClearStorageClassSpecs();
1486 }
1487
1488 // C++11 [dcl.fct.spec]p5:
1489 // The virtual specifier shall be used only in the initial
1490 // declaration of a non-static class member function;
1491 // C++11 [dcl.fct.spec]p6:
1492 // The explicit specifier shall be used only in the declaration of
1493 // a constructor or conversion function within its class
1494 // definition;
1495 if (isFriendSpecified() && (isVirtualSpecified() || hasExplicitSpecifier())) {
1496 StringRef Keyword;
1497 FixItHint Hint;
1498 SourceLocation SCLoc;
1499
1500 if (isVirtualSpecified()) {
1501 Keyword = "virtual";
1502 SCLoc = getVirtualSpecLoc();
1503 Hint = FixItHint::CreateRemoval(RemoveRange: SCLoc);
1504 } else {
1505 Keyword = "explicit";
1506 SCLoc = getExplicitSpecLoc();
1507 Hint = FixItHint::CreateRemoval(RemoveRange: getExplicitSpecRange());
1508 }
1509
1510 S.Diag(Loc: SCLoc, DiagID: diag::err_friend_decl_spec)
1511 << Keyword << Hint;
1512
1513 FS_virtual_specified = false;
1514 FS_explicit_specifier = ExplicitSpecifier();
1515 FS_virtualLoc = FS_explicitLoc = SourceLocation();
1516 }
1517}
1518
1519bool DeclSpec::isMissingDeclaratorOk() {
1520 TST tst = getTypeSpecType();
1521 return isDeclRep(T: tst) && getRepAsDecl() != nullptr &&
1522 StorageClassSpec != DeclSpec::SCS_typedef;
1523}
1524
1525void UnqualifiedId::setOperatorFunctionId(SourceLocation OperatorLoc,
1526 OverloadedOperatorKind Op,
1527 SourceLocation SymbolLocations[3]) {
1528 Kind = UnqualifiedIdKind::IK_OperatorFunctionId;
1529 StartLocation = OperatorLoc;
1530 EndLocation = OperatorLoc;
1531 new (&OperatorFunctionId) struct OFI;
1532 OperatorFunctionId.Operator = Op;
1533 for (unsigned I = 0; I != 3; ++I) {
1534 OperatorFunctionId.SymbolLocations[I] = SymbolLocations[I];
1535
1536 if (SymbolLocations[I].isValid())
1537 EndLocation = SymbolLocations[I];
1538 }
1539}
1540
1541bool VirtSpecifiers::SetSpecifier(Specifier VS, SourceLocation Loc,
1542 const char *&PrevSpec) {
1543 if (!FirstLocation.isValid())
1544 FirstLocation = Loc;
1545 LastLocation = Loc;
1546 LastSpecifier = VS;
1547
1548 if (Specifiers & VS) {
1549 PrevSpec = getSpecifierName(VS);
1550 return true;
1551 }
1552
1553 Specifiers |= VS;
1554
1555 switch (VS) {
1556 default: llvm_unreachable("Unknown specifier!");
1557 case VS_Override: VS_overrideLoc = Loc; break;
1558 case VS_GNU_Final:
1559 case VS_Sealed:
1560 case VS_Final: VS_finalLoc = Loc; break;
1561 case VS_Abstract: VS_abstractLoc = Loc; break;
1562 }
1563
1564 return false;
1565}
1566
1567const char *VirtSpecifiers::getSpecifierName(Specifier VS) {
1568 switch (VS) {
1569 default: llvm_unreachable("Unknown specifier");
1570 case VS_Override: return "override";
1571 case VS_Final: return "final";
1572 case VS_GNU_Final: return "__final";
1573 case VS_Sealed: return "sealed";
1574 case VS_Abstract: return "abstract";
1575 }
1576}
1577