1 //===- TypeLoc.cpp - Type Source Info Wrapper -----------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file defines the TypeLoc subclasses implementations.
11 //===----------------------------------------------------------------------===//
13 #include "clang/AST/TypeLoc.h"
14 #include "clang/AST/DeclTemplate.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/NestedNameSpecifier.h"
19 #include "clang/AST/TemplateBase.h"
20 #include "clang/AST/TemplateName.h"
21 #include "clang/AST/TypeLocVisitor.h"
22 #include "clang/Basic/SourceLocation.h"
23 #include "clang/Basic/Specifiers.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/MathExtras.h"
31 using namespace clang;
33 static const unsigned TypeLocMaxDataAlign = alignof(void *);
35 //===----------------------------------------------------------------------===//
36 // TypeLoc Implementation
37 //===----------------------------------------------------------------------===//
41 class TypeLocRanger : public TypeLocVisitor<TypeLocRanger, SourceRange> {
43 #define ABSTRACT_TYPELOC(CLASS, PARENT)
44 #define TYPELOC(CLASS, PARENT) \
45 SourceRange Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc) { \
46 return TyLoc.getLocalSourceRange(); \
48 #include "clang/AST/TypeLocNodes.def"
53 SourceRange TypeLoc::getLocalSourceRangeImpl(TypeLoc TL) {
54 if (TL.isNull()) return SourceRange();
55 return TypeLocRanger().Visit(TL);
60 class TypeAligner : public TypeLocVisitor<TypeAligner, unsigned> {
62 #define ABSTRACT_TYPELOC(CLASS, PARENT)
63 #define TYPELOC(CLASS, PARENT) \
64 unsigned Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc) { \
65 return TyLoc.getLocalDataAlignment(); \
67 #include "clang/AST/TypeLocNodes.def"
72 /// Returns the alignment of the type source info data block.
73 unsigned TypeLoc::getLocalAlignmentForType(QualType Ty) {
74 if (Ty.isNull()) return 1;
75 return TypeAligner().Visit(TypeLoc(Ty, nullptr));
80 class TypeSizer : public TypeLocVisitor<TypeSizer, unsigned> {
82 #define ABSTRACT_TYPELOC(CLASS, PARENT)
83 #define TYPELOC(CLASS, PARENT) \
84 unsigned Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc) { \
85 return TyLoc.getLocalDataSize(); \
87 #include "clang/AST/TypeLocNodes.def"
92 /// Returns the size of the type source info data block.
93 unsigned TypeLoc::getFullDataSizeForType(QualType Ty) {
95 TypeLoc TyLoc(Ty, nullptr);
96 unsigned MaxAlign = 1;
97 while (!TyLoc.isNull()) {
98 unsigned Align = getLocalAlignmentForType(TyLoc.getType());
99 MaxAlign = std::max(Align, MaxAlign);
100 Total = llvm::alignTo(Total, Align);
101 Total += TypeSizer().Visit(TyLoc);
102 TyLoc = TyLoc.getNextTypeLoc();
104 Total = llvm::alignTo(Total, MaxAlign);
110 class NextLoc : public TypeLocVisitor<NextLoc, TypeLoc> {
112 #define ABSTRACT_TYPELOC(CLASS, PARENT)
113 #define TYPELOC(CLASS, PARENT) \
114 TypeLoc Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc) { \
115 return TyLoc.getNextTypeLoc(); \
117 #include "clang/AST/TypeLocNodes.def"
122 /// Get the next TypeLoc pointed by this TypeLoc, e.g for "int*" the
123 /// TypeLoc is a PointerLoc and next TypeLoc is for "int".
124 TypeLoc TypeLoc::getNextTypeLocImpl(TypeLoc TL) {
125 return NextLoc().Visit(TL);
128 /// Initializes a type location, and all of its children
129 /// recursively, as if the entire tree had been written in the
131 void TypeLoc::initializeImpl(ASTContext &Context, TypeLoc TL,
132 SourceLocation Loc) {
134 switch (TL.getTypeLocClass()) {
135 #define ABSTRACT_TYPELOC(CLASS, PARENT)
136 #define TYPELOC(CLASS, PARENT) \
138 CLASS##TypeLoc TLCasted = TL.castAs<CLASS##TypeLoc>(); \
139 TLCasted.initializeLocal(Context, Loc); \
140 TL = TLCasted.getNextTypeLoc(); \
144 #include "clang/AST/TypeLocNodes.def"
151 class TypeLocCopier : public TypeLocVisitor<TypeLocCopier> {
155 TypeLocCopier(TypeLoc source) : Source(source) {}
157 #define ABSTRACT_TYPELOC(CLASS, PARENT)
158 #define TYPELOC(CLASS, PARENT) \
159 void Visit##CLASS##TypeLoc(CLASS##TypeLoc dest) { \
160 dest.copyLocal(Source.castAs<CLASS##TypeLoc>()); \
162 #include "clang/AST/TypeLocNodes.def"
167 void TypeLoc::copy(TypeLoc other) {
168 assert(getFullDataSize() == other.getFullDataSize());
170 // If both data pointers are aligned to the maximum alignment, we
171 // can memcpy because getFullDataSize() accurately reflects the
172 // layout of the data.
173 if (reinterpret_cast<uintptr_t>(Data) ==
174 llvm::alignTo(reinterpret_cast<uintptr_t>(Data),
175 TypeLocMaxDataAlign) &&
176 reinterpret_cast<uintptr_t>(other.Data) ==
177 llvm::alignTo(reinterpret_cast<uintptr_t>(other.Data),
178 TypeLocMaxDataAlign)) {
179 memcpy(Data, other.Data, getFullDataSize());
183 // Copy each of the pieces.
184 TypeLoc TL(getType(), Data);
186 TypeLocCopier(other).Visit(TL);
187 other = other.getNextTypeLoc();
188 } while ((TL = TL.getNextTypeLoc()));
191 SourceLocation TypeLoc::getBeginLoc() const {
193 TypeLoc LeftMost = Cur;
195 switch (Cur.getTypeLocClass()) {
200 if (Cur.castAs<FunctionProtoTypeLoc>().getTypePtr()
201 ->hasTrailingReturn()) {
206 case FunctionNoProto:
208 case DependentSizedArray:
209 case IncompleteArray:
211 // FIXME: Currently QualifiedTypeLoc does not have a source range
213 Cur = Cur.getNextTypeLoc();
216 if (Cur.getLocalSourceRange().getBegin().isValid())
218 Cur = Cur.getNextTypeLoc();
225 return LeftMost.getLocalSourceRange().getBegin();
228 SourceLocation TypeLoc::getEndLoc() const {
232 switch (Cur.getTypeLocClass()) {
236 return Last.getLocalSourceRange().getEnd();
239 case DependentSizedArray:
240 case IncompleteArray:
242 case FunctionNoProto:
243 // The innermost type with suffix syntax always determines the end of the
248 if (Cur.castAs<FunctionProtoTypeLoc>().getTypePtr()->hasTrailingReturn())
253 case ObjCObjectPointer:
254 // `id` and `id<...>` have no star location.
255 if (Cur.castAs<ObjCObjectPointerTypeLoc>().getStarLoc().isInvalid())
261 case LValueReference:
262 case RValueReference:
264 // Types with prefix syntax only determine the end of the type if there
265 // is no suffix type.
273 Cur = Cur.getNextTypeLoc();
279 struct TSTChecker : public TypeLocVisitor<TSTChecker, bool> {
280 // Overload resolution does the real work for us.
281 static bool isTypeSpec(TypeSpecTypeLoc _) { return true; }
282 static bool isTypeSpec(TypeLoc _) { return false; }
284 #define ABSTRACT_TYPELOC(CLASS, PARENT)
285 #define TYPELOC(CLASS, PARENT) \
286 bool Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc) { \
287 return isTypeSpec(TyLoc); \
289 #include "clang/AST/TypeLocNodes.def"
294 /// Determines if the given type loc corresponds to a
295 /// TypeSpecTypeLoc. Since there is not actually a TypeSpecType in
296 /// the type hierarchy, this is made somewhat complicated.
298 /// There are a lot of types that currently use TypeSpecTypeLoc
299 /// because it's a convenient base class. Ideally we would not accept
300 /// those here, but ideally we would have better implementations for
302 bool TypeSpecTypeLoc::isKind(const TypeLoc &TL) {
303 if (TL.getType().hasLocalQualifiers()) return false;
304 return TSTChecker().Visit(TL);
307 bool TagTypeLoc::isDefinition() const {
308 TagDecl *D = getDecl();
309 return D->isCompleteDefinition() &&
310 (D->getIdentifier() == nullptr || D->getLocation() == getNameLoc());
313 // Reimplemented to account for GNU/C++ extension
314 // typeof unary-expression
315 // where there are no parentheses.
316 SourceRange TypeOfExprTypeLoc::getLocalSourceRange() const {
317 if (getRParenLoc().isValid())
318 return SourceRange(getTypeofLoc(), getRParenLoc());
320 return SourceRange(getTypeofLoc(),
321 getUnderlyingExpr()->getSourceRange().getEnd());
325 TypeSpecifierType BuiltinTypeLoc::getWrittenTypeSpec() const {
326 if (needsExtraLocalData())
327 return static_cast<TypeSpecifierType>(getWrittenBuiltinSpecs().Type);
328 switch (getTypePtr()->getKind()) {
329 case BuiltinType::Void:
331 case BuiltinType::Bool:
333 case BuiltinType::Char_U:
334 case BuiltinType::Char_S:
336 case BuiltinType::Char8:
338 case BuiltinType::Char16:
340 case BuiltinType::Char32:
342 case BuiltinType::WChar_S:
343 case BuiltinType::WChar_U:
345 case BuiltinType::UChar:
346 case BuiltinType::UShort:
347 case BuiltinType::UInt:
348 case BuiltinType::ULong:
349 case BuiltinType::ULongLong:
350 case BuiltinType::UInt128:
351 case BuiltinType::SChar:
352 case BuiltinType::Short:
353 case BuiltinType::Int:
354 case BuiltinType::Long:
355 case BuiltinType::LongLong:
356 case BuiltinType::Int128:
357 case BuiltinType::Half:
358 case BuiltinType::Float:
359 case BuiltinType::Double:
360 case BuiltinType::LongDouble:
361 case BuiltinType::Float16:
362 case BuiltinType::Float128:
363 case BuiltinType::Ibm128:
364 case BuiltinType::ShortAccum:
365 case BuiltinType::Accum:
366 case BuiltinType::LongAccum:
367 case BuiltinType::UShortAccum:
368 case BuiltinType::UAccum:
369 case BuiltinType::ULongAccum:
370 case BuiltinType::ShortFract:
371 case BuiltinType::Fract:
372 case BuiltinType::LongFract:
373 case BuiltinType::UShortFract:
374 case BuiltinType::UFract:
375 case BuiltinType::ULongFract:
376 case BuiltinType::SatShortAccum:
377 case BuiltinType::SatAccum:
378 case BuiltinType::SatLongAccum:
379 case BuiltinType::SatUShortAccum:
380 case BuiltinType::SatUAccum:
381 case BuiltinType::SatULongAccum:
382 case BuiltinType::SatShortFract:
383 case BuiltinType::SatFract:
384 case BuiltinType::SatLongFract:
385 case BuiltinType::SatUShortFract:
386 case BuiltinType::SatUFract:
387 case BuiltinType::SatULongFract:
388 case BuiltinType::BFloat16:
389 llvm_unreachable("Builtin type needs extra local data!");
390 // Fall through, if the impossible happens.
392 case BuiltinType::NullPtr:
393 case BuiltinType::Overload:
394 case BuiltinType::Dependent:
395 case BuiltinType::BoundMember:
396 case BuiltinType::UnknownAny:
397 case BuiltinType::ARCUnbridgedCast:
398 case BuiltinType::PseudoObject:
399 case BuiltinType::ObjCId:
400 case BuiltinType::ObjCClass:
401 case BuiltinType::ObjCSel:
402 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
403 case BuiltinType::Id:
404 #include "clang/Basic/OpenCLImageTypes.def"
405 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
406 case BuiltinType::Id:
407 #include "clang/Basic/OpenCLExtensionTypes.def"
408 case BuiltinType::OCLSampler:
409 case BuiltinType::OCLEvent:
410 case BuiltinType::OCLClkEvent:
411 case BuiltinType::OCLQueue:
412 case BuiltinType::OCLReserveID:
413 #define SVE_TYPE(Name, Id, SingletonId) \
414 case BuiltinType::Id:
415 #include "clang/Basic/AArch64SVEACLETypes.def"
416 #define PPC_VECTOR_TYPE(Name, Id, Size) \
417 case BuiltinType::Id:
418 #include "clang/Basic/PPCTypes.def"
419 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
420 #include "clang/Basic/RISCVVTypes.def"
421 case BuiltinType::BuiltinFn:
422 case BuiltinType::IncompleteMatrixIdx:
423 case BuiltinType::OMPArraySection:
424 case BuiltinType::OMPArrayShaping:
425 case BuiltinType::OMPIterator:
426 return TST_unspecified;
429 llvm_unreachable("Invalid BuiltinType Kind!");
432 TypeLoc TypeLoc::IgnoreParensImpl(TypeLoc TL) {
433 while (ParenTypeLoc PTL = TL.getAs<ParenTypeLoc>())
434 TL = PTL.getInnerLoc();
438 SourceLocation TypeLoc::findNullabilityLoc() const {
439 if (auto ATL = getAs<AttributedTypeLoc>()) {
440 const Attr *A = ATL.getAttr();
441 if (A && (isa<TypeNullableAttr>(A) || isa<TypeNonNullAttr>(A) ||
442 isa<TypeNullUnspecifiedAttr>(A)))
443 return A->getLocation();
449 TypeLoc TypeLoc::findExplicitQualifierLoc() const {
451 if (auto qual = getAs<QualifiedTypeLoc>())
454 TypeLoc loc = IgnoreParens();
457 if (auto attr = loc.getAs<AttributedTypeLoc>()) {
458 if (attr.isQualifier()) return attr;
459 return attr.getModifiedLoc().findExplicitQualifierLoc();
462 // C11 _Atomic types.
463 if (auto atomic = loc.getAs<AtomicTypeLoc>()) {
470 void ObjCTypeParamTypeLoc::initializeLocal(ASTContext &Context,
471 SourceLocation Loc) {
473 if (!getNumProtocols()) return;
475 setProtocolLAngleLoc(Loc);
476 setProtocolRAngleLoc(Loc);
477 for (unsigned i = 0, e = getNumProtocols(); i != e; ++i)
478 setProtocolLoc(i, Loc);
481 void ObjCObjectTypeLoc::initializeLocal(ASTContext &Context,
482 SourceLocation Loc) {
483 setHasBaseTypeAsWritten(true);
484 setTypeArgsLAngleLoc(Loc);
485 setTypeArgsRAngleLoc(Loc);
486 for (unsigned i = 0, e = getNumTypeArgs(); i != e; ++i) {
488 Context.getTrivialTypeSourceInfo(
489 getTypePtr()->getTypeArgsAsWritten()[i], Loc));
491 setProtocolLAngleLoc(Loc);
492 setProtocolRAngleLoc(Loc);
493 for (unsigned i = 0, e = getNumProtocols(); i != e; ++i)
494 setProtocolLoc(i, Loc);
497 SourceRange AttributedTypeLoc::getLocalSourceRange() const {
498 // Note that this does *not* include the range of the attribute
500 // __attribute__((foo(bar)))
501 // ^~~~~~~~~~~~~~~ ~~
505 // That enclosure doesn't necessarily belong to a single attribute
507 return getAttr() ? getAttr()->getRange() : SourceRange();
510 void TypeOfTypeLoc::initializeLocal(ASTContext &Context,
511 SourceLocation Loc) {
512 TypeofLikeTypeLoc<TypeOfTypeLoc, TypeOfType, TypeOfTypeLocInfo>
513 ::initializeLocal(Context, Loc);
514 this->getLocalData()->UnderlyingTInfo = Context.getTrivialTypeSourceInfo(
515 getUnderlyingType(), Loc);
518 void UnaryTransformTypeLoc::initializeLocal(ASTContext &Context,
519 SourceLocation Loc) {
523 this->setUnderlyingTInfo(
524 Context.getTrivialTypeSourceInfo(getTypePtr()->getBaseType(), Loc));
527 void ElaboratedTypeLoc::initializeLocal(ASTContext &Context,
528 SourceLocation Loc) {
529 setElaboratedKeywordLoc(Loc);
530 NestedNameSpecifierLocBuilder Builder;
531 Builder.MakeTrivial(Context, getTypePtr()->getQualifier(), Loc);
532 setQualifierLoc(Builder.getWithLocInContext(Context));
535 void DependentNameTypeLoc::initializeLocal(ASTContext &Context,
536 SourceLocation Loc) {
537 setElaboratedKeywordLoc(Loc);
538 NestedNameSpecifierLocBuilder Builder;
539 Builder.MakeTrivial(Context, getTypePtr()->getQualifier(), Loc);
540 setQualifierLoc(Builder.getWithLocInContext(Context));
545 DependentTemplateSpecializationTypeLoc::initializeLocal(ASTContext &Context,
546 SourceLocation Loc) {
547 setElaboratedKeywordLoc(Loc);
548 if (getTypePtr()->getQualifier()) {
549 NestedNameSpecifierLocBuilder Builder;
550 Builder.MakeTrivial(Context, getTypePtr()->getQualifier(), Loc);
551 setQualifierLoc(Builder.getWithLocInContext(Context));
553 setQualifierLoc(NestedNameSpecifierLoc());
555 setTemplateKeywordLoc(Loc);
556 setTemplateNameLoc(Loc);
559 TemplateSpecializationTypeLoc::initializeArgLocs(Context, getNumArgs(),
560 getTypePtr()->getArgs(),
564 void TemplateSpecializationTypeLoc::initializeArgLocs(ASTContext &Context,
566 const TemplateArgument *Args,
567 TemplateArgumentLocInfo *ArgInfos,
568 SourceLocation Loc) {
569 for (unsigned i = 0, e = NumArgs; i != e; ++i) {
570 switch (Args[i].getKind()) {
571 case TemplateArgument::Null:
572 llvm_unreachable("Impossible TemplateArgument");
574 case TemplateArgument::Integral:
575 case TemplateArgument::Declaration:
576 case TemplateArgument::NullPtr:
577 ArgInfos[i] = TemplateArgumentLocInfo();
580 case TemplateArgument::Expression:
581 ArgInfos[i] = TemplateArgumentLocInfo(Args[i].getAsExpr());
584 case TemplateArgument::Type:
585 ArgInfos[i] = TemplateArgumentLocInfo(
586 Context.getTrivialTypeSourceInfo(Args[i].getAsType(),
590 case TemplateArgument::Template:
591 case TemplateArgument::TemplateExpansion: {
592 NestedNameSpecifierLocBuilder Builder;
593 TemplateName Template = Args[i].getAsTemplateOrTemplatePattern();
594 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
595 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
596 else if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
597 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
599 ArgInfos[i] = TemplateArgumentLocInfo(
600 Context, Builder.getWithLocInContext(Context), Loc,
601 Args[i].getKind() == TemplateArgument::Template ? SourceLocation()
606 case TemplateArgument::Pack:
607 ArgInfos[i] = TemplateArgumentLocInfo();
613 DeclarationNameInfo AutoTypeLoc::getConceptNameInfo() const {
614 return DeclarationNameInfo(getNamedConcept()->getDeclName(),
615 getLocalData()->ConceptNameLoc);
618 void AutoTypeLoc::initializeLocal(ASTContext &Context, SourceLocation Loc) {
619 setNestedNameSpecifierLoc(NestedNameSpecifierLoc());
620 setTemplateKWLoc(Loc);
621 setConceptNameLoc(Loc);
622 setFoundDecl(nullptr);
625 TemplateSpecializationTypeLoc::initializeArgLocs(Context, getNumArgs(),
626 getTypePtr()->getArgs(),
634 class GetContainedAutoTypeLocVisitor :
635 public TypeLocVisitor<GetContainedAutoTypeLocVisitor, TypeLoc> {
637 using TypeLocVisitor<GetContainedAutoTypeLocVisitor, TypeLoc>::Visit;
639 TypeLoc VisitAutoTypeLoc(AutoTypeLoc TL) {
643 // Only these types can contain the desired 'auto' type.
645 TypeLoc VisitElaboratedTypeLoc(ElaboratedTypeLoc T) {
646 return Visit(T.getNamedTypeLoc());
649 TypeLoc VisitQualifiedTypeLoc(QualifiedTypeLoc T) {
650 return Visit(T.getUnqualifiedLoc());
653 TypeLoc VisitPointerTypeLoc(PointerTypeLoc T) {
654 return Visit(T.getPointeeLoc());
657 TypeLoc VisitBlockPointerTypeLoc(BlockPointerTypeLoc T) {
658 return Visit(T.getPointeeLoc());
661 TypeLoc VisitReferenceTypeLoc(ReferenceTypeLoc T) {
662 return Visit(T.getPointeeLoc());
665 TypeLoc VisitMemberPointerTypeLoc(MemberPointerTypeLoc T) {
666 return Visit(T.getPointeeLoc());
669 TypeLoc VisitArrayTypeLoc(ArrayTypeLoc T) {
670 return Visit(T.getElementLoc());
673 TypeLoc VisitFunctionTypeLoc(FunctionTypeLoc T) {
674 return Visit(T.getReturnLoc());
677 TypeLoc VisitParenTypeLoc(ParenTypeLoc T) {
678 return Visit(T.getInnerLoc());
681 TypeLoc VisitAttributedTypeLoc(AttributedTypeLoc T) {
682 return Visit(T.getModifiedLoc());
685 TypeLoc VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc T) {
686 return Visit(T.getInnerLoc());
689 TypeLoc VisitAdjustedTypeLoc(AdjustedTypeLoc T) {
690 return Visit(T.getOriginalLoc());
693 TypeLoc VisitPackExpansionTypeLoc(PackExpansionTypeLoc T) {
694 return Visit(T.getPatternLoc());
700 AutoTypeLoc TypeLoc::getContainedAutoTypeLoc() const {
701 TypeLoc Res = GetContainedAutoTypeLocVisitor().Visit(*this);
703 return AutoTypeLoc();
704 return Res.getAs<AutoTypeLoc>();