clang 19.0.0git
ASTContext.cpp
Go to the documentation of this file.
1//===- ASTContext.cpp - Context to hold long-lived AST nodes --------------===//
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 the ASTContext interface.
10//
11//===----------------------------------------------------------------------===//
12
14#include "CXXABI.h"
15#include "Interp/Context.h"
16#include "clang/AST/APValue.h"
20#include "clang/AST/Attr.h"
22#include "clang/AST/CharUnits.h"
23#include "clang/AST/Comment.h"
24#include "clang/AST/Decl.h"
25#include "clang/AST/DeclBase.h"
26#include "clang/AST/DeclCXX.h"
28#include "clang/AST/DeclObjC.h"
33#include "clang/AST/Expr.h"
34#include "clang/AST/ExprCXX.h"
37#include "clang/AST/Mangle.h"
43#include "clang/AST/Stmt.h"
47#include "clang/AST/Type.h"
48#include "clang/AST/TypeLoc.h"
56#include "clang/Basic/LLVM.h"
58#include "clang/Basic/Linkage.h"
59#include "clang/Basic/Module.h"
69#include "llvm/ADT/APFixedPoint.h"
70#include "llvm/ADT/APInt.h"
71#include "llvm/ADT/APSInt.h"
72#include "llvm/ADT/ArrayRef.h"
73#include "llvm/ADT/DenseMap.h"
74#include "llvm/ADT/DenseSet.h"
75#include "llvm/ADT/FoldingSet.h"
76#include "llvm/ADT/PointerUnion.h"
77#include "llvm/ADT/STLExtras.h"
78#include "llvm/ADT/SmallPtrSet.h"
79#include "llvm/ADT/SmallVector.h"
80#include "llvm/ADT/StringExtras.h"
81#include "llvm/ADT/StringRef.h"
82#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
83#include "llvm/Support/Capacity.h"
84#include "llvm/Support/Casting.h"
85#include "llvm/Support/Compiler.h"
86#include "llvm/Support/ErrorHandling.h"
87#include "llvm/Support/MD5.h"
88#include "llvm/Support/MathExtras.h"
89#include "llvm/Support/raw_ostream.h"
90#include "llvm/TargetParser/Triple.h"
91#include <algorithm>
92#include <cassert>
93#include <cstddef>
94#include <cstdint>
95#include <cstdlib>
96#include <map>
97#include <memory>
98#include <optional>
99#include <string>
100#include <tuple>
101#include <utility>
102
103using namespace clang;
104
115
116/// \returns The locations that are relevant when searching for Doc comments
117/// related to \p D.
120 assert(D);
121
122 // User can not attach documentation to implicit declarations.
123 if (D->isImplicit())
124 return {};
125
126 // User can not attach documentation to implicit instantiations.
127 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
128 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
129 return {};
130 }
131
132 if (const auto *VD = dyn_cast<VarDecl>(D)) {
133 if (VD->isStaticDataMember() &&
134 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
135 return {};
136 }
137
138 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
139 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
140 return {};
141 }
142
143 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
144 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
145 if (TSK == TSK_ImplicitInstantiation ||
146 TSK == TSK_Undeclared)
147 return {};
148 }
149
150 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
151 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
152 return {};
153 }
154 if (const auto *TD = dyn_cast<TagDecl>(D)) {
155 // When tag declaration (but not definition!) is part of the
156 // decl-specifier-seq of some other declaration, it doesn't get comment
157 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
158 return {};
159 }
160 // TODO: handle comments for function parameters properly.
161 if (isa<ParmVarDecl>(D))
162 return {};
163
164 // TODO: we could look up template parameter documentation in the template
165 // documentation.
166 if (isa<TemplateTypeParmDecl>(D) ||
167 isa<NonTypeTemplateParmDecl>(D) ||
168 isa<TemplateTemplateParmDecl>(D))
169 return {};
170
172 // Find declaration location.
173 // For Objective-C declarations we generally don't expect to have multiple
174 // declarators, thus use declaration starting location as the "declaration
175 // location".
176 // For all other declarations multiple declarators are used quite frequently,
177 // so we use the location of the identifier as the "declaration location".
178 SourceLocation BaseLocation;
179 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
180 isa<ObjCPropertyDecl>(D) || isa<RedeclarableTemplateDecl>(D) ||
181 isa<ClassTemplateSpecializationDecl>(D) ||
182 // Allow association with Y across {} in `typedef struct X {} Y`.
183 isa<TypedefDecl>(D))
184 BaseLocation = D->getBeginLoc();
185 else
186 BaseLocation = D->getLocation();
187
188 if (!D->getLocation().isMacroID()) {
189 Locations.emplace_back(BaseLocation);
190 } else {
191 const auto *DeclCtx = D->getDeclContext();
192
193 // When encountering definitions generated from a macro (that are not
194 // contained by another declaration in the macro) we need to try and find
195 // the comment at the location of the expansion but if there is no comment
196 // there we should retry to see if there is a comment inside the macro as
197 // well. To this end we return first BaseLocation to first look at the
198 // expansion site, the second value is the spelling location of the
199 // beginning of the declaration defined inside the macro.
200 if (!(DeclCtx &&
201 Decl::castFromDeclContext(DeclCtx)->getLocation().isMacroID())) {
202 Locations.emplace_back(SourceMgr.getExpansionLoc(BaseLocation));
203 }
204
205 // We use Decl::getBeginLoc() and not just BaseLocation here to ensure that
206 // we don't refer to the macro argument location at the expansion site (this
207 // can happen if the name's spelling is provided via macro argument), and
208 // always to the declaration itself.
209 Locations.emplace_back(SourceMgr.getSpellingLoc(D->getBeginLoc()));
210 }
211
212 return Locations;
213}
214
216 const Decl *D, const SourceLocation RepresentativeLocForDecl,
217 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
218 // If the declaration doesn't map directly to a location in a file, we
219 // can't find the comment.
220 if (RepresentativeLocForDecl.isInvalid() ||
221 !RepresentativeLocForDecl.isFileID())
222 return nullptr;
223
224 // If there are no comments anywhere, we won't find anything.
225 if (CommentsInTheFile.empty())
226 return nullptr;
227
228 // Decompose the location for the declaration and find the beginning of the
229 // file buffer.
230 const std::pair<FileID, unsigned> DeclLocDecomp =
231 SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
232
233 // Slow path.
234 auto OffsetCommentBehindDecl =
235 CommentsInTheFile.lower_bound(DeclLocDecomp.second);
236
237 // First check whether we have a trailing comment.
238 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
239 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
240 if ((CommentBehindDecl->isDocumentation() ||
241 LangOpts.CommentOpts.ParseAllComments) &&
242 CommentBehindDecl->isTrailingComment() &&
243 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
244 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
245
246 // Check that Doxygen trailing comment comes after the declaration, starts
247 // on the same line and in the same file as the declaration.
248 if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
249 Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
250 OffsetCommentBehindDecl->first)) {
251 return CommentBehindDecl;
252 }
253 }
254 }
255
256 // The comment just after the declaration was not a trailing comment.
257 // Let's look at the previous comment.
258 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
259 return nullptr;
260
261 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
262 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
263
264 // Check that we actually have a non-member Doxygen comment.
265 if (!(CommentBeforeDecl->isDocumentation() ||
266 LangOpts.CommentOpts.ParseAllComments) ||
267 CommentBeforeDecl->isTrailingComment())
268 return nullptr;
269
270 // Decompose the end of the comment.
271 const unsigned CommentEndOffset =
272 Comments.getCommentEndOffset(CommentBeforeDecl);
273
274 // Get the corresponding buffer.
275 bool Invalid = false;
276 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
277 &Invalid).data();
278 if (Invalid)
279 return nullptr;
280
281 // Extract text between the comment and declaration.
282 StringRef Text(Buffer + CommentEndOffset,
283 DeclLocDecomp.second - CommentEndOffset);
284
285 // There should be no other declarations or preprocessor directives between
286 // comment and declaration.
287 if (Text.find_last_of(";{}#@") != StringRef::npos)
288 return nullptr;
289
290 return CommentBeforeDecl;
291}
292
294 const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr);
295
296 for (const auto DeclLoc : DeclLocs) {
297 // If the declaration doesn't map directly to a location in a file, we
298 // can't find the comment.
299 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
300 continue;
301
304 CommentsLoaded = true;
305 }
306
307 if (Comments.empty())
308 continue;
309
310 const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
311 if (!File.isValid())
312 continue;
313
314 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
315 if (!CommentsInThisFile || CommentsInThisFile->empty())
316 continue;
317
318 if (RawComment *Comment =
319 getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile))
320 return Comment;
321 }
322
323 return nullptr;
324}
325
327 assert(LangOpts.RetainCommentsFromSystemHeaders ||
328 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
329 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
330}
331
332/// If we have a 'templated' declaration for a template, adjust 'D' to
333/// refer to the actual template.
334/// If we have an implicit instantiation, adjust 'D' to refer to template.
335static const Decl &adjustDeclToTemplate(const Decl &D) {
336 if (const auto *FD = dyn_cast<FunctionDecl>(&D)) {
337 // Is this function declaration part of a function template?
338 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
339 return *FTD;
340
341 // Nothing to do if function is not an implicit instantiation.
342 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
343 return D;
344
345 // Function is an implicit instantiation of a function template?
346 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
347 return *FTD;
348
349 // Function is instantiated from a member definition of a class template?
350 if (const FunctionDecl *MemberDecl =
352 return *MemberDecl;
353
354 return D;
355 }
356 if (const auto *VD = dyn_cast<VarDecl>(&D)) {
357 // Static data member is instantiated from a member definition of a class
358 // template?
359 if (VD->isStaticDataMember())
360 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
361 return *MemberDecl;
362
363 return D;
364 }
365 if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) {
366 // Is this class declaration part of a class template?
367 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
368 return *CTD;
369
370 // Class is an implicit instantiation of a class template or partial
371 // specialization?
372 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
373 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
374 return D;
375 llvm::PointerUnion<ClassTemplateDecl *,
378 return PU.is<ClassTemplateDecl *>()
379 ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>())
380 : *static_cast<const Decl *>(
382 }
383
384 // Class is instantiated from a member definition of a class template?
385 if (const MemberSpecializationInfo *Info =
386 CRD->getMemberSpecializationInfo())
387 return *Info->getInstantiatedFrom();
388
389 return D;
390 }
391 if (const auto *ED = dyn_cast<EnumDecl>(&D)) {
392 // Enum is instantiated from a member definition of a class template?
393 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
394 return *MemberDecl;
395
396 return D;
397 }
398 // FIXME: Adjust alias templates?
399 return D;
400}
401
403 const Decl *D,
404 const Decl **OriginalDecl) const {
405 if (!D) {
406 if (OriginalDecl)
407 OriginalDecl = nullptr;
408 return nullptr;
409 }
410
411 D = &adjustDeclToTemplate(*D);
412
413 // Any comment directly attached to D?
414 {
415 auto DeclComment = DeclRawComments.find(D);
416 if (DeclComment != DeclRawComments.end()) {
417 if (OriginalDecl)
418 *OriginalDecl = D;
419 return DeclComment->second;
420 }
421 }
422
423 // Any comment attached to any redeclaration of D?
424 const Decl *CanonicalD = D->getCanonicalDecl();
425 if (!CanonicalD)
426 return nullptr;
427
428 {
429 auto RedeclComment = RedeclChainComments.find(CanonicalD);
430 if (RedeclComment != RedeclChainComments.end()) {
431 if (OriginalDecl)
432 *OriginalDecl = RedeclComment->second;
433 auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
434 assert(CommentAtRedecl != DeclRawComments.end() &&
435 "This decl is supposed to have comment attached.");
436 return CommentAtRedecl->second;
437 }
438 }
439
440 // Any redeclarations of D that we haven't checked for comments yet?
441 // We can't use DenseMap::iterator directly since it'd get invalid.
442 auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * {
443 return CommentlessRedeclChains.lookup(CanonicalD);
444 }();
445
446 for (const auto Redecl : D->redecls()) {
447 assert(Redecl);
448 // Skip all redeclarations that have been checked previously.
449 if (LastCheckedRedecl) {
450 if (LastCheckedRedecl == Redecl) {
451 LastCheckedRedecl = nullptr;
452 }
453 continue;
454 }
455 const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
456 if (RedeclComment) {
457 cacheRawCommentForDecl(*Redecl, *RedeclComment);
458 if (OriginalDecl)
459 *OriginalDecl = Redecl;
460 return RedeclComment;
461 }
462 CommentlessRedeclChains[CanonicalD] = Redecl;
463 }
464
465 if (OriginalDecl)
466 *OriginalDecl = nullptr;
467 return nullptr;
468}
469
471 const RawComment &Comment) const {
472 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
473 DeclRawComments.try_emplace(&OriginalD, &Comment);
474 const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
475 RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
476 CommentlessRedeclChains.erase(CanonicalDecl);
477}
478
479static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
481 const DeclContext *DC = ObjCMethod->getDeclContext();
482 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
483 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
484 if (!ID)
485 return;
486 // Add redeclared method here.
487 for (const auto *Ext : ID->known_extensions()) {
488 if (ObjCMethodDecl *RedeclaredMethod =
489 Ext->getMethod(ObjCMethod->getSelector(),
490 ObjCMethod->isInstanceMethod()))
491 Redeclared.push_back(RedeclaredMethod);
492 }
493 }
494}
495
497 const Preprocessor *PP) {
498 if (Comments.empty() || Decls.empty())
499 return;
500
501 FileID File;
502 for (const Decl *D : Decls) {
503 if (D->isInvalidDecl())
504 continue;
505
506 D = &adjustDeclToTemplate(*D);
507 SourceLocation Loc = D->getLocation();
508 if (Loc.isValid()) {
509 // See if there are any new comments that are not attached to a decl.
510 // The location doesn't have to be precise - we care only about the file.
511 File = SourceMgr.getDecomposedLoc(Loc).first;
512 break;
513 }
514 }
515
516 if (File.isInvalid())
517 return;
518
519 auto CommentsInThisFile = Comments.getCommentsInFile(File);
520 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
521 CommentsInThisFile->rbegin()->second->isAttached())
522 return;
523
524 // There is at least one comment not attached to a decl.
525 // Maybe it should be attached to one of Decls?
526 //
527 // Note that this way we pick up not only comments that precede the
528 // declaration, but also comments that *follow* the declaration -- thanks to
529 // the lookahead in the lexer: we've consumed the semicolon and looked
530 // ahead through comments.
531 for (const Decl *D : Decls) {
532 assert(D);
533 if (D->isInvalidDecl())
534 continue;
535
536 D = &adjustDeclToTemplate(*D);
537
538 if (DeclRawComments.count(D) > 0)
539 continue;
540
541 const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr);
542
543 for (const auto DeclLoc : DeclLocs) {
544 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
545 continue;
546
547 if (RawComment *const DocComment = getRawCommentForDeclNoCacheImpl(
548 D, DeclLoc, *CommentsInThisFile)) {
549 cacheRawCommentForDecl(*D, *DocComment);
550 comments::FullComment *FC = DocComment->parse(*this, PP, D);
551 ParsedComments[D->getCanonicalDecl()] = FC;
552 break;
553 }
554 }
555 }
556}
557
559 const Decl *D) const {
560 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
561 ThisDeclInfo->CommentDecl = D;
562 ThisDeclInfo->IsFilled = false;
563 ThisDeclInfo->fill();
564 ThisDeclInfo->CommentDecl = FC->getDecl();
565 if (!ThisDeclInfo->TemplateParameters)
566 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
568 new (*this) comments::FullComment(FC->getBlocks(),
569 ThisDeclInfo);
570 return CFC;
571}
572
575 return RC ? RC->parse(*this, nullptr, D) : nullptr;
576}
577
579 const Decl *D,
580 const Preprocessor *PP) const {
581 if (!D || D->isInvalidDecl())
582 return nullptr;
583 D = &adjustDeclToTemplate(*D);
584
585 const Decl *Canonical = D->getCanonicalDecl();
586 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
587 ParsedComments.find(Canonical);
588
589 if (Pos != ParsedComments.end()) {
590 if (Canonical != D) {
591 comments::FullComment *FC = Pos->second;
593 return CFC;
594 }
595 return Pos->second;
596 }
597
598 const Decl *OriginalDecl = nullptr;
599
600 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
601 if (!RC) {
602 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
604 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
605 if (OMD && OMD->isPropertyAccessor())
606 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
607 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
608 return cloneFullComment(FC, D);
609 if (OMD)
610 addRedeclaredMethods(OMD, Overridden);
611 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
612 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
613 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
614 return cloneFullComment(FC, D);
615 }
616 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
617 // Attach any tag type's documentation to its typedef if latter
618 // does not have one of its own.
619 QualType QT = TD->getUnderlyingType();
620 if (const auto *TT = QT->getAs<TagType>())
621 if (const Decl *TD = TT->getDecl())
623 return cloneFullComment(FC, D);
624 }
625 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
626 while (IC->getSuperClass()) {
627 IC = IC->getSuperClass();
629 return cloneFullComment(FC, D);
630 }
631 }
632 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
633 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
635 return cloneFullComment(FC, D);
636 }
637 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
638 if (!(RD = RD->getDefinition()))
639 return nullptr;
640 // Check non-virtual bases.
641 for (const auto &I : RD->bases()) {
642 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
643 continue;
644 QualType Ty = I.getType();
645 if (Ty.isNull())
646 continue;
648 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
649 continue;
650
652 return cloneFullComment(FC, D);
653 }
654 }
655 // Check virtual bases.
656 for (const auto &I : RD->vbases()) {
657 if (I.getAccessSpecifier() != AS_public)
658 continue;
659 QualType Ty = I.getType();
660 if (Ty.isNull())
661 continue;
662 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
663 if (!(VirtualBase= VirtualBase->getDefinition()))
664 continue;
666 return cloneFullComment(FC, D);
667 }
668 }
669 }
670 return nullptr;
671 }
672
673 // If the RawComment was attached to other redeclaration of this Decl, we
674 // should parse the comment in context of that other Decl. This is important
675 // because comments can contain references to parameter names which can be
676 // different across redeclarations.
677 if (D != OriginalDecl && OriginalDecl)
678 return getCommentForDecl(OriginalDecl, PP);
679
680 comments::FullComment *FC = RC->parse(*this, PP, D);
681 ParsedComments[Canonical] = FC;
682 return FC;
683}
684
685void
686ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
687 const ASTContext &C,
689 ID.AddInteger(Parm->getDepth());
690 ID.AddInteger(Parm->getPosition());
691 ID.AddBoolean(Parm->isParameterPack());
692
694 ID.AddInteger(Params->size());
696 PEnd = Params->end();
697 P != PEnd; ++P) {
698 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
699 ID.AddInteger(0);
700 ID.AddBoolean(TTP->isParameterPack());
701 if (TTP->isExpandedParameterPack()) {
702 ID.AddBoolean(true);
703 ID.AddInteger(TTP->getNumExpansionParameters());
704 } else
705 ID.AddBoolean(false);
706 continue;
707 }
708
709 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
710 ID.AddInteger(1);
711 ID.AddBoolean(NTTP->isParameterPack());
712 ID.AddPointer(C.getUnconstrainedType(C.getCanonicalType(NTTP->getType()))
713 .getAsOpaquePtr());
714 if (NTTP->isExpandedParameterPack()) {
715 ID.AddBoolean(true);
716 ID.AddInteger(NTTP->getNumExpansionTypes());
717 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
718 QualType T = NTTP->getExpansionType(I);
719 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
720 }
721 } else
722 ID.AddBoolean(false);
723 continue;
724 }
725
726 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
727 ID.AddInteger(2);
728 Profile(ID, C, TTP);
729 }
730}
731
733ASTContext::getCanonicalTemplateTemplateParmDecl(
734 TemplateTemplateParmDecl *TTP) const {
735 // Check if we already have a canonical template template parameter.
736 llvm::FoldingSetNodeID ID;
737 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
738 void *InsertPos = nullptr;
739 CanonicalTemplateTemplateParm *Canonical
740 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
741 if (Canonical)
742 return Canonical->getParam();
743
744 // Build a canonical template parameter list.
746 SmallVector<NamedDecl *, 4> CanonParams;
747 CanonParams.reserve(Params->size());
749 PEnd = Params->end();
750 P != PEnd; ++P) {
751 // Note that, per C++20 [temp.over.link]/6, when determining whether
752 // template-parameters are equivalent, constraints are ignored.
753 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
756 TTP->getDepth(), TTP->getIndex(), nullptr, false,
757 TTP->isParameterPack(), /*HasTypeConstraint=*/false,
759 ? std::optional<unsigned>(TTP->getNumExpansionParameters())
760 : std::nullopt);
761 CanonParams.push_back(NewTTP);
762 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
766 if (NTTP->isExpandedParameterPack()) {
767 SmallVector<QualType, 2> ExpandedTypes;
769 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
770 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
771 ExpandedTInfos.push_back(
772 getTrivialTypeSourceInfo(ExpandedTypes.back()));
773 }
774
778 NTTP->getDepth(),
779 NTTP->getPosition(), nullptr,
780 T,
781 TInfo,
782 ExpandedTypes,
783 ExpandedTInfos);
784 } else {
788 NTTP->getDepth(),
789 NTTP->getPosition(), nullptr,
790 T,
791 NTTP->isParameterPack(),
792 TInfo);
793 }
794 CanonParams.push_back(Param);
795 } else
796 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
797 cast<TemplateTemplateParmDecl>(*P)));
798 }
799
802 TTP->getPosition(), TTP->isParameterPack(), nullptr, /*Typename=*/false,
804 CanonParams, SourceLocation(),
805 /*RequiresClause=*/nullptr));
806
807 // Get the new insert position for the node we care about.
808 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
809 assert(!Canonical && "Shouldn't be in the map!");
810 (void)Canonical;
811
812 // Create the canonical template template parameter entry.
813 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
814 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
815 return CanonTTP;
816}
817
819 auto Kind = getTargetInfo().getCXXABI().getKind();
820 return getLangOpts().CXXABI.value_or(Kind);
821}
822
823CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
824 if (!LangOpts.CPlusPlus) return nullptr;
825
826 switch (getCXXABIKind()) {
827 case TargetCXXABI::AppleARM64:
828 case TargetCXXABI::Fuchsia:
829 case TargetCXXABI::GenericARM: // Same as Itanium at this level
830 case TargetCXXABI::iOS:
831 case TargetCXXABI::WatchOS:
832 case TargetCXXABI::GenericAArch64:
833 case TargetCXXABI::GenericMIPS:
834 case TargetCXXABI::GenericItanium:
835 case TargetCXXABI::WebAssembly:
836 case TargetCXXABI::XL:
837 return CreateItaniumCXXABI(*this);
838 case TargetCXXABI::Microsoft:
839 return CreateMicrosoftCXXABI(*this);
840 }
841 llvm_unreachable("Invalid CXXABI type!");
842}
843
845 if (!InterpContext) {
846 InterpContext.reset(new interp::Context(*this));
847 }
848 return *InterpContext.get();
849}
850
852 if (!ParentMapCtx)
853 ParentMapCtx.reset(new ParentMapContext(*this));
854 return *ParentMapCtx.get();
855}
856
858 const LangOptions &LangOpts) {
859 switch (LangOpts.getAddressSpaceMapMangling()) {
861 return TI.useAddressSpaceMapMangling();
863 return true;
865 return false;
866 }
867 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
868}
869
871 IdentifierTable &idents, SelectorTable &sels,
872 Builtin::Context &builtins, TranslationUnitKind TUKind)
873 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize),
874 DependentSizedArrayTypes(this_()), DependentSizedExtVectorTypes(this_()),
875 DependentAddressSpaceTypes(this_()), DependentVectorTypes(this_()),
876 DependentSizedMatrixTypes(this_()),
877 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize),
878 DependentTypeOfExprTypes(this_()), DependentDecltypeTypes(this_()),
879 TemplateSpecializationTypes(this_()),
880 DependentTemplateSpecializationTypes(this_()), AutoTypes(this_()),
881 DependentBitIntTypes(this_()), SubstTemplateTemplateParmPacks(this_()),
882 ArrayParameterTypes(this_()), CanonTemplateTemplateParms(this_()),
883 SourceMgr(SM), LangOpts(LOpts),
884 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
885 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
886 LangOpts.XRayNeverInstrumentFiles,
887 LangOpts.XRayAttrListFiles, SM)),
888 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
889 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
890 BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this),
891 Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
892 CompCategories(this_()), LastSDM(nullptr, 0) {
894}
895
897 // Release the DenseMaps associated with DeclContext objects.
898 // FIXME: Is this the ideal solution?
899 ReleaseDeclContextMaps();
900
901 // Call all of the deallocation functions on all of their targets.
902 for (auto &Pair : Deallocations)
903 (Pair.first)(Pair.second);
904 Deallocations.clear();
905
906 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
907 // because they can contain DenseMaps.
908 for (llvm::DenseMap<const ObjCContainerDecl*,
909 const ASTRecordLayout*>::iterator
910 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
911 // Increment in loop to prevent using deallocated memory.
912 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
913 R->Destroy(*this);
914 ObjCLayouts.clear();
915
916 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
917 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
918 // Increment in loop to prevent using deallocated memory.
919 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
920 R->Destroy(*this);
921 }
922 ASTRecordLayouts.clear();
923
924 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
925 AEnd = DeclAttrs.end();
926 A != AEnd; ++A)
927 A->second->~AttrVec();
928 DeclAttrs.clear();
929
930 for (const auto &Value : ModuleInitializers)
931 Value.second->~PerModuleInitializers();
932 ModuleInitializers.clear();
933}
934
936
937void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
938 TraversalScope = TopLevelDecls;
940}
941
942void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
943 Deallocations.push_back({Callback, Data});
944}
945
946void
948 ExternalSource = std::move(Source);
949}
950
952 llvm::errs() << "\n*** AST Context Stats:\n";
953 llvm::errs() << " " << Types.size() << " types total.\n";
954
955 unsigned counts[] = {
956#define TYPE(Name, Parent) 0,
957#define ABSTRACT_TYPE(Name, Parent)
958#include "clang/AST/TypeNodes.inc"
959 0 // Extra
960 };
961
962 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
963 Type *T = Types[i];
964 counts[(unsigned)T->getTypeClass()]++;
965 }
966
967 unsigned Idx = 0;
968 unsigned TotalBytes = 0;
969#define TYPE(Name, Parent) \
970 if (counts[Idx]) \
971 llvm::errs() << " " << counts[Idx] << " " << #Name \
972 << " types, " << sizeof(Name##Type) << " each " \
973 << "(" << counts[Idx] * sizeof(Name##Type) \
974 << " bytes)\n"; \
975 TotalBytes += counts[Idx] * sizeof(Name##Type); \
976 ++Idx;
977#define ABSTRACT_TYPE(Name, Parent)
978#include "clang/AST/TypeNodes.inc"
979
980 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
981
982 // Implicit special member functions.
983 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
985 << " implicit default constructors created\n";
986 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
988 << " implicit copy constructors created\n";
990 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
992 << " implicit move constructors created\n";
993 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
995 << " implicit copy assignment operators created\n";
997 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
999 << " implicit move assignment operators created\n";
1000 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1002 << " implicit destructors created\n";
1003
1004 if (ExternalSource) {
1005 llvm::errs() << "\n";
1007 }
1008
1009 BumpAlloc.PrintStats();
1010}
1011
1013 bool NotifyListeners) {
1014 if (NotifyListeners)
1015 if (auto *Listener = getASTMutationListener())
1017
1018 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1019}
1020
1022 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1023 if (It == MergedDefModules.end())
1024 return;
1025
1026 auto &Merged = It->second;
1028 for (Module *&M : Merged)
1029 if (!Found.insert(M).second)
1030 M = nullptr;
1031 llvm::erase(Merged, nullptr);
1032}
1033
1036 auto MergedIt =
1037 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1038 if (MergedIt == MergedDefModules.end())
1039 return std::nullopt;
1040 return MergedIt->second;
1041}
1042
1043void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1044 if (LazyInitializers.empty())
1045 return;
1046
1047 auto *Source = Ctx.getExternalSource();
1048 assert(Source && "lazy initializers but no external source");
1049
1050 auto LazyInits = std::move(LazyInitializers);
1051 LazyInitializers.clear();
1052
1053 for (auto ID : LazyInits)
1054 Initializers.push_back(Source->GetExternalDecl(ID));
1055
1056 assert(LazyInitializers.empty() &&
1057 "GetExternalDecl for lazy module initializer added more inits");
1058}
1059
1061 // One special case: if we add a module initializer that imports another
1062 // module, and that module's only initializer is an ImportDecl, simplify.
1063 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1064 auto It = ModuleInitializers.find(ID->getImportedModule());
1065
1066 // Maybe the ImportDecl does nothing at all. (Common case.)
1067 if (It == ModuleInitializers.end())
1068 return;
1069
1070 // Maybe the ImportDecl only imports another ImportDecl.
1071 auto &Imported = *It->second;
1072 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1073 Imported.resolve(*this);
1074 auto *OnlyDecl = Imported.Initializers.front();
1075 if (isa<ImportDecl>(OnlyDecl))
1076 D = OnlyDecl;
1077 }
1078 }
1079
1080 auto *&Inits = ModuleInitializers[M];
1081 if (!Inits)
1082 Inits = new (*this) PerModuleInitializers;
1083 Inits->Initializers.push_back(D);
1084}
1085
1088 auto *&Inits = ModuleInitializers[M];
1089 if (!Inits)
1090 Inits = new (*this) PerModuleInitializers;
1091 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1092 IDs.begin(), IDs.end());
1093}
1094
1096 auto It = ModuleInitializers.find(M);
1097 if (It == ModuleInitializers.end())
1098 return std::nullopt;
1099
1100 auto *Inits = It->second;
1101 Inits->resolve(*this);
1102 return Inits->Initializers;
1103}
1104
1106 assert(M->isNamedModule());
1107 assert(!CurrentCXXNamedModule &&
1108 "We should set named module for ASTContext for only once");
1109 CurrentCXXNamedModule = M;
1110}
1111
1113 if (!ExternCContext)
1114 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1115
1116 return ExternCContext;
1117}
1118
1121 const IdentifierInfo *II) const {
1122 auto *BuiltinTemplate =
1124 BuiltinTemplate->setImplicit();
1125 getTranslationUnitDecl()->addDecl(BuiltinTemplate);
1126
1127 return BuiltinTemplate;
1128}
1129
1132 if (!MakeIntegerSeqDecl)
1135 return MakeIntegerSeqDecl;
1136}
1137
1140 if (!TypePackElementDecl)
1143 return TypePackElementDecl;
1144}
1145
1147 RecordDecl::TagKind TK) const {
1149 RecordDecl *NewDecl;
1150 if (getLangOpts().CPlusPlus)
1151 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1152 Loc, &Idents.get(Name));
1153 else
1154 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1155 &Idents.get(Name));
1156 NewDecl->setImplicit();
1157 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1158 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1159 return NewDecl;
1160}
1161
1163 StringRef Name) const {
1166 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1167 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1168 NewDecl->setImplicit();
1169 return NewDecl;
1170}
1171
1173 if (!Int128Decl)
1174 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1175 return Int128Decl;
1176}
1177
1179 if (!UInt128Decl)
1180 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1181 return UInt128Decl;
1182}
1183
1184void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1185 auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K);
1187 Types.push_back(Ty);
1188}
1189
1191 const TargetInfo *AuxTarget) {
1192 assert((!this->Target || this->Target == &Target) &&
1193 "Incorrect target reinitialization");
1194 assert(VoidTy.isNull() && "Context reinitialized?");
1195
1196 this->Target = &Target;
1197 this->AuxTarget = AuxTarget;
1198
1199 ABI.reset(createCXXABI(Target));
1200 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1201
1202 // C99 6.2.5p19.
1203 InitBuiltinType(VoidTy, BuiltinType::Void);
1204
1205 // C99 6.2.5p2.
1206 InitBuiltinType(BoolTy, BuiltinType::Bool);
1207 // C99 6.2.5p3.
1208 if (LangOpts.CharIsSigned)
1209 InitBuiltinType(CharTy, BuiltinType::Char_S);
1210 else
1211 InitBuiltinType(CharTy, BuiltinType::Char_U);
1212 // C99 6.2.5p4.
1213 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1214 InitBuiltinType(ShortTy, BuiltinType::Short);
1215 InitBuiltinType(IntTy, BuiltinType::Int);
1216 InitBuiltinType(LongTy, BuiltinType::Long);
1217 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1218
1219 // C99 6.2.5p6.
1220 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1221 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1222 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1223 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1224 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1225
1226 // C99 6.2.5p10.
1227 InitBuiltinType(FloatTy, BuiltinType::Float);
1228 InitBuiltinType(DoubleTy, BuiltinType::Double);
1229 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1230
1231 // GNU extension, __float128 for IEEE quadruple precision
1232 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1233
1234 // __ibm128 for IBM extended precision
1235 InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128);
1236
1237 // C11 extension ISO/IEC TS 18661-3
1238 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1239
1240 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1241 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1242 InitBuiltinType(AccumTy, BuiltinType::Accum);
1243 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1244 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1245 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1246 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1247 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1248 InitBuiltinType(FractTy, BuiltinType::Fract);
1249 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1250 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1251 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1252 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1253 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1254 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1255 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1256 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1257 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1258 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1259 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1260 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1261 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1262 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1263 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1264 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
1265
1266 // GNU extension, 128-bit integers.
1267 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1268 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1269
1270 // C++ 3.9.1p5
1271 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1272 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1273 else // -fshort-wchar makes wchar_t be unsigned.
1274 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1275 if (LangOpts.CPlusPlus && LangOpts.WChar)
1277 else {
1278 // C99 (or C++ using -fno-wchar).
1279 WideCharTy = getFromTargetType(Target.getWCharType());
1280 }
1281
1282 WIntTy = getFromTargetType(Target.getWIntType());
1283
1284 // C++20 (proposed)
1285 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1286
1287 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1288 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1289 else // C99
1290 Char16Ty = getFromTargetType(Target.getChar16Type());
1291
1292 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1293 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1294 else // C99
1295 Char32Ty = getFromTargetType(Target.getChar32Type());
1296
1297 // Placeholder type for type-dependent expressions whose type is
1298 // completely unknown. No code should ever check a type against
1299 // DependentTy and users should never see it; however, it is here to
1300 // help diagnose failures to properly check for type-dependent
1301 // expressions.
1302 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1303
1304 // Placeholder type for functions.
1305 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1306
1307 // Placeholder type for bound members.
1308 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1309
1310 // Placeholder type for unresolved templates.
1311 InitBuiltinType(UnresolvedTemplateTy, BuiltinType::UnresolvedTemplate);
1312
1313 // Placeholder type for pseudo-objects.
1314 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1315
1316 // "any" type; useful for debugger-like clients.
1317 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1318
1319 // Placeholder type for unbridged ARC casts.
1320 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1321
1322 // Placeholder type for builtin functions.
1323 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1324
1325 // Placeholder type for OMP array sections.
1326 if (LangOpts.OpenMP) {
1327 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1328 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1329 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1330 }
1331 // Placeholder type for OpenACC array sections, if we are ALSO in OMP mode,
1332 // don't bother, as we're just using the same type as OMP.
1333 if (LangOpts.OpenACC && !LangOpts.OpenMP) {
1334 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1335 }
1336 if (LangOpts.MatrixTypes)
1337 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1338
1339 // Builtin types for 'id', 'Class', and 'SEL'.
1340 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1341 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1342 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1343
1344 if (LangOpts.OpenCL) {
1345#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1346 InitBuiltinType(SingletonId, BuiltinType::Id);
1347#include "clang/Basic/OpenCLImageTypes.def"
1348
1349 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1350 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1351 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1352 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1353 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1354
1355#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1356 InitBuiltinType(Id##Ty, BuiltinType::Id);
1357#include "clang/Basic/OpenCLExtensionTypes.def"
1358 }
1359
1360 if (Target.hasAArch64SVETypes()) {
1361#define SVE_TYPE(Name, Id, SingletonId) \
1362 InitBuiltinType(SingletonId, BuiltinType::Id);
1363#include "clang/Basic/AArch64SVEACLETypes.def"
1364 }
1365
1366 if (Target.getTriple().isPPC64()) {
1367#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1368 InitBuiltinType(Id##Ty, BuiltinType::Id);
1369#include "clang/Basic/PPCTypes.def"
1370#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1371 InitBuiltinType(Id##Ty, BuiltinType::Id);
1372#include "clang/Basic/PPCTypes.def"
1373 }
1374
1375 if (Target.hasRISCVVTypes()) {
1376#define RVV_TYPE(Name, Id, SingletonId) \
1377 InitBuiltinType(SingletonId, BuiltinType::Id);
1378#include "clang/Basic/RISCVVTypes.def"
1379 }
1380
1381 if (Target.getTriple().isWasm() && Target.hasFeature("reference-types")) {
1382#define WASM_TYPE(Name, Id, SingletonId) \
1383 InitBuiltinType(SingletonId, BuiltinType::Id);
1384#include "clang/Basic/WebAssemblyReferenceTypes.def"
1385 }
1386
1387 // Builtin type for __objc_yes and __objc_no
1388 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1390
1391 ObjCConstantStringType = QualType();
1392
1393 ObjCSuperType = QualType();
1394
1395 // void * type
1396 if (LangOpts.OpenCLGenericAddressSpace) {
1397 auto Q = VoidTy.getQualifiers();
1401 } else {
1403 }
1404
1405 // nullptr type (C++0x 2.14.7)
1406 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1407
1408 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1409 InitBuiltinType(HalfTy, BuiltinType::Half);
1410
1411 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1412
1413 // Builtin type used to help define __builtin_va_list.
1414 VaListTagDecl = nullptr;
1415
1416 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1417 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1420 }
1421}
1422
1424 return SourceMgr.getDiagnostics();
1425}
1426
1428 AttrVec *&Result = DeclAttrs[D];
1429 if (!Result) {
1430 void *Mem = Allocate(sizeof(AttrVec));
1431 Result = new (Mem) AttrVec;
1432 }
1433
1434 return *Result;
1435}
1436
1437/// Erase the attributes corresponding to the given declaration.
1439 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1440 if (Pos != DeclAttrs.end()) {
1441 Pos->second->~AttrVec();
1442 DeclAttrs.erase(Pos);
1443 }
1444}
1445
1446// FIXME: Remove ?
1449 assert(Var->isStaticDataMember() && "Not a static data member");
1451 .dyn_cast<MemberSpecializationInfo *>();
1452}
1453
1456 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1457 TemplateOrInstantiation.find(Var);
1458 if (Pos == TemplateOrInstantiation.end())
1459 return {};
1460
1461 return Pos->second;
1462}
1463
1464void
1467 SourceLocation PointOfInstantiation) {
1468 assert(Inst->isStaticDataMember() && "Not a static data member");
1469 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1471 Tmpl, TSK, PointOfInstantiation));
1472}
1473
1474void
1477 assert(!TemplateOrInstantiation[Inst] &&
1478 "Already noted what the variable was instantiated from");
1479 TemplateOrInstantiation[Inst] = TSI;
1480}
1481
1482NamedDecl *
1484 return InstantiatedFromUsingDecl.lookup(UUD);
1485}
1486
1487void
1489 assert((isa<UsingDecl>(Pattern) ||
1490 isa<UnresolvedUsingValueDecl>(Pattern) ||
1491 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1492 "pattern decl is not a using decl");
1493 assert((isa<UsingDecl>(Inst) ||
1494 isa<UnresolvedUsingValueDecl>(Inst) ||
1495 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1496 "instantiation did not produce a using decl");
1497 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1498 InstantiatedFromUsingDecl[Inst] = Pattern;
1499}
1500
1503 return InstantiatedFromUsingEnumDecl.lookup(UUD);
1504}
1505
1507 UsingEnumDecl *Pattern) {
1508 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1509 InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1510}
1511
1514 return InstantiatedFromUsingShadowDecl.lookup(Inst);
1515}
1516
1517void
1519 UsingShadowDecl *Pattern) {
1520 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1521 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1522}
1523
1525 return InstantiatedFromUnnamedFieldDecl.lookup(Field);
1526}
1527
1529 FieldDecl *Tmpl) {
1530 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1531 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1532 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1533 "Already noted what unnamed field was instantiated from");
1534
1535 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1536}
1537
1540 return overridden_methods(Method).begin();
1541}
1542
1545 return overridden_methods(Method).end();
1546}
1547
1548unsigned
1550 auto Range = overridden_methods(Method);
1551 return Range.end() - Range.begin();
1552}
1553
1556 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1557 OverriddenMethods.find(Method->getCanonicalDecl());
1558 if (Pos == OverriddenMethods.end())
1559 return overridden_method_range(nullptr, nullptr);
1560 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1561}
1562
1564 const CXXMethodDecl *Overridden) {
1565 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1566 OverriddenMethods[Method].push_back(Overridden);
1567}
1568
1570 const NamedDecl *D,
1571 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1572 assert(D);
1573
1574 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1575 Overridden.append(overridden_methods_begin(CXXMethod),
1576 overridden_methods_end(CXXMethod));
1577 return;
1578 }
1579
1580 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1581 if (!Method)
1582 return;
1583
1585 Method->getOverriddenMethods(OverDecls);
1586 Overridden.append(OverDecls.begin(), OverDecls.end());
1587}
1588
1590 assert(!Import->getNextLocalImport() &&
1591 "Import declaration already in the chain");
1592 assert(!Import->isFromASTFile() && "Non-local import declaration");
1593 if (!FirstLocalImport) {
1594 FirstLocalImport = Import;
1595 LastLocalImport = Import;
1596 return;
1597 }
1598
1599 LastLocalImport->setNextLocalImport(Import);
1600 LastLocalImport = Import;
1601}
1602
1603//===----------------------------------------------------------------------===//
1604// Type Sizing and Analysis
1605//===----------------------------------------------------------------------===//
1606
1607/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1608/// scalar floating point type.
1609const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1610 switch (T->castAs<BuiltinType>()->getKind()) {
1611 default:
1612 llvm_unreachable("Not a floating point type!");
1613 case BuiltinType::BFloat16:
1614 return Target->getBFloat16Format();
1615 case BuiltinType::Float16:
1616 return Target->getHalfFormat();
1617 case BuiltinType::Half:
1618 return Target->getHalfFormat();
1619 case BuiltinType::Float: return Target->getFloatFormat();
1620 case BuiltinType::Double: return Target->getDoubleFormat();
1621 case BuiltinType::Ibm128:
1622 return Target->getIbm128Format();
1623 case BuiltinType::LongDouble:
1624 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1625 return AuxTarget->getLongDoubleFormat();
1626 return Target->getLongDoubleFormat();
1627 case BuiltinType::Float128:
1628 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1629 return AuxTarget->getFloat128Format();
1630 return Target->getFloat128Format();
1631 }
1632}
1633
1634CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1635 unsigned Align = Target->getCharWidth();
1636
1637 const unsigned AlignFromAttr = D->getMaxAlignment();
1638 if (AlignFromAttr)
1639 Align = AlignFromAttr;
1640
1641 // __attribute__((aligned)) can increase or decrease alignment
1642 // *except* on a struct or struct member, where it only increases
1643 // alignment unless 'packed' is also specified.
1644 //
1645 // It is an error for alignas to decrease alignment, so we can
1646 // ignore that possibility; Sema should diagnose it.
1647 bool UseAlignAttrOnly;
1648 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D))
1649 UseAlignAttrOnly =
1650 FD->hasAttr<PackedAttr>() || FD->getParent()->hasAttr<PackedAttr>();
1651 else
1652 UseAlignAttrOnly = AlignFromAttr != 0;
1653 // If we're using the align attribute only, just ignore everything
1654 // else about the declaration and its type.
1655 if (UseAlignAttrOnly) {
1656 // do nothing
1657 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1658 QualType T = VD->getType();
1659 if (const auto *RT = T->getAs<ReferenceType>()) {
1660 if (ForAlignof)
1661 T = RT->getPointeeType();
1662 else
1663 T = getPointerType(RT->getPointeeType());
1664 }
1665 QualType BaseT = getBaseElementType(T);
1666 if (T->isFunctionType())
1667 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1668 else if (!BaseT->isIncompleteType()) {
1669 // Adjust alignments of declarations with array type by the
1670 // large-array alignment on the target.
1671 if (const ArrayType *arrayType = getAsArrayType(T)) {
1672 unsigned MinWidth = Target->getLargeArrayMinWidth();
1673 if (!ForAlignof && MinWidth) {
1674 if (isa<VariableArrayType>(arrayType))
1675 Align = std::max(Align, Target->getLargeArrayAlign());
1676 else if (isa<ConstantArrayType>(arrayType) &&
1677 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1678 Align = std::max(Align, Target->getLargeArrayAlign());
1679 }
1680 }
1681 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1682 if (BaseT.getQualifiers().hasUnaligned())
1683 Align = Target->getCharWidth();
1684 }
1685
1686 // Ensure miminum alignment for global variables.
1687 if (const auto *VD = dyn_cast<VarDecl>(D))
1688 if (VD->hasGlobalStorage() && !ForAlignof) {
1689 uint64_t TypeSize =
1690 !BaseT->isIncompleteType() ? getTypeSize(T.getTypePtr()) : 0;
1691 Align = std::max(Align, getMinGlobalAlignOfVar(TypeSize, VD));
1692 }
1693
1694 // Fields can be subject to extra alignment constraints, like if
1695 // the field is packed, the struct is packed, or the struct has a
1696 // a max-field-alignment constraint (#pragma pack). So calculate
1697 // the actual alignment of the field within the struct, and then
1698 // (as we're expected to) constrain that by the alignment of the type.
1699 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1700 const RecordDecl *Parent = Field->getParent();
1701 // We can only produce a sensible answer if the record is valid.
1702 if (!Parent->isInvalidDecl()) {
1703 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1704
1705 // Start with the record's overall alignment.
1706 unsigned FieldAlign = toBits(Layout.getAlignment());
1707
1708 // Use the GCD of that and the offset within the record.
1709 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1710 if (Offset > 0) {
1711 // Alignment is always a power of 2, so the GCD will be a power of 2,
1712 // which means we get to do this crazy thing instead of Euclid's.
1713 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1714 if (LowBitOfOffset < FieldAlign)
1715 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1716 }
1717
1718 Align = std::min(Align, FieldAlign);
1719 }
1720 }
1721 }
1722
1723 // Some targets have hard limitation on the maximum requestable alignment in
1724 // aligned attribute for static variables.
1725 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1726 const auto *VD = dyn_cast<VarDecl>(D);
1727 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1728 Align = std::min(Align, MaxAlignedAttr);
1729
1730 return toCharUnitsFromBits(Align);
1731}
1732
1734 return toCharUnitsFromBits(Target->getExnObjectAlignment());
1735}
1736
1737// getTypeInfoDataSizeInChars - Return the size of a type, in
1738// chars. If the type is a record, its data size is returned. This is
1739// the size of the memcpy that's performed when assigning this type
1740// using a trivial copy/move assignment operator.
1743
1744 // In C++, objects can sometimes be allocated into the tail padding
1745 // of a base-class subobject. We decide whether that's possible
1746 // during class layout, so here we can just trust the layout results.
1747 if (getLangOpts().CPlusPlus) {
1748 if (const auto *RT = T->getAs<RecordType>();
1749 RT && !RT->getDecl()->isInvalidDecl()) {
1750 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1751 Info.Width = layout.getDataSize();
1752 }
1753 }
1754
1755 return Info;
1756}
1757
1758/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1759/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1762 const ConstantArrayType *CAT) {
1763 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1764 uint64_t Size = CAT->getZExtSize();
1765 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1766 (uint64_t)(-1)/Size) &&
1767 "Overflow in array type char size evaluation");
1768 uint64_t Width = EltInfo.Width.getQuantity() * Size;
1769 unsigned Align = EltInfo.Align.getQuantity();
1770 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1772 Width = llvm::alignTo(Width, Align);
1775 EltInfo.AlignRequirement);
1776}
1777
1779 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1780 return getConstantArrayInfoInChars(*this, CAT);
1781 TypeInfo Info = getTypeInfo(T);
1784}
1785
1787 return getTypeInfoInChars(T.getTypePtr());
1788}
1789
1791 // HLSL doesn't promote all small integer types to int, it
1792 // just uses the rank-based promotion rules for all types.
1793 if (getLangOpts().HLSL)
1794 return false;
1795
1796 if (const auto *BT = T->getAs<BuiltinType>())
1797 switch (BT->getKind()) {
1798 case BuiltinType::Bool:
1799 case BuiltinType::Char_S:
1800 case BuiltinType::Char_U:
1801 case BuiltinType::SChar:
1802 case BuiltinType::UChar:
1803 case BuiltinType::Short:
1804 case BuiltinType::UShort:
1805 case BuiltinType::WChar_S:
1806 case BuiltinType::WChar_U:
1807 case BuiltinType::Char8:
1808 case BuiltinType::Char16:
1809 case BuiltinType::Char32:
1810 return true;
1811 default:
1812 return false;
1813 }
1814
1815 // Enumerated types are promotable to their compatible integer types
1816 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
1817 if (const auto *ET = T->getAs<EnumType>()) {
1818 if (T->isDependentType() || ET->getDecl()->getPromotionType().isNull() ||
1819 ET->getDecl()->isScoped())
1820 return false;
1821
1822 return true;
1823 }
1824
1825 return false;
1826}
1827
1830}
1831
1833 return isAlignmentRequired(T.getTypePtr());
1834}
1835
1837 bool NeedsPreferredAlignment) const {
1838 // An alignment on a typedef overrides anything else.
1839 if (const auto *TT = T->getAs<TypedefType>())
1840 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1841 return Align;
1842
1843 // If we have an (array of) complete type, we're done.
1845 if (!T->isIncompleteType())
1846 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
1847
1848 // If we had an array type, its element type might be a typedef
1849 // type with an alignment attribute.
1850 if (const auto *TT = T->getAs<TypedefType>())
1851 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1852 return Align;
1853
1854 // Otherwise, see if the declaration of the type had an attribute.
1855 if (const auto *TT = T->getAs<TagType>())
1856 return TT->getDecl()->getMaxAlignment();
1857
1858 return 0;
1859}
1860
1862 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1863 if (I != MemoizedTypeInfo.end())
1864 return I->second;
1865
1866 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1867 TypeInfo TI = getTypeInfoImpl(T);
1868 MemoizedTypeInfo[T] = TI;
1869 return TI;
1870}
1871
1872/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1873/// method does not work on incomplete types.
1874///
1875/// FIXME: Pointers into different addr spaces could have different sizes and
1876/// alignment requirements: getPointerInfo should take an AddrSpace, this
1877/// should take a QualType, &c.
1878TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1879 uint64_t Width = 0;
1880 unsigned Align = 8;
1883 switch (T->getTypeClass()) {
1884#define TYPE(Class, Base)
1885#define ABSTRACT_TYPE(Class, Base)
1886#define NON_CANONICAL_TYPE(Class, Base)
1887#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1888#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1889 case Type::Class: \
1890 assert(!T->isDependentType() && "should not see dependent types here"); \
1891 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1892#include "clang/AST/TypeNodes.inc"
1893 llvm_unreachable("Should not see dependent types");
1894
1895 case Type::FunctionNoProto:
1896 case Type::FunctionProto:
1897 // GCC extension: alignof(function) = 32 bits
1898 Width = 0;
1899 Align = 32;
1900 break;
1901
1902 case Type::IncompleteArray:
1903 case Type::VariableArray:
1904 case Type::ConstantArray:
1905 case Type::ArrayParameter: {
1906 // Model non-constant sized arrays as size zero, but track the alignment.
1907 uint64_t Size = 0;
1908 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1909 Size = CAT->getZExtSize();
1910
1911 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
1912 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
1913 "Overflow in array type bit size evaluation");
1914 Width = EltInfo.Width * Size;
1915 Align = EltInfo.Align;
1916 AlignRequirement = EltInfo.AlignRequirement;
1917 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1918 getTargetInfo().getPointerWidth(LangAS::Default) == 64)
1919 Width = llvm::alignTo(Width, Align);
1920 break;
1921 }
1922
1923 case Type::ExtVector:
1924 case Type::Vector: {
1925 const auto *VT = cast<VectorType>(T);
1926 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1927 Width = VT->isExtVectorBoolType() ? VT->getNumElements()
1928 : EltInfo.Width * VT->getNumElements();
1929 // Enforce at least byte size and alignment.
1930 Width = std::max<unsigned>(8, Width);
1931 Align = std::max<unsigned>(8, Width);
1932
1933 // If the alignment is not a power of 2, round up to the next power of 2.
1934 // This happens for non-power-of-2 length vectors.
1935 if (Align & (Align-1)) {
1936 Align = llvm::bit_ceil(Align);
1937 Width = llvm::alignTo(Width, Align);
1938 }
1939 // Adjust the alignment based on the target max.
1940 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1941 if (TargetVectorAlign && TargetVectorAlign < Align)
1942 Align = TargetVectorAlign;
1943 if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
1944 // Adjust the alignment for fixed-length SVE vectors. This is important
1945 // for non-power-of-2 vector lengths.
1946 Align = 128;
1947 else if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
1948 // Adjust the alignment for fixed-length SVE predicates.
1949 Align = 16;
1950 else if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
1951 VT->getVectorKind() == VectorKind::RVVFixedLengthMask)
1952 // Adjust the alignment for fixed-length RVV vectors.
1953 Align = std::min<unsigned>(64, Width);
1954 break;
1955 }
1956
1957 case Type::ConstantMatrix: {
1958 const auto *MT = cast<ConstantMatrixType>(T);
1959 TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
1960 // The internal layout of a matrix value is implementation defined.
1961 // Initially be ABI compatible with arrays with respect to alignment and
1962 // size.
1963 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
1964 Align = ElementInfo.Align;
1965 break;
1966 }
1967
1968 case Type::Builtin:
1969 switch (cast<BuiltinType>(T)->getKind()) {
1970 default: llvm_unreachable("Unknown builtin type!");
1971 case BuiltinType::Void:
1972 // GCC extension: alignof(void) = 8 bits.
1973 Width = 0;
1974 Align = 8;
1975 break;
1976 case BuiltinType::Bool:
1977 Width = Target->getBoolWidth();
1978 Align = Target->getBoolAlign();
1979 break;
1980 case BuiltinType::Char_S:
1981 case BuiltinType::Char_U:
1982 case BuiltinType::UChar:
1983 case BuiltinType::SChar:
1984 case BuiltinType::Char8:
1985 Width = Target->getCharWidth();
1986 Align = Target->getCharAlign();
1987 break;
1988 case BuiltinType::WChar_S:
1989 case BuiltinType::WChar_U:
1990 Width = Target->getWCharWidth();
1991 Align = Target->getWCharAlign();
1992 break;
1993 case BuiltinType::Char16:
1994 Width = Target->getChar16Width();
1995 Align = Target->getChar16Align();
1996 break;
1997 case BuiltinType::Char32:
1998 Width = Target->getChar32Width();
1999 Align = Target->getChar32Align();
2000 break;
2001 case BuiltinType::UShort:
2002 case BuiltinType::Short:
2003 Width = Target->getShortWidth();
2004 Align = Target->getShortAlign();
2005 break;
2006 case BuiltinType::UInt:
2007 case BuiltinType::Int:
2008 Width = Target->getIntWidth();
2009 Align = Target->getIntAlign();
2010 break;
2011 case BuiltinType::ULong:
2012 case BuiltinType::Long:
2013 Width = Target->getLongWidth();
2014 Align = Target->getLongAlign();
2015 break;
2016 case BuiltinType::ULongLong:
2017 case BuiltinType::LongLong:
2018 Width = Target->getLongLongWidth();
2019 Align = Target->getLongLongAlign();
2020 break;
2021 case BuiltinType::Int128:
2022 case BuiltinType::UInt128:
2023 Width = 128;
2024 Align = Target->getInt128Align();
2025 break;
2026 case BuiltinType::ShortAccum:
2027 case BuiltinType::UShortAccum:
2028 case BuiltinType::SatShortAccum:
2029 case BuiltinType::SatUShortAccum:
2030 Width = Target->getShortAccumWidth();
2031 Align = Target->getShortAccumAlign();
2032 break;
2033 case BuiltinType::Accum:
2034 case BuiltinType::UAccum:
2035 case BuiltinType::SatAccum:
2036 case BuiltinType::SatUAccum:
2037 Width = Target->getAccumWidth();
2038 Align = Target->getAccumAlign();
2039 break;
2040 case BuiltinType::LongAccum:
2041 case BuiltinType::ULongAccum:
2042 case BuiltinType::SatLongAccum:
2043 case BuiltinType::SatULongAccum:
2044 Width = Target->getLongAccumWidth();
2045 Align = Target->getLongAccumAlign();
2046 break;
2047 case BuiltinType::ShortFract:
2048 case BuiltinType::UShortFract:
2049 case BuiltinType::SatShortFract:
2050 case BuiltinType::SatUShortFract:
2051 Width = Target->getShortFractWidth();
2052 Align = Target->getShortFractAlign();
2053 break;
2054 case BuiltinType::Fract:
2055 case BuiltinType::UFract:
2056 case BuiltinType::SatFract:
2057 case BuiltinType::SatUFract:
2058 Width = Target->getFractWidth();
2059 Align = Target->getFractAlign();
2060 break;
2061 case BuiltinType::LongFract:
2062 case BuiltinType::ULongFract:
2063 case BuiltinType::SatLongFract:
2064 case BuiltinType::SatULongFract:
2065 Width = Target->getLongFractWidth();
2066 Align = Target->getLongFractAlign();
2067 break;
2068 case BuiltinType::BFloat16:
2069 if (Target->hasBFloat16Type()) {
2070 Width = Target->getBFloat16Width();
2071 Align = Target->getBFloat16Align();
2072 } else if ((getLangOpts().SYCLIsDevice ||
2073 (getLangOpts().OpenMP &&
2074 getLangOpts().OpenMPIsTargetDevice)) &&
2075 AuxTarget->hasBFloat16Type()) {
2076 Width = AuxTarget->getBFloat16Width();
2077 Align = AuxTarget->getBFloat16Align();
2078 }
2079 break;
2080 case BuiltinType::Float16:
2081 case BuiltinType::Half:
2082 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2083 !getLangOpts().OpenMPIsTargetDevice) {
2084 Width = Target->getHalfWidth();
2085 Align = Target->getHalfAlign();
2086 } else {
2087 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2088 "Expected OpenMP device compilation.");
2089 Width = AuxTarget->getHalfWidth();
2090 Align = AuxTarget->getHalfAlign();
2091 }
2092 break;
2093 case BuiltinType::Float:
2094 Width = Target->getFloatWidth();
2095 Align = Target->getFloatAlign();
2096 break;
2097 case BuiltinType::Double:
2098 Width = Target->getDoubleWidth();
2099 Align = Target->getDoubleAlign();
2100 break;
2101 case BuiltinType::Ibm128:
2102 Width = Target->getIbm128Width();
2103 Align = Target->getIbm128Align();
2104 break;
2105 case BuiltinType::LongDouble:
2106 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2107 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2108 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2109 Width = AuxTarget->getLongDoubleWidth();
2110 Align = AuxTarget->getLongDoubleAlign();
2111 } else {
2112 Width = Target->getLongDoubleWidth();
2113 Align = Target->getLongDoubleAlign();
2114 }
2115 break;
2116 case BuiltinType::Float128:
2117 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2118 !getLangOpts().OpenMPIsTargetDevice) {
2119 Width = Target->getFloat128Width();
2120 Align = Target->getFloat128Align();
2121 } else {
2122 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2123 "Expected OpenMP device compilation.");
2124 Width = AuxTarget->getFloat128Width();
2125 Align = AuxTarget->getFloat128Align();
2126 }
2127 break;
2128 case BuiltinType::NullPtr:
2129 // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
2130 Width = Target->getPointerWidth(LangAS::Default);
2131 Align = Target->getPointerAlign(LangAS::Default);
2132 break;
2133 case BuiltinType::ObjCId:
2134 case BuiltinType::ObjCClass:
2135 case BuiltinType::ObjCSel:
2136 Width = Target->getPointerWidth(LangAS::Default);
2137 Align = Target->getPointerAlign(LangAS::Default);
2138 break;
2139 case BuiltinType::OCLSampler:
2140 case BuiltinType::OCLEvent:
2141 case BuiltinType::OCLClkEvent:
2142 case BuiltinType::OCLQueue:
2143 case BuiltinType::OCLReserveID:
2144#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2145 case BuiltinType::Id:
2146#include "clang/Basic/OpenCLImageTypes.def"
2147#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2148 case BuiltinType::Id:
2149#include "clang/Basic/OpenCLExtensionTypes.def"
2150 AS = Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
2151 Width = Target->getPointerWidth(AS);
2152 Align = Target->getPointerAlign(AS);
2153 break;
2154 // The SVE types are effectively target-specific. The length of an
2155 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2156 // of 128 bits. There is one predicate bit for each vector byte, so the
2157 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2158 //
2159 // Because the length is only known at runtime, we use a dummy value
2160 // of 0 for the static length. The alignment values are those defined
2161 // by the Procedure Call Standard for the Arm Architecture.
2162#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \
2163 IsSigned, IsFP, IsBF) \
2164 case BuiltinType::Id: \
2165 Width = 0; \
2166 Align = 128; \
2167 break;
2168#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \
2169 case BuiltinType::Id: \
2170 Width = 0; \
2171 Align = 16; \
2172 break;
2173#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
2174 case BuiltinType::Id: \
2175 Width = 0; \
2176 Align = 16; \
2177 break;
2178#include "clang/Basic/AArch64SVEACLETypes.def"
2179#define PPC_VECTOR_TYPE(Name, Id, Size) \
2180 case BuiltinType::Id: \
2181 Width = Size; \
2182 Align = Size; \
2183 break;
2184#include "clang/Basic/PPCTypes.def"
2185#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
2186 IsFP, IsBF) \
2187 case BuiltinType::Id: \
2188 Width = 0; \
2189 Align = ElBits; \
2190 break;
2191#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2192 case BuiltinType::Id: \
2193 Width = 0; \
2194 Align = 8; \
2195 break;
2196#include "clang/Basic/RISCVVTypes.def"
2197#define WASM_TYPE(Name, Id, SingletonId) \
2198 case BuiltinType::Id: \
2199 Width = 0; \
2200 Align = 8; \
2201 break;
2202#include "clang/Basic/WebAssemblyReferenceTypes.def"
2203 }
2204 break;
2205 case Type::ObjCObjectPointer:
2206 Width = Target->getPointerWidth(LangAS::Default);
2207 Align = Target->getPointerAlign(LangAS::Default);
2208 break;
2209 case Type::BlockPointer:
2210 AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
2211 Width = Target->getPointerWidth(AS);
2212 Align = Target->getPointerAlign(AS);
2213 break;
2214 case Type::LValueReference:
2215 case Type::RValueReference:
2216 // alignof and sizeof should never enter this code path here, so we go
2217 // the pointer route.
2218 AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
2219 Width = Target->getPointerWidth(AS);
2220 Align = Target->getPointerAlign(AS);
2221 break;
2222 case Type::Pointer:
2223 AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
2224 Width = Target->getPointerWidth(AS);
2225 Align = Target->getPointerAlign(AS);
2226 break;
2227 case Type::MemberPointer: {
2228 const auto *MPT = cast<MemberPointerType>(T);
2229 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2230 Width = MPI.Width;
2231 Align = MPI.Align;
2232 break;
2233 }
2234 case Type::Complex: {
2235 // Complex types have the same alignment as their elements, but twice the
2236 // size.
2237 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2238 Width = EltInfo.Width * 2;
2239 Align = EltInfo.Align;
2240 break;
2241 }
2242 case Type::ObjCObject:
2243 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2244 case Type::Adjusted:
2245 case Type::Decayed:
2246 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2247 case Type::ObjCInterface: {
2248 const auto *ObjCI = cast<ObjCInterfaceType>(T);
2249 if (ObjCI->getDecl()->isInvalidDecl()) {
2250 Width = 8;
2251 Align = 8;
2252 break;
2253 }
2254 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2255 Width = toBits(Layout.getSize());
2256 Align = toBits(Layout.getAlignment());
2257 break;
2258 }
2259 case Type::BitInt: {
2260 const auto *EIT = cast<BitIntType>(T);
2261 Align = Target->getBitIntAlign(EIT->getNumBits());
2262 Width = Target->getBitIntWidth(EIT->getNumBits());
2263 break;
2264 }
2265 case Type::Record:
2266 case Type::Enum: {
2267 const auto *TT = cast<TagType>(T);
2268
2269 if (TT->getDecl()->isInvalidDecl()) {
2270 Width = 8;
2271 Align = 8;
2272 break;
2273 }
2274
2275 if (const auto *ET = dyn_cast<EnumType>(TT)) {
2276 const EnumDecl *ED = ET->getDecl();
2277 TypeInfo Info =
2279 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2280 Info.Align = AttrAlign;
2282 }
2283 return Info;
2284 }
2285
2286 const auto *RT = cast<RecordType>(TT);
2287 const RecordDecl *RD = RT->getDecl();
2288 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2289 Width = toBits(Layout.getSize());
2290 Align = toBits(Layout.getAlignment());
2291 AlignRequirement = RD->hasAttr<AlignedAttr>()
2294 break;
2295 }
2296
2297 case Type::SubstTemplateTypeParm:
2298 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2299 getReplacementType().getTypePtr());
2300
2301 case Type::Auto:
2302 case Type::DeducedTemplateSpecialization: {
2303 const auto *A = cast<DeducedType>(T);
2304 assert(!A->getDeducedType().isNull() &&
2305 "cannot request the size of an undeduced or dependent auto type");
2306 return getTypeInfo(A->getDeducedType().getTypePtr());
2307 }
2308
2309 case Type::Paren:
2310 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2311
2312 case Type::MacroQualified:
2313 return getTypeInfo(
2314 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2315
2316 case Type::ObjCTypeParam:
2317 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2318
2319 case Type::Using:
2320 return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr());
2321
2322 case Type::Typedef: {
2323 const auto *TT = cast<TypedefType>(T);
2324 TypeInfo Info = getTypeInfo(TT->desugar().getTypePtr());
2325 // If the typedef has an aligned attribute on it, it overrides any computed
2326 // alignment we have. This violates the GCC documentation (which says that
2327 // attribute(aligned) can only round up) but matches its implementation.
2328 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2329 Align = AttrAlign;
2330 AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2331 } else {
2332 Align = Info.Align;
2333 AlignRequirement = Info.AlignRequirement;
2334 }
2335 Width = Info.Width;
2336 break;
2337 }
2338
2339 case Type::Elaborated:
2340 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
2341
2342 case Type::Attributed:
2343 return getTypeInfo(
2344 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2345
2346 case Type::CountAttributed:
2347 return getTypeInfo(cast<CountAttributedType>(T)->desugar().getTypePtr());
2348
2349 case Type::BTFTagAttributed:
2350 return getTypeInfo(
2351 cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr());
2352
2353 case Type::Atomic: {
2354 // Start with the base type information.
2355 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2356 Width = Info.Width;
2357 Align = Info.Align;
2358
2359 if (!Width) {
2360 // An otherwise zero-sized type should still generate an
2361 // atomic operation.
2362 Width = Target->getCharWidth();
2363 assert(Align);
2364 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2365 // If the size of the type doesn't exceed the platform's max
2366 // atomic promotion width, make the size and alignment more
2367 // favorable to atomic operations:
2368
2369 // Round the size up to a power of 2.
2370 Width = llvm::bit_ceil(Width);
2371
2372 // Set the alignment equal to the size.
2373 Align = static_cast<unsigned>(Width);
2374 }
2375 }
2376 break;
2377
2378 case Type::Pipe:
2379 Width = Target->getPointerWidth(LangAS::opencl_global);
2380 Align = Target->getPointerAlign(LangAS::opencl_global);
2381 break;
2382 }
2383
2384 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2385 return TypeInfo(Width, Align, AlignRequirement);
2386}
2387
2389 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2390 if (I != MemoizedUnadjustedAlign.end())
2391 return I->second;
2392
2393 unsigned UnadjustedAlign;
2394 if (const auto *RT = T->getAs<RecordType>()) {
2395 const RecordDecl *RD = RT->getDecl();
2396 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2397 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2398 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2399 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2400 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2401 } else {
2402 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2403 }
2404
2405 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2406 return UnadjustedAlign;
2407}
2408
2410 unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign(
2411 getTargetInfo().getTriple(), Target->getTargetOpts().FeatureMap);
2412 return SimdAlign;
2413}
2414
2415/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2417 return CharUnits::fromQuantity(BitSize / getCharWidth());
2418}
2419
2420/// toBits - Convert a size in characters to a size in characters.
2421int64_t ASTContext::toBits(CharUnits CharSize) const {
2422 return CharSize.getQuantity() * getCharWidth();
2423}
2424
2425/// getTypeSizeInChars - Return the size of the specified type, in characters.
2426/// This method does not work on incomplete types.
2428 return getTypeInfoInChars(T).Width;
2429}
2431 return getTypeInfoInChars(T).Width;
2432}
2433
2434/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2435/// characters. This method does not work on incomplete types.
2438}
2441}
2442
2443/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2444/// type, in characters, before alignment adjustments. This method does
2445/// not work on incomplete types.
2448}
2451}
2452
2453/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2454/// type for the current target in bits. This can be different than the ABI
2455/// alignment in cases where it is beneficial for performance or backwards
2456/// compatibility preserving to overalign a data type. (Note: despite the name,
2457/// the preferred alignment is ABI-impacting, and not an optimization.)
2459 TypeInfo TI = getTypeInfo(T);
2460 unsigned ABIAlign = TI.Align;
2461
2463
2464 // The preferred alignment of member pointers is that of a pointer.
2465 if (T->isMemberPointerType())
2466 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2467
2468 if (!Target->allowsLargerPreferedTypeAlignment())
2469 return ABIAlign;
2470
2471 if (const auto *RT = T->getAs<RecordType>()) {
2472 const RecordDecl *RD = RT->getDecl();
2473
2474 // When used as part of a typedef, or together with a 'packed' attribute,
2475 // the 'aligned' attribute can be used to decrease alignment. Note that the
2476 // 'packed' case is already taken into consideration when computing the
2477 // alignment, we only need to handle the typedef case here.
2479 RD->isInvalidDecl())
2480 return ABIAlign;
2481
2482 unsigned PreferredAlign = static_cast<unsigned>(
2483 toBits(getASTRecordLayout(RD).PreferredAlignment));
2484 assert(PreferredAlign >= ABIAlign &&
2485 "PreferredAlign should be at least as large as ABIAlign.");
2486 return PreferredAlign;
2487 }
2488
2489 // Double (and, for targets supporting AIX `power` alignment, long double) and
2490 // long long should be naturally aligned (despite requiring less alignment) if
2491 // possible.
2492 if (const auto *CT = T->getAs<ComplexType>())
2493 T = CT->getElementType().getTypePtr();
2494 if (const auto *ET = T->getAs<EnumType>())
2495 T = ET->getDecl()->getIntegerType().getTypePtr();
2496 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2497 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2498 T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2499 (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2500 Target->defaultsToAIXPowerAlignment()))
2501 // Don't increase the alignment if an alignment attribute was specified on a
2502 // typedef declaration.
2503 if (!TI.isAlignRequired())
2504 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2505
2506 return ABIAlign;
2507}
2508
2509/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2510/// for __attribute__((aligned)) on this target, to be used if no alignment
2511/// value is specified.
2514}
2515
2516/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2517/// to a global variable of the specified type.
2519 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2520 return std::max(getPreferredTypeAlign(T),
2521 getMinGlobalAlignOfVar(TypeSize, VD));
2522}
2523
2524/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2525/// should be given to a global variable of the specified type.
2527 const VarDecl *VD) const {
2529}
2530
2532 const VarDecl *VD) const {
2533 // Make the default handling as that of a non-weak definition in the
2534 // current translation unit.
2535 bool HasNonWeakDef = !VD || (VD->hasDefinition() && !VD->isWeak());
2536 return getTargetInfo().getMinGlobalAlign(Size, HasNonWeakDef);
2537}
2538
2540 CharUnits Offset = CharUnits::Zero();
2541 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2542 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2543 Offset += Layout->getBaseClassOffset(Base);
2544 Layout = &getASTRecordLayout(Base);
2545 }
2546 return Offset;
2547}
2548
2550 const ValueDecl *MPD = MP.getMemberPointerDecl();
2553 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2554 const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext());
2555 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2556 const CXXRecordDecl *Base = RD;
2557 const CXXRecordDecl *Derived = Path[I];
2558 if (DerivedMember)
2559 std::swap(Base, Derived);
2561 RD = Path[I];
2562 }
2563 if (DerivedMember)
2565 return ThisAdjustment;
2566}
2567
2568/// DeepCollectObjCIvars -
2569/// This routine first collects all declared, but not synthesized, ivars in
2570/// super class and then collects all ivars, including those synthesized for
2571/// current class. This routine is used for implementation of current class
2572/// when all ivars, declared and synthesized are known.
2574 bool leafClass,
2576 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2577 DeepCollectObjCIvars(SuperClass, false, Ivars);
2578 if (!leafClass) {
2579 llvm::append_range(Ivars, OI->ivars());
2580 } else {
2581 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2582 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2583 Iv= Iv->getNextIvar())
2584 Ivars.push_back(Iv);
2585 }
2586}
2587
2588/// CollectInheritedProtocols - Collect all protocols in current class and
2589/// those inherited by it.
2592 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2593 // We can use protocol_iterator here instead of
2594 // all_referenced_protocol_iterator since we are walking all categories.
2595 for (auto *Proto : OI->all_referenced_protocols()) {
2596 CollectInheritedProtocols(Proto, Protocols);
2597 }
2598
2599 // Categories of this Interface.
2600 for (const auto *Cat : OI->visible_categories())
2601 CollectInheritedProtocols(Cat, Protocols);
2602
2603 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2604 while (SD) {
2605 CollectInheritedProtocols(SD, Protocols);
2606 SD = SD->getSuperClass();
2607 }
2608 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2609 for (auto *Proto : OC->protocols()) {
2610 CollectInheritedProtocols(Proto, Protocols);
2611 }
2612 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2613 // Insert the protocol.
2614 if (!Protocols.insert(
2615 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2616 return;
2617
2618 for (auto *Proto : OP->protocols())
2619 CollectInheritedProtocols(Proto, Protocols);
2620 }
2621}
2622
2624 const RecordDecl *RD,
2625 bool CheckIfTriviallyCopyable) {
2626 assert(RD->isUnion() && "Must be union type");
2627 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2628
2629 for (const auto *Field : RD->fields()) {
2630 if (!Context.hasUniqueObjectRepresentations(Field->getType(),
2631 CheckIfTriviallyCopyable))
2632 return false;
2633 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2634 if (FieldSize != UnionSize)
2635 return false;
2636 }
2637 return !RD->field_empty();
2638}
2639
2640static int64_t getSubobjectOffset(const FieldDecl *Field,
2641 const ASTContext &Context,
2642 const clang::ASTRecordLayout & /*Layout*/) {
2643 return Context.getFieldOffset(Field);
2644}
2645
2646static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2647 const ASTContext &Context,
2648 const clang::ASTRecordLayout &Layout) {
2649 return Context.toBits(Layout.getBaseClassOffset(RD));
2650}
2651
2652static std::optional<int64_t>
2654 const RecordDecl *RD,
2655 bool CheckIfTriviallyCopyable);
2656
2657static std::optional<int64_t>
2658getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context,
2659 bool CheckIfTriviallyCopyable) {
2660 if (Field->getType()->isRecordType()) {
2661 const RecordDecl *RD = Field->getType()->getAsRecordDecl();
2662 if (!RD->isUnion())
2663 return structHasUniqueObjectRepresentations(Context, RD,
2664 CheckIfTriviallyCopyable);
2665 }
2666
2667 // A _BitInt type may not be unique if it has padding bits
2668 // but if it is a bitfield the padding bits are not used.
2669 bool IsBitIntType = Field->getType()->isBitIntType();
2670 if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2671 !Context.hasUniqueObjectRepresentations(Field->getType(),
2672 CheckIfTriviallyCopyable))
2673 return std::nullopt;
2674
2675 int64_t FieldSizeInBits =
2676 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2677 if (Field->isBitField()) {
2678 // If we have explicit padding bits, they don't contribute bits
2679 // to the actual object representation, so return 0.
2680 if (Field->isUnnamedBitField())
2681 return 0;
2682
2683 int64_t BitfieldSize = Field->getBitWidthValue(Context);
2684 if (IsBitIntType) {
2685 if ((unsigned)BitfieldSize >
2686 cast<BitIntType>(Field->getType())->getNumBits())
2687 return std::nullopt;
2688 } else if (BitfieldSize > FieldSizeInBits) {
2689 return std::nullopt;
2690 }
2691 FieldSizeInBits = BitfieldSize;
2692 } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations(
2693 Field->getType(), CheckIfTriviallyCopyable)) {
2694 return std::nullopt;
2695 }
2696 return FieldSizeInBits;
2697}
2698
2699static std::optional<int64_t>
2701 bool CheckIfTriviallyCopyable) {
2702 return structHasUniqueObjectRepresentations(Context, RD,
2703 CheckIfTriviallyCopyable);
2704}
2705
2706template <typename RangeT>
2708 const RangeT &Subobjects, int64_t CurOffsetInBits,
2709 const ASTContext &Context, const clang::ASTRecordLayout &Layout,
2710 bool CheckIfTriviallyCopyable) {
2711 for (const auto *Subobject : Subobjects) {
2712 std::optional<int64_t> SizeInBits =
2713 getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable);
2714 if (!SizeInBits)
2715 return std::nullopt;
2716 if (*SizeInBits != 0) {
2717 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2718 if (Offset != CurOffsetInBits)
2719 return std::nullopt;
2720 CurOffsetInBits += *SizeInBits;
2721 }
2722 }
2723 return CurOffsetInBits;
2724}
2725
2726static std::optional<int64_t>
2728 const RecordDecl *RD,
2729 bool CheckIfTriviallyCopyable) {
2730 assert(!RD->isUnion() && "Must be struct/class type");
2731 const auto &Layout = Context.getASTRecordLayout(RD);
2732
2733 int64_t CurOffsetInBits = 0;
2734 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2735 if (ClassDecl->isDynamicClass())
2736 return std::nullopt;
2737
2739 for (const auto &Base : ClassDecl->bases()) {
2740 // Empty types can be inherited from, and non-empty types can potentially
2741 // have tail padding, so just make sure there isn't an error.
2742 Bases.emplace_back(Base.getType()->getAsCXXRecordDecl());
2743 }
2744
2745 llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
2746 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
2747 });
2748
2749 std::optional<int64_t> OffsetAfterBases =
2751 Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable);
2752 if (!OffsetAfterBases)
2753 return std::nullopt;
2754 CurOffsetInBits = *OffsetAfterBases;
2755 }
2756
2757 std::optional<int64_t> OffsetAfterFields =
2759 RD->fields(), CurOffsetInBits, Context, Layout,
2760 CheckIfTriviallyCopyable);
2761 if (!OffsetAfterFields)
2762 return std::nullopt;
2763 CurOffsetInBits = *OffsetAfterFields;
2764
2765 return CurOffsetInBits;
2766}
2767
2769 QualType Ty, bool CheckIfTriviallyCopyable) const {
2770 // C++17 [meta.unary.prop]:
2771 // The predicate condition for a template specialization
2772 // has_unique_object_representations<T> shall be satisfied if and only if:
2773 // (9.1) - T is trivially copyable, and
2774 // (9.2) - any two objects of type T with the same value have the same
2775 // object representation, where:
2776 // - two objects of array or non-union class type are considered to have
2777 // the same value if their respective sequences of direct subobjects
2778 // have the same values, and
2779 // - two objects of union type are considered to have the same value if
2780 // they have the same active member and the corresponding members have
2781 // the same value.
2782 // The set of scalar types for which this condition holds is
2783 // implementation-defined. [ Note: If a type has padding bits, the condition
2784 // does not hold; otherwise, the condition holds true for unsigned integral
2785 // types. -- end note ]
2786 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2787
2788 // Arrays are unique only if their element type is unique.
2789 if (Ty->isArrayType())
2791 CheckIfTriviallyCopyable);
2792
2793 // (9.1) - T is trivially copyable...
2794 if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(*this))
2795 return false;
2796
2797 // All integrals and enums are unique.
2798 if (Ty->isIntegralOrEnumerationType()) {
2799 // Except _BitInt types that have padding bits.
2800 if (const auto *BIT = Ty->getAs<BitIntType>())
2801 return getTypeSize(BIT) == BIT->getNumBits();
2802
2803 return true;
2804 }
2805
2806 // All other pointers are unique.
2807 if (Ty->isPointerType())
2808 return true;
2809
2810 if (const auto *MPT = Ty->getAs<MemberPointerType>())
2811 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2812
2813 if (Ty->isRecordType()) {
2814 const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl();
2815
2816 if (Record->isInvalidDecl())
2817 return false;
2818
2819 if (Record->isUnion())
2821 CheckIfTriviallyCopyable);
2822
2823 std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(
2824 *this, Record, CheckIfTriviallyCopyable);
2825
2826 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(Ty));
2827 }
2828
2829 // FIXME: More cases to handle here (list by rsmith):
2830 // vectors (careful about, eg, vector of 3 foo)
2831 // _Complex int and friends
2832 // _Atomic T
2833 // Obj-C block pointers
2834 // Obj-C object pointers
2835 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2836 // clk_event_t, queue_t, reserve_id_t)
2837 // There're also Obj-C class types and the Obj-C selector type, but I think it
2838 // makes sense for those to return false here.
2839
2840 return false;
2841}
2842
2844 unsigned count = 0;
2845 // Count ivars declared in class extension.
2846 for (const auto *Ext : OI->known_extensions())
2847 count += Ext->ivar_size();
2848
2849 // Count ivar defined in this class's implementation. This
2850 // includes synthesized ivars.
2851 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2852 count += ImplDecl->ivar_size();
2853
2854 return count;
2855}
2856
2858 if (!E)
2859 return false;
2860
2861 // nullptr_t is always treated as null.
2862 if (E->getType()->isNullPtrType()) return true;
2863
2864 if (E->getType()->isAnyPointerType() &&
2867 return true;
2868
2869 // Unfortunately, __null has type 'int'.
2870 if (isa<GNUNullExpr>(E)) return true;
2871
2872 return false;
2873}
2874
2875/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
2876/// exists.
2878 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2879 I = ObjCImpls.find(D);
2880 if (I != ObjCImpls.end())
2881 return cast<ObjCImplementationDecl>(I->second);
2882 return nullptr;
2883}
2884
2885/// Get the implementation of ObjCCategoryDecl, or nullptr if none
2886/// exists.
2888 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2889 I = ObjCImpls.find(D);
2890 if (I != ObjCImpls.end())
2891 return cast<ObjCCategoryImplDecl>(I->second);
2892 return nullptr;
2893}
2894
2895/// Set the implementation of ObjCInterfaceDecl.
2897 ObjCImplementationDecl *ImplD) {
2898 assert(IFaceD && ImplD && "Passed null params");
2899 ObjCImpls[IFaceD] = ImplD;
2900}
2901
2902/// Set the implementation of ObjCCategoryDecl.
2904 ObjCCategoryImplDecl *ImplD) {
2905 assert(CatD && ImplD && "Passed null params");
2906 ObjCImpls[CatD] = ImplD;
2907}
2908
2909const ObjCMethodDecl *
2911 return ObjCMethodRedecls.lookup(MD);
2912}
2913
2915 const ObjCMethodDecl *Redecl) {
2916 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2917 ObjCMethodRedecls[MD] = Redecl;
2918}
2919
2921 const NamedDecl *ND) const {
2922 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
2923 return ID;
2924 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
2925 return CD->getClassInterface();
2926 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
2927 return IMD->getClassInterface();
2928
2929 return nullptr;
2930}
2931
2932/// Get the copy initialization expression of VarDecl, or nullptr if
2933/// none exists.
2935 assert(VD && "Passed null params");
2936 assert(VD->hasAttr<BlocksAttr>() &&
2937 "getBlockVarCopyInits - not __block var");
2938 auto I = BlockVarCopyInits.find(VD);
2939 if (I != BlockVarCopyInits.end())
2940 return I->second;
2941 return {nullptr, false};
2942}
2943
2944/// Set the copy initialization expression of a block var decl.
2946 bool CanThrow) {
2947 assert(VD && CopyExpr && "Passed null params");
2948 assert(VD->hasAttr<BlocksAttr>() &&
2949 "setBlockVarCopyInits - not __block var");
2950 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
2951}
2952
2954 unsigned DataSize) const {
2955 if (!DataSize)
2957 else
2958 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
2959 "incorrect data size provided to CreateTypeSourceInfo!");
2960
2961 auto *TInfo =
2962 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2963 new (TInfo) TypeSourceInfo(T, DataSize);
2964 return TInfo;
2965}
2966
2968 SourceLocation L) const {
2970 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
2971 return DI;
2972}
2973
2974const ASTRecordLayout &
2976 return getObjCLayout(D, nullptr);
2977}
2978
2979const ASTRecordLayout &
2981 const ObjCImplementationDecl *D) const {
2982 return getObjCLayout(D->getClassInterface(), D);
2983}
2984
2987 bool &AnyNonCanonArgs) {
2988 SmallVector<TemplateArgument, 16> CanonArgs(Args);
2989 for (auto &Arg : CanonArgs) {
2990 TemplateArgument OrigArg = Arg;
2991 Arg = C.getCanonicalTemplateArgument(Arg);
2992 AnyNonCanonArgs |= !Arg.structurallyEquals(OrigArg);
2993 }
2994 return CanonArgs;
2995}
2996
2997//===----------------------------------------------------------------------===//
2998// Type creation/memoization methods
2999//===----------------------------------------------------------------------===//
3000
3002ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3003 unsigned fastQuals = quals.getFastQualifiers();
3004 quals.removeFastQualifiers();
3005
3006 // Check if we've already instantiated this type.
3007 llvm::FoldingSetNodeID ID;
3008 ExtQuals::Profile(ID, baseType, quals);
3009 void *insertPos = nullptr;
3010 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
3011 assert(eq->getQualifiers() == quals);
3012 return QualType(eq, fastQuals);
3013 }
3014
3015 // If the base type is not canonical, make the appropriate canonical type.
3016 QualType canon;
3017 if (!baseType->isCanonicalUnqualified()) {
3018 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3019 canonSplit.Quals.addConsistentQualifiers(quals);
3020 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
3021
3022 // Re-find the insert position.
3023 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
3024 }
3025
3026 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3027 ExtQualNodes.InsertNode(eq, insertPos);
3028 return QualType(eq, fastQuals);
3029}
3030
3032 LangAS AddressSpace) const {
3033 QualType CanT = getCanonicalType(T);
3034 if (CanT.getAddressSpace() == AddressSpace)
3035 return T;
3036
3037 // If we are composing extended qualifiers together, merge together
3038 // into one ExtQuals node.
3039 QualifierCollector Quals;
3040 const Type *TypeNode = Quals.strip(T);
3041
3042 // If this type already has an address space specified, it cannot get
3043 // another one.
3044 assert(!Quals.hasAddressSpace() &&
3045 "Type cannot be in multiple addr spaces!");
3046 Quals.addAddressSpace(AddressSpace);
3047
3048 return getExtQualType(TypeNode, Quals);
3049}
3050
3052 // If the type is not qualified with an address space, just return it
3053 // immediately.
3054 if (!T.hasAddressSpace())
3055 return T;
3056
3057 // If we are composing extended qualifiers together, merge together
3058 // into one ExtQuals node.
3059 QualifierCollector Quals;
3060 const Type *TypeNode;
3061
3062 while (T.hasAddressSpace()) {
3063 TypeNode = Quals.strip(T);
3064
3065 // If the type no longer has an address space after stripping qualifiers,
3066 // jump out.
3067 if (!QualType(TypeNode, 0).hasAddressSpace())
3068 break;
3069
3070 // There might be sugar in the way. Strip it and try again.
3071 T = T.getSingleStepDesugaredType(*this);
3072 }
3073
3074 Quals.removeAddressSpace();
3075
3076 // Removal of the address space can mean there are no longer any
3077 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3078 // or required.
3079 if (Quals.hasNonFastQualifiers())
3080 return getExtQualType(TypeNode, Quals);
3081 else
3082 return QualType(TypeNode, Quals.getFastQualifiers());
3083}
3084
3086 Qualifiers::GC GCAttr) const {
3087 QualType CanT = getCanonicalType(T);
3088 if (CanT.getObjCGCAttr() == GCAttr)
3089 return T;
3090
3091 if (const auto *ptr = T->getAs<PointerType>()) {
3092 QualType Pointee = ptr->getPointeeType();
3093 if (Pointee->isAnyPointerType()) {
3094 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
3095 return getPointerType(ResultType);
3096 }
3097 }
3098
3099 // If we are composing extended qualifiers together, merge together
3100 // into one ExtQuals node.
3101 QualifierCollector Quals;
3102 const Type *TypeNode = Quals.strip(T);
3103
3104 // If this type already has an ObjCGC specified, it cannot get
3105 // another one.
3106 assert(!Quals.hasObjCGCAttr() &&
3107 "Type cannot have multiple ObjCGCs!");
3108 Quals.addObjCGCAttr(GCAttr);
3109
3110 return getExtQualType(TypeNode, Quals);
3111}
3112
3114 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3115 QualType Pointee = Ptr->getPointeeType();
3116 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3117 return getPointerType(removeAddrSpaceQualType(Pointee));
3118 }
3119 }
3120 return T;
3121}
3122
3124 QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull,
3125 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3126 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3127
3128 llvm::FoldingSetNodeID ID;
3129 CountAttributedType::Profile(ID, WrappedTy, CountExpr, CountInBytes, OrNull);
3130
3131 void *InsertPos = nullptr;
3132 CountAttributedType *CATy =
3133 CountAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
3134 if (CATy)
3135 return QualType(CATy, 0);
3136
3137 QualType CanonTy = getCanonicalType(WrappedTy);
3138 size_t Size = CountAttributedType::totalSizeToAlloc<TypeCoupledDeclRefInfo>(
3139 DependentDecls.size());
3141 new (CATy) CountAttributedType(WrappedTy, CanonTy, CountExpr, CountInBytes,
3142 OrNull, DependentDecls);
3143 Types.push_back(CATy);
3144 CountAttributedTypes.InsertNode(CATy, InsertPos);
3145
3146 return QualType(CATy, 0);
3147}
3148
3150 FunctionType::ExtInfo Info) {
3151 if (T->getExtInfo() == Info)
3152 return T;
3153
3155 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3156 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3157 } else {
3158 const auto *FPT = cast<FunctionProtoType>(T);
3159 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3160 EPI.ExtInfo = Info;
3161 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3162 }
3163
3164 return cast<FunctionType>(Result.getTypePtr());
3165}
3166
3168 QualType ResultType) {
3169 FD = FD->getMostRecentDecl();
3170 while (true) {
3171 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
3172 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3173 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
3174 if (FunctionDecl *Next = FD->getPreviousDecl())
3175 FD = Next;
3176 else
3177 break;
3178 }
3180 L->DeducedReturnType(FD, ResultType);
3181}
3182
3183/// Get a function type and produce the equivalent function type with the
3184/// specified exception specification. Type sugar that can be present on a
3185/// declaration of a function with an exception specification is permitted
3186/// and preserved. Other type sugar (for instance, typedefs) is not.
3188 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3189 // Might have some parens.
3190 if (const auto *PT = dyn_cast<ParenType>(Orig))
3191 return getParenType(
3192 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
3193
3194 // Might be wrapped in a macro qualified type.
3195 if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig))
3196 return getMacroQualifiedType(
3197 getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI),
3198 MQT->getMacroIdentifier());
3199
3200 // Might have a calling-convention attribute.
3201 if (const auto *AT = dyn_cast<AttributedType>(Orig))
3202 return getAttributedType(
3203 AT->getAttrKind(),
3204 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
3205 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
3206
3207 // Anything else must be a function type. Rebuild it with the new exception
3208 // specification.
3209 const auto *Proto = Orig->castAs<FunctionProtoType>();
3210 return getFunctionType(
3211 Proto->getReturnType(), Proto->getParamTypes(),
3212 Proto->getExtProtoInfo().withExceptionSpec(ESI));
3213}
3214
3216 QualType U) const {
3217 return hasSameType(T, U) ||
3218 (getLangOpts().CPlusPlus17 &&
3221}
3222
3224 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3225 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3226 SmallVector<QualType, 16> Args(Proto->param_types().size());
3227 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3228 Args[i] = removePtrSizeAddrSpace(Proto->param_types()[i]);
3229 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3230 }
3231
3232 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3233 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3234 return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3235 }
3236
3237 return T;
3238}
3239
3241 return hasSameType(T, U) ||
3244}
3245
3248 bool AsWritten) {
3249 // Update the type.
3250 QualType Updated =
3252 FD->setType(Updated);
3253
3254 if (!AsWritten)
3255 return;
3256
3257 // Update the type in the type source information too.
3258 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3259 // If the type and the type-as-written differ, we may need to update
3260 // the type-as-written too.
3261 if (TSInfo->getType() != FD->getType())
3262 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3263
3264 // FIXME: When we get proper type location information for exceptions,
3265 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3266 // up the TypeSourceInfo;
3267 assert(TypeLoc::getFullDataSizeForType(Updated) ==
3268 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3269 "TypeLoc size mismatch from updating exception specification");
3270 TSInfo->overrideType(Updated);
3271 }
3272}
3273
3274/// getComplexType - Return the uniqued reference to the type for a complex
3275/// number with the specified element type.
3277 // Unique pointers, to guarantee there is only one pointer of a particular
3278 // structure.
3279 llvm::FoldingSetNodeID ID;
3281
3282 void *InsertPos = nullptr;
3283 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3284 return QualType(CT, 0);
3285
3286 // If the pointee type isn't canonical, this won't be a canonical type either,
3287 // so fill in the canonical type field.
3288 QualType Canonical;
3289 if (!T.isCanonical()) {
3290 Canonical = getComplexType(getCanonicalType(T));
3291
3292 // Get the new insert position for the node we care about.
3293 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3294 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3295 }
3296 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
3297 Types.push_back(New);
3298 ComplexTypes.InsertNode(New, InsertPos);
3299 return QualType(New, 0);
3300}
3301
3302/// getPointerType - Return the uniqued reference to the type for a pointer to
3303/// the specified type.
3305 // Unique pointers, to guarantee there is only one pointer of a particular
3306 // structure.
3307 llvm::FoldingSetNodeID ID;
3309
3310 void *InsertPos = nullptr;
3311 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3312 return QualType(PT, 0);
3313
3314 // If the pointee type isn't canonical, this won't be a canonical type either,
3315 // so fill in the canonical type field.
3316 QualType Canonical;
3317 if (!T.isCanonical()) {
3318 Canonical = getPointerType(getCanonicalType(T));
3319
3320 // Get the new insert position for the node we care about.
3321 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3322 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3323 }
3324 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
3325 Types.push_back(New);
3326 PointerTypes.InsertNode(New, InsertPos);
3327 return QualType(New, 0);
3328}
3329
3331 llvm::FoldingSetNodeID ID;
3332 AdjustedType::Profile(ID, Orig, New);
3333 void *InsertPos = nullptr;
3334 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3335 if (AT)
3336 return QualType(AT, 0);
3337
3338 QualType Canonical = getCanonicalType(New);
3339
3340 // Get the new insert position for the node we care about.
3341 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3342 assert(!AT && "Shouldn't be in the map!");
3343
3344 AT = new (*this, alignof(AdjustedType))
3345 AdjustedType(Type::Adjusted, Orig, New, Canonical);
3346 Types.push_back(AT);
3347 AdjustedTypes.InsertNode(AT, InsertPos);
3348 return QualType(AT, 0);
3349}
3350
3352 llvm::FoldingSetNodeID ID;
3353 AdjustedType::Profile(ID, Orig, Decayed);
3354 void *InsertPos = nullptr;
3355 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3356 if (AT)
3357 return QualType(AT, 0);
3358
3359 QualType Canonical = getCanonicalType(Decayed);
3360
3361 // Get the new insert position for the node we care about.
3362 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3363 assert(!AT && "Shouldn't be in the map!");
3364
3365 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
3366 Types.push_back(AT);
3367 AdjustedTypes.InsertNode(AT, InsertPos);
3368 return QualType(AT, 0);
3369}
3370
3372 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
3373
3374 QualType Decayed;
3375
3376 // C99 6.7.5.3p7:
3377 // A declaration of a parameter as "array of type" shall be
3378 // adjusted to "qualified pointer to type", where the type
3379 // qualifiers (if any) are those specified within the [ and ] of
3380 // the array type derivation.
3381 if (T->isArrayType())
3382 Decayed = getArrayDecayedType(T);
3383
3384 // C99 6.7.5.3p8:
3385 // A declaration of a parameter as "function returning type"
3386 // shall be adjusted to "pointer to function returning type", as
3387 // in 6.3.2.1.
3388 if (T->isFunctionType())
3389 Decayed = getPointerType(T);
3390
3391 return getDecayedType(T, Decayed);
3392}
3393
3395 if (Ty->isArrayParameterType())
3396 return Ty;
3397 assert(Ty->isConstantArrayType() && "Ty must be an array type.");
3398 const auto *ATy = cast<ConstantArrayType>(Ty);
3399 llvm::FoldingSetNodeID ID;
3400 ATy->Profile(ID, *this, ATy->getElementType(), ATy->getZExtSize(),
3401 ATy->getSizeExpr(), ATy->getSizeModifier(),
3402 ATy->getIndexTypeQualifiers().getAsOpaqueValue());
3403 void *InsertPos = nullptr;
3404 ArrayParameterType *AT =
3405 ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
3406 if (AT)
3407 return QualType(AT, 0);
3408
3409 QualType Canonical;
3410 if (!Ty.isCanonical()) {
3411 Canonical = getArrayParameterType(getCanonicalType(Ty));
3412
3413 // Get the new insert position for the node we care about.
3414 AT = ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
3415 assert(!AT && "Shouldn't be in the map!");
3416 }
3417
3418 AT = new (*this, alignof(ArrayParameterType))
3419 ArrayParameterType(ATy, Canonical);
3420 Types.push_back(AT);
3421 ArrayParameterTypes.InsertNode(AT, InsertPos);
3422 return QualType(AT, 0);
3423}
3424
3425/// getBlockPointerType - Return the uniqued reference to the type for
3426/// a pointer to the specified block.
3428 assert(T->isFunctionType() && "block of function types only");
3429 // Unique pointers, to guarantee there is only one block of a particular
3430 // structure.
3431 llvm::FoldingSetNodeID ID;
3433
3434 void *InsertPos = nullptr;
3435 if (BlockPointerType *PT =
3436 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3437 return QualType(PT, 0);
3438
3439 // If the block pointee type isn't canonical, this won't be a canonical
3440 // type either so fill in the canonical type field.
3441 QualType Canonical;
3442 if (!T.isCanonical()) {
3444
3445 // Get the new insert position for the node we care about.
3446 BlockPointerType *NewIP =
3447 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3448 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3449 }
3450 auto *New =
3451 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
3452 Types.push_back(New);
3453 BlockPointerTypes.InsertNode(New, InsertPos);
3454 return QualType(New, 0);
3455}
3456
3457/// getLValueReferenceType - Return the uniqued reference to the type for an
3458/// lvalue reference to the specified type.
3460ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
3461 assert((!T->isPlaceholderType() ||
3462 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
3463 "Unresolved placeholder type");
3464
3465 // Unique pointers, to guarantee there is only one pointer of a particular
3466 // structure.
3467 llvm::FoldingSetNodeID ID;
3468 ReferenceType::Profile(ID, T, SpelledAsLValue);
3469
3470 void *InsertPos = nullptr;
3471 if (LValueReferenceType *RT =
3472 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3473 return QualType(RT, 0);
3474
3475 const auto *InnerRef = T->getAs<ReferenceType>();
3476
3477 // If the referencee type isn't canonical, this won't be a canonical type
3478 // either, so fill in the canonical type field.
3479 QualType Canonical;
3480 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
3481 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3482 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
3483
3484 // Get the new insert position for the node we care about.
3485 LValueReferenceType *NewIP =
3486 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3487 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3488 }
3489
3490 auto *New = new (*this, alignof(LValueReferenceType))
3491 LValueReferenceType(T, Canonical, SpelledAsLValue);
3492 Types.push_back(New);
3493 LValueReferenceTypes.InsertNode(New, InsertPos);
3494
3495 return QualType(New, 0);
3496}
3497
3498/// getRValueReferenceType - Return the uniqued reference to the type for an
3499/// rvalue reference to the specified type.
3501 assert((!T->isPlaceholderType() ||
3502 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
3503 "Unresolved placeholder type");
3504
3505 // Unique pointers, to guarantee there is only one pointer of a particular
3506 // structure.
3507 llvm::FoldingSetNodeID ID;
3508 ReferenceType::Profile(ID, T, false);
3509
3510 void *InsertPos = nullptr;
3511 if (RValueReferenceType *RT =
3512 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3513 return QualType(RT, 0);
3514
3515 const auto *InnerRef = T->getAs<ReferenceType>();
3516
3517 // If the referencee type isn't canonical, this won't be a canonical type
3518 // either, so fill in the canonical type field.
3519 QualType Canonical;
3520 if (InnerRef || !T.isCanonical()) {
3521 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3522 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
3523
3524 // Get the new insert position for the node we care about.
3525 RValueReferenceType *NewIP =
3526 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3527 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3528 }
3529
3530 auto *New = new (*this, alignof(RValueReferenceType))
3531 RValueReferenceType(T, Canonical);
3532 Types.push_back(New);
3533 RValueReferenceTypes.InsertNode(New, InsertPos);
3534 return QualType(New, 0);
3535}
3536
3537/// getMemberPointerType - Return the uniqued reference to the type for a
3538/// member pointer to the specified type, in the specified class.
3540 // Unique pointers, to guarantee there is only one pointer of a particular
3541 // structure.
3542 llvm::FoldingSetNodeID ID;
3543 MemberPointerType::Profile(ID, T, Cls);
3544
3545 void *InsertPos = nullptr;
3546 if (MemberPointerType *PT =
3547 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3548 return QualType(PT, 0);
3549
3550 // If the pointee or class type isn't canonical, this won't be a canonical
3551 // type either, so fill in the canonical type field.
3552 QualType Canonical;
3553 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
3555
3556 // Get the new insert position for the node we care about.
3557 MemberPointerType *NewIP =
3558 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3559 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3560 }
3561 auto *New = new (*this, alignof(MemberPointerType))
3562 MemberPointerType(T, Cls, Canonical);
3563 Types.push_back(New);
3564 MemberPointerTypes.InsertNode(New, InsertPos);
3565 return QualType(New, 0);
3566}
3567
3568/// getConstantArrayType - Return the unique reference to the type for an
3569/// array of the specified element type.
3571 const llvm::APInt &ArySizeIn,
3572 const Expr *SizeExpr,
3574 unsigned IndexTypeQuals) const {
3575 assert((EltTy->isDependentType() ||
3576 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
3577 "Constant array of VLAs is illegal!");
3578
3579 // We only need the size as part of the type if it's instantiation-dependent.
3580 if (SizeExpr && !SizeExpr->isInstantiationDependent())
3581 SizeExpr = nullptr;
3582
3583 // Convert the array size into a canonical width matching the pointer size for
3584 // the target.
3585 llvm::APInt ArySize(ArySizeIn);
3586 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
3587
3588 llvm::FoldingSetNodeID ID;
3589 ConstantArrayType::Profile(ID, *this, EltTy, ArySize.getZExtValue(), SizeExpr,
3590 ASM, IndexTypeQuals);
3591
3592 void *InsertPos = nullptr;
3593 if (ConstantArrayType *ATP =
3594 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
3595 return QualType(ATP, 0);
3596
3597 // If the element type isn't canonical or has qualifiers, or the array bound
3598 // is instantiation-dependent, this won't be a canonical type either, so fill
3599 // in the canonical type field.
3600 QualType Canon;
3601 // FIXME: Check below should look for qualifiers behind sugar.
3602 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
3603 SplitQualType canonSplit = getCanonicalType(EltTy).split();
3604 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
3605 ASM, IndexTypeQuals);
3606 Canon = getQualifiedType(Canon, canonSplit.Quals);
3607
3608 // Get the new insert position for the node we care about.
3609 ConstantArrayType *NewIP =
3610 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
3611 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3612 }
3613
3614 auto *New = ConstantArrayType::Create(*this, EltTy, Canon, ArySize, SizeExpr,
3615 ASM, IndexTypeQuals);
3616 ConstantArrayTypes.InsertNode(New, InsertPos);
3617 Types.push_back(New);
3618 return QualType(New, 0);
3619}
3620
3621/// getVariableArrayDecayedType - Turns the given type, which may be
3622/// variably-modified, into the corresponding type with all the known
3623/// sizes replaced with [*].
3625 // Vastly most common case.
3626 if (!type->isVariablyModifiedType()) return type;
3627
3628 QualType result;
3629
3630 SplitQualType split = type.getSplitDesugaredType();
3631 const Type *ty = split.Ty;
3632 switch (ty->getTypeClass()) {
3633#define TYPE(Class, Base)
3634#define ABSTRACT_TYPE(Class, Base)
3635#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3636#include "clang/AST/TypeNodes.inc"
3637 llvm_unreachable("didn't desugar past all non-canonical types?");
3638
3639 // These types should never be variably-modified.
3640 case Type::Builtin:
3641 case Type::Complex:
3642 case Type::Vector:
3643 case Type::DependentVector:
3644 case Type::ExtVector:
3645 case Type::DependentSizedExtVector:
3646 case Type::ConstantMatrix:
3647 case Type::DependentSizedMatrix:
3648 case Type::DependentAddressSpace:
3649 case Type::ObjCObject:
3650 case Type::ObjCInterface:
3651 case Type::ObjCObjectPointer:
3652 case Type::Record:
3653 case Type::Enum:
3654 case Type::UnresolvedUsing:
3655 case Type::TypeOfExpr:
3656 case Type::TypeOf:
3657 case Type::Decltype:
3658 case Type::UnaryTransform:
3659 case Type::DependentName:
3660 case Type::InjectedClassName:
3661 case Type::TemplateSpecialization:
3662 case Type::DependentTemplateSpecialization:
3663 case Type::TemplateTypeParm:
3664 case Type::SubstTemplateTypeParmPack:
3665 case Type::Auto:
3666 case Type::DeducedTemplateSpecialization:
3667 case Type::PackExpansion:
3668 case Type::PackIndexing:
3669 case Type::BitInt:
3670 case Type::DependentBitInt:
3671 case Type::ArrayParameter:
3672 llvm_unreachable("type should never be variably-modified");
3673
3674 // These types can be variably-modified but should never need to
3675 // further decay.
3676 case Type::FunctionNoProto:
3677 case Type::FunctionProto:
3678 case Type::BlockPointer:
3679 case Type::MemberPointer:
3680 case Type::Pipe:
3681 return type;
3682
3683 // These types can be variably-modified. All these modifications
3684 // preserve structure except as noted by comments.
3685 // TODO: if we ever care about optimizing VLAs, there are no-op
3686 // optimizations available here.
3687 case Type::Pointer:
3689 cast<PointerType>(ty)->getPointeeType()));
3690 break;
3691
3692 case Type::LValueReference: {
3693 const auto *lv = cast<LValueReferenceType>(ty);
3694 result = getLValueReferenceType(
3695 getVariableArrayDecayedType(lv->getPointeeType()),
3696 lv->isSpelledAsLValue());
3697 break;
3698 }
3699
3700 case Type::RValueReference: {
3701 const auto *lv = cast<RValueReferenceType>(ty);
3702 result = getRValueReferenceType(
3703 getVariableArrayDecayedType(lv->getPointeeType()));
3704 break;
3705 }
3706
3707 case Type::Atomic: {
3708 const auto *at = cast<AtomicType>(ty);
3709 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3710 break;
3711 }
3712
3713 case Type::ConstantArray: {
3714 const auto *cat = cast<ConstantArrayType>(ty);
3715 result = getConstantArrayType(
3716 getVariableArrayDecayedType(cat->getElementType()),
3717 cat->getSize(),
3718 cat->getSizeExpr(),
3719 cat->getSizeModifier(),
3720 cat->getIndexTypeCVRQualifiers());
3721 break;
3722 }
3723
3724 case Type::DependentSizedArray: {
3725 const auto *dat = cast<DependentSizedArrayType>(ty);
3727 getVariableArrayDecayedType(dat->getElementType()),
3728 dat->getSizeExpr(),
3729 dat->getSizeModifier(),
3730 dat->getIndexTypeCVRQualifiers(),
3731 dat->getBracketsRange());
3732 break;
3733 }
3734
3735 // Turn incomplete types into [*] types.
3736 case Type::IncompleteArray: {
3737 const auto *iat = cast<IncompleteArrayType>(ty);
3738 result =
3740 /*size*/ nullptr, ArraySizeModifier::Normal,
3741 iat->getIndexTypeCVRQualifiers(), SourceRange());
3742 break;
3743 }
3744
3745 // Turn VLA types into [*] types.
3746 case Type::VariableArray: {
3747 const auto *vat = cast<VariableArrayType>(ty);
3748 result = getVariableArrayType(
3749 getVariableArrayDecayedType(vat->getElementType()),
3750 /*size*/ nullptr, ArraySizeModifier::Star,
3751 vat->getIndexTypeCVRQualifiers(), vat->getBracketsRange());
3752 break;
3753 }
3754 }
3755
3756 // Apply the top-level qualifiers from the original.
3757 return getQualifiedType(result, split.Quals);
3758}
3759
3760/// getVariableArrayType - Returns a non-unique reference to the type for a
3761/// variable array of the specified element type.
3764 unsigned IndexTypeQuals,
3765 SourceRange Brackets) const {
3766 // Since we don't unique expressions, it isn't possible to unique VLA's
3767 // that have an expression provided for their size.
3768 QualType Canon;
3769
3770 // Be sure to pull qualifiers off the element type.
3771 // FIXME: Check below should look for qualifiers behind sugar.
3772 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3773 SplitQualType canonSplit = getCanonicalType(EltTy).split();
3774 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
3775 IndexTypeQuals, Brackets);
3776 Canon = getQualifiedType(Canon, canonSplit.Quals);
3777 }
3778
3779 auto *New = new (*this, alignof(VariableArrayType))
3780 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
3781
3782 VariableArrayTypes.push_back(New);
3783 Types.push_back(New);
3784 return QualType(New, 0);
3785}
3786
3787/// getDependentSizedArrayType - Returns a non-unique reference to
3788/// the type for a dependently-sized array of the specified element
3789/// type.
3791 Expr *numElements,
3793 unsigned elementTypeQuals,
3794 SourceRange brackets) const {
3795 assert((!numElements || numElements->isTypeDependent() ||
3796 numElements->isValueDependent()) &&
3797 "Size must be type- or value-dependent!");
3798
3799 SplitQualType canonElementType = getCanonicalType(elementType).split();
3800
3801 void *insertPos = nullptr;
3802 llvm::FoldingSetNodeID ID;
3804 ID, *this, numElements ? QualType(canonElementType.Ty, 0) : elementType,
3805 ASM, elementTypeQuals, numElements);
3806
3807 // Look for an existing type with these properties.
3808 DependentSizedArrayType *canonTy =
3809 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3810
3811 // Dependently-sized array types that do not have a specified number
3812 // of elements will have their sizes deduced from a dependent
3813 // initializer.
3814 if (!numElements) {
3815 if (canonTy)
3816 return QualType(canonTy, 0);
3817
3818 auto *newType = new (*this, alignof(DependentSizedArrayType))
3819 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
3820 elementTypeQuals, brackets);
3821 DependentSizedArrayTypes.InsertNode(newType, insertPos);
3822 Types.push_back(newType);
3823 return QualType(newType, 0);
3824 }
3825
3826 // If we don't have one, build one.
3827 if (!canonTy) {
3828 canonTy = new (*this, alignof(DependentSizedArrayType))
3829 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
3830 numElements, ASM, elementTypeQuals, brackets);
3831 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3832 Types.push_back(canonTy);
3833 }
3834
3835 // Apply qualifiers from the element type to the array.
3836 QualType canon = getQualifiedType(QualType(canonTy,0),
3837 canonElementType.Quals);
3838
3839 // If we didn't need extra canonicalization for the element type or the size
3840 // expression, then just use that as our result.
3841 if (QualType(canonElementType.Ty, 0) == elementType &&
3842 canonTy->getSizeExpr() == numElements)
3843 return canon;
3844
3845 // Otherwise, we need to build a type which follows the spelling
3846 // of the element type.
3847 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
3848 DependentSizedArrayType(elementType, canon, numElements, ASM,
3849 elementTypeQuals, brackets);
3850 Types.push_back(sugaredType);
3851 return QualType(sugaredType, 0);
3852}
3853
3856 unsigned elementTypeQuals) const {
3857 llvm::FoldingSetNodeID ID;
3858 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
3859
3860 void *insertPos = nullptr;
3861 if (IncompleteArrayType *iat =
3862 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3863 return QualType(iat, 0);
3864
3865 // If the element type isn't canonical, this won't be a canonical type
3866 // either, so fill in the canonical type field. We also have to pull
3867 // qualifiers off the element type.
3868 QualType canon;
3869
3870 // FIXME: Check below should look for qualifiers behind sugar.
3871 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3872 SplitQualType canonSplit = getCanonicalType(elementType).split();
3873 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
3874 ASM, elementTypeQuals);
3875 canon = getQualifiedType(canon, canonSplit.Quals);
3876
3877 // Get the new insert position for the node we care about.
3878 IncompleteArrayType *existing =
3879 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3880 assert(!existing && "Shouldn't be in the map!"); (void) existing;
3881 }
3882
3883 auto *newType = new (*this, alignof(IncompleteArrayType))
3884 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
3885
3886 IncompleteArrayTypes.InsertNode(newType, insertPos);
3887 Types.push_back(newType);
3888 return QualType(newType, 0);
3889}
3890
3893#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
3894 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
3895 NUMVECTORS};
3896
3897#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
3898 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
3899
3900 switch (Ty->getKind()) {
3901 default:
3902 llvm_unreachable("Unsupported builtin vector type");
3903 case BuiltinType::SveInt8:
3904 return SVE_INT_ELTTY(8, 16, true, 1);
3905 case BuiltinType::SveUint8:
3906 return SVE_INT_ELTTY(8, 16, false, 1);
3907 case BuiltinType::SveInt8x2:
3908 return SVE_INT_ELTTY(8, 16, true, 2);
3909 case BuiltinType::SveUint8x2:
3910 return SVE_INT_ELTTY(8, 16, false, 2);
3911 case BuiltinType::SveInt8x3:
3912 return SVE_INT_ELTTY(8, 16, true, 3);
3913 case BuiltinType::SveUint8x3:
3914 return SVE_INT_ELTTY(8, 16, false, 3);
3915 case BuiltinType::SveInt8x4:
3916 return SVE_INT_ELTTY(8, 16, true, 4);
3917 case BuiltinType::SveUint8x4:
3918 return SVE_INT_ELTTY(8, 16, false, 4);
3919 case BuiltinType::SveInt16:
3920 return SVE_INT_ELTTY(16, 8, true, 1);
3921 case BuiltinType::SveUint16:
3922 return SVE_INT_ELTTY(16, 8, false, 1);
3923 case BuiltinType::SveInt16x2:
3924 return SVE_INT_ELTTY(16, 8, true, 2);
3925 case BuiltinType::SveUint16x2:
3926 return SVE_INT_ELTTY(16, 8, false, 2);
3927 case BuiltinType::SveInt16x3:
3928 return SVE_INT_ELTTY(16, 8, true, 3);
3929 case BuiltinType::SveUint16x3:
3930 return SVE_INT_ELTTY(16, 8, false, 3);
3931 case BuiltinType::SveInt16x4:
3932 return SVE_INT_ELTTY(16, 8, true, 4);
3933 case BuiltinType::SveUint16x4:
3934 return SVE_INT_ELTTY(16, 8, false, 4);
3935 case BuiltinType::SveInt32:
3936 return SVE_INT_ELTTY(32, 4, true, 1);
3937 case BuiltinType::SveUint32:
3938 return SVE_INT_ELTTY(32, 4, false, 1);
3939 case BuiltinType::SveInt32x2:
3940 return SVE_INT_ELTTY(32, 4, true, 2);
3941 case BuiltinType::SveUint32x2:
3942 return SVE_INT_ELTTY(32, 4, false, 2);
3943 case BuiltinType::SveInt32x3:
3944 return SVE_INT_ELTTY(32, 4, true, 3);
3945 case BuiltinType::SveUint32x3:
3946 return SVE_INT_ELTTY(32, 4, false, 3);
3947 case BuiltinType::SveInt32x4:
3948 return SVE_INT_ELTTY(32, 4, true, 4);
3949 case BuiltinType::SveUint32x4:
3950 return SVE_INT_ELTTY(32, 4, false, 4);
3951 case BuiltinType::SveInt64:
3952 return SVE_INT_ELTTY(64, 2, true, 1);
3953 case BuiltinType::SveUint64:
3954 return SVE_INT_ELTTY(64, 2, false, 1);
3955 case BuiltinType::SveInt64x2:
3956 return SVE_INT_ELTTY(64, 2, true, 2);
3957 case BuiltinType::SveUint64x2:
3958 return SVE_INT_ELTTY(64, 2, false, 2);
3959 case BuiltinType::SveInt64x3:
3960 return SVE_INT_ELTTY(64, 2, true, 3);
3961 case BuiltinType::SveUint64x3:
3962 return SVE_INT_ELTTY(64, 2, false, 3);
3963 case BuiltinType::SveInt64x4:
3964 return SVE_INT_ELTTY(64, 2, true, 4);
3965 case BuiltinType::SveUint64x4:
3966 return SVE_INT_ELTTY(64, 2, false, 4);
3967 case BuiltinType::SveBool:
3968 return SVE_ELTTY(BoolTy, 16, 1);
3969 case BuiltinType::SveBoolx2:
3970 return SVE_ELTTY(BoolTy, 16, 2);
3971 case BuiltinType::SveBoolx4:
3972 return SVE_ELTTY(BoolTy, 16, 4);
3973 case BuiltinType::SveFloat16:
3974 return SVE_ELTTY(HalfTy, 8, 1);
3975 case BuiltinType::SveFloat16x2:
3976 return SVE_ELTTY(HalfTy, 8, 2);
3977 case BuiltinType::SveFloat16x3:
3978 return SVE_ELTTY(HalfTy, 8, 3);
3979 case BuiltinType::SveFloat16x4:
3980 return SVE_ELTTY(HalfTy, 8, 4);
3981 case BuiltinType::SveFloat32:
3982 return SVE_ELTTY(FloatTy, 4, 1);
3983 case BuiltinType::SveFloat32x2:
3984 return SVE_ELTTY(FloatTy, 4, 2);
3985 case BuiltinType::SveFloat32x3:
3986 return SVE_ELTTY(FloatTy, 4, 3);
3987 case BuiltinType::SveFloat32x4:
3988 return SVE_ELTTY(FloatTy, 4, 4);
3989 case BuiltinType::SveFloat64:
3990 return SVE_ELTTY(DoubleTy, 2, 1);
3991 case BuiltinType::SveFloat64x2:
3992 return SVE_ELTTY(DoubleTy, 2, 2);
3993 case BuiltinType::SveFloat64x3:
3994 return SVE_ELTTY(DoubleTy, 2, 3);
3995 case BuiltinType::SveFloat64x4:
3996 return SVE_ELTTY(DoubleTy, 2, 4);
3997 case BuiltinType::SveBFloat16:
3998 return SVE_ELTTY(BFloat16Ty, 8, 1);
3999 case BuiltinType::SveBFloat16x2:
4000 return SVE_ELTTY(BFloat16Ty, 8, 2);
4001 case BuiltinType::SveBFloat16x3:
4002 return SVE_ELTTY(BFloat16Ty, 8, 3);
4003 case BuiltinType::SveBFloat16x4:
4004 return SVE_ELTTY(BFloat16Ty, 8, 4);
4005#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4006 IsSigned) \
4007 case BuiltinType::Id: \
4008 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4009 llvm::ElementCount::getScalable(NumEls), NF};
4010#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4011 case BuiltinType::Id: \
4012 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4013 llvm::ElementCount::getScalable(NumEls), NF};
4014#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4015 case BuiltinType::Id: \
4016 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4017#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4018 case BuiltinType::Id: \
4019 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4020#include "clang/Basic/RISCVVTypes.def"
4021 }
4022}
4023
4024/// getExternrefType - Return a WebAssembly externref type, which represents an
4025/// opaque reference to a host value.
4027 if (Target->getTriple().isWasm() && Target->hasFeature("reference-types")) {
4028#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4029 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4030 return SingletonId;
4031#include "clang/Basic/WebAssemblyReferenceTypes.def"
4032 }
4033 llvm_unreachable(
4034 "shouldn't try to generate type externref outside WebAssembly target");
4035}
4036
4037/// getScalableVectorType - Return the unique reference to a scalable vector
4038/// type of the specified element type and size. VectorType must be a built-in
4039/// type.
4041 unsigned NumFields) const {
4042 if (Target->hasAArch64SVETypes()) {
4043 uint64_t EltTySize = getTypeSize(EltTy);
4044#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \
4045 IsSigned, IsFP, IsBF) \
4046 if (!EltTy->isBooleanType() && \
4047 ((EltTy->hasIntegerRepresentation() && \
4048 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4049 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4050 IsFP && !IsBF) || \
4051 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4052 IsBF && !IsFP)) && \
4053 EltTySize == ElBits && NumElts == NumEls) { \
4054 return SingletonId; \
4055 }
4056#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \
4057 if (EltTy->isBooleanType() && NumElts == NumEls) \
4058 return SingletonId;
4059#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingleTonId)
4060#include "clang/Basic/AArch64SVEACLETypes.def"
4061 } else if (Target->hasRISCVVTypes()) {
4062 uint64_t EltTySize = getTypeSize(EltTy);
4063#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4064 IsFP, IsBF) \
4065 if (!EltTy->isBooleanType() && \
4066 ((EltTy->hasIntegerRepresentation() && \
4067 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4068 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4069 IsFP && !IsBF) || \
4070 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4071 IsBF && !IsFP)) && \
4072 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4073 return SingletonId;
4074#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4075 if (EltTy->isBooleanType() && NumElts == NumEls) \
4076 return SingletonId;
4077#include "clang/Basic/RISCVVTypes.def"
4078 }
4079 return QualType();
4080}
4081
4082/// getVectorType - Return the unique reference to a vector type of
4083/// the specified element type and size. VectorType must be a built-in type.
4085 VectorKind VecKind) const {
4086 assert(vecType->isBuiltinType() ||
4087 (vecType->isBitIntType() &&
4088 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4089 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits()) &&
4090 vecType->castAs<BitIntType>()->getNumBits() >= 8));
4091
4092 // Check if we've already instantiated a vector of this type.
4093 llvm::FoldingSetNodeID ID;
4094 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
4095
4096 void *InsertPos = nullptr;
4097 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4098 return QualType(VTP, 0);
4099
4100 // If the element type isn't canonical, this won't be a canonical type either,
4101 // so fill in the canonical type field.
4102 QualType Canonical;
4103 if (!vecType.isCanonical()) {
4104 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4105
4106 // Get the new insert position for the node we care about.
4107 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4108 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4109 }
4110 auto *New = new (*this, alignof(VectorType))
4111 VectorType(vecType, NumElts, Canonical, VecKind);
4112 VectorTypes.InsertNode(New, InsertPos);
4113 Types.push_back(New);
4114 return QualType(New, 0);
4115}
4116
4118 SourceLocation AttrLoc,
4119 VectorKind VecKind) const {
4120 llvm::FoldingSetNodeID ID;
4121 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4122 VecKind);
4123 void *InsertPos = nullptr;
4124 DependentVectorType *Canon =
4125 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4127
4128 if (Canon) {
4129 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4130 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4131 } else {
4132 QualType CanonVecTy = getCanonicalType(VecType);
4133 if (CanonVecTy == VecType) {
4134 New = new (*this, alignof(DependentVectorType))
4135 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4136
4137 DependentVectorType *CanonCheck =
4138 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4139 assert(!CanonCheck &&
4140 "Dependent-sized vector_size canonical type broken");
4141 (void)CanonCheck;
4142 DependentVectorTypes.InsertNode(New, InsertPos);
4143 } else {
4144 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4145 SourceLocation(), VecKind);
4146 New = new (*this, alignof(DependentVectorType))
4147 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4148 }
4149 }
4150
4151 Types.push_back(New);
4152 return QualType(New, 0);
4153}
4154
4155/// getExtVectorType - Return the unique reference to an extended vector type of
4156/// the specified element type and size. VectorType must be a built-in type.
4158 unsigned NumElts) const {
4159 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4160 (vecType->isBitIntType() &&
4161 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4162 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits()) &&
4163 vecType->castAs<BitIntType>()->getNumBits() >= 8));
4164
4165 // Check if we've already instantiated a vector of this type.
4166 llvm::FoldingSetNodeID ID;
4167 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4169 void *InsertPos = nullptr;
4170 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4171 return QualType(VTP, 0);
4172
4173 // If the element type isn't canonical, this won't be a canonical type either,
4174 // so fill in the canonical type field.
4175 QualType Canonical;
4176 if (!vecType.isCanonical()) {
4177 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4178
4179 // Get the new insert position for the node we care about.
4180 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4181 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4182 }
4183 auto *New = new (*this, alignof(ExtVectorType))
4184 ExtVectorType(vecType, NumElts, Canonical);
4185 VectorTypes.InsertNode(New, InsertPos);
4186 Types.push_back(New);
4187 return QualType(New, 0);
4188}
4189
4192 Expr *SizeExpr,
4193 SourceLocation AttrLoc) const {
4194 llvm::FoldingSetNodeID ID;
4196 SizeExpr);
4197
4198 void *InsertPos = nullptr;
4200 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4202 if (Canon) {
4203 // We already have a canonical version of this array type; use it as
4204 // the canonical type for a newly-built type.
4205 New = new (*this, alignof(DependentSizedExtVectorType))
4206 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4207 AttrLoc);
4208 } else {
4209 QualType CanonVecTy = getCanonicalType(vecType);
4210 if (CanonVecTy == vecType) {
4211 New = new (*this, alignof(DependentSizedExtVectorType))
4212 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4213
4214 DependentSizedExtVectorType *CanonCheck
4215 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4216 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4217 (void)CanonCheck;
4218 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4219 } else {
4220 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4221 SourceLocation());
4222 New = new (*this, alignof(DependentSizedExtVectorType))
4223 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4224 }
4225 }
4226
4227 Types.push_back(New);
4228 return QualType(New, 0);
4229}
4230
4232 unsigned NumColumns) const {
4233 llvm::FoldingSetNodeID ID;
4234 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4235 Type::ConstantMatrix);
4236
4237 assert(MatrixType::isValidElementType(ElementTy) &&
4238 "need a valid element type");
4239 assert(ConstantMatrixType::isDimensionValid(NumRows) &&
4241 "need valid matrix dimensions");
4242 void *InsertPos = nullptr;
4243 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4244 return QualType(MTP, 0);
4245
4246 QualType Canonical;
4247 if (!ElementTy.isCanonical()) {
4248 Canonical =
4249 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4250
4251 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4252 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4253 (void)NewIP;
4254 }
4255
4256 auto *New = new (*this, alignof(ConstantMatrixType))
4257 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4258 MatrixTypes.InsertNode(New, InsertPos);
4259 Types.push_back(New);
4260 return QualType(New, 0);
4261}
4262
4264 Expr *RowExpr,
4265 Expr *ColumnExpr,
4266 SourceLocation AttrLoc) const {
4267 QualType CanonElementTy = getCanonicalType(ElementTy);
4268 llvm::FoldingSetNodeID ID;
4269 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4270 ColumnExpr);
4271
4272 void *InsertPos = nullptr;
4274 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4275
4276 if (!Canon) {
4277 Canon = new (*this, alignof(DependentSizedMatrixType))
4278 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4279 ColumnExpr, AttrLoc);
4280#ifndef NDEBUG
4281 DependentSizedMatrixType *CanonCheck =
4282 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4283 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4284#endif
4285 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4286 Types.push_back(Canon);
4287 }
4288
4289 // Already have a canonical version of the matrix type
4290 //
4291 // If it exactly matches the requested type, use it directly.
4292 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4293 Canon->getRowExpr() == ColumnExpr)
4294 return QualType(Canon, 0);
4295
4296 // Use Canon as the canonical type for newly-built type.
4297 DependentSizedMatrixType *New = new (*this, alignof(DependentSizedMatrixType))
4298 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4299 ColumnExpr, AttrLoc);
4300 Types.push_back(New);
4301 return QualType(New, 0);
4302}
4303
4305 Expr *AddrSpaceExpr,
4306 SourceLocation AttrLoc) const {
4307 assert(AddrSpaceExpr->isInstantiationDependent());
4308
4309 QualType canonPointeeType = getCanonicalType(PointeeType);
4310
4311 void *insertPos = nullptr;
4312 llvm::FoldingSetNodeID ID;
4313 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4314 AddrSpaceExpr);
4315
4316 DependentAddressSpaceType *canonTy =
4317 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4318
4319 if (!canonTy) {
4320 canonTy = new (*this, alignof(DependentAddressSpaceType))
4321 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
4322 AttrLoc);
4323 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4324 Types.push_back(canonTy);
4325 }
4326
4327 if (canonPointeeType == PointeeType &&
4328 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4329 return QualType(canonTy, 0);
4330
4331 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
4332 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
4333 AddrSpaceExpr, AttrLoc);
4334 Types.push_back(sugaredType);
4335 return QualType(sugaredType, 0);
4336}
4337
4338/// Determine whether \p T is canonical as the result type of a function.
4340 return T.isCanonical() &&
4341 (T.getObjCLifetime() == Qualifiers::OCL_None ||
4342 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4343}
4344
4345/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4348 const FunctionType::ExtInfo &Info) const {
4349 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
4350 // functionality creates a function without a prototype regardless of
4351 // language mode (so it makes them even in C++). Once the rewriter has been
4352 // fixed, this assertion can be enabled again.
4353 //assert(!LangOpts.requiresStrictPrototypes() &&
4354 // "strict prototypes are disabled");
4355
4356 // Unique functions, to guarantee there is only one function of a particular
4357 // structure.
4358 llvm::FoldingSetNodeID ID;
4359 FunctionNoProtoType::Profile(ID, ResultTy, Info);
4360
4361 void *InsertPos = nullptr;
4362 if (FunctionNoProtoType *FT =
4363 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4364 return QualType(FT, 0);
4365
4366 QualType Canonical;
4367 if (!isCanonicalResultType(ResultTy)) {
4368 Canonical =
4370
4371 // Get the new insert position for the node we care about.
4372 FunctionNoProtoType *NewIP =
4373 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4374 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4375 }
4376
4377 auto *New = new (*this, alignof(FunctionNoProtoType))
4378 FunctionNoProtoType(ResultTy, Canonical, Info);
4379 Types.push_back(New);
4380 FunctionNoProtoTypes.InsertNode(New, InsertPos);
4381 return QualType(New, 0);
4382}
4383
4386 CanQualType CanResultType = getCanonicalType(ResultType);
4387
4388 // Canonical result types do not have ARC lifetime qualifiers.
4389 if (CanResultType.getQualifiers().hasObjCLifetime()) {
4390 Qualifiers Qs = CanResultType.getQualifiers();
4391 Qs.removeObjCLifetime();
4393 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
4394 }
4395
4396 return CanResultType;
4397}
4398
4400 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
4401 if (ESI.Type == EST_None)
4402 return true;
4403 if (!NoexceptInType)
4404 return false;
4405
4406 // C++17 onwards: exception specification is part of the type, as a simple
4407 // boolean "can this function type throw".
4408 if (ESI.Type == EST_BasicNoexcept)
4409 return true;
4410
4411 // A noexcept(expr) specification is (possibly) canonical if expr is
4412 // value-dependent.
4413 if (ESI.Type == EST_DependentNoexcept)
4414 return true;
4415
4416 // A dynamic exception specification is canonical if it only contains pack
4417 // expansions (so we can't tell whether it's non-throwing) and all its
4418 // contained types are canonical.
4419 if (ESI.Type == EST_Dynamic) {
4420 bool AnyPackExpansions = false;
4421 for (QualType ET : ESI.Exceptions) {
4422 if (!ET.isCanonical())
4423 return false;
4424 if (ET->getAs<PackExpansionType>())
4425 AnyPackExpansions = true;
4426 }
4427 return AnyPackExpansions;
4428 }
4429
4430 return false;
4431}
4432
4433QualType ASTContext::getFunctionTypeInternal(
4434 QualType ResultTy, ArrayRef<QualType> ArgArray,
4435 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
4436 size_t NumArgs = ArgArray.size();
4437
4438 // Unique functions, to guarantee there is only one function of a particular
4439 // structure.
4440 llvm::FoldingSetNodeID ID;
4441 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
4442 *this, true);
4443
4444 QualType Canonical;
4445 bool Unique = false;
4446
4447 void *InsertPos = nullptr;
4448 if (FunctionProtoType *FPT =
4449 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4450 QualType Existing = QualType(FPT, 0);
4451
4452 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
4453 // it so long as our exception specification doesn't contain a dependent
4454 // noexcept expression, or we're just looking for a canonical type.
4455 // Otherwise, we're going to need to create a type
4456 // sugar node to hold the concrete expression.
4457 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
4458 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
4459 return Existing;
4460
4461 // We need a new type sugar node for this one, to hold the new noexcept
4462 // expression. We do no canonicalization here, but that's OK since we don't
4463 // expect to see the same noexcept expression much more than once.
4464 Canonical = getCanonicalType(Existing);
4465 Unique = true;
4466 }
4467
4468 bool NoexceptInType = getLangOpts().CPlusPlus17;
4469 bool IsCanonicalExceptionSpec =
4471
4472 // Determine whether the type being created is already canonical or not.
4473 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
4474 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
4475 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
4476 if (!ArgArray[i].isCanonicalAsParam())
4477 isCanonical = false;
4478
4479 if (OnlyWantCanonical)
4480 assert(isCanonical &&
4481 "given non-canonical parameters constructing canonical type");
4482
4483 // If this type isn't canonical, get the canonical version of it if we don't
4484 // already have it. The exception spec is only partially part of the
4485 // canonical type, and only in C++17 onwards.
4486 if (!isCanonical && Canonical.isNull()) {
4487 SmallVector<QualType, 16> CanonicalArgs;
4488 CanonicalArgs.reserve(NumArgs);
4489 for (unsigned i = 0; i != NumArgs; ++i)
4490 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
4491
4492 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
4493 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
4494 CanonicalEPI.HasTrailingReturn = false;
4495
4496 if (IsCanonicalExceptionSpec) {
4497 // Exception spec is already OK.
4498 } else if (NoexceptInType) {
4499 switch (EPI.ExceptionSpec.Type) {
4501 // We don't know yet. It shouldn't matter what we pick here; no-one
4502 // should ever look at this.
4503 [[fallthrough]];
4504 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
4505 CanonicalEPI.ExceptionSpec.Type = EST_None;
4506 break;
4507
4508 // A dynamic exception specification is almost always "not noexcept",
4509 // with the exception that a pack expansion might expand to no types.
4510 case EST_Dynamic: {
4511 bool AnyPacks = false;
4512 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
4513 if (ET->getAs<PackExpansionType>())
4514 AnyPacks = true;
4515 ExceptionTypeStorage.push_back(getCanonicalType(ET));
4516 }
4517 if (!AnyPacks)
4518 CanonicalEPI.ExceptionSpec.Type = EST_None;
4519 else {
4520 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
4521 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
4522 }
4523 break;
4524 }
4525
4526 case EST_DynamicNone:
4527 case EST_BasicNoexcept:
4528 case EST_NoexceptTrue:
4529 case EST_NoThrow:
4530 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
4531 break;
4532
4534 llvm_unreachable("dependent noexcept is already canonical");
4535 }
4536 } else {
4538 }
4539
4540 // Adjust the canonical function result type.
4541 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
4542 Canonical =
4543 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
4544
4545 // Get the new insert position for the node we care about.
4546 FunctionProtoType *NewIP =
4547 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4548 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4549 }
4550
4551 // Compute the needed size to hold this FunctionProtoType and the
4552 // various trailing objects.
4553 auto ESH = FunctionProtoType::getExceptionSpecSize(
4554 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
4555 size_t Size = FunctionProtoType::totalSizeToAlloc<
4560 EPI.requiresFunctionProtoTypeArmAttributes(), ESH.NumExceptionType,
4561 ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
4562 EPI.ExtParameterInfos ? NumArgs : 0,
4563 EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
4564
4565 auto *FTP = (FunctionProtoType *)Allocate(Size, alignof(FunctionProtoType));
4567 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
4568 Types.push_back(FTP);
4569 if (!Unique)
4570 FunctionProtoTypes.InsertNode(FTP, InsertPos);
4571 return QualType(FTP, 0);
4572}
4573
4574QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
4575 llvm::FoldingSetNodeID ID;
4576 PipeType::Profile(ID, T, ReadOnly);
4577
4578 void *InsertPos = nullptr;
4579 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
4580 return QualType(PT, 0);
4581
4582 // If the pipe element type isn't canonical, this won't be a canonical type
4583 // either, so fill in the canonical type field.
4584 QualType Canonical;
4585 if (!T.isCanonical()) {
4586 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
4587
4588 // Get the new insert position for the node we care about.
4589 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
4590 assert(!NewIP && "Shouldn't be in the map!");
4591 (void)NewIP;
4592 }
4593 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
4594 Types.push_back(New);
4595 PipeTypes.InsertNode(New, InsertPos);
4596 return QualType(New, 0);
4597}
4598
4600 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
4601 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
4602 : Ty;
4603}
4604
4606 return getPipeType(T, true);
4607}
4608
4610 return getPipeType(T, false);
4611}
4612
4613QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
4614 llvm::FoldingSetNodeID ID;
4615 BitIntType::Profile(ID, IsUnsigned, NumBits);
4616
4617 void *InsertPos = nullptr;
4618 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
4619 return QualType(EIT, 0);
4620
4621 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
4622 BitIntTypes.InsertNode(New, InsertPos);
4623 Types.push_back(New);
4624 return QualType(New, 0);
4625}
4626
4628 Expr *NumBitsExpr) const {
4629 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
4630 llvm::FoldingSetNodeID ID;
4631 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
4632
4633 void *InsertPos = nullptr;
4634 if (DependentBitIntType *Existing =
4635 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
4636 return QualType(Existing, 0);
4637
4638 auto *New = new (*this, alignof(DependentBitIntType))
4639 DependentBitIntType(IsUnsigned, NumBitsExpr);
4640 DependentBitIntTypes.InsertNode(New, InsertPos);
4641
4642 Types.push_back(New);
4643 return QualType(New, 0);
4644}
4645
4646#ifndef NDEBUG
4648 if (!isa<CXXRecordDecl>(D)) return false;
4649 const auto *RD = cast<CXXRecordDecl>(D);
4650 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
4651 return true;
4652 if (RD->getDescribedClassTemplate() &&
4653 !isa<ClassTemplateSpecializationDecl>(RD))
4654 return true;
4655 return false;
4656}
4657#endif
4658
4659/// getInjectedClassNameType - Return the unique reference to the
4660/// injected class name type for the specified templated declaration.
4662 QualType TST) const {
4664 if (Decl->TypeForDecl) {
4665 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
4666 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
4667 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
4668 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4669 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
4670 } else {
4671 Type *newType = new (*this, alignof(InjectedClassNameType))
4673 Decl->TypeForDecl = newType;
4674 Types.push_back(newType);
4675 }
4676 return QualType(Decl->TypeForDecl, 0);
4677}
4678
4679/// getTypeDeclType - Return the unique reference to the type for the
4680/// specified type declaration.
4681QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
4682 assert(Decl && "Passed null for Decl param");
4683 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
4684
4685 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
4686 return getTypedefType(Typedef);
4687
4688 assert(!isa<TemplateTypeParmDecl>(Decl) &&
4689 "Template type parameter types are always available.");
4690
4691 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
4692 assert(Record->isFirstDecl() && "struct/union has previous declaration");
4694 return getRecordType(Record);
4695 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
4696 assert(Enum->isFirstDecl() && "enum has previous declaration");
4697 return getEnumType(Enum);
4698 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
4699 return getUnresolvedUsingType(Using);
4700 } else
4701 llvm_unreachable("TypeDecl without a type?");
4702
4703 return QualType(Decl->TypeForDecl, 0);
4704}
4705
4706/// getTypedefType - Return the unique reference to the type for the
4707/// specified typedef name decl.
4709 QualType Underlying) const {
4710 if (!Decl->TypeForDecl) {
4711 if (Underlying.isNull())
4712 Underlying = Decl->getUnderlyingType();
4713 auto *NewType = new (*this, alignof(TypedefType)) TypedefType(
4714 Type::Typedef, Decl, QualType(), getCanonicalType(Underlying));
4715 Decl->TypeForDecl = NewType;
4716 Types.push_back(NewType);
4717 return QualType(NewType, 0);
4718 }
4719 if (Underlying.isNull() || Decl->getUnderlyingType() == Underlying)
4720 return QualType(Decl->TypeForDecl, 0);
4721 assert(hasSameType(Decl->getUnderlyingType(), Underlying));
4722
4723 llvm::FoldingSetNodeID ID;
4724 TypedefType::Profile(ID, Decl, Underlying);
4725
4726 void *InsertPos = nullptr;
4727 if (TypedefType *T = TypedefTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4728 assert(!T->typeMatchesDecl() &&
4729 "non-divergent case should be handled with TypeDecl");
4730 return QualType(T, 0);
4731 }
4732
4733 void *Mem = Allocate(TypedefType::totalSizeToAlloc<QualType>(true),
4734 alignof(TypedefType));
4735 auto *NewType = new (Mem) TypedefType(Type::Typedef, Decl, Underlying,
4736 getCanonicalType(Underlying));
4737 TypedefTypes.InsertNode(NewType, InsertPos);
4738 Types.push_back(NewType);
4739 return QualType(NewType, 0);
4740}
4741
4743 QualType Underlying) const {
4744 llvm::FoldingSetNodeID ID;
4745 UsingType::Profile(ID, Found, Underlying);
4746
4747 void *InsertPos = nullptr;
4748 if (UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos))
4749 return QualType(T, 0);
4750
4751 const Type *TypeForDecl =
4752 cast<TypeDecl>(Found->getTargetDecl())->getTypeForDecl();
4753
4754 assert(!Underlying.hasLocalQualifiers());
4755 QualType Canon = Underlying->getCanonicalTypeInternal();
4756 assert(TypeForDecl->getCanonicalTypeInternal() == Canon);
4757
4758 if (Underlying.getTypePtr() == TypeForDecl)
4759 Underlying = QualType();
4760 void *Mem =
4761 Allocate(UsingType::totalSizeToAlloc<QualType>(!Underlying.isNull()),
4762 alignof(UsingType));
4763 UsingType *NewType = new (Mem) UsingType(Found, Underlying, Canon);
4764 Types.push_back(NewType);
4765 UsingTypes.InsertNode(NewType, InsertPos);
4766 return QualType(NewType, 0);
4767}
4768
4770 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4771
4772 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
4773 if (PrevDecl->TypeForDecl)
4774 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4775
4776 auto *newType = new (*this, alignof(RecordType)) RecordType(Decl);
4777 Decl->TypeForDecl = newType;
4778 Types.push_back(newType);
4779 return QualType(newType, 0);
4780}
4781
4783 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4784
4785 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
4786 if (PrevDecl->TypeForDecl)
4787 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4788
4789 auto *newType = new (*this, alignof(EnumType)) EnumType(Decl);
4790 Decl->TypeForDecl = newType;
4791 Types.push_back(newType);
4792 return QualType(newType, 0);
4793}
4794
4796 const UnresolvedUsingTypenameDecl *Decl) const {
4797 if (Decl->TypeForDecl)
4798 return QualType(Decl->TypeForDecl, 0);
4799
4800 if (const UnresolvedUsingTypenameDecl *CanonicalDecl =
4802 if (CanonicalDecl->TypeForDecl)
4803 return QualType(Decl->TypeForDecl = CanonicalDecl->TypeForDecl, 0);
4804
4805 Type *newType =
4806 new (*this, alignof(UnresolvedUsingType)) UnresolvedUsingType(Decl);
4807 Decl->TypeForDecl = newType;
4808 Types.push_back(newType);
4809 return QualType(newType, 0);
4810}
4811
4813 QualType modifiedType,
4814 QualType equivalentType) const {
4815 llvm::FoldingSetNodeID id;
4816 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
4817
4818 void *insertPos = nullptr;
4819 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
4820 if (type) return QualType(type, 0);
4821
4822 QualType canon = getCanonicalType(equivalentType);
4823 type = new (*this, alignof(AttributedType))
4824 AttributedType(canon, attrKind, modifiedType, equivalentType);
4825
4826 Types.push_back(type);
4827 AttributedTypes.InsertNode(type, insertPos);
4828
4829 return QualType(type, 0);
4830}
4831
4832QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
4833 QualType Wrapped) {
4834 llvm::FoldingSetNodeID ID;
4835 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
4836
4837 void *InsertPos = nullptr;
4839 BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
4840 if (Ty)
4841 return QualType(Ty, 0);
4842
4843 QualType Canon = getCanonicalType(Wrapped);
4844 Ty = new (*this, alignof(BTFTagAttributedType))
4845 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
4846
4847 Types.push_back(Ty);
4848 BTFTagAttributedTypes.InsertNode(Ty, InsertPos);
4849
4850 return QualType(Ty, 0);
4851}
4852
4853/// Retrieve a substitution-result type.
4855 QualType Replacement, Decl *AssociatedDecl, unsigned Index,
4856 std::optional<unsigned> PackIndex) const {
4857 llvm::FoldingSetNodeID ID;
4858 SubstTemplateTypeParmType::Profile(ID, Replacement, AssociatedDecl, Index,
4859 PackIndex);
4860 void *InsertPos = nullptr;
4861 SubstTemplateTypeParmType *SubstParm =
4862 SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4863
4864 if (!SubstParm) {
4865 void *Mem = Allocate(SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
4866 !Replacement.isCanonical()),
4867 alignof(SubstTemplateTypeParmType));
4868 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
4869 Index, PackIndex);
4870 Types.push_back(SubstParm);
4871 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
4872 }
4873
4874 return QualType(SubstParm, 0);
4875}
4876
4877/// Retrieve a
4880 unsigned Index, bool Final,
4881 const TemplateArgument &ArgPack) {
4882#ifndef NDEBUG
4883 for (const auto &P : ArgPack.pack_elements())
4884 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
4885#endif
4886
4887 llvm::FoldingSetNodeID ID;
4888 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
4889 ArgPack);
4890 void *InsertPos = nullptr;
4891 if (SubstTemplateTypeParmPackType *SubstParm =
4892 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
4893 return QualType(SubstParm, 0);
4894
4895 QualType Canon;
4896 {
4897 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
4898 if (!AssociatedDecl->isCanonicalDecl() ||
4899 !CanonArgPack.structurallyEquals(ArgPack)) {
4901 AssociatedDecl->getCanonicalDecl(), Index, Final, CanonArgPack);
4902 [[maybe_unused]] const auto *Nothing =
4903 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
4904 assert(!Nothing);
4905 }
4906 }
4907
4908 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
4909 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
4910 ArgPack);
4911 Types.push_back(SubstParm);
4912 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
4913 return QualType(SubstParm, 0);
4914}
4915
4916/// Retrieve the template type parameter type for a template
4917/// parameter or parameter pack with the given depth, index, and (optionally)
4918/// name.
4919QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
4920 bool ParameterPack,
4921 TemplateTypeParmDecl *TTPDecl) const {
4922 llvm::FoldingSetNodeID ID;
4923 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
4924 void *InsertPos = nullptr;
4925 TemplateTypeParmType *TypeParm
4926 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4927
4928 if (TypeParm)
4929 return QualType(TypeParm, 0);
4930
4931 if (TTPDecl) {
4932 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
4933 TypeParm = new (*this, alignof(TemplateTypeParmType))
4934 TemplateTypeParmType(TTPDecl, Canon);
4935
4936 TemplateTypeParmType *TypeCheck
4937 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4938 assert(!TypeCheck && "Template type parameter canonical type broken");
4939 (void)TypeCheck;
4940 } else
4941 TypeParm = new (*this, alignof(TemplateTypeParmType))
4942 TemplateTypeParmType(Depth, Index, ParameterPack);
4943
4944 Types.push_back(TypeParm);
4945 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
4946
4947 return QualType(TypeParm, 0);
4948}
4949
4952 SourceLocation NameLoc,
4953 const TemplateArgumentListInfo &Args,
4954 QualType Underlying) const {
4955 assert(!Name.getAsDependentTemplateName() &&
4956 "No dependent template names here!");
4957 QualType TST =
4958 getTemplateSpecializationType(Name, Args.arguments(), Underlying);
4959
4964 TL.setTemplateNameLoc(NameLoc);
4965 TL.setLAngleLoc(Args.getLAngleLoc());
4966 TL.setRAngleLoc(Args.getRAngleLoc());
4967 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4968 TL.setArgLocInfo(i, Args[i].getLocInfo());
4969 return DI;
4970}
4971
4975 QualType Underlying) const {
4976 assert(!Template.getAsDependentTemplateName() &&
4977 "No dependent template names here!");
4978
4980 ArgVec.reserve(Args.size());
4981 for (const TemplateArgumentLoc &Arg : Args)
4982 ArgVec.push_back(Arg.getArgument());
4983
4984 return getTemplateSpecializationType(Template, ArgVec, Underlying);
4985}
4986
4987#ifndef NDEBUG
4989 for (const TemplateArgument &Arg : Args)
4990 if (Arg.isPackExpansion())
4991 return true;
4992
4993 return true;
4994}
4995#endif
4996
5000 QualType Underlying) const {
5001 assert(!Template.getAsDependentTemplateName() &&
5002 "No dependent template names here!");
5003 // Look through qualified template names.
5005 Template = QTN->getUnderlyingTemplate();
5006
5007 const auto *TD = Template.getAsTemplateDecl();
5008 bool IsTypeAlias = TD && TD->isTypeAlias();
5009 QualType CanonType;
5010 if (!Underlying.isNull())
5011 CanonType = getCanonicalType(Underlying);
5012 else {
5013 // We can get here with an alias template when the specialization contains
5014 // a pack expansion that does not match up with a parameter pack.
5015 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
5016 "Caller must compute aliased type");
5017 IsTypeAlias = false;
5018 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
5019 }
5020
5021 // Allocate the (non-canonical) template specialization type, but don't
5022 // try to unique it: these types typically have location information that
5023 // we don't unique and don't want to lose.
5024 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
5025 sizeof(TemplateArgument) * Args.size() +
5026 (IsTypeAlias ? sizeof(QualType) : 0),
5028 auto *Spec
5029 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
5030 IsTypeAlias ? Underlying : QualType());
5031
5032 Types.push_back(Spec);
5033 return QualType(Spec, 0);
5034}
5035
5037 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
5038 assert(!Template.getAsDependentTemplateName() &&
5039 "No dependent template names here!");
5040
5041 // Look through qualified template names.
5043 Template = TemplateName(QTN->getUnderlyingTemplate());
5044
5045 // Build the canonical template specialization type.
5046 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
5047 bool AnyNonCanonArgs = false;
5048 auto CanonArgs =
5049 ::getCanonicalTemplateArguments(*this, Args, AnyNonCanonArgs);
5050
5051 // Determine whether this canonical template specialization type already
5052 // exists.
5053 llvm::FoldingSetNodeID ID;
5054 TemplateSpecializationType::Profile(ID, CanonTemplate,
5055 CanonArgs, *this);
5056
5057 void *InsertPos = nullptr;
5059 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5060
5061 if (!Spec) {
5062 // Allocate a new canonical template specialization type.
5063 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
5064 sizeof(TemplateArgument) * CanonArgs.size()),
5066 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
5067 CanonArgs,
5068 QualType(), QualType());
5069 Types.push_back(Spec);
5070 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
5071 }