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