clang 20.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 "ByteCode/Context.h"
15#include "CXXABI.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"
36#include "clang/AST/Mangle.h"
42#include "clang/AST/Stmt.h"
45#include "clang/AST/Type.h"
46#include "clang/AST/TypeLoc.h"
54#include "clang/Basic/LLVM.h"
56#include "clang/Basic/Linkage.h"
57#include "clang/Basic/Module.h"
67#include "llvm/ADT/APFixedPoint.h"
68#include "llvm/ADT/APInt.h"
69#include "llvm/ADT/APSInt.h"
70#include "llvm/ADT/ArrayRef.h"
71#include "llvm/ADT/DenseMap.h"
72#include "llvm/ADT/DenseSet.h"
73#include "llvm/ADT/FoldingSet.h"
74#include "llvm/ADT/PointerUnion.h"
75#include "llvm/ADT/STLExtras.h"
76#include "llvm/ADT/SmallPtrSet.h"
77#include "llvm/ADT/SmallVector.h"
78#include "llvm/ADT/StringExtras.h"
79#include "llvm/ADT/StringRef.h"
80#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
81#include "llvm/Support/Capacity.h"
82#include "llvm/Support/Compiler.h"
83#include "llvm/Support/ErrorHandling.h"
84#include "llvm/Support/MD5.h"
85#include "llvm/Support/MathExtras.h"
86#include "llvm/Support/SipHash.h"
87#include "llvm/Support/raw_ostream.h"
88#include "llvm/TargetParser/AArch64TargetParser.h"
89#include "llvm/TargetParser/Triple.h"
90#include <algorithm>
91#include <cassert>
92#include <cstddef>
93#include <cstdint>
94#include <cstdlib>
95#include <map>
96#include <memory>
97#include <optional>
98#include <string>
99#include <tuple>
100#include <utility>
101
102using namespace clang;
103
114
115template <> struct llvm::DenseMapInfo<llvm::FoldingSetNodeID> {
116 static FoldingSetNodeID getEmptyKey() { return FoldingSetNodeID{}; }
117
118 static FoldingSetNodeID getTombstoneKey() {
119 FoldingSetNodeID id;
120 for (size_t i = 0; i < sizeof(id) / sizeof(unsigned); ++i) {
121 id.AddInteger(std::numeric_limits<unsigned>::max());
122 }
123 return id;
124 }
125
126 static unsigned getHashValue(const FoldingSetNodeID &Val) {
127 return Val.ComputeHash();
128 }
129
130 static bool isEqual(const FoldingSetNodeID &LHS,
131 const FoldingSetNodeID &RHS) {
132 return LHS == RHS;
133 }
134};
135
136/// \returns The locations that are relevant when searching for Doc comments
137/// related to \p D.
140 assert(D);
141
142 // User can not attach documentation to implicit declarations.
143 if (D->isImplicit())
144 return {};
145
146 // User can not attach documentation to implicit instantiations.
147 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
148 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
149 return {};
150 }
151
152 if (const auto *VD = dyn_cast<VarDecl>(D)) {
153 if (VD->isStaticDataMember() &&
154 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
155 return {};
156 }
157
158 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
159 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
160 return {};
161 }
162
163 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
164 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
165 if (TSK == TSK_ImplicitInstantiation ||
166 TSK == TSK_Undeclared)
167 return {};
168 }
169
170 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
171 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
172 return {};
173 }
174 if (const auto *TD = dyn_cast<TagDecl>(D)) {
175 // When tag declaration (but not definition!) is part of the
176 // decl-specifier-seq of some other declaration, it doesn't get comment
177 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
178 return {};
179 }
180 // TODO: handle comments for function parameters properly.
181 if (isa<ParmVarDecl>(D))
182 return {};
183
184 // TODO: we could look up template parameter documentation in the template
185 // documentation.
186 if (isa<TemplateTypeParmDecl>(D) ||
187 isa<NonTypeTemplateParmDecl>(D) ||
188 isa<TemplateTemplateParmDecl>(D))
189 return {};
190
192 // Find declaration location.
193 // For Objective-C declarations we generally don't expect to have multiple
194 // declarators, thus use declaration starting location as the "declaration
195 // location".
196 // For all other declarations multiple declarators are used quite frequently,
197 // so we use the location of the identifier as the "declaration location".
198 SourceLocation BaseLocation;
199 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
200 isa<ObjCPropertyDecl>(D) || isa<RedeclarableTemplateDecl>(D) ||
201 isa<ClassTemplateSpecializationDecl>(D) ||
202 // Allow association with Y across {} in `typedef struct X {} Y`.
203 isa<TypedefDecl>(D))
204 BaseLocation = D->getBeginLoc();
205 else
206 BaseLocation = D->getLocation();
207
208 if (!D->getLocation().isMacroID()) {
209 Locations.emplace_back(BaseLocation);
210 } else {
211 const auto *DeclCtx = D->getDeclContext();
212
213 // When encountering definitions generated from a macro (that are not
214 // contained by another declaration in the macro) we need to try and find
215 // the comment at the location of the expansion but if there is no comment
216 // there we should retry to see if there is a comment inside the macro as
217 // well. To this end we return first BaseLocation to first look at the
218 // expansion site, the second value is the spelling location of the
219 // beginning of the declaration defined inside the macro.
220 if (!(DeclCtx &&
221 Decl::castFromDeclContext(DeclCtx)->getLocation().isMacroID())) {
222 Locations.emplace_back(SourceMgr.getExpansionLoc(BaseLocation));
223 }
224
225 // We use Decl::getBeginLoc() and not just BaseLocation here to ensure that
226 // we don't refer to the macro argument location at the expansion site (this
227 // can happen if the name's spelling is provided via macro argument), and
228 // always to the declaration itself.
229 Locations.emplace_back(SourceMgr.getSpellingLoc(D->getBeginLoc()));
230 }
231
232 return Locations;
233}
234
236 const Decl *D, const SourceLocation RepresentativeLocForDecl,
237 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
238 // If the declaration doesn't map directly to a location in a file, we
239 // can't find the comment.
240 if (RepresentativeLocForDecl.isInvalid() ||
241 !RepresentativeLocForDecl.isFileID())
242 return nullptr;
243
244 // If there are no comments anywhere, we won't find anything.
245 if (CommentsInTheFile.empty())
246 return nullptr;
247
248 // Decompose the location for the declaration and find the beginning of the
249 // file buffer.
250 const std::pair<FileID, unsigned> DeclLocDecomp =
251 SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
252
253 // Slow path.
254 auto OffsetCommentBehindDecl =
255 CommentsInTheFile.lower_bound(DeclLocDecomp.second);
256
257 // First check whether we have a trailing comment.
258 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
259 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
260 if ((CommentBehindDecl->isDocumentation() ||
261 LangOpts.CommentOpts.ParseAllComments) &&
262 CommentBehindDecl->isTrailingComment() &&
263 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
264 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
265
266 // Check that Doxygen trailing comment comes after the declaration, starts
267 // on the same line and in the same file as the declaration.
268 if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
269 Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
270 OffsetCommentBehindDecl->first)) {
271 return CommentBehindDecl;
272 }
273 }
274 }
275
276 // The comment just after the declaration was not a trailing comment.
277 // Let's look at the previous comment.
278 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
279 return nullptr;
280
281 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
282 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
283
284 // Check that we actually have a non-member Doxygen comment.
285 if (!(CommentBeforeDecl->isDocumentation() ||
286 LangOpts.CommentOpts.ParseAllComments) ||
287 CommentBeforeDecl->isTrailingComment())
288 return nullptr;
289
290 // Decompose the end of the comment.
291 const unsigned CommentEndOffset =
292 Comments.getCommentEndOffset(CommentBeforeDecl);
293
294 // Get the corresponding buffer.
295 bool Invalid = false;
296 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
297 &Invalid).data();
298 if (Invalid)
299 return nullptr;
300
301 // Extract text between the comment and declaration.
302 StringRef Text(Buffer + CommentEndOffset,
303 DeclLocDecomp.second - CommentEndOffset);
304
305 // There should be no other declarations or preprocessor directives between
306 // comment and declaration.
307 if (Text.find_last_of(";{}#@") != StringRef::npos)
308 return nullptr;
309
310 return CommentBeforeDecl;
311}
312
314 const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr);
315
316 for (const auto DeclLoc : DeclLocs) {
317 // If the declaration doesn't map directly to a location in a file, we
318 // can't find the comment.
319 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
320 continue;
321
324 CommentsLoaded = true;
325 }
326
327 if (Comments.empty())
328 continue;
329
330 const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
331 if (!File.isValid())
332 continue;
333
334 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
335 if (!CommentsInThisFile || CommentsInThisFile->empty())
336 continue;
337
338 if (RawComment *Comment =
339 getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile))
340 return Comment;
341 }
342
343 return nullptr;
344}
345
347 assert(LangOpts.RetainCommentsFromSystemHeaders ||
348 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
349 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
350}
351
352/// If we have a 'templated' declaration for a template, adjust 'D' to
353/// refer to the actual template.
354/// If we have an implicit instantiation, adjust 'D' to refer to template.
355static const Decl &adjustDeclToTemplate(const Decl &D) {
356 if (const auto *FD = dyn_cast<FunctionDecl>(&D)) {
357 // Is this function declaration part of a function template?
358 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
359 return *FTD;
360
361 // Nothing to do if function is not an implicit instantiation.
362 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
363 return D;
364
365 // Function is an implicit instantiation of a function template?
366 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
367 return *FTD;
368
369 // Function is instantiated from a member definition of a class template?
370 if (const FunctionDecl *MemberDecl =
372 return *MemberDecl;
373
374 return D;
375 }
376 if (const auto *VD = dyn_cast<VarDecl>(&D)) {
377 // Static data member is instantiated from a member definition of a class
378 // template?
379 if (VD->isStaticDataMember())
380 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
381 return *MemberDecl;
382
383 return D;
384 }
385 if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) {
386 // Is this class declaration part of a class template?
387 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
388 return *CTD;
389
390 // Class is an implicit instantiation of a class template or partial
391 // specialization?
392 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
393 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
394 return D;
395 llvm::PointerUnion<ClassTemplateDecl *,
398 return isa<ClassTemplateDecl *>(PU)
399 ? *static_cast<const Decl *>(cast<ClassTemplateDecl *>(PU))
400 : *static_cast<const Decl *>(
401 cast<ClassTemplatePartialSpecializationDecl *>(PU));
402 }
403
404 // Class is instantiated from a member definition of a class template?
405 if (const MemberSpecializationInfo *Info =
406 CRD->getMemberSpecializationInfo())
407 return *Info->getInstantiatedFrom();
408
409 return D;
410 }
411 if (const auto *ED = dyn_cast<EnumDecl>(&D)) {
412 // Enum is instantiated from a member definition of a class template?
413 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
414 return *MemberDecl;
415
416 return D;
417 }
418 // FIXME: Adjust alias templates?
419 return D;
420}
421
423 const Decl *D,
424 const Decl **OriginalDecl) const {
425 if (!D) {
426 if (OriginalDecl)
427 OriginalDecl = nullptr;
428 return nullptr;
429 }
430
432
433 // Any comment directly attached to D?
434 {
435 auto DeclComment = DeclRawComments.find(D);
436 if (DeclComment != DeclRawComments.end()) {
437 if (OriginalDecl)
438 *OriginalDecl = D;
439 return DeclComment->second;
440 }
441 }
442
443 // Any comment attached to any redeclaration of D?
444 const Decl *CanonicalD = D->getCanonicalDecl();
445 if (!CanonicalD)
446 return nullptr;
447
448 {
449 auto RedeclComment = RedeclChainComments.find(CanonicalD);
450 if (RedeclComment != RedeclChainComments.end()) {
451 if (OriginalDecl)
452 *OriginalDecl = RedeclComment->second;
453 auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
454 assert(CommentAtRedecl != DeclRawComments.end() &&
455 "This decl is supposed to have comment attached.");
456 return CommentAtRedecl->second;
457 }
458 }
459
460 // Any redeclarations of D that we haven't checked for comments yet?
461 const Decl *LastCheckedRedecl = [&]() {
462 const Decl *LastChecked = CommentlessRedeclChains.lookup(CanonicalD);
463 bool CanUseCommentlessCache = false;
464 if (LastChecked) {
465 for (auto *Redecl : CanonicalD->redecls()) {
466 if (Redecl == D) {
467 CanUseCommentlessCache = true;
468 break;
469 }
470 if (Redecl == LastChecked)
471 break;
472 }
473 }
474 // FIXME: This could be improved so that even if CanUseCommentlessCache
475 // is false, once we've traversed past CanonicalD we still skip ahead
476 // LastChecked.
477 return CanUseCommentlessCache ? LastChecked : nullptr;
478 }();
479
480 for (const Decl *Redecl : D->redecls()) {
481 assert(Redecl);
482 // Skip all redeclarations that have been checked previously.
483 if (LastCheckedRedecl) {
484 if (LastCheckedRedecl == Redecl) {
485 LastCheckedRedecl = nullptr;
486 }
487 continue;
488 }
489 const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
490 if (RedeclComment) {
491 cacheRawCommentForDecl(*Redecl, *RedeclComment);
492 if (OriginalDecl)
493 *OriginalDecl = Redecl;
494 return RedeclComment;
495 }
496 CommentlessRedeclChains[CanonicalD] = Redecl;
497 }
498
499 if (OriginalDecl)
500 *OriginalDecl = nullptr;
501 return nullptr;
502}
503
505 const RawComment &Comment) const {
506 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
507 DeclRawComments.try_emplace(&OriginalD, &Comment);
508 const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
509 RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
510 CommentlessRedeclChains.erase(CanonicalDecl);
511}
512
513static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
515 const DeclContext *DC = ObjCMethod->getDeclContext();
516 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
517 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
518 if (!ID)
519 return;
520 // Add redeclared method here.
521 for (const auto *Ext : ID->known_extensions()) {
522 if (ObjCMethodDecl *RedeclaredMethod =
523 Ext->getMethod(ObjCMethod->getSelector(),
524 ObjCMethod->isInstanceMethod()))
525 Redeclared.push_back(RedeclaredMethod);
526 }
527 }
528}
529
531 const Preprocessor *PP) {
532 if (Comments.empty() || Decls.empty())
533 return;
534
535 FileID File;
536 for (const Decl *D : Decls) {
537 if (D->isInvalidDecl())
538 continue;
539
542 if (Loc.isValid()) {
543 // See if there are any new comments that are not attached to a decl.
544 // The location doesn't have to be precise - we care only about the file.
545 File = SourceMgr.getDecomposedLoc(Loc).first;
546 break;
547 }
548 }
549
550 if (File.isInvalid())
551 return;
552
553 auto CommentsInThisFile = Comments.getCommentsInFile(File);
554 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
555 CommentsInThisFile->rbegin()->second->isAttached())
556 return;
557
558 // There is at least one comment not attached to a decl.
559 // Maybe it should be attached to one of Decls?
560 //
561 // Note that this way we pick up not only comments that precede the
562 // declaration, but also comments that *follow* the declaration -- thanks to
563 // the lookahead in the lexer: we've consumed the semicolon and looked
564 // ahead through comments.
565 for (const Decl *D : Decls) {
566 assert(D);
567 if (D->isInvalidDecl())
568 continue;
569
571
572 if (DeclRawComments.count(D) > 0)
573 continue;
574
575 const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr);
576
577 for (const auto DeclLoc : DeclLocs) {
578 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
579 continue;
580
581 if (RawComment *const DocComment = getRawCommentForDeclNoCacheImpl(
582 D, DeclLoc, *CommentsInThisFile)) {
583 cacheRawCommentForDecl(*D, *DocComment);
584 comments::FullComment *FC = DocComment->parse(*this, PP, D);
586 break;
587 }
588 }
589 }
590}
591
593 const Decl *D) const {
594 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
595 ThisDeclInfo->CommentDecl = D;
596 ThisDeclInfo->IsFilled = false;
597 ThisDeclInfo->fill();
598 ThisDeclInfo->CommentDecl = FC->getDecl();
599 if (!ThisDeclInfo->TemplateParameters)
600 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
602 new (*this) comments::FullComment(FC->getBlocks(),
603 ThisDeclInfo);
604 return CFC;
605}
606
609 return RC ? RC->parse(*this, nullptr, D) : nullptr;
610}
611
613 const Decl *D,
614 const Preprocessor *PP) const {
615 if (!D || D->isInvalidDecl())
616 return nullptr;
618
619 const Decl *Canonical = D->getCanonicalDecl();
620 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
621 ParsedComments.find(Canonical);
622
623 if (Pos != ParsedComments.end()) {
624 if (Canonical != D) {
625 comments::FullComment *FC = Pos->second;
627 return CFC;
628 }
629 return Pos->second;
630 }
631
632 const Decl *OriginalDecl = nullptr;
633
634 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
635 if (!RC) {
636 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
638 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
639 if (OMD && OMD->isPropertyAccessor())
640 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
641 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
642 return cloneFullComment(FC, D);
643 if (OMD)
644 addRedeclaredMethods(OMD, Overridden);
645 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
646 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
647 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
648 return cloneFullComment(FC, D);
649 }
650 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
651 // Attach any tag type's documentation to its typedef if latter
652 // does not have one of its own.
653 QualType QT = TD->getUnderlyingType();
654 if (const auto *TT = QT->getAs<TagType>())
655 if (const Decl *TD = TT->getDecl())
657 return cloneFullComment(FC, D);
658 }
659 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
660 while (IC->getSuperClass()) {
661 IC = IC->getSuperClass();
663 return cloneFullComment(FC, D);
664 }
665 }
666 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
667 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
669 return cloneFullComment(FC, D);
670 }
671 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
672 if (!(RD = RD->getDefinition()))
673 return nullptr;
674 // Check non-virtual bases.
675 for (const auto &I : RD->bases()) {
676 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
677 continue;
678 QualType Ty = I.getType();
679 if (Ty.isNull())
680 continue;
682 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
683 continue;
684
686 return cloneFullComment(FC, D);
687 }
688 }
689 // Check virtual bases.
690 for (const auto &I : RD->vbases()) {
691 if (I.getAccessSpecifier() != AS_public)
692 continue;
693 QualType Ty = I.getType();
694 if (Ty.isNull())
695 continue;
696 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
697 if (!(VirtualBase= VirtualBase->getDefinition()))
698 continue;
700 return cloneFullComment(FC, D);
701 }
702 }
703 }
704 return nullptr;
705 }
706
707 // If the RawComment was attached to other redeclaration of this Decl, we
708 // should parse the comment in context of that other Decl. This is important
709 // because comments can contain references to parameter names which can be
710 // different across redeclarations.
711 if (D != OriginalDecl && OriginalDecl)
712 return getCommentForDecl(OriginalDecl, PP);
713
714 comments::FullComment *FC = RC->parse(*this, PP, D);
715 ParsedComments[Canonical] = FC;
716 return FC;
717}
718
719void
720ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
721 const ASTContext &C,
723 ID.AddInteger(Parm->getDepth());
724 ID.AddInteger(Parm->getPosition());
725 ID.AddBoolean(Parm->isParameterPack());
726
728 ID.AddInteger(Params->size());
730 PEnd = Params->end();
731 P != PEnd; ++P) {
732 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
733 ID.AddInteger(0);
734 ID.AddBoolean(TTP->isParameterPack());
735 if (TTP->isExpandedParameterPack()) {
736 ID.AddBoolean(true);
737 ID.AddInteger(TTP->getNumExpansionParameters());
738 } else
739 ID.AddBoolean(false);
740 continue;
741 }
742
743 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
744 ID.AddInteger(1);
745 ID.AddBoolean(NTTP->isParameterPack());
746 ID.AddPointer(C.getUnconstrainedType(C.getCanonicalType(NTTP->getType()))
747 .getAsOpaquePtr());
748 if (NTTP->isExpandedParameterPack()) {
749 ID.AddBoolean(true);
750 ID.AddInteger(NTTP->getNumExpansionTypes());
751 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
752 QualType T = NTTP->getExpansionType(I);
753 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
754 }
755 } else
756 ID.AddBoolean(false);
757 continue;
758 }
759
760 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
761 ID.AddInteger(2);
762 Profile(ID, C, TTP);
763 }
764}
765
767ASTContext::getCanonicalTemplateTemplateParmDecl(
768 TemplateTemplateParmDecl *TTP) const {
769 // Check if we already have a canonical template template parameter.
770 llvm::FoldingSetNodeID ID;
771 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
772 void *InsertPos = nullptr;
773 CanonicalTemplateTemplateParm *Canonical
774 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
775 if (Canonical)
776 return Canonical->getParam();
777
778 // Build a canonical template parameter list.
780 SmallVector<NamedDecl *, 4> CanonParams;
781 CanonParams.reserve(Params->size());
783 PEnd = Params->end();
784 P != PEnd; ++P) {
785 // Note that, per C++20 [temp.over.link]/6, when determining whether
786 // template-parameters are equivalent, constraints are ignored.
787 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
790 TTP->getDepth(), TTP->getIndex(), nullptr, false,
791 TTP->isParameterPack(), /*HasTypeConstraint=*/false,
793 ? std::optional<unsigned>(TTP->getNumExpansionParameters())
794 : std::nullopt);
795 CanonParams.push_back(NewTTP);
796 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
800 if (NTTP->isExpandedParameterPack()) {
801 SmallVector<QualType, 2> ExpandedTypes;
803 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
804 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
805 ExpandedTInfos.push_back(
806 getTrivialTypeSourceInfo(ExpandedTypes.back()));
807 }
808
812 NTTP->getDepth(),
813 NTTP->getPosition(), nullptr,
814 T,
815 TInfo,
816 ExpandedTypes,
817 ExpandedTInfos);
818 } else {
822 NTTP->getDepth(),
823 NTTP->getPosition(), nullptr,
824 T,
825 NTTP->isParameterPack(),
826 TInfo);
827 }
828 CanonParams.push_back(Param);
829 } else
830 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
831 cast<TemplateTemplateParmDecl>(*P)));
832 }
833
836 TTP->getPosition(), TTP->isParameterPack(), nullptr, /*Typename=*/false,
838 CanonParams, SourceLocation(),
839 /*RequiresClause=*/nullptr));
840
841 // Get the new insert position for the node we care about.
842 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
843 assert(!Canonical && "Shouldn't be in the map!");
844 (void)Canonical;
845
846 // Create the canonical template template parameter entry.
847 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
848 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
849 return CanonTTP;
850}
851
852/// Check if a type can have its sanitizer instrumentation elided based on its
853/// presence within an ignorelist.
855 const QualType &Ty) const {
856 std::string TyName = Ty.getUnqualifiedType().getAsString(getPrintingPolicy());
857 return NoSanitizeL->containsType(Mask, TyName) &&
858 !NoSanitizeL->containsType(Mask, TyName, "sanitize");
859}
860
862 auto Kind = getTargetInfo().getCXXABI().getKind();
863 return getLangOpts().CXXABI.value_or(Kind);
864}
865
866CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
867 if (!LangOpts.CPlusPlus) return nullptr;
868
869 switch (getCXXABIKind()) {
870 case TargetCXXABI::AppleARM64:
871 case TargetCXXABI::Fuchsia:
872 case TargetCXXABI::GenericARM: // Same as Itanium at this level
873 case TargetCXXABI::iOS:
874 case TargetCXXABI::WatchOS:
875 case TargetCXXABI::GenericAArch64:
876 case TargetCXXABI::GenericMIPS:
877 case TargetCXXABI::GenericItanium:
878 case TargetCXXABI::WebAssembly:
879 case TargetCXXABI::XL:
880 return CreateItaniumCXXABI(*this);
881 case TargetCXXABI::Microsoft:
882 return CreateMicrosoftCXXABI(*this);
883 }
884 llvm_unreachable("Invalid CXXABI type!");
885}
886
888 if (!InterpContext) {
889 InterpContext.reset(new interp::Context(*this));
890 }
891 return *InterpContext.get();
892}
893
895 if (!ParentMapCtx)
896 ParentMapCtx.reset(new ParentMapContext(*this));
897 return *ParentMapCtx.get();
898}
899
901 const LangOptions &LangOpts) {
902 switch (LangOpts.getAddressSpaceMapMangling()) {
904 return TI.useAddressSpaceMapMangling();
906 return true;
908 return false;
909 }
910 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
911}
912
914 IdentifierTable &idents, SelectorTable &sels,
915 Builtin::Context &builtins, TranslationUnitKind TUKind)
916 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize),
917 DependentSizedArrayTypes(this_()), DependentSizedExtVectorTypes(this_()),
918 DependentAddressSpaceTypes(this_()), DependentVectorTypes(this_()),
919 DependentSizedMatrixTypes(this_()),
920 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize),
921 DependentTypeOfExprTypes(this_()), DependentDecltypeTypes(this_()),
922 TemplateSpecializationTypes(this_()),
923 DependentTemplateSpecializationTypes(this_()),
924 DependentBitIntTypes(this_()), SubstTemplateTemplateParmPacks(this_()),
925 DeducedTemplates(this_()), ArrayParameterTypes(this_()),
926 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
927 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
928 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
929 LangOpts.XRayNeverInstrumentFiles,
930 LangOpts.XRayAttrListFiles, SM)),
931 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
932 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
933 BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this),
934 Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
935 CompCategories(this_()), LastSDM(nullptr, 0) {
937}
938
940 // Release the DenseMaps associated with DeclContext objects.
941 // FIXME: Is this the ideal solution?
942 ReleaseDeclContextMaps();
943
944 // Call all of the deallocation functions on all of their targets.
945 for (auto &Pair : Deallocations)
946 (Pair.first)(Pair.second);
947 Deallocations.clear();
948
949 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
950 // because they can contain DenseMaps.
951 for (llvm::DenseMap<const ObjCContainerDecl*,
952 const ASTRecordLayout*>::iterator
953 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
954 // Increment in loop to prevent using deallocated memory.
955 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
956 R->Destroy(*this);
957 ObjCLayouts.clear();
958
959 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
960 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
961 // Increment in loop to prevent using deallocated memory.
962 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
963 R->Destroy(*this);
964 }
965 ASTRecordLayouts.clear();
966
967 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
968 AEnd = DeclAttrs.end();
969 A != AEnd; ++A)
970 A->second->~AttrVec();
971 DeclAttrs.clear();
972
973 for (const auto &Value : ModuleInitializers)
974 Value.second->~PerModuleInitializers();
975 ModuleInitializers.clear();
976}
977
979
980void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
981 TraversalScope = TopLevelDecls;
983}
984
985void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
986 Deallocations.push_back({Callback, Data});
987}
988
989void
991 ExternalSource = std::move(Source);
992}
993
995 llvm::errs() << "\n*** AST Context Stats:\n";
996 llvm::errs() << " " << Types.size() << " types total.\n";
997
998 unsigned counts[] = {
999#define TYPE(Name, Parent) 0,
1000#define ABSTRACT_TYPE(Name, Parent)
1001#include "clang/AST/TypeNodes.inc"
1002 0 // Extra
1003 };
1004
1005 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1006 Type *T = Types[i];
1007 counts[(unsigned)T->getTypeClass()]++;
1008 }
1009
1010 unsigned Idx = 0;
1011 unsigned TotalBytes = 0;
1012#define TYPE(Name, Parent) \
1013 if (counts[Idx]) \
1014 llvm::errs() << " " << counts[Idx] << " " << #Name \
1015 << " types, " << sizeof(Name##Type) << " each " \
1016 << "(" << counts[Idx] * sizeof(Name##Type) \
1017 << " bytes)\n"; \
1018 TotalBytes += counts[Idx] * sizeof(Name##Type); \
1019 ++Idx;
1020#define ABSTRACT_TYPE(Name, Parent)
1021#include "clang/AST/TypeNodes.inc"
1022
1023 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1024
1025 // Implicit special member functions.
1026 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1028 << " implicit default constructors created\n";
1029 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1031 << " implicit copy constructors created\n";
1032 if (getLangOpts().CPlusPlus)
1033 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1035 << " implicit move constructors created\n";
1036 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1038 << " implicit copy assignment operators created\n";
1039 if (getLangOpts().CPlusPlus)
1040 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1042 << " implicit move assignment operators created\n";
1043 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1045 << " implicit destructors created\n";
1046
1047 if (ExternalSource) {
1048 llvm::errs() << "\n";
1050 }
1051
1052 BumpAlloc.PrintStats();
1053}
1054
1056 bool NotifyListeners) {
1057 if (NotifyListeners)
1058 if (auto *Listener = getASTMutationListener())
1060
1061 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1062}
1063
1065 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1066 if (It == MergedDefModules.end())
1067 return;
1068
1069 auto &Merged = It->second;
1070 llvm::DenseSet<Module*> Found;
1071 for (Module *&M : Merged)
1072 if (!Found.insert(M).second)
1073 M = nullptr;
1074 llvm::erase(Merged, nullptr);
1075}
1076
1079 auto MergedIt =
1080 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1081 if (MergedIt == MergedDefModules.end())
1082 return {};
1083 return MergedIt->second;
1084}
1085
1086void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1087 if (LazyInitializers.empty())
1088 return;
1089
1090 auto *Source = Ctx.getExternalSource();
1091 assert(Source && "lazy initializers but no external source");
1092
1093 auto LazyInits = std::move(LazyInitializers);
1094 LazyInitializers.clear();
1095
1096 for (auto ID : LazyInits)
1097 Initializers.push_back(Source->GetExternalDecl(ID));
1098
1099 assert(LazyInitializers.empty() &&
1100 "GetExternalDecl for lazy module initializer added more inits");
1101}
1102
1104 // One special case: if we add a module initializer that imports another
1105 // module, and that module's only initializer is an ImportDecl, simplify.
1106 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1107 auto It = ModuleInitializers.find(ID->getImportedModule());
1108
1109 // Maybe the ImportDecl does nothing at all. (Common case.)
1110 if (It == ModuleInitializers.end())
1111 return;
1112
1113 // Maybe the ImportDecl only imports another ImportDecl.
1114 auto &Imported = *It->second;
1115 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1116 Imported.resolve(*this);
1117 auto *OnlyDecl = Imported.Initializers.front();
1118 if (isa<ImportDecl>(OnlyDecl))
1119 D = OnlyDecl;
1120 }
1121 }
1122
1123 auto *&Inits = ModuleInitializers[M];
1124 if (!Inits)
1125 Inits = new (*this) PerModuleInitializers;
1126 Inits->Initializers.push_back(D);
1127}
1128
1131 auto *&Inits = ModuleInitializers[M];
1132 if (!Inits)
1133 Inits = new (*this) PerModuleInitializers;
1134 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1135 IDs.begin(), IDs.end());
1136}
1137
1139 auto It = ModuleInitializers.find(M);
1140 if (It == ModuleInitializers.end())
1141 return {};
1142
1143 auto *Inits = It->second;
1144 Inits->resolve(*this);
1145 return Inits->Initializers;
1146}
1147
1149 assert(M->isNamedModule());
1150 assert(!CurrentCXXNamedModule &&
1151 "We should set named module for ASTContext for only once");
1152 CurrentCXXNamedModule = M;
1153}
1154
1155bool ASTContext::isInSameModule(const Module *M1, const Module *M2) {
1156 if (!M1 != !M2)
1157 return false;
1158
1159 /// Get the representative module for M. The representative module is the
1160 /// first module unit for a specific primary module name. So that the module
1161 /// units have the same representative module belongs to the same module.
1162 ///
1163 /// The process is helpful to reduce the expensive string operations.
1164 auto GetRepresentativeModule = [this](const Module *M) {
1165 auto Iter = SameModuleLookupSet.find(M);
1166 if (Iter != SameModuleLookupSet.end())
1167 return Iter->second;
1168
1169 const Module *RepresentativeModule =
1170 PrimaryModuleNameMap.try_emplace(M->getPrimaryModuleInterfaceName(), M)
1171 .first->second;
1172 SameModuleLookupSet[M] = RepresentativeModule;
1173 return RepresentativeModule;
1174 };
1175
1176 assert(M1 && "Shouldn't call `isInSameModule` if both M1 and M2 are none.");
1177 return GetRepresentativeModule(M1) == GetRepresentativeModule(M2);
1178}
1179
1181 if (!ExternCContext)
1182 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1183
1184 return ExternCContext;
1185}
1186
1189 const IdentifierInfo *II) const {
1190 auto *BuiltinTemplate =
1192 BuiltinTemplate->setImplicit();
1193 getTranslationUnitDecl()->addDecl(BuiltinTemplate);
1194
1195 return BuiltinTemplate;
1196}
1197
1200 if (!MakeIntegerSeqDecl)
1203 return MakeIntegerSeqDecl;
1204}
1205
1208 if (!TypePackElementDecl)
1211 return TypePackElementDecl;
1212}
1213
1215 if (!BuiltinCommonTypeDecl)
1216 BuiltinCommonTypeDecl = buildBuiltinTemplateDecl(
1218 return BuiltinCommonTypeDecl;
1219}
1220
1222 RecordDecl::TagKind TK) const {
1224 RecordDecl *NewDecl;
1225 if (getLangOpts().CPlusPlus)
1226 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1227 Loc, &Idents.get(Name));
1228 else
1229 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1230 &Idents.get(Name));
1231 NewDecl->setImplicit();
1232 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1233 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1234 return NewDecl;
1235}
1236
1238 StringRef Name) const {
1241 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1242 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1243 NewDecl->setImplicit();
1244 return NewDecl;
1245}
1246
1248 if (!Int128Decl)
1249 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1250 return Int128Decl;
1251}
1252
1254 if (!UInt128Decl)
1255 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1256 return UInt128Decl;
1257}
1258
1259void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1260 auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K);
1262 Types.push_back(Ty);
1263}
1264
1266 const TargetInfo *AuxTarget) {
1267 assert((!this->Target || this->Target == &Target) &&
1268 "Incorrect target reinitialization");
1269 assert(VoidTy.isNull() && "Context reinitialized?");
1270
1271 this->Target = &Target;
1272 this->AuxTarget = AuxTarget;
1273
1274 ABI.reset(createCXXABI(Target));
1275 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1276
1277 // C99 6.2.5p19.
1278 InitBuiltinType(VoidTy, BuiltinType::Void);
1279
1280 // C99 6.2.5p2.
1281 InitBuiltinType(BoolTy, BuiltinType::Bool);
1282 // C99 6.2.5p3.
1283 if (LangOpts.CharIsSigned)
1284 InitBuiltinType(CharTy, BuiltinType::Char_S);
1285 else
1286 InitBuiltinType(CharTy, BuiltinType::Char_U);
1287 // C99 6.2.5p4.
1288 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1289 InitBuiltinType(ShortTy, BuiltinType::Short);
1290 InitBuiltinType(IntTy, BuiltinType::Int);
1291 InitBuiltinType(LongTy, BuiltinType::Long);
1292 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1293
1294 // C99 6.2.5p6.
1295 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1296 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1297 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1298 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1299 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1300
1301 // C99 6.2.5p10.
1302 InitBuiltinType(FloatTy, BuiltinType::Float);
1303 InitBuiltinType(DoubleTy, BuiltinType::Double);
1304 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1305
1306 // GNU extension, __float128 for IEEE quadruple precision
1307 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1308
1309 // __ibm128 for IBM extended precision
1310 InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128);
1311
1312 // C11 extension ISO/IEC TS 18661-3
1313 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1314
1315 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1316 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1317 InitBuiltinType(AccumTy, BuiltinType::Accum);
1318 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1319 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1320 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1321 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1322 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1323 InitBuiltinType(FractTy, BuiltinType::Fract);
1324 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1325 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1326 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1327 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1328 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1329 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1330 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1331 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1332 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1333 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1334 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1335 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1336 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1337 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1338 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1339 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
1340
1341 // GNU extension, 128-bit integers.
1342 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1343 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1344
1345 // C++ 3.9.1p5
1346 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1347 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1348 else // -fshort-wchar makes wchar_t be unsigned.
1349 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1350 if (LangOpts.CPlusPlus && LangOpts.WChar)
1352 else {
1353 // C99 (or C++ using -fno-wchar).
1354 WideCharTy = getFromTargetType(Target.getWCharType());
1355 }
1356
1357 WIntTy = getFromTargetType(Target.getWIntType());
1358
1359 // C++20 (proposed)
1360 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1361
1362 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1363 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1364 else // C99
1365 Char16Ty = getFromTargetType(Target.getChar16Type());
1366
1367 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1368 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1369 else // C99
1370 Char32Ty = getFromTargetType(Target.getChar32Type());
1371
1372 // Placeholder type for type-dependent expressions whose type is
1373 // completely unknown. No code should ever check a type against
1374 // DependentTy and users should never see it; however, it is here to
1375 // help diagnose failures to properly check for type-dependent
1376 // expressions.
1377 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1378
1379 // Placeholder type for functions.
1380 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1381
1382 // Placeholder type for bound members.
1383 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1384
1385 // Placeholder type for unresolved templates.
1386 InitBuiltinType(UnresolvedTemplateTy, BuiltinType::UnresolvedTemplate);
1387
1388 // Placeholder type for pseudo-objects.
1389 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1390
1391 // "any" type; useful for debugger-like clients.
1392 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1393
1394 // Placeholder type for unbridged ARC casts.
1395 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1396
1397 // Placeholder type for builtin functions.
1398 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1399
1400 // Placeholder type for OMP array sections.
1401 if (LangOpts.OpenMP) {
1402 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1403 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1404 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1405 }
1406 // Placeholder type for OpenACC array sections, if we are ALSO in OMP mode,
1407 // don't bother, as we're just using the same type as OMP.
1408 if (LangOpts.OpenACC && !LangOpts.OpenMP) {
1409 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1410 }
1411 if (LangOpts.MatrixTypes)
1412 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1413
1414 // Builtin types for 'id', 'Class', and 'SEL'.
1415 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1416 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1417 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1418
1419 if (LangOpts.OpenCL) {
1420#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1421 InitBuiltinType(SingletonId, BuiltinType::Id);
1422#include "clang/Basic/OpenCLImageTypes.def"
1423
1424 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1425 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1426 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1427 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1428 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1429
1430#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1431 InitBuiltinType(Id##Ty, BuiltinType::Id);
1432#include "clang/Basic/OpenCLExtensionTypes.def"
1433 }
1434
1435 if (LangOpts.HLSL) {
1436#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1437 InitBuiltinType(SingletonId, BuiltinType::Id);
1438#include "clang/Basic/HLSLIntangibleTypes.def"
1439 }
1440
1441 if (Target.hasAArch64SVETypes() ||
1442 (AuxTarget && AuxTarget->hasAArch64SVETypes())) {
1443#define SVE_TYPE(Name, Id, SingletonId) \
1444 InitBuiltinType(SingletonId, BuiltinType::Id);
1445#include "clang/Basic/AArch64SVEACLETypes.def"
1446 }
1447
1448 if (Target.getTriple().isPPC64()) {
1449#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1450 InitBuiltinType(Id##Ty, BuiltinType::Id);
1451#include "clang/Basic/PPCTypes.def"
1452#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1453 InitBuiltinType(Id##Ty, BuiltinType::Id);
1454#include "clang/Basic/PPCTypes.def"
1455 }
1456
1457 if (Target.hasRISCVVTypes()) {
1458#define RVV_TYPE(Name, Id, SingletonId) \
1459 InitBuiltinType(SingletonId, BuiltinType::Id);
1460#include "clang/Basic/RISCVVTypes.def"
1461 }
1462
1463 if (Target.getTriple().isWasm() && Target.hasFeature("reference-types")) {
1464#define WASM_TYPE(Name, Id, SingletonId) \
1465 InitBuiltinType(SingletonId, BuiltinType::Id);
1466#include "clang/Basic/WebAssemblyReferenceTypes.def"
1467 }
1468
1469 if (Target.getTriple().isAMDGPU() ||
1470 (AuxTarget && AuxTarget->getTriple().isAMDGPU())) {
1471#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
1472 InitBuiltinType(SingletonId, BuiltinType::Id);
1473#include "clang/Basic/AMDGPUTypes.def"
1474 }
1475
1476 // Builtin type for __objc_yes and __objc_no
1477 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1479
1480 ObjCConstantStringType = QualType();
1481
1482 ObjCSuperType = QualType();
1483
1484 // void * type
1485 if (LangOpts.OpenCLGenericAddressSpace) {
1486 auto Q = VoidTy.getQualifiers();
1490 } else {
1492 }
1493
1494 // nullptr type (C++0x 2.14.7)
1495 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1496
1497 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1498 InitBuiltinType(HalfTy, BuiltinType::Half);
1499
1500 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1501
1502 // Builtin type used to help define __builtin_va_list.
1503 VaListTagDecl = nullptr;
1504
1505 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1506 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1509 }
1510}
1511
1513 return SourceMgr.getDiagnostics();
1514}
1515
1517 AttrVec *&Result = DeclAttrs[D];
1518 if (!Result) {
1519 void *Mem = Allocate(sizeof(AttrVec));
1520 Result = new (Mem) AttrVec;
1521 }
1522
1523 return *Result;
1524}
1525
1526/// Erase the attributes corresponding to the given declaration.
1528 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1529 if (Pos != DeclAttrs.end()) {
1530 Pos->second->~AttrVec();
1531 DeclAttrs.erase(Pos);
1532 }
1533}
1534
1535// FIXME: Remove ?
1538 assert(Var->isStaticDataMember() && "Not a static data member");
1540 .dyn_cast<MemberSpecializationInfo *>();
1541}
1542
1545 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1546 TemplateOrInstantiation.find(Var);
1547 if (Pos == TemplateOrInstantiation.end())
1548 return {};
1549
1550 return Pos->second;
1551}
1552
1553void
1556 SourceLocation PointOfInstantiation) {
1557 assert(Inst->isStaticDataMember() && "Not a static data member");
1558 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1560 Tmpl, TSK, PointOfInstantiation));
1561}
1562
1563void
1566 assert(!TemplateOrInstantiation[Inst] &&
1567 "Already noted what the variable was instantiated from");
1568 TemplateOrInstantiation[Inst] = TSI;
1569}
1570
1571NamedDecl *
1573 return InstantiatedFromUsingDecl.lookup(UUD);
1574}
1575
1576void
1578 assert((isa<UsingDecl>(Pattern) ||
1579 isa<UnresolvedUsingValueDecl>(Pattern) ||
1580 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1581 "pattern decl is not a using decl");
1582 assert((isa<UsingDecl>(Inst) ||
1583 isa<UnresolvedUsingValueDecl>(Inst) ||
1584 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1585 "instantiation did not produce a using decl");
1586 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1587 InstantiatedFromUsingDecl[Inst] = Pattern;
1588}
1589
1592 return InstantiatedFromUsingEnumDecl.lookup(UUD);
1593}
1594
1596 UsingEnumDecl *Pattern) {
1597 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1598 InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1599}
1600
1603 return InstantiatedFromUsingShadowDecl.lookup(Inst);
1604}
1605
1606void
1608 UsingShadowDecl *Pattern) {
1609 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1610 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1611}
1612
1613FieldDecl *
1615 return InstantiatedFromUnnamedFieldDecl.lookup(Field);
1616}
1617
1619 FieldDecl *Tmpl) {
1620 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1621 "Instantiated field decl is not unnamed");
1622 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1623 "Template field decl is not unnamed");
1624 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1625 "Already noted what unnamed field was instantiated from");
1626
1627 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1628}
1629
1632 return overridden_methods(Method).begin();
1633}
1634
1637 return overridden_methods(Method).end();
1638}
1639
1640unsigned
1642 auto Range = overridden_methods(Method);
1643 return Range.end() - Range.begin();
1644}
1645
1648 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1649 OverriddenMethods.find(Method->getCanonicalDecl());
1650 if (Pos == OverriddenMethods.end())
1651 return overridden_method_range(nullptr, nullptr);
1652 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1653}
1654
1656 const CXXMethodDecl *Overridden) {
1657 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1658 OverriddenMethods[Method].push_back(Overridden);
1659}
1660
1662 const NamedDecl *D,
1663 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1664 assert(D);
1665
1666 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1667 Overridden.append(overridden_methods_begin(CXXMethod),
1668 overridden_methods_end(CXXMethod));
1669 return;
1670 }
1671
1672 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1673 if (!Method)
1674 return;
1675
1677 Method->getOverriddenMethods(OverDecls);
1678 Overridden.append(OverDecls.begin(), OverDecls.end());
1679}
1680
1682 assert(!Import->getNextLocalImport() &&
1683 "Import declaration already in the chain");
1684 assert(!Import->isFromASTFile() && "Non-local import declaration");
1685 if (!FirstLocalImport) {
1686 FirstLocalImport = Import;
1687 LastLocalImport = Import;
1688 return;
1689 }
1690
1691 LastLocalImport->setNextLocalImport(Import);
1692 LastLocalImport = Import;
1693}
1694
1695//===----------------------------------------------------------------------===//
1696// Type Sizing and Analysis
1697//===----------------------------------------------------------------------===//
1698
1699/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1700/// scalar floating point type.
1701const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1702 switch (T->castAs<BuiltinType>()->getKind()) {
1703 default:
1704 llvm_unreachable("Not a floating point type!");
1705 case BuiltinType::BFloat16:
1706 return Target->getBFloat16Format();
1707 case BuiltinType::Float16:
1708 return Target->getHalfFormat();
1709 case BuiltinType::Half:
1710 return Target->getHalfFormat();
1711 case BuiltinType::Float: return Target->getFloatFormat();
1712 case BuiltinType::Double: return Target->getDoubleFormat();
1713 case BuiltinType::Ibm128:
1714 return Target->getIbm128Format();
1715 case BuiltinType::LongDouble:
1716 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1717 return AuxTarget->getLongDoubleFormat();
1718 return Target->getLongDoubleFormat();
1719 case BuiltinType::Float128:
1720 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1721 return AuxTarget->getFloat128Format();
1722 return Target->getFloat128Format();
1723 }
1724}
1725
1726CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1727 unsigned Align = Target->getCharWidth();
1728
1729 const unsigned AlignFromAttr = D->getMaxAlignment();
1730 if (AlignFromAttr)
1731 Align = AlignFromAttr;
1732
1733 // __attribute__((aligned)) can increase or decrease alignment
1734 // *except* on a struct or struct member, where it only increases
1735 // alignment unless 'packed' is also specified.
1736 //
1737 // It is an error for alignas to decrease alignment, so we can
1738 // ignore that possibility; Sema should diagnose it.
1739 bool UseAlignAttrOnly;
1740 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D))
1741 UseAlignAttrOnly =
1742 FD->hasAttr<PackedAttr>() || FD->getParent()->hasAttr<PackedAttr>();
1743 else
1744 UseAlignAttrOnly = AlignFromAttr != 0;
1745 // If we're using the align attribute only, just ignore everything
1746 // else about the declaration and its type.
1747 if (UseAlignAttrOnly) {
1748 // do nothing
1749 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1750 QualType T = VD->getType();
1751 if (const auto *RT = T->getAs<ReferenceType>()) {
1752 if (ForAlignof)
1753 T = RT->getPointeeType();
1754 else
1755 T = getPointerType(RT->getPointeeType());
1756 }
1757 QualType BaseT = getBaseElementType(T);
1758 if (T->isFunctionType())
1759 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1760 else if (!BaseT->isIncompleteType()) {
1761 // Adjust alignments of declarations with array type by the
1762 // large-array alignment on the target.
1763 if (const ArrayType *arrayType = getAsArrayType(T)) {
1764 unsigned MinWidth = Target->getLargeArrayMinWidth();
1765 if (!ForAlignof && MinWidth) {
1766 if (isa<VariableArrayType>(arrayType))
1767 Align = std::max(Align, Target->getLargeArrayAlign());
1768 else if (isa<ConstantArrayType>(arrayType) &&
1769 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1770 Align = std::max(Align, Target->getLargeArrayAlign());
1771 }
1772 }
1773 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1774 if (BaseT.getQualifiers().hasUnaligned())
1775 Align = Target->getCharWidth();
1776 }
1777
1778 // Ensure miminum alignment for global variables.
1779 if (const auto *VD = dyn_cast<VarDecl>(D))
1780 if (VD->hasGlobalStorage() && !ForAlignof) {
1781 uint64_t TypeSize =
1782 !BaseT->isIncompleteType() ? getTypeSize(T.getTypePtr()) : 0;
1783 Align = std::max(Align, getMinGlobalAlignOfVar(TypeSize, VD));
1784 }
1785
1786 // Fields can be subject to extra alignment constraints, like if
1787 // the field is packed, the struct is packed, or the struct has a
1788 // a max-field-alignment constraint (#pragma pack). So calculate
1789 // the actual alignment of the field within the struct, and then
1790 // (as we're expected to) constrain that by the alignment of the type.
1791 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1792 const RecordDecl *Parent = Field->getParent();
1793 // We can only produce a sensible answer if the record is valid.
1794 if (!Parent->isInvalidDecl()) {
1795 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1796
1797 // Start with the record's overall alignment.
1798 unsigned FieldAlign = toBits(Layout.getAlignment());
1799
1800 // Use the GCD of that and the offset within the record.
1801 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1802 if (Offset > 0) {
1803 // Alignment is always a power of 2, so the GCD will be a power of 2,
1804 // which means we get to do this crazy thing instead of Euclid's.
1805 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1806 if (LowBitOfOffset < FieldAlign)
1807 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1808 }
1809
1810 Align = std::min(Align, FieldAlign);
1811 }
1812 }
1813 }
1814
1815 // Some targets have hard limitation on the maximum requestable alignment in
1816 // aligned attribute for static variables.
1817 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1818 const auto *VD = dyn_cast<VarDecl>(D);
1819 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1820 Align = std::min(Align, MaxAlignedAttr);
1821
1822 return toCharUnitsFromBits(Align);
1823}
1824
1826 return toCharUnitsFromBits(Target->getExnObjectAlignment());
1827}
1828
1829// getTypeInfoDataSizeInChars - Return the size of a type, in
1830// chars. If the type is a record, its data size is returned. This is
1831// the size of the memcpy that's performed when assigning this type
1832// using a trivial copy/move assignment operator.
1835
1836 // In C++, objects can sometimes be allocated into the tail padding
1837 // of a base-class subobject. We decide whether that's possible
1838 // during class layout, so here we can just trust the layout results.
1839 if (getLangOpts().CPlusPlus) {
1840 if (const auto *RT = T->getAs<RecordType>();
1841 RT && !RT->getDecl()->isInvalidDecl()) {
1842 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1843 Info.Width = layout.getDataSize();
1844 }
1845 }
1846
1847 return Info;
1848}
1849
1850/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1851/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1854 const ConstantArrayType *CAT) {
1855 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1856 uint64_t Size = CAT->getZExtSize();
1857 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1858 (uint64_t)(-1)/Size) &&
1859 "Overflow in array type char size evaluation");
1860 uint64_t Width = EltInfo.Width.getQuantity() * Size;
1861 unsigned Align = EltInfo.Align.getQuantity();
1862 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1864 Width = llvm::alignTo(Width, Align);
1867 EltInfo.AlignRequirement);
1868}
1869
1871 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1872 return getConstantArrayInfoInChars(*this, CAT);
1873 TypeInfo Info = getTypeInfo(T);
1876}
1877
1879 return getTypeInfoInChars(T.getTypePtr());
1880}
1881
1883 // HLSL doesn't promote all small integer types to int, it
1884 // just uses the rank-based promotion rules for all types.
1885 if (getLangOpts().HLSL)
1886 return false;
1887
1888 if (const auto *BT = T->getAs<BuiltinType>())
1889 switch (BT->getKind()) {
1890 case BuiltinType::Bool:
1891 case BuiltinType::Char_S:
1892 case BuiltinType::Char_U:
1893 case BuiltinType::SChar:
1894 case BuiltinType::UChar:
1895 case BuiltinType::Short:
1896 case BuiltinType::UShort:
1897 case BuiltinType::WChar_S:
1898 case BuiltinType::WChar_U:
1899 case BuiltinType::Char8:
1900 case BuiltinType::Char16:
1901 case BuiltinType::Char32:
1902 return true;
1903 default:
1904 return false;
1905 }
1906
1907 // Enumerated types are promotable to their compatible integer types
1908 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
1909 if (const auto *ET = T->getAs<EnumType>()) {
1910 if (T->isDependentType() || ET->getDecl()->getPromotionType().isNull() ||
1911 ET->getDecl()->isScoped())
1912 return false;
1913
1914 return true;
1915 }
1916
1917 return false;
1918}
1919
1922}
1923
1925 return isAlignmentRequired(T.getTypePtr());
1926}
1927
1929 bool NeedsPreferredAlignment) const {
1930 // An alignment on a typedef overrides anything else.
1931 if (const auto *TT = T->getAs<TypedefType>())
1932 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1933 return Align;
1934
1935 // If we have an (array of) complete type, we're done.
1937 if (!T->isIncompleteType())
1938 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
1939
1940 // If we had an array type, its element type might be a typedef
1941 // type with an alignment attribute.
1942 if (const auto *TT = T->getAs<TypedefType>())
1943 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1944 return Align;
1945
1946 // Otherwise, see if the declaration of the type had an attribute.
1947 if (const auto *TT = T->getAs<TagType>())
1948 return TT->getDecl()->getMaxAlignment();
1949
1950 return 0;
1951}
1952
1954 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1955 if (I != MemoizedTypeInfo.end())
1956 return I->second;
1957
1958 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1959 TypeInfo TI = getTypeInfoImpl(T);
1960 MemoizedTypeInfo[T] = TI;
1961 return TI;
1962}
1963
1964/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1965/// method does not work on incomplete types.
1966///
1967/// FIXME: Pointers into different addr spaces could have different sizes and
1968/// alignment requirements: getPointerInfo should take an AddrSpace, this
1969/// should take a QualType, &c.
1970TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1971 uint64_t Width = 0;
1972 unsigned Align = 8;
1975 switch (T->getTypeClass()) {
1976#define TYPE(Class, Base)
1977#define ABSTRACT_TYPE(Class, Base)
1978#define NON_CANONICAL_TYPE(Class, Base)
1979#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1980#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1981 case Type::Class: \
1982 assert(!T->isDependentType() && "should not see dependent types here"); \
1983 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1984#include "clang/AST/TypeNodes.inc"
1985 llvm_unreachable("Should not see dependent types");
1986
1987 case Type::FunctionNoProto:
1988 case Type::FunctionProto:
1989 // GCC extension: alignof(function) = 32 bits
1990 Width = 0;
1991 Align = 32;
1992 break;
1993
1994 case Type::IncompleteArray:
1995 case Type::VariableArray:
1996 case Type::ConstantArray:
1997 case Type::ArrayParameter: {
1998 // Model non-constant sized arrays as size zero, but track the alignment.
1999 uint64_t Size = 0;
2000 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
2001 Size = CAT->getZExtSize();
2002
2003 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
2004 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
2005 "Overflow in array type bit size evaluation");
2006 Width = EltInfo.Width * Size;
2007 Align = EltInfo.Align;
2008 AlignRequirement = EltInfo.AlignRequirement;
2009 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
2010 getTargetInfo().getPointerWidth(LangAS::Default) == 64)
2011 Width = llvm::alignTo(Width, Align);
2012 break;
2013 }
2014
2015 case Type::ExtVector:
2016 case Type::Vector: {
2017 const auto *VT = cast<VectorType>(T);
2018 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
2019 Width = VT->isExtVectorBoolType() ? VT->getNumElements()
2020 : EltInfo.Width * VT->getNumElements();
2021 // Enforce at least byte size and alignment.
2022 Width = std::max<unsigned>(8, Width);
2023 Align = std::max<unsigned>(8, Width);
2024
2025 // If the alignment is not a power of 2, round up to the next power of 2.
2026 // This happens for non-power-of-2 length vectors.
2027 if (Align & (Align-1)) {
2028 Align = llvm::bit_ceil(Align);
2029 Width = llvm::alignTo(Width, Align);
2030 }
2031 // Adjust the alignment based on the target max.
2032 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
2033 if (TargetVectorAlign && TargetVectorAlign < Align)
2034 Align = TargetVectorAlign;
2035 if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
2036 // Adjust the alignment for fixed-length SVE vectors. This is important
2037 // for non-power-of-2 vector lengths.
2038 Align = 128;
2039 else if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
2040 // Adjust the alignment for fixed-length SVE predicates.
2041 Align = 16;
2042 else if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
2043 VT->getVectorKind() == VectorKind::RVVFixedLengthMask ||
2044 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
2045 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
2046 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4)
2047 // Adjust the alignment for fixed-length RVV vectors.
2048 Align = std::min<unsigned>(64, Width);
2049 break;
2050 }
2051
2052 case Type::ConstantMatrix: {
2053 const auto *MT = cast<ConstantMatrixType>(T);
2054 TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
2055 // The internal layout of a matrix value is implementation defined.
2056 // Initially be ABI compatible with arrays with respect to alignment and
2057 // size.
2058 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
2059 Align = ElementInfo.Align;
2060 break;
2061 }
2062
2063 case Type::Builtin:
2064 switch (cast<BuiltinType>(T)->getKind()) {
2065 default: llvm_unreachable("Unknown builtin type!");
2066 case BuiltinType::Void:
2067 // GCC extension: alignof(void) = 8 bits.
2068 Width = 0;
2069 Align = 8;
2070 break;
2071 case BuiltinType::Bool:
2072 Width = Target->getBoolWidth();
2073 Align = Target->getBoolAlign();
2074 break;
2075 case BuiltinType::Char_S:
2076 case BuiltinType::Char_U:
2077 case BuiltinType::UChar:
2078 case BuiltinType::SChar:
2079 case BuiltinType::Char8:
2080 Width = Target->getCharWidth();
2081 Align = Target->getCharAlign();
2082 break;
2083 case BuiltinType::WChar_S:
2084 case BuiltinType::WChar_U:
2085 Width = Target->getWCharWidth();
2086 Align = Target->getWCharAlign();
2087 break;
2088 case BuiltinType::Char16:
2089 Width = Target->getChar16Width();
2090 Align = Target->getChar16Align();
2091 break;
2092 case BuiltinType::Char32:
2093 Width = Target->getChar32Width();
2094 Align = Target->getChar32Align();
2095 break;
2096 case BuiltinType::UShort:
2097 case BuiltinType::Short:
2098 Width = Target->getShortWidth();
2099 Align = Target->getShortAlign();
2100 break;
2101 case BuiltinType::UInt:
2102 case BuiltinType::Int:
2103 Width = Target->getIntWidth();
2104 Align = Target->getIntAlign();
2105 break;
2106 case BuiltinType::ULong:
2107 case BuiltinType::Long:
2108 Width = Target->getLongWidth();
2109 Align = Target->getLongAlign();
2110 break;
2111 case BuiltinType::ULongLong:
2112 case BuiltinType::LongLong:
2113 Width = Target->getLongLongWidth();
2114 Align = Target->getLongLongAlign();
2115 break;
2116 case BuiltinType::Int128:
2117 case BuiltinType::UInt128:
2118 Width = 128;
2119 Align = Target->getInt128Align();
2120 break;
2121 case BuiltinType::ShortAccum:
2122 case BuiltinType::UShortAccum:
2123 case BuiltinType::SatShortAccum:
2124 case BuiltinType::SatUShortAccum:
2125 Width = Target->getShortAccumWidth();
2126 Align = Target->getShortAccumAlign();
2127 break;
2128 case BuiltinType::Accum:
2129 case BuiltinType::UAccum:
2130 case BuiltinType::SatAccum:
2131 case BuiltinType::SatUAccum:
2132 Width = Target->getAccumWidth();
2133 Align = Target->getAccumAlign();
2134 break;
2135 case BuiltinType::LongAccum:
2136 case BuiltinType::ULongAccum:
2137 case BuiltinType::SatLongAccum:
2138 case BuiltinType::SatULongAccum:
2139 Width = Target->getLongAccumWidth();
2140 Align = Target->getLongAccumAlign();
2141 break;
2142 case BuiltinType::ShortFract:
2143 case BuiltinType::UShortFract:
2144 case BuiltinType::SatShortFract:
2145 case BuiltinType::SatUShortFract:
2146 Width = Target->getShortFractWidth();
2147 Align = Target->getShortFractAlign();
2148 break;
2149 case BuiltinType::Fract:
2150 case BuiltinType::UFract:
2151 case BuiltinType::SatFract:
2152 case BuiltinType::SatUFract:
2153 Width = Target->getFractWidth();
2154 Align = Target->getFractAlign();
2155 break;
2156 case BuiltinType::LongFract:
2157 case BuiltinType::ULongFract:
2158 case BuiltinType::SatLongFract:
2159 case BuiltinType::SatULongFract:
2160 Width = Target->getLongFractWidth();
2161 Align = Target->getLongFractAlign();
2162 break;
2163 case BuiltinType::BFloat16:
2164 if (Target->hasBFloat16Type()) {
2165 Width = Target->getBFloat16Width();
2166 Align = Target->getBFloat16Align();
2167 } else if ((getLangOpts().SYCLIsDevice ||
2168 (getLangOpts().OpenMP &&
2169 getLangOpts().OpenMPIsTargetDevice)) &&
2170 AuxTarget->hasBFloat16Type()) {
2171 Width = AuxTarget->getBFloat16Width();
2172 Align = AuxTarget->getBFloat16Align();
2173 }
2174 break;
2175 case BuiltinType::Float16:
2176 case BuiltinType::Half:
2177 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2178 !getLangOpts().OpenMPIsTargetDevice) {
2179 Width = Target->getHalfWidth();
2180 Align = Target->getHalfAlign();
2181 } else {
2182 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2183 "Expected OpenMP device compilation.");
2184 Width = AuxTarget->getHalfWidth();
2185 Align = AuxTarget->getHalfAlign();
2186 }
2187 break;
2188 case BuiltinType::Float:
2189 Width = Target->getFloatWidth();
2190 Align = Target->getFloatAlign();
2191 break;
2192 case BuiltinType::Double:
2193 Width = Target->getDoubleWidth();
2194 Align = Target->getDoubleAlign();
2195 break;
2196 case BuiltinType::Ibm128:
2197 Width = Target->getIbm128Width();
2198 Align = Target->getIbm128Align();
2199 break;
2200 case BuiltinType::LongDouble:
2201 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2202 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2203 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2204 Width = AuxTarget->getLongDoubleWidth();
2205 Align = AuxTarget->getLongDoubleAlign();
2206 } else {
2207 Width = Target->getLongDoubleWidth();
2208 Align = Target->getLongDoubleAlign();
2209 }
2210 break;
2211 case BuiltinType::Float128:
2212 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2213 !getLangOpts().OpenMPIsTargetDevice) {
2214 Width = Target->getFloat128Width();
2215 Align = Target->getFloat128Align();
2216 } else {
2217 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2218 "Expected OpenMP device compilation.");
2219 Width = AuxTarget->getFloat128Width();
2220 Align = AuxTarget->getFloat128Align();
2221 }
2222 break;
2223 case BuiltinType::NullPtr:
2224 // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
2225 Width = Target->getPointerWidth(LangAS::Default);
2226 Align = Target->getPointerAlign(LangAS::Default);
2227 break;
2228 case BuiltinType::ObjCId:
2229 case BuiltinType::ObjCClass:
2230 case BuiltinType::ObjCSel:
2231 Width = Target->getPointerWidth(LangAS::Default);
2232 Align = Target->getPointerAlign(LangAS::Default);
2233 break;
2234 case BuiltinType::OCLSampler:
2235 case BuiltinType::OCLEvent:
2236 case BuiltinType::OCLClkEvent:
2237 case BuiltinType::OCLQueue:
2238 case BuiltinType::OCLReserveID:
2239#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2240 case BuiltinType::Id:
2241#include "clang/Basic/OpenCLImageTypes.def"
2242#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2243 case BuiltinType::Id:
2244#include "clang/Basic/OpenCLExtensionTypes.def"
2245 AS = Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
2246 Width = Target->getPointerWidth(AS);
2247 Align = Target->getPointerAlign(AS);
2248 break;
2249 // The SVE types are effectively target-specific. The length of an
2250 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2251 // of 128 bits. There is one predicate bit for each vector byte, so the
2252 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2253 //
2254 // Because the length is only known at runtime, we use a dummy value
2255 // of 0 for the static length. The alignment values are those defined
2256 // by the Procedure Call Standard for the Arm Architecture.
2257#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
2258 case BuiltinType::Id: \
2259 Width = 0; \
2260 Align = 128; \
2261 break;
2262#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
2263 case BuiltinType::Id: \
2264 Width = 0; \
2265 Align = 16; \
2266 break;
2267#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
2268 case BuiltinType::Id: \
2269 Width = 0; \
2270 Align = 16; \
2271 break;
2272#define SVE_SCALAR_TYPE(Name, MangledName, Id, SingletonId, Bits) \
2273 case BuiltinType::Id: \
2274 Width = Bits; \
2275 Align = Bits; \
2276 break;
2277#include "clang/Basic/AArch64SVEACLETypes.def"
2278#define PPC_VECTOR_TYPE(Name, Id, Size) \
2279 case BuiltinType::Id: \
2280 Width = Size; \
2281 Align = Size; \
2282 break;
2283#include "clang/Basic/PPCTypes.def"
2284#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
2285 IsFP, IsBF) \
2286 case BuiltinType::Id: \
2287 Width = 0; \
2288 Align = ElBits; \
2289 break;
2290#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2291 case BuiltinType::Id: \
2292 Width = 0; \
2293 Align = 8; \
2294 break;
2295#include "clang/Basic/RISCVVTypes.def"
2296#define WASM_TYPE(Name, Id, SingletonId) \
2297 case BuiltinType::Id: \
2298 Width = 0; \
2299 Align = 8; \
2300 break;
2301#include "clang/Basic/WebAssemblyReferenceTypes.def"
2302#define AMDGPU_TYPE(NAME, ID, SINGLETONID, WIDTH, ALIGN) \
2303 case BuiltinType::ID: \
2304 Width = WIDTH; \
2305 Align = ALIGN; \
2306 break;
2307#include "clang/Basic/AMDGPUTypes.def"
2308#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2309#include "clang/Basic/HLSLIntangibleTypes.def"
2310 Width = Target->getPointerWidth(LangAS::Default);
2311 Align = Target->getPointerAlign(LangAS::Default);
2312 break;
2313 }
2314 break;
2315 case Type::ObjCObjectPointer:
2316 Width = Target->getPointerWidth(LangAS::Default);
2317 Align = Target->getPointerAlign(LangAS::Default);
2318 break;
2319 case Type::BlockPointer:
2320 AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
2321 Width = Target->getPointerWidth(AS);
2322 Align = Target->getPointerAlign(AS);
2323 break;
2324 case Type::LValueReference:
2325 case Type::RValueReference:
2326 // alignof and sizeof should never enter this code path here, so we go
2327 // the pointer route.
2328 AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
2329 Width = Target->getPointerWidth(AS);
2330 Align = Target->getPointerAlign(AS);
2331 break;
2332 case Type::Pointer:
2333 AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
2334 Width = Target->getPointerWidth(AS);
2335 Align = Target->getPointerAlign(AS);
2336 break;
2337 case Type::MemberPointer: {
2338 const auto *MPT = cast<MemberPointerType>(T);
2339 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2340 Width = MPI.Width;
2341 Align = MPI.Align;
2342 break;
2343 }
2344 case Type::Complex: {
2345 // Complex types have the same alignment as their elements, but twice the
2346 // size.
2347 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2348 Width = EltInfo.Width * 2;
2349 Align = EltInfo.Align;
2350 break;
2351 }
2352 case Type::ObjCObject:
2353 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2354 case Type::Adjusted:
2355 case Type::Decayed:
2356 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2357 case Type::ObjCInterface: {
2358 const auto *ObjCI = cast<ObjCInterfaceType>(T);
2359 if (ObjCI->getDecl()->isInvalidDecl()) {
2360 Width = 8;
2361 Align = 8;
2362 break;
2363 }
2364 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2365 Width = toBits(Layout.getSize());
2366 Align = toBits(Layout.getAlignment());
2367 break;
2368 }
2369 case Type::BitInt: {
2370 const auto *EIT = cast<BitIntType>(T);
2371 Align = Target->getBitIntAlign(EIT->getNumBits());
2372 Width = Target->getBitIntWidth(EIT->getNumBits());
2373 break;
2374 }
2375 case Type::Record:
2376 case Type::Enum: {
2377 const auto *TT = cast<TagType>(T);
2378
2379 if (TT->getDecl()->isInvalidDecl()) {
2380 Width = 8;
2381 Align = 8;
2382 break;
2383 }
2384
2385 if (const auto *ET = dyn_cast<EnumType>(TT)) {
2386 const EnumDecl *ED = ET->getDecl();
2387 TypeInfo Info =
2389 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2390 Info.Align = AttrAlign;
2392 }
2393 return Info;
2394 }
2395
2396 const auto *RT = cast<RecordType>(TT);
2397 const RecordDecl *RD = RT->getDecl();
2398 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2399 Width = toBits(Layout.getSize());
2400 Align = toBits(Layout.getAlignment());
2401 AlignRequirement = RD->hasAttr<AlignedAttr>()
2404 break;
2405 }
2406
2407 case Type::SubstTemplateTypeParm:
2408 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2409 getReplacementType().getTypePtr());
2410
2411 case Type::Auto:
2412 case Type::DeducedTemplateSpecialization: {
2413 const auto *A = cast<DeducedType>(T);
2414 assert(!A->getDeducedType().isNull() &&
2415 "cannot request the size of an undeduced or dependent auto type");
2416 return getTypeInfo(A->getDeducedType().getTypePtr());
2417 }
2418
2419 case Type::Paren:
2420 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2421
2422 case Type::MacroQualified:
2423 return getTypeInfo(
2424 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2425
2426 case Type::ObjCTypeParam:
2427 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2428
2429 case Type::Using:
2430 return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr());
2431
2432 case Type::Typedef: {
2433 const auto *TT = cast<TypedefType>(T);
2434 TypeInfo Info = getTypeInfo(TT->desugar().getTypePtr());
2435 // If the typedef has an aligned attribute on it, it overrides any computed
2436 // alignment we have. This violates the GCC documentation (which says that
2437 // attribute(aligned) can only round up) but matches its implementation.
2438 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2439 Align = AttrAlign;
2440 AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2441 } else {
2442 Align = Info.Align;
2443 AlignRequirement = Info.AlignRequirement;
2444 }
2445 Width = Info.Width;
2446 break;
2447 }
2448
2449 case Type::Elaborated:
2450 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
2451
2452 case Type::Attributed:
2453 return getTypeInfo(
2454 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2455
2456 case Type::CountAttributed:
2457 return getTypeInfo(cast<CountAttributedType>(T)->desugar().getTypePtr());
2458
2459 case Type::BTFTagAttributed:
2460 return getTypeInfo(
2461 cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr());
2462
2463 case Type::HLSLAttributedResource:
2464 return getTypeInfo(
2465 cast<HLSLAttributedResourceType>(T)->getWrappedType().getTypePtr());
2466
2467 case Type::Atomic: {
2468 // Start with the base type information.
2469 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2470 Width = Info.Width;
2471 Align = Info.Align;
2472
2473 if (!Width) {
2474 // An otherwise zero-sized type should still generate an
2475 // atomic operation.
2476 Width = Target->getCharWidth();
2477 assert(Align);
2478 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2479 // If the size of the type doesn't exceed the platform's max
2480 // atomic promotion width, make the size and alignment more
2481 // favorable to atomic operations:
2482
2483 // Round the size up to a power of 2.
2484 Width = llvm::bit_ceil(Width);
2485
2486 // Set the alignment equal to the size.
2487 Align = static_cast<unsigned>(Width);
2488 }
2489 }
2490 break;
2491
2492 case Type::Pipe:
2493 Width = Target->getPointerWidth(LangAS::opencl_global);
2494 Align = Target->getPointerAlign(LangAS::opencl_global);
2495 break;
2496 }
2497
2498 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2499 return TypeInfo(Width, Align, AlignRequirement);
2500}
2501
2503 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2504 if (I != MemoizedUnadjustedAlign.end())
2505 return I->second;
2506
2507 unsigned UnadjustedAlign;
2508 if (const auto *RT = T->getAs<RecordType>()) {
2509 const RecordDecl *RD = RT->getDecl();
2510 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2511 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2512 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2513 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2514 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2515 } else {
2516 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2517 }
2518
2519 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2520 return UnadjustedAlign;
2521}
2522
2524 unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign(
2525 getTargetInfo().getTriple(), Target->getTargetOpts().FeatureMap);
2526 return SimdAlign;
2527}
2528
2529/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2531 return CharUnits::fromQuantity(BitSize / getCharWidth());
2532}
2533
2534/// toBits - Convert a size in characters to a size in characters.
2535int64_t ASTContext::toBits(CharUnits CharSize) const {
2536 return CharSize.getQuantity() * getCharWidth();
2537}
2538
2539/// getTypeSizeInChars - Return the size of the specified type, in characters.
2540/// This method does not work on incomplete types.
2542 return getTypeInfoInChars(T).Width;
2543}
2545 return getTypeInfoInChars(T).Width;
2546}
2547
2548/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2549/// characters. This method does not work on incomplete types.
2552}
2555}
2556
2557/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2558/// type, in characters, before alignment adjustments. This method does
2559/// not work on incomplete types.
2562}
2565}
2566
2567/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2568/// type for the current target in bits. This can be different than the ABI
2569/// alignment in cases where it is beneficial for performance or backwards
2570/// compatibility preserving to overalign a data type. (Note: despite the name,
2571/// the preferred alignment is ABI-impacting, and not an optimization.)
2573 TypeInfo TI = getTypeInfo(T);
2574 unsigned ABIAlign = TI.Align;
2575
2577
2578 // The preferred alignment of member pointers is that of a pointer.
2579 if (T->isMemberPointerType())
2580 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2581
2582 if (!Target->allowsLargerPreferedTypeAlignment())
2583 return ABIAlign;
2584
2585 if (const auto *RT = T->getAs<RecordType>()) {
2586 const RecordDecl *RD = RT->getDecl();
2587
2588 // When used as part of a typedef, or together with a 'packed' attribute,
2589 // the 'aligned' attribute can be used to decrease alignment. Note that the
2590 // 'packed' case is already taken into consideration when computing the
2591 // alignment, we only need to handle the typedef case here.
2593 RD->isInvalidDecl())
2594 return ABIAlign;
2595
2596 unsigned PreferredAlign = static_cast<unsigned>(
2597 toBits(getASTRecordLayout(RD).PreferredAlignment));
2598 assert(PreferredAlign >= ABIAlign &&
2599 "PreferredAlign should be at least as large as ABIAlign.");
2600 return PreferredAlign;
2601 }
2602
2603 // Double (and, for targets supporting AIX `power` alignment, long double) and
2604 // long long should be naturally aligned (despite requiring less alignment) if
2605 // possible.
2606 if (const auto *CT = T->getAs<ComplexType>())
2607 T = CT->getElementType().getTypePtr();
2608 if (const auto *ET = T->getAs<EnumType>())
2609 T = ET->getDecl()->getIntegerType().getTypePtr();
2610 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2611 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2612 T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2613 (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2614 Target->defaultsToAIXPowerAlignment()))
2615 // Don't increase the alignment if an alignment attribute was specified on a
2616 // typedef declaration.
2617 if (!TI.isAlignRequired())
2618 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2619
2620 return ABIAlign;
2621}
2622
2623/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2624/// for __attribute__((aligned)) on this target, to be used if no alignment
2625/// value is specified.
2628}
2629
2630/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2631/// to a global variable of the specified type.
2633 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2634 return std::max(getPreferredTypeAlign(T),
2635 getMinGlobalAlignOfVar(TypeSize, VD));
2636}
2637
2638/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2639/// should be given to a global variable of the specified type.
2641 const VarDecl *VD) const {
2643}
2644
2646 const VarDecl *VD) const {
2647 // Make the default handling as that of a non-weak definition in the
2648 // current translation unit.
2649 bool HasNonWeakDef = !VD || (VD->hasDefinition() && !VD->isWeak());
2650 return getTargetInfo().getMinGlobalAlign(Size, HasNonWeakDef);
2651}
2652
2654 CharUnits Offset = CharUnits::Zero();
2655 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2656 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2657 Offset += Layout->getBaseClassOffset(Base);
2658 Layout = &getASTRecordLayout(Base);
2659 }
2660 return Offset;
2661}
2662
2664 const ValueDecl *MPD = MP.getMemberPointerDecl();
2667 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2668 const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext());
2669 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2670 const CXXRecordDecl *Base = RD;
2671 const CXXRecordDecl *Derived = Path[I];
2672 if (DerivedMember)
2673 std::swap(Base, Derived);
2675 RD = Path[I];
2676 }
2677 if (DerivedMember)
2679 return ThisAdjustment;
2680}
2681
2682/// DeepCollectObjCIvars -
2683/// This routine first collects all declared, but not synthesized, ivars in
2684/// super class and then collects all ivars, including those synthesized for
2685/// current class. This routine is used for implementation of current class
2686/// when all ivars, declared and synthesized are known.
2688 bool leafClass,
2690 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2691 DeepCollectObjCIvars(SuperClass, false, Ivars);
2692 if (!leafClass) {
2693 llvm::append_range(Ivars, OI->ivars());
2694 } else {
2695 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2696 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2697 Iv= Iv->getNextIvar())
2698 Ivars.push_back(Iv);
2699 }
2700}
2701
2702/// CollectInheritedProtocols - Collect all protocols in current class and
2703/// those inherited by it.
2706 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2707 // We can use protocol_iterator here instead of
2708 // all_referenced_protocol_iterator since we are walking all categories.
2709 for (auto *Proto : OI->all_referenced_protocols()) {
2710 CollectInheritedProtocols(Proto, Protocols);
2711 }
2712
2713 // Categories of this Interface.
2714 for (const auto *Cat : OI->visible_categories())
2715 CollectInheritedProtocols(Cat, Protocols);
2716
2717 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2718 while (SD) {
2719 CollectInheritedProtocols(SD, Protocols);
2720 SD = SD->getSuperClass();
2721 }
2722 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2723 for (auto *Proto : OC->protocols()) {
2724 CollectInheritedProtocols(Proto, Protocols);
2725 }
2726 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2727 // Insert the protocol.
2728 if (!Protocols.insert(
2729 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2730 return;
2731
2732 for (auto *Proto : OP->protocols())
2733 CollectInheritedProtocols(Proto, Protocols);
2734 }
2735}
2736
2738 const RecordDecl *RD,
2739 bool CheckIfTriviallyCopyable) {
2740 assert(RD->isUnion() && "Must be union type");
2741 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2742
2743 for (const auto *Field : RD->fields()) {
2744 if (!Context.hasUniqueObjectRepresentations(Field->getType(),
2745 CheckIfTriviallyCopyable))
2746 return false;
2747 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2748 if (FieldSize != UnionSize)
2749 return false;
2750 }
2751 return !RD->field_empty();
2752}
2753
2754static int64_t getSubobjectOffset(const FieldDecl *Field,
2755 const ASTContext &Context,
2756 const clang::ASTRecordLayout & /*Layout*/) {
2757 return Context.getFieldOffset(Field);
2758}
2759
2760static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2761 const ASTContext &Context,
2762 const clang::ASTRecordLayout &Layout) {
2763 return Context.toBits(Layout.getBaseClassOffset(RD));
2764}
2765
2766static std::optional<int64_t>
2768 const RecordDecl *RD,
2769 bool CheckIfTriviallyCopyable);
2770
2771static std::optional<int64_t>
2772getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context,
2773 bool CheckIfTriviallyCopyable) {
2774 if (Field->getType()->isRecordType()) {
2775 const RecordDecl *RD = Field->getType()->getAsRecordDecl();
2776 if (!RD->isUnion())
2777 return structHasUniqueObjectRepresentations(Context, RD,
2778 CheckIfTriviallyCopyable);
2779 }
2780
2781 // A _BitInt type may not be unique if it has padding bits
2782 // but if it is a bitfield the padding bits are not used.
2783 bool IsBitIntType = Field->getType()->isBitIntType();
2784 if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2785 !Context.hasUniqueObjectRepresentations(Field->getType(),
2786 CheckIfTriviallyCopyable))
2787 return std::nullopt;
2788
2789 int64_t FieldSizeInBits =
2790 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2791 if (Field->isBitField()) {
2792 // If we have explicit padding bits, they don't contribute bits
2793 // to the actual object representation, so return 0.
2794 if (Field->isUnnamedBitField())
2795 return 0;
2796
2797 int64_t BitfieldSize = Field->getBitWidthValue();
2798 if (IsBitIntType) {
2799 if ((unsigned)BitfieldSize >
2800 cast<BitIntType>(Field->getType())->getNumBits())
2801 return std::nullopt;
2802 } else if (BitfieldSize > FieldSizeInBits) {
2803 return std::nullopt;
2804 }
2805 FieldSizeInBits = BitfieldSize;
2806 } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations(
2807 Field->getType(), CheckIfTriviallyCopyable)) {
2808 return std::nullopt;
2809 }
2810 return FieldSizeInBits;
2811}
2812
2813static std::optional<int64_t>
2815 bool CheckIfTriviallyCopyable) {
2816 return structHasUniqueObjectRepresentations(Context, RD,
2817 CheckIfTriviallyCopyable);
2818}
2819
2820template <typename RangeT>
2822 const RangeT &Subobjects, int64_t CurOffsetInBits,
2823 const ASTContext &Context, const clang::ASTRecordLayout &Layout,
2824 bool CheckIfTriviallyCopyable) {
2825 for (const auto *Subobject : Subobjects) {
2826 std::optional<int64_t> SizeInBits =
2827 getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable);
2828 if (!SizeInBits)
2829 return std::nullopt;
2830 if (*SizeInBits != 0) {
2831 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2832 if (Offset != CurOffsetInBits)
2833 return std::nullopt;
2834 CurOffsetInBits += *SizeInBits;
2835 }
2836 }
2837 return CurOffsetInBits;
2838}
2839
2840static std::optional<int64_t>
2842 const RecordDecl *RD,
2843 bool CheckIfTriviallyCopyable) {
2844 assert(!RD->isUnion() && "Must be struct/class type");
2845 const auto &Layout = Context.getASTRecordLayout(RD);
2846
2847 int64_t CurOffsetInBits = 0;
2848 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2849 if (ClassDecl->isDynamicClass())
2850 return std::nullopt;
2851
2853 for (const auto &Base : ClassDecl->bases()) {
2854 // Empty types can be inherited from, and non-empty types can potentially
2855 // have tail padding, so just make sure there isn't an error.
2856 Bases.emplace_back(Base.getType()->getAsCXXRecordDecl());
2857 }
2858
2859 llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
2860 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
2861 });
2862
2863 std::optional<int64_t> OffsetAfterBases =
2865 Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable);
2866 if (!OffsetAfterBases)
2867 return std::nullopt;
2868 CurOffsetInBits = *OffsetAfterBases;
2869 }
2870
2871 std::optional<int64_t> OffsetAfterFields =
2873 RD->fields(), CurOffsetInBits, Context, Layout,
2874 CheckIfTriviallyCopyable);
2875 if (!OffsetAfterFields)
2876 return std::nullopt;
2877 CurOffsetInBits = *OffsetAfterFields;
2878
2879 return CurOffsetInBits;
2880}
2881
2883 QualType Ty, bool CheckIfTriviallyCopyable) const {
2884 // C++17 [meta.unary.prop]:
2885 // The predicate condition for a template specialization
2886 // has_unique_object_representations<T> shall be satisfied if and only if:
2887 // (9.1) - T is trivially copyable, and
2888 // (9.2) - any two objects of type T with the same value have the same
2889 // object representation, where:
2890 // - two objects of array or non-union class type are considered to have
2891 // the same value if their respective sequences of direct subobjects
2892 // have the same values, and
2893 // - two objects of union type are considered to have the same value if
2894 // they have the same active member and the corresponding members have
2895 // the same value.
2896 // The set of scalar types for which this condition holds is
2897 // implementation-defined. [ Note: If a type has padding bits, the condition
2898 // does not hold; otherwise, the condition holds true for unsigned integral
2899 // types. -- end note ]
2900 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2901
2902 // Arrays are unique only if their element type is unique.
2903 if (Ty->isArrayType())
2905 CheckIfTriviallyCopyable);
2906
2907 assert((Ty->isVoidType() || !Ty->isIncompleteType()) &&
2908 "hasUniqueObjectRepresentations should not be called with an "
2909 "incomplete type");
2910
2911 // (9.1) - T is trivially copyable...
2912 if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(*this))
2913 return false;
2914
2915 // All integrals and enums are unique.
2916 if (Ty->isIntegralOrEnumerationType()) {
2917 // Except _BitInt types that have padding bits.
2918 if (const auto *BIT = Ty->getAs<BitIntType>())
2919 return getTypeSize(BIT) == BIT->getNumBits();
2920
2921 return true;
2922 }
2923
2924 // All other pointers are unique.
2925 if (Ty->isPointerType())
2926 return true;
2927
2928 if (const auto *MPT = Ty->getAs<MemberPointerType>())
2929 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2930
2931 if (Ty->isRecordType()) {
2932 const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl();
2933
2934 if (Record->isInvalidDecl())
2935 return false;
2936
2937 if (Record->isUnion())
2939 CheckIfTriviallyCopyable);
2940
2941 std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(
2942 *this, Record, CheckIfTriviallyCopyable);
2943
2944 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(Ty));
2945 }
2946
2947 // FIXME: More cases to handle here (list by rsmith):
2948 // vectors (careful about, eg, vector of 3 foo)
2949 // _Complex int and friends
2950 // _Atomic T
2951 // Obj-C block pointers
2952 // Obj-C object pointers
2953 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2954 // clk_event_t, queue_t, reserve_id_t)
2955 // There're also Obj-C class types and the Obj-C selector type, but I think it
2956 // makes sense for those to return false here.
2957
2958 return false;
2959}
2960
2962 unsigned count = 0;
2963 // Count ivars declared in class extension.
2964 for (const auto *Ext : OI->known_extensions())
2965 count += Ext->ivar_size();
2966
2967 // Count ivar defined in this class's implementation. This
2968 // includes synthesized ivars.
2969 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2970 count += ImplDecl->ivar_size();
2971
2972 return count;
2973}
2974
2976 if (!E)
2977 return false;
2978
2979 // nullptr_t is always treated as null.
2980 if (E->getType()->isNullPtrType()) return true;
2981
2982 if (E->getType()->isAnyPointerType() &&
2985 return true;
2986
2987 // Unfortunately, __null has type 'int'.
2988 if (isa<GNUNullExpr>(E)) return true;
2989
2990 return false;
2991}
2992
2993/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
2994/// exists.
2996 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2997 I = ObjCImpls.find(D);
2998 if (I != ObjCImpls.end())
2999 return cast<ObjCImplementationDecl>(I->second);
3000 return nullptr;
3001}
3002
3003/// Get the implementation of ObjCCategoryDecl, or nullptr if none
3004/// exists.
3006 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3007 I = ObjCImpls.find(D);
3008 if (I != ObjCImpls.end())
3009 return cast<ObjCCategoryImplDecl>(I->second);
3010 return nullptr;
3011}
3012
3013/// Set the implementation of ObjCInterfaceDecl.
3015 ObjCImplementationDecl *ImplD) {
3016 assert(IFaceD && ImplD && "Passed null params");
3017 ObjCImpls[IFaceD] = ImplD;
3018}
3019
3020/// Set the implementation of ObjCCategoryDecl.
3022 ObjCCategoryImplDecl *ImplD) {
3023 assert(CatD && ImplD && "Passed null params");
3024 ObjCImpls[CatD] = ImplD;
3025}
3026
3027const ObjCMethodDecl *
3029 return ObjCMethodRedecls.lookup(MD);
3030}
3031
3033 const ObjCMethodDecl *Redecl) {
3034 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
3035 ObjCMethodRedecls[MD] = Redecl;
3036}
3037
3039 const NamedDecl *ND) const {
3040 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
3041 return ID;
3042 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
3043 return CD->getClassInterface();
3044 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
3045 return IMD->getClassInterface();
3046
3047 return nullptr;
3048}
3049
3050/// Get the copy initialization expression of VarDecl, or nullptr if
3051/// none exists.
3053 assert(VD && "Passed null params");
3054 assert(VD->hasAttr<BlocksAttr>() &&
3055 "getBlockVarCopyInits - not __block var");
3056 auto I = BlockVarCopyInits.find(VD);
3057 if (I != BlockVarCopyInits.end())
3058 return I->second;
3059 return {nullptr, false};
3060}
3061
3062/// Set the copy initialization expression of a block var decl.
3064 bool CanThrow) {
3065 assert(VD && CopyExpr && "Passed null params");
3066 assert(VD->hasAttr<BlocksAttr>() &&
3067 "setBlockVarCopyInits - not __block var");
3068 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
3069}
3070
3072 unsigned DataSize) const {
3073 if (!DataSize)
3075 else
3076 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
3077 "incorrect data size provided to CreateTypeSourceInfo!");
3078
3079 auto *TInfo =
3080 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
3081 new (TInfo) TypeSourceInfo(T, DataSize);
3082 return TInfo;
3083}
3084
3086 SourceLocation L) const {
3088 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
3089 return DI;
3090}
3091
3092const ASTRecordLayout &
3094 return getObjCLayout(D, nullptr);
3095}
3096
3097const ASTRecordLayout &
3099 const ObjCImplementationDecl *D) const {
3100 return getObjCLayout(D->getClassInterface(), D);
3101}
3102
3105 bool &AnyNonCanonArgs) {
3106 SmallVector<TemplateArgument, 16> CanonArgs(Args);
3107 for (auto &Arg : CanonArgs) {
3108 TemplateArgument OrigArg = Arg;
3109 Arg = C.getCanonicalTemplateArgument(Arg);
3110 AnyNonCanonArgs |= !Arg.structurallyEquals(OrigArg);
3111 }
3112 return CanonArgs;
3113}
3114
3115//===----------------------------------------------------------------------===//
3116// Type creation/memoization methods
3117//===----------------------------------------------------------------------===//
3118
3120ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3121 unsigned fastQuals = quals.getFastQualifiers();
3122 quals.removeFastQualifiers();
3123
3124 // Check if we've already instantiated this type.
3125 llvm::FoldingSetNodeID ID;
3126 ExtQuals::Profile(ID, baseType, quals);
3127 void *insertPos = nullptr;
3128 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
3129 assert(eq->getQualifiers() == quals);
3130 return QualType(eq, fastQuals);
3131 }
3132
3133 // If the base type is not canonical, make the appropriate canonical type.
3134 QualType canon;
3135 if (!baseType->isCanonicalUnqualified()) {
3136 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3137 canonSplit.Quals.addConsistentQualifiers(quals);
3138 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
3139
3140 // Re-find the insert position.
3141 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
3142 }
3143
3144 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3145 ExtQualNodes.InsertNode(eq, insertPos);
3146 return QualType(eq, fastQuals);
3147}
3148
3150 LangAS AddressSpace) const {
3151 QualType CanT = getCanonicalType(T);
3152 if (CanT.getAddressSpace() == AddressSpace)
3153 return T;
3154
3155 // If we are composing extended qualifiers together, merge together
3156 // into one ExtQuals node.
3157 QualifierCollector Quals;
3158 const Type *TypeNode = Quals.strip(T);
3159
3160 // If this type already has an address space specified, it cannot get
3161 // another one.
3162 assert(!Quals.hasAddressSpace() &&
3163 "Type cannot be in multiple addr spaces!");
3164 Quals.addAddressSpace(AddressSpace);
3165
3166 return getExtQualType(TypeNode, Quals);
3167}
3168
3170 // If the type is not qualified with an address space, just return it
3171 // immediately.
3172 if (!T.hasAddressSpace())
3173 return T;
3174
3175 QualifierCollector Quals;
3176 const Type *TypeNode;
3177 // For arrays, strip the qualifier off the element type, then reconstruct the
3178 // array type
3179 if (T.getTypePtr()->isArrayType()) {
3180 T = getUnqualifiedArrayType(T, Quals);
3181 TypeNode = T.getTypePtr();
3182 } else {
3183 // If we are composing extended qualifiers together, merge together
3184 // into one ExtQuals node.
3185 while (T.hasAddressSpace()) {
3186 TypeNode = Quals.strip(T);
3187
3188 // If the type no longer has an address space after stripping qualifiers,
3189 // jump out.
3190 if (!QualType(TypeNode, 0).hasAddressSpace())
3191 break;
3192
3193 // There might be sugar in the way. Strip it and try again.
3194 T = T.getSingleStepDesugaredType(*this);
3195 }
3196 }
3197
3198 Quals.removeAddressSpace();
3199
3200 // Removal of the address space can mean there are no longer any
3201 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3202 // or required.
3203 if (Quals.hasNonFastQualifiers())
3204 return getExtQualType(TypeNode, Quals);
3205 else
3206 return QualType(TypeNode, Quals.getFastQualifiers());
3207}
3208
3209uint16_t
3211 assert(RD->isPolymorphic() &&
3212 "Attempted to get vtable pointer discriminator on a monomorphic type");
3213 std::unique_ptr<MangleContext> MC(createMangleContext());
3214 SmallString<256> Str;
3215 llvm::raw_svector_ostream Out(Str);
3216 MC->mangleCXXVTable(RD, Out);
3217 return llvm::getPointerAuthStableSipHash(Str);
3218}
3219
3220/// Encode a function type for use in the discriminator of a function pointer
3221/// type. We can't use the itanium scheme for this since C has quite permissive
3222/// rules for type compatibility that we need to be compatible with.
3223///
3224/// Formally, this function associates every function pointer type T with an
3225/// encoded string E(T). Let the equivalence relation T1 ~ T2 be defined as
3226/// E(T1) == E(T2). E(T) is part of the ABI of values of type T. C type
3227/// compatibility requires equivalent treatment under the ABI, so
3228/// CCompatible(T1, T2) must imply E(T1) == E(T2), that is, CCompatible must be
3229/// a subset of ~. Crucially, however, it must be a proper subset because
3230/// CCompatible is not an equivalence relation: for example, int[] is compatible
3231/// with both int[1] and int[2], but the latter are not compatible with each
3232/// other. Therefore this encoding function must be careful to only distinguish
3233/// types if there is no third type with which they are both required to be
3234/// compatible.
3236 raw_ostream &OS, QualType QT) {
3237 // FIXME: Consider address space qualifiers.
3238 const Type *T = QT.getCanonicalType().getTypePtr();
3239
3240 // FIXME: Consider using the C++ type mangling when we encounter a construct
3241 // that is incompatible with C.
3242
3243 switch (T->getTypeClass()) {
3244 case Type::Atomic:
3246 Ctx, OS, cast<AtomicType>(T)->getValueType());
3247
3248 case Type::LValueReference:
3249 OS << "R";
3251 cast<ReferenceType>(T)->getPointeeType());
3252 return;
3253 case Type::RValueReference:
3254 OS << "O";
3256 cast<ReferenceType>(T)->getPointeeType());
3257 return;
3258
3259 case Type::Pointer:
3260 // C11 6.7.6.1p2:
3261 // For two pointer types to be compatible, both shall be identically
3262 // qualified and both shall be pointers to compatible types.
3263 // FIXME: we should also consider pointee types.
3264 OS << "P";
3265 return;
3266
3267 case Type::ObjCObjectPointer:
3268 case Type::BlockPointer:
3269 OS << "P";
3270 return;
3271
3272 case Type::Complex:
3273 OS << "C";
3275 Ctx, OS, cast<ComplexType>(T)->getElementType());
3276
3277 case Type::VariableArray:
3278 case Type::ConstantArray:
3279 case Type::IncompleteArray:
3280 case Type::ArrayParameter:
3281 // C11 6.7.6.2p6:
3282 // For two array types to be compatible, both shall have compatible
3283 // element types, and if both size specifiers are present, and are integer
3284 // constant expressions, then both size specifiers shall have the same
3285 // constant value [...]
3286 //
3287 // So since ElemType[N] has to be compatible ElemType[], we can't encode the
3288 // width of the array.
3289 OS << "A";
3291 Ctx, OS, cast<ArrayType>(T)->getElementType());
3292
3293 case Type::ObjCInterface:
3294 case Type::ObjCObject:
3295 OS << "<objc_object>";
3296 return;
3297
3298 case Type::Enum: {
3299 // C11 6.7.2.2p4:
3300 // Each enumerated type shall be compatible with char, a signed integer
3301 // type, or an unsigned integer type.
3302 //
3303 // So we have to treat enum types as integers.
3304 QualType UnderlyingType = cast<EnumType>(T)->getDecl()->getIntegerType();
3306 Ctx, OS, UnderlyingType.isNull() ? Ctx.IntTy : UnderlyingType);
3307 }
3308
3309 case Type::FunctionNoProto:
3310 case Type::FunctionProto: {
3311 // C11 6.7.6.3p15:
3312 // For two function types to be compatible, both shall specify compatible
3313 // return types. Moreover, the parameter type lists, if both are present,
3314 // shall agree in the number of parameters and in the use of the ellipsis
3315 // terminator; corresponding parameters shall have compatible types.
3316 //
3317 // That paragraph goes on to describe how unprototyped functions are to be
3318 // handled, which we ignore here. Unprototyped function pointers are hashed
3319 // as though they were prototyped nullary functions since thats probably
3320 // what the user meant. This behavior is non-conforming.
3321 // FIXME: If we add a "custom discriminator" function type attribute we
3322 // should encode functions as their discriminators.
3323 OS << "F";
3324 const auto *FuncType = cast<FunctionType>(T);
3325 encodeTypeForFunctionPointerAuth(Ctx, OS, FuncType->getReturnType());
3326 if (const auto *FPT = dyn_cast<FunctionProtoType>(FuncType)) {
3327 for (QualType Param : FPT->param_types()) {
3328 Param = Ctx.getSignatureParameterType(Param);
3329 encodeTypeForFunctionPointerAuth(Ctx, OS, Param);
3330 }
3331 if (FPT->isVariadic())
3332 OS << "z";
3333 }
3334 OS << "E";
3335 return;
3336 }
3337
3338 case Type::MemberPointer: {
3339 OS << "M";
3340 const auto *MPT = T->castAs<MemberPointerType>();
3341 encodeTypeForFunctionPointerAuth(Ctx, OS, QualType(MPT->getClass(), 0));
3342 encodeTypeForFunctionPointerAuth(Ctx, OS, MPT->getPointeeType());
3343 return;
3344 }
3345 case Type::ExtVector:
3346 case Type::Vector:
3347 OS << "Dv" << Ctx.getTypeSizeInChars(T).getQuantity();
3348 break;
3349
3350 // Don't bother discriminating based on these types.
3351 case Type::Pipe:
3352 case Type::BitInt:
3353 case Type::ConstantMatrix:
3354 OS << "?";
3355 return;
3356
3357 case Type::Builtin: {
3358 const auto *BTy = T->castAs<BuiltinType>();
3359 switch (BTy->getKind()) {
3360#define SIGNED_TYPE(Id, SingletonId) \
3361 case BuiltinType::Id: \
3362 OS << "i"; \
3363 return;
3364#define UNSIGNED_TYPE(Id, SingletonId) \
3365 case BuiltinType::Id: \
3366 OS << "i"; \
3367 return;
3368#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
3369#define BUILTIN_TYPE(Id, SingletonId)
3370#include "clang/AST/BuiltinTypes.def"
3371 llvm_unreachable("placeholder types should not appear here.");
3372
3373 case BuiltinType::Half:
3374 OS << "Dh";
3375 return;
3376 case BuiltinType::Float:
3377 OS << "f";
3378 return;
3379 case BuiltinType::Double:
3380 OS << "d";
3381 return;
3382 case BuiltinType::LongDouble:
3383 OS << "e";
3384 return;
3385 case BuiltinType::Float16:
3386 OS << "DF16_";
3387 return;
3388 case BuiltinType::Float128:
3389 OS << "g";
3390 return;
3391
3392 case BuiltinType::Void:
3393 OS << "v";
3394 return;
3395
3396 case BuiltinType::ObjCId:
3397 case BuiltinType::ObjCClass:
3398 case BuiltinType::ObjCSel:
3399 case BuiltinType::NullPtr:
3400 OS << "P";
3401 return;
3402
3403 // Don't bother discriminating based on OpenCL types.
3404 case BuiltinType::OCLSampler:
3405 case BuiltinType::OCLEvent:
3406 case BuiltinType::OCLClkEvent:
3407 case BuiltinType::OCLQueue:
3408 case BuiltinType::OCLReserveID:
3409 case BuiltinType::BFloat16:
3410 case BuiltinType::VectorQuad:
3411 case BuiltinType::VectorPair:
3412 OS << "?";
3413 return;
3414
3415 // Don't bother discriminating based on these seldom-used types.
3416 case BuiltinType::Ibm128:
3417 return;
3418#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3419 case BuiltinType::Id: \
3420 return;
3421#include "clang/Basic/OpenCLImageTypes.def"
3422#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3423 case BuiltinType::Id: \
3424 return;
3425#include "clang/Basic/OpenCLExtensionTypes.def"
3426#define SVE_TYPE(Name, Id, SingletonId) \
3427 case BuiltinType::Id: \
3428 return;
3429#include "clang/Basic/AArch64SVEACLETypes.def"
3430#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3431 case BuiltinType::Id: \
3432 return;
3433#include "clang/Basic/HLSLIntangibleTypes.def"
3434 case BuiltinType::Dependent:
3435 llvm_unreachable("should never get here");
3436#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
3437#include "clang/Basic/AMDGPUTypes.def"
3438 case BuiltinType::WasmExternRef:
3439#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3440#include "clang/Basic/RISCVVTypes.def"
3441 llvm_unreachable("not yet implemented");
3442 }
3443 llvm_unreachable("should never get here");
3444 }
3445 case Type::Record: {
3446 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
3447 const IdentifierInfo *II = RD->getIdentifier();
3448
3449 // In C++, an immediate typedef of an anonymous struct or union
3450 // is considered to name it for ODR purposes, but C's specification
3451 // of type compatibility does not have a similar rule. Using the typedef
3452 // name in function type discriminators anyway, as we do here,
3453 // therefore technically violates the C standard: two function pointer
3454 // types defined in terms of two typedef'd anonymous structs with
3455 // different names are formally still compatible, but we are assigning
3456 // them different discriminators and therefore incompatible ABIs.
3457 //
3458 // This is a relatively minor violation that significantly improves
3459 // discrimination in some cases and has not caused problems in
3460 // practice. Regardless, it is now part of the ABI in places where
3461 // function type discrimination is used, and it can no longer be
3462 // changed except on new platforms.
3463
3464 if (!II)
3465 if (const TypedefNameDecl *Typedef = RD->getTypedefNameForAnonDecl())
3466 II = Typedef->getDeclName().getAsIdentifierInfo();
3467
3468 if (!II) {
3469 OS << "<anonymous_record>";
3470 return;
3471 }
3472 OS << II->getLength() << II->getName();
3473 return;
3474 }
3475 case Type::HLSLAttributedResource:
3476 llvm_unreachable("should never get here");
3477 break;
3478 case Type::DeducedTemplateSpecialization:
3479 case Type::Auto:
3480#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3481#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3482#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3483#define ABSTRACT_TYPE(Class, Base)
3484#define TYPE(Class, Base)
3485#include "clang/AST/TypeNodes.inc"
3486 llvm_unreachable("unexpected non-canonical or dependent type!");
3487 return;
3488 }
3489}
3490
3492 assert(!T->isDependentType() &&
3493 "cannot compute type discriminator of a dependent type");
3494
3495 SmallString<256> Str;
3496 llvm::raw_svector_ostream Out(Str);
3497
3499 T = T->getPointeeType();
3500
3501 if (T->isFunctionType()) {
3503 } else {
3504 T = T.getUnqualifiedType();
3505 // Calls to member function pointers don't need to worry about
3506 // language interop or the laxness of the C type compatibility rules.
3507 // We just mangle the member pointer type directly, which is
3508 // implicitly much stricter about type matching. However, we do
3509 // strip any top-level exception specification before this mangling.
3510 // C++23 requires calls to work when the function type is convertible
3511 // to the pointer type by a function pointer conversion, which can
3512 // change the exception specification. This does not technically
3513 // require the exception specification to not affect representation,
3514 // because the function pointer conversion is still always a direct
3515 // value conversion and therefore an opportunity to resign the
3516 // pointer. (This is in contrast to e.g. qualification conversions,
3517 // which can be applied in nested pointer positions, effectively
3518 // requiring qualified and unqualified representations to match.)
3519 // However, it is pragmatic to ignore exception specifications
3520 // because it allows a certain amount of `noexcept` mismatching
3521 // to not become a visible ODR problem. This also leaves some
3522 // room for the committee to add laxness to function pointer
3523 // conversions in future standards.
3524 if (auto *MPT = T->getAs<MemberPointerType>())
3525 if (MPT->isMemberFunctionPointer()) {
3526 QualType PointeeType = MPT->getPointeeType();
3527 if (PointeeType->castAs<FunctionProtoType>()->getExceptionSpecType() !=
3528 EST_None) {
3530 T = getMemberPointerType(FT, MPT->getClass());
3531 }
3532 }
3533 std::unique_ptr<MangleContext> MC(createMangleContext());
3534 MC->mangleCanonicalTypeName(T, Out);
3535 }
3536
3537 return llvm::getPointerAuthStableSipHash(Str);
3538}
3539
3541 Qualifiers::GC GCAttr) const {
3542 QualType CanT = getCanonicalType(T);
3543 if (CanT.getObjCGCAttr() == GCAttr)
3544 return T;
3545
3546 if (const auto *ptr = T->getAs<PointerType>()) {
3547 QualType Pointee = ptr->getPointeeType();
3548 if (Pointee->isAnyPointerType()) {
3549 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
3550 return getPointerType(ResultType);
3551 }
3552 }
3553
3554 // If we are composing extended qualifiers together, merge together
3555 // into one ExtQuals node.
3556 QualifierCollector Quals;
3557 const Type *TypeNode = Quals.strip(T);
3558
3559 // If this type already has an ObjCGC specified, it cannot get
3560 // another one.
3561 assert(!Quals.hasObjCGCAttr() &&
3562 "Type cannot have multiple ObjCGCs!");
3563 Quals.addObjCGCAttr(GCAttr);
3564
3565 return getExtQualType(TypeNode, Quals);
3566}
3567
3569 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3570 QualType Pointee = Ptr->getPointeeType();
3571 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3572 return getPointerType(removeAddrSpaceQualType(Pointee));
3573 }
3574 }
3575 return T;
3576}
3577
3579 QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull,
3580 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3581 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3582
3583 llvm::FoldingSetNodeID ID;
3584 CountAttributedType::Profile(ID, WrappedTy, CountExpr, CountInBytes, OrNull);
3585
3586 void *InsertPos = nullptr;
3587 CountAttributedType *CATy =
3588 CountAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
3589 if (CATy)
3590 return QualType(CATy, 0);
3591
3592 QualType CanonTy = getCanonicalType(WrappedTy);
3593 size_t Size = CountAttributedType::totalSizeToAlloc<TypeCoupledDeclRefInfo>(
3594 DependentDecls.size());
3596 new (CATy) CountAttributedType(WrappedTy, CanonTy, CountExpr, CountInBytes,
3597 OrNull, DependentDecls);
3598 Types.push_back(CATy);
3599 CountAttributedTypes.InsertNode(CATy, InsertPos);
3600
3601 return QualType(CATy, 0);
3602}
3603
3606 llvm::function_ref<QualType(QualType)> Adjust) const {
3607 switch (Orig->getTypeClass()) {
3608 case Type::Attributed: {
3609 const auto *AT = cast<AttributedType>(Orig);
3610 return getAttributedType(AT->getAttrKind(),
3611 adjustType(AT->getModifiedType(), Adjust),
3612 adjustType(AT->getEquivalentType(), Adjust),
3613 AT->getAttr());
3614 }
3615
3616 case Type::BTFTagAttributed: {
3617 const auto *BTFT = dyn_cast<BTFTagAttributedType>(Orig);
3618 return getBTFTagAttributedType(BTFT->getAttr(),
3619 adjustType(BTFT->getWrappedType(), Adjust));
3620 }
3621
3622 case Type::Elaborated: {
3623 const auto *ET = cast<ElaboratedType>(Orig);
3624 return getElaboratedType(ET->getKeyword(), ET->getQualifier(),
3625 adjustType(ET->getNamedType(), Adjust));
3626 }
3627
3628 case Type::Paren:
3629 return getParenType(
3630 adjustType(cast<ParenType>(Orig)->getInnerType(), Adjust));
3631
3632 case Type::Adjusted: {
3633 const auto *AT = cast<AdjustedType>(Orig);
3634 return getAdjustedType(AT->getOriginalType(),
3635 adjustType(AT->getAdjustedType(), Adjust));
3636 }
3637
3638 case Type::MacroQualified: {
3639 const auto *MQT = cast<MacroQualifiedType>(Orig);
3640 return getMacroQualifiedType(adjustType(MQT->getUnderlyingType(), Adjust),
3641 MQT->getMacroIdentifier());
3642 }
3643
3644 default:
3645 return Adjust(Orig);
3646 }
3647}
3648
3650 FunctionType::ExtInfo Info) {
3651 if (T->getExtInfo() == Info)
3652 return T;
3653
3655 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3656 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3657 } else {
3658 const auto *FPT = cast<FunctionProtoType>(T);
3659 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3660 EPI.ExtInfo = Info;
3661 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3662 }
3663
3664 return cast<FunctionType>(Result.getTypePtr());
3665}
3666
3668 QualType ResultType) {
3669 return adjustType(FunctionType, [&](QualType Orig) {
3670 if (const auto *FNPT = Orig->getAs<FunctionNoProtoType>())
3671 return getFunctionNoProtoType(ResultType, FNPT->getExtInfo());
3672
3673 const auto *FPT = Orig->castAs<FunctionProtoType>();
3674 return getFunctionType(ResultType, FPT->getParamTypes(),
3675 FPT->getExtProtoInfo());
3676 });
3677}
3678
3680 QualType ResultType) {
3681 FD = FD->getMostRecentDecl();
3682 while (true) {
3683 FD->setType(adjustFunctionResultType(FD->getType(), ResultType));
3684 if (FunctionDecl *Next = FD->getPreviousDecl())
3685 FD = Next;
3686 else
3687 break;
3688 }
3690 L->DeducedReturnType(FD, ResultType);
3691}
3692
3693/// Get a function type and produce the equivalent function type with the
3694/// specified exception specification. Type sugar that can be present on a
3695/// declaration of a function with an exception specification is permitted
3696/// and preserved. Other type sugar (for instance, typedefs) is not.
3698 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3699 return adjustType(Orig, [&](QualType Ty) {
3700 const auto *Proto = Ty->castAs<FunctionProtoType>();
3701 return getFunctionType(Proto->getReturnType(), Proto->getParamTypes(),
3702 Proto->getExtProtoInfo().withExceptionSpec(ESI));
3703 });
3704}
3705
3707 QualType U) const {
3708 return hasSameType(T, U) ||
3709 (getLangOpts().CPlusPlus17 &&
3712}
3713
3715 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3716 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3717 SmallVector<QualType, 16> Args(Proto->param_types().size());
3718 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3719 Args[i] = removePtrSizeAddrSpace(Proto->param_types()[i]);
3720 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3721 }
3722
3723 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3724 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3725 return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3726 }
3727
3728 return T;
3729}
3730
3732 return hasSameType(T, U) ||
3735}
3736
3738 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3739 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3740 EPI.ExtParameterInfos = nullptr;
3741 return getFunctionType(Proto->getReturnType(), Proto->param_types(), EPI);
3742 }
3743 return T;
3744}
3745
3747 QualType U) const {
3750}
3751
3754 bool AsWritten) {
3755 // Update the type.
3756 QualType Updated =
3758 FD->setType(Updated);
3759
3760 if (!AsWritten)
3761 return;
3762
3763 // Update the type in the type source information too.
3764 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3765 // If the type and the type-as-written differ, we may need to update
3766 // the type-as-written too.
3767 if (TSInfo->getType() != FD->getType())
3768 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3769
3770 // FIXME: When we get proper type location information for exceptions,
3771 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3772 // up the TypeSourceInfo;
3773 assert(TypeLoc::getFullDataSizeForType(Updated) ==
3774 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3775 "TypeLoc size mismatch from updating exception specification");
3776 TSInfo->overrideType(Updated);
3777 }
3778}
3779
3780/// getComplexType - Return the uniqued reference to the type for a complex
3781/// number with the specified element type.
3783 // Unique pointers, to guarantee there is only one pointer of a particular
3784 // structure.
3785 llvm::FoldingSetNodeID ID;
3787
3788 void *InsertPos = nullptr;
3789 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3790 return QualType(CT, 0);
3791
3792 // If the pointee type isn't canonical, this won't be a canonical type either,
3793 // so fill in the canonical type field.
3794 QualType Canonical;
3795 if (!T.isCanonical()) {
3796 Canonical = getComplexType(getCanonicalType(T));
3797
3798 // Get the new insert position for the node we care about.
3799 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3800 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3801 }
3802 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
3803 Types.push_back(New);
3804 ComplexTypes.InsertNode(New, InsertPos);
3805 return QualType(New, 0);
3806}
3807
3808/// getPointerType - Return the uniqued reference to the type for a pointer to
3809/// the specified type.
3811 // Unique pointers, to guarantee there is only one pointer of a particular
3812 // structure.
3813 llvm::FoldingSetNodeID ID;
3815
3816 void *InsertPos = nullptr;
3817 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3818 return QualType(PT, 0);
3819
3820 // If the pointee type isn't canonical, this won't be a canonical type either,
3821 // so fill in the canonical type field.
3822 QualType Canonical;
3823 if (!T.isCanonical()) {
3824 Canonical = getPointerType(getCanonicalType(T));
3825
3826 // Get the new insert position for the node we care about.
3827 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3828 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3829 }
3830 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
3831 Types.push_back(New);
3832 PointerTypes.InsertNode(New, InsertPos);
3833 return QualType(New, 0);
3834}
3835
3837 llvm::FoldingSetNodeID ID;
3838 AdjustedType::Profile(ID, Orig, New);
3839 void *InsertPos = nullptr;
3840 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3841 if (AT)
3842 return QualType(AT, 0);
3843
3844 QualType Canonical = getCanonicalType(New);
3845
3846 // Get the new insert position for the node we care about.
3847 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3848 assert(!AT && "Shouldn't be in the map!");
3849
3850 AT = new (*this, alignof(AdjustedType))
3851 AdjustedType(Type::Adjusted, Orig, New, Canonical);
3852 Types.push_back(AT);
3853 AdjustedTypes.InsertNode(AT, InsertPos);
3854 return QualType(AT, 0);
3855}
3856
3858 llvm::FoldingSetNodeID ID;
3859 AdjustedType::Profile(ID, Orig, Decayed);
3860 void *InsertPos = nullptr;
3861 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3862 if (AT)
3863 return QualType(AT, 0);
3864
3865 QualType Canonical = getCanonicalType(Decayed);
3866
3867 // Get the new insert position for the node we care about.
3868 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3869 assert(!AT && "Shouldn't be in the map!");
3870
3871 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
3872 Types.push_back(AT);
3873 AdjustedTypes.InsertNode(AT, InsertPos);
3874 return QualType(AT, 0);
3875}
3876
3878 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
3879
3880 QualType Decayed;
3881
3882 // C99 6.7.5.3p7:
3883 // A declaration of a parameter as "array of type" shall be
3884 // adjusted to "qualified pointer to type", where the type
3885 // qualifiers (if any) are those specified within the [ and ] of
3886 // the array type derivation.
3887 if (T->isArrayType())
3888 Decayed = getArrayDecayedType(T);
3889
3890 // C99 6.7.5.3p8:
3891 // A declaration of a parameter as "function returning type"
3892 // shall be adjusted to "pointer to function returning type", as
3893 // in 6.3.2.1.
3894 if (T->isFunctionType())
3895 Decayed = getPointerType(T);
3896
3897 return getDecayedType(T, Decayed);
3898}
3899
3901 if (Ty->isArrayParameterType())
3902 return Ty;
3903 assert(Ty->isConstantArrayType() && "Ty must be an array type.");
3904 const auto *ATy = cast<ConstantArrayType>(Ty);
3905 llvm::FoldingSetNodeID ID;
3906 ATy->Profile(ID, *this, ATy->getElementType(), ATy->getZExtSize(),
3907 ATy->getSizeExpr(), ATy->getSizeModifier(),
3908 ATy->getIndexTypeQualifiers().getAsOpaqueValue());
3909 void *InsertPos = nullptr;
3910 ArrayParameterType *AT =
3911 ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
3912 if (AT)
3913 return QualType(AT, 0);
3914
3915 QualType Canonical;
3916 if (!Ty.isCanonical()) {
3917 Canonical = getArrayParameterType(getCanonicalType(Ty));
3918
3919 // Get the new insert position for the node we care about.
3920 AT = ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
3921 assert(!AT && "Shouldn't be in the map!");
3922 }
3923
3924 AT = new (*this, alignof(ArrayParameterType))
3925 ArrayParameterType(ATy, Canonical);
3926 Types.push_back(AT);
3927 ArrayParameterTypes.InsertNode(AT, InsertPos);
3928 return QualType(AT, 0);
3929}
3930
3931/// getBlockPointerType - Return the uniqued reference to the type for
3932/// a pointer to the specified block.
3934 assert(T->isFunctionType() && "block of function types only");
3935 // Unique pointers, to guarantee there is only one block of a particular
3936 // structure.
3937 llvm::FoldingSetNodeID ID;
3939
3940 void *InsertPos = nullptr;
3941 if (BlockPointerType *PT =
3942 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3943 return QualType(PT, 0);
3944
3945 // If the block pointee type isn't canonical, this won't be a canonical
3946 // type either so fill in the canonical type field.
3947 QualType Canonical;
3948 if (!T.isCanonical()) {
3950
3951 // Get the new insert position for the node we care about.
3952 BlockPointerType *NewIP =
3953 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3954 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3955 }
3956 auto *New =
3957 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
3958 Types.push_back(New);
3959 BlockPointerTypes.InsertNode(New, InsertPos);
3960 return QualType(New, 0);
3961}
3962
3963/// getLValueReferenceType - Return the uniqued reference to the type for an
3964/// lvalue reference to the specified type.
3966ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
3967 assert((!T->isPlaceholderType() ||
3968 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
3969 "Unresolved placeholder type");
3970
3971 // Unique pointers, to guarantee there is only one pointer of a particular
3972 // structure.
3973 llvm::FoldingSetNodeID ID;
3974 ReferenceType::Profile(ID, T, SpelledAsLValue);
3975
3976 void *InsertPos = nullptr;
3977 if (LValueReferenceType *RT =
3978 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3979 return QualType(RT, 0);
3980
3981 const auto *InnerRef = T->getAs<ReferenceType>();
3982
3983 // If the referencee type isn't canonical, this won't be a canonical type
3984 // either, so fill in the canonical type field.
3985 QualType Canonical;
3986 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
3987 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3988 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
3989
3990 // Get the new insert position for the node we care about.
3991 LValueReferenceType *NewIP =
3992 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3993 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3994 }
3995
3996 auto *New = new (*this, alignof(LValueReferenceType))
3997 LValueReferenceType(T, Canonical, SpelledAsLValue);
3998 Types.push_back(New);
3999 LValueReferenceTypes.InsertNode(New, InsertPos);
4000
4001 return QualType(New, 0);
4002}
4003
4004/// getRValueReferenceType - Return the uniqued reference to the type for an
4005/// rvalue reference to the specified type.
4007 assert((!T->isPlaceholderType() ||
4008 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4009 "Unresolved placeholder type");
4010
4011 // Unique pointers, to guarantee there is only one pointer of a particular
4012 // structure.
4013 llvm::FoldingSetNodeID ID;
4014 ReferenceType::Profile(ID, T, false);
4015
4016 void *InsertPos = nullptr;
4017 if (RValueReferenceType *RT =
4018 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4019 return QualType(RT, 0);
4020
4021 const auto *InnerRef = T->getAs<ReferenceType>();
4022
4023 // If the referencee type isn't canonical, this won't be a canonical type
4024 // either, so fill in the canonical type field.
4025 QualType Canonical;
4026 if (InnerRef || !T.isCanonical()) {
4027 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4028 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
4029
4030 // Get the new insert position for the node we care about.
4031 RValueReferenceType *NewIP =
4032 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4033 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4034 }
4035
4036 auto *New = new (*this, alignof(RValueReferenceType))
4037 RValueReferenceType(T, Canonical);
4038 Types.push_back(New);
4039 RValueReferenceTypes.InsertNode(New, InsertPos);
4040 return QualType(New, 0);
4041}
4042
4043/// getMemberPointerType - Return the uniqued reference to the type for a
4044/// member pointer to the specified type, in the specified class.
4046 // Unique pointers, to guarantee there is only one pointer of a particular
4047 // structure.
4048 llvm::FoldingSetNodeID ID;
4049 MemberPointerType::Profile(ID, T, Cls);
4050
4051 void *InsertPos = nullptr;
4052 if (MemberPointerType *PT =
4053 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4054 return QualType(PT, 0);
4055
4056 // If the pointee or class type isn't canonical, this won't be a canonical
4057 // type either, so fill in the canonical type field.
4058 QualType Canonical;
4059 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
4061
4062 // Get the new insert position for the node we care about.
4063 MemberPointerType *NewIP =
4064 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4065 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4066 }
4067 auto *New = new (*this, alignof(MemberPointerType))
4068 MemberPointerType(T, Cls, Canonical);
4069 Types.push_back(New);
4070 MemberPointerTypes.InsertNode(New, InsertPos);
4071 return QualType(New, 0);
4072}
4073
4074/// getConstantArrayType - Return the unique reference to the type for an
4075/// array of the specified element type.
4077 const llvm::APInt &ArySizeIn,
4078 const Expr *SizeExpr,
4080 unsigned IndexTypeQuals) const {
4081 assert((EltTy->isDependentType() ||
4082 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
4083 "Constant array of VLAs is illegal!");
4084
4085 // We only need the size as part of the type if it's instantiation-dependent.
4086 if (SizeExpr && !SizeExpr->isInstantiationDependent())
4087 SizeExpr = nullptr;
4088
4089 // Convert the array size into a canonical width matching the pointer size for
4090 // the target.
4091 llvm::APInt ArySize(ArySizeIn);
4092 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
4093
4094 llvm::FoldingSetNodeID ID;
4095 ConstantArrayType::Profile(ID, *this, EltTy, ArySize.getZExtValue(), SizeExpr,
4096 ASM, IndexTypeQuals);
4097
4098 void *InsertPos = nullptr;
4099 if (ConstantArrayType *ATP =
4100 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
4101 return QualType(ATP, 0);
4102
4103 // If the element type isn't canonical or has qualifiers, or the array bound
4104 // is instantiation-dependent, this won't be a canonical type either, so fill
4105 // in the canonical type field.
4106 QualType Canon;
4107 // FIXME: Check below should look for qualifiers behind sugar.
4108 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
4109 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4110 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
4111 ASM, IndexTypeQuals);
4112 Canon = getQualifiedType(Canon, canonSplit.Quals);
4113
4114 // Get the new insert position for the node we care about.
4115 ConstantArrayType *NewIP =
4116 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
4117 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4118 }
4119
4120 auto *New = ConstantArrayType::Create(*this, EltTy, Canon, ArySize, SizeExpr,
4121 ASM, IndexTypeQuals);
4122 ConstantArrayTypes.InsertNode(New, InsertPos);
4123 Types.push_back(New);
4124 return QualType(New, 0);
4125}
4126
4127/// getVariableArrayDecayedType - Turns the given type, which may be
4128/// variably-modified, into the corresponding type with all the known
4129/// sizes replaced with [*].
4131 // Vastly most common case.
4132 if (!type->isVariablyModifiedType()) return type;
4133
4134 QualType result;
4135
4136 SplitQualType split = type.getSplitDesugaredType();
4137 const Type *ty = split.Ty;
4138 switch (ty->getTypeClass()) {
4139#define TYPE(Class, Base)
4140#define ABSTRACT_TYPE(Class, Base)
4141#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4142#include "clang/AST/TypeNodes.inc"
4143 llvm_unreachable("didn't desugar past all non-canonical types?");
4144
4145 // These types should never be variably-modified.
4146 case Type::Builtin:
4147 case Type::Complex:
4148 case Type::Vector:
4149 case Type::DependentVector:
4150 case Type::ExtVector:
4151 case Type::DependentSizedExtVector:
4152 case Type::ConstantMatrix:
4153 case Type::DependentSizedMatrix:
4154 case Type::DependentAddressSpace:
4155 case Type::ObjCObject:
4156 case Type::ObjCInterface:
4157 case Type::ObjCObjectPointer:
4158 case Type::Record:
4159 case Type::Enum:
4160 case Type::UnresolvedUsing:
4161 case Type::TypeOfExpr:
4162 case Type::TypeOf:
4163 case Type::Decltype:
4164 case Type::UnaryTransform:
4165 case Type::DependentName:
4166 case Type::InjectedClassName:
4167 case Type::TemplateSpecialization:
4168 case Type::DependentTemplateSpecialization:
4169 case Type::TemplateTypeParm:
4170 case Type::SubstTemplateTypeParmPack:
4171 case Type::Auto:
4172 case Type::DeducedTemplateSpecialization:
4173 case Type::PackExpansion:
4174 case Type::PackIndexing:
4175 case Type::BitInt:
4176 case Type::DependentBitInt:
4177 case Type::ArrayParameter:
4178 case Type::HLSLAttributedResource:
4179 llvm_unreachable("type should never be variably-modified");
4180
4181 // These types can be variably-modified but should never need to
4182 // further decay.
4183 case Type::FunctionNoProto:
4184 case Type::FunctionProto:
4185 case Type::BlockPointer:
4186 case Type::MemberPointer:
4187 case Type::Pipe:
4188 return type;
4189
4190 // These types can be variably-modified. All these modifications
4191 // preserve structure except as noted by comments.
4192 // TODO: if we ever care about optimizing VLAs, there are no-op
4193 // optimizations available here.
4194 case Type::Pointer:
4196 cast<PointerType>(ty)->getPointeeType()));
4197 break;
4198
4199 case Type::LValueReference: {
4200 const auto *lv = cast<LValueReferenceType>(ty);
4201 result = getLValueReferenceType(
4202 getVariableArrayDecayedType(lv->getPointeeType()),
4203 lv->isSpelledAsLValue());
4204 break;
4205 }
4206
4207 case Type::RValueReference: {
4208 const auto *lv = cast<RValueReferenceType>(ty);
4209 result = getRValueReferenceType(
4210 getVariableArrayDecayedType(lv->getPointeeType()));
4211 break;
4212 }
4213
4214 case Type::Atomic: {
4215 const auto *at = cast<AtomicType>(ty);
4216 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
4217 break;
4218 }
4219
4220 case Type::ConstantArray: {
4221 const auto *cat = cast<ConstantArrayType>(ty);
4222 result = getConstantArrayType(
4223 getVariableArrayDecayedType(cat->getElementType()),
4224 cat->getSize(),
4225 cat->getSizeExpr(),
4226 cat->getSizeModifier(),
4227 cat->getIndexTypeCVRQualifiers());
4228 break;
4229 }
4230
4231 case Type::DependentSizedArray: {
4232 const auto *dat = cast<DependentSizedArrayType>(ty);
4234 getVariableArrayDecayedType(dat->getElementType()),
4235 dat->getSizeExpr(),
4236 dat->getSizeModifier(),
4237 dat->getIndexTypeCVRQualifiers(),
4238 dat->getBracketsRange());
4239 break;
4240 }
4241
4242 // Turn incomplete types into [*] types.
4243 case Type::IncompleteArray: {
4244 const auto *iat = cast<IncompleteArrayType>(ty);
4245 result =
4247 /*size*/ nullptr, ArraySizeModifier::Normal,
4248 iat->getIndexTypeCVRQualifiers(), SourceRange());
4249 break;
4250 }
4251
4252 // Turn VLA types into [*] types.
4253 case Type::VariableArray: {
4254 const auto *vat = cast<VariableArrayType>(ty);
4255 result = getVariableArrayType(
4256 getVariableArrayDecayedType(vat->getElementType()),
4257 /*size*/ nullptr, ArraySizeModifier::Star,
4258 vat->getIndexTypeCVRQualifiers(), vat->getBracketsRange());
4259 break;
4260 }
4261 }
4262
4263 // Apply the top-level qualifiers from the original.
4264 return getQualifiedType(result, split.Quals);
4265}
4266
4267/// getVariableArrayType - Returns a non-unique reference to the type for a
4268/// variable array of the specified element type.
4271 unsigned IndexTypeQuals,
4272 SourceRange Brackets) const {
4273 // Since we don't unique expressions, it isn't possible to unique VLA's
4274 // that have an expression provided for their size.
4275 QualType Canon;
4276
4277 // Be sure to pull qualifiers off the element type.
4278 // FIXME: Check below should look for qualifiers behind sugar.
4279 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
4280 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4281 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
4282 IndexTypeQuals, Brackets);
4283 Canon = getQualifiedType(Canon, canonSplit.Quals);
4284 }
4285
4286 auto *New = new (*this, alignof(VariableArrayType))
4287 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
4288
4289 VariableArrayTypes.push_back(New);
4290 Types.push_back(New);
4291 return QualType(New, 0);
4292}
4293
4294/// getDependentSizedArrayType - Returns a non-unique reference to
4295/// the type for a dependently-sized array of the specified element
4296/// type.
4298 Expr *numElements,
4300 unsigned elementTypeQuals,
4301 SourceRange brackets) const {
4302 assert((!numElements || numElements->isTypeDependent() ||
4303 numElements->isValueDependent()) &&
4304 "Size must be type- or value-dependent!");
4305
4306 SplitQualType canonElementType = getCanonicalType(elementType).split();
4307
4308 void *insertPos = nullptr;
4309 llvm::FoldingSetNodeID ID;
4311 ID, *this, numElements ? QualType(canonElementType.Ty, 0) : elementType,
4312 ASM, elementTypeQuals, numElements);
4313
4314 // Look for an existing type with these properties.
4315 DependentSizedArrayType *canonTy =
4316 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4317
4318 // Dependently-sized array types that do not have a specified number
4319 // of elements will have their sizes deduced from a dependent
4320 // initializer.
4321 if (!numElements) {
4322 if (canonTy)
4323 return QualType(canonTy, 0);
4324
4325 auto *newType = new (*this, alignof(DependentSizedArrayType))
4326 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
4327 elementTypeQuals, brackets);
4328 DependentSizedArrayTypes.InsertNode(newType, insertPos);
4329 Types.push_back(newType);
4330 return QualType(newType, 0);
4331 }
4332
4333 // If we don't have one, build one.
4334 if (!canonTy) {
4335 canonTy = new (*this, alignof(DependentSizedArrayType))
4336 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
4337 numElements, ASM, elementTypeQuals, brackets);
4338 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
4339 Types.push_back(canonTy);
4340 }
4341
4342 // Apply qualifiers from the element type to the array.
4343 QualType canon = getQualifiedType(QualType(canonTy,0),
4344 canonElementType.Quals);
4345
4346 // If we didn't need extra canonicalization for the element type or the size
4347 // expression, then just use that as our result.
4348 if (QualType(canonElementType.Ty, 0) == elementType &&
4349 canonTy->getSizeExpr() == numElements)
4350 return canon;
4351
4352 // Otherwise, we need to build a type which follows the spelling
4353 // of the element type.
4354 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
4355 DependentSizedArrayType(elementType, canon, numElements, ASM,
4356 elementTypeQuals, brackets);
4357 Types.push_back(sugaredType);
4358 return QualType(sugaredType, 0);
4359}
4360
4363 unsigned elementTypeQuals) const {
4364 llvm::FoldingSetNodeID ID;
4365 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
4366
4367 void *insertPos = nullptr;
4368 if (IncompleteArrayType *iat =
4369 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
4370 return QualType(iat, 0);
4371
4372 // If the element type isn't canonical, this won't be a canonical type
4373 // either, so fill in the canonical type field. We also have to pull
4374 // qualifiers off the element type.
4375 QualType canon;
4376
4377 // FIXME: Check below should look for qualifiers behind sugar.
4378 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
4379 SplitQualType canonSplit = getCanonicalType(elementType).split();
4380 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
4381 ASM, elementTypeQuals);
4382 canon = getQualifiedType(canon, canonSplit.Quals);
4383
4384 // Get the new insert position for the node we care about.
4385 IncompleteArrayType *existing =
4386 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4387 assert(!existing && "Shouldn't be in the map!"); (void) existing;
4388 }
4389
4390 auto *newType = new (*this, alignof(IncompleteArrayType))
4391 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
4392
4393 IncompleteArrayTypes.InsertNode(newType, insertPos);
4394 Types.push_back(newType);
4395 return QualType(newType, 0);
4396}
4397
4400#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
4401 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
4402 NUMVECTORS};
4403
4404#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
4405 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
4406
4407 switch (Ty->getKind()) {
4408 default:
4409 llvm_unreachable("Unsupported builtin vector type");
4410
4411#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4412 ElBits, NF, IsSigned) \
4413 case BuiltinType::Id: \
4414 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4415 llvm::ElementCount::getScalable(NumEls), NF};
4416#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4417 ElBits, NF) \
4418 case BuiltinType::Id: \
4419 return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy), \
4420 llvm::ElementCount::getScalable(NumEls), NF};
4421#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4422 ElBits, NF) \
4423 case BuiltinType::Id: \
4424 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4425#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4426 ElBits, NF) \
4427 case BuiltinType::Id: \
4428 return {MFloat8Ty, llvm::ElementCount::getScalable(NumEls), NF};
4429#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4430 case BuiltinType::Id: \
4431 return {BoolTy, llvm::ElementCount::getScalable(NumEls), NF};
4432#define SVE_TYPE(Name, Id, SingletonId)
4433#include "clang/Basic/AArch64SVEACLETypes.def"
4434
4435#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4436 IsSigned) \
4437 case BuiltinType::Id: \
4438 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4439 llvm::ElementCount::getScalable(NumEls), NF};
4440#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4441 case BuiltinType::Id: \
4442 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4443 llvm::ElementCount::getScalable(NumEls), NF};
4444#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4445 case BuiltinType::Id: \
4446 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4447#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4448 case BuiltinType::Id: \
4449 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4450#include "clang/Basic/RISCVVTypes.def"
4451 }
4452}
4453
4454/// getExternrefType - Return a WebAssembly externref type, which represents an
4455/// opaque reference to a host value.
4457 if (Target->getTriple().isWasm() && Target->hasFeature("reference-types")) {
4458#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4459 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4460 return SingletonId;
4461#include "clang/Basic/WebAssemblyReferenceTypes.def"
4462 }
4463 llvm_unreachable(
4464 "shouldn't try to generate type externref outside WebAssembly target");
4465}
4466
4467/// getScalableVectorType - Return the unique reference to a scalable vector
4468/// type of the specified element type and size. VectorType must be a built-in
4469/// type.
4471 unsigned NumFields) const {
4472 if (Target->hasAArch64SVETypes()) {
4473 uint64_t EltTySize = getTypeSize(EltTy);
4474
4475#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4476 ElBits, NF, IsSigned) \
4477 if (EltTy->hasIntegerRepresentation() && !EltTy->isBooleanType() && \
4478 EltTy->hasSignedIntegerRepresentation() == IsSigned && \
4479 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4480 return SingletonId; \
4481 }
4482#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4483 ElBits, NF) \
4484 if (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4485 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4486 return SingletonId; \
4487 }
4488#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4489 ElBits, NF) \
4490 if (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4491 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4492 return SingletonId; \
4493 }
4494#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4495 ElBits, NF) \
4496 if (EltTy->isMFloat8Type() && EltTySize == ElBits && \
4497 NumElts == (NumEls * NF) && NumFields == 1) { \
4498 return SingletonId; \
4499 }
4500#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4501 if (EltTy->isBooleanType() && NumElts == (NumEls * NF) && NumFields == 1) \
4502 return SingletonId;
4503#define SVE_TYPE(Name, Id, SingletonId)
4504#include "clang/Basic/AArch64SVEACLETypes.def"
4505 } else if (Target->hasRISCVVTypes()) {
4506 uint64_t EltTySize = getTypeSize(EltTy);
4507#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4508 IsFP, IsBF) \
4509 if (!EltTy->isBooleanType() && \
4510 ((EltTy->hasIntegerRepresentation() && \
4511 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4512 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4513 IsFP && !IsBF) || \
4514 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4515 IsBF && !IsFP)) && \
4516 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4517 return SingletonId;
4518#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4519 if (EltTy->isBooleanType() && NumElts == NumEls) \
4520 return SingletonId;
4521#include "clang/Basic/RISCVVTypes.def"
4522 }
4523 return QualType();
4524}
4525
4526/// getVectorType - Return the unique reference to a vector type of
4527/// the specified element type and size. VectorType must be a built-in type.
4529 VectorKind VecKind) const {
4530 assert(vecType->isBuiltinType() ||
4531 (vecType->isBitIntType() &&
4532 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4533 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits()) &&
4534 vecType->castAs<BitIntType>()->getNumBits() >= 8));
4535
4536 // Check if we've already instantiated a vector of this type.
4537 llvm::FoldingSetNodeID ID;
4538 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
4539
4540 void *InsertPos = nullptr;
4541 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4542 return QualType(VTP, 0);
4543
4544 // If the element type isn't canonical, this won't be a canonical type either,
4545 // so fill in the canonical type field.
4546 QualType Canonical;
4547 if (!vecType.isCanonical()) {
4548 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4549
4550 // Get the new insert position for the node we care about.
4551 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4552 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4553 }
4554 auto *New = new (*this, alignof(VectorType))
4555 VectorType(vecType, NumElts, Canonical, VecKind);
4556 VectorTypes.InsertNode(New, InsertPos);
4557 Types.push_back(New);
4558 return QualType(New, 0);
4559}
4560
4562 SourceLocation AttrLoc,
4563 VectorKind VecKind) const {
4564 llvm::FoldingSetNodeID ID;
4565 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4566 VecKind);
4567 void *InsertPos = nullptr;
4568 DependentVectorType *Canon =
4569 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4571
4572 if (Canon) {
4573 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4574 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4575 } else {
4576 QualType CanonVecTy = getCanonicalType(VecType);
4577 if (CanonVecTy == VecType) {
4578 New = new (*this, alignof(DependentVectorType))
4579 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4580
4581 DependentVectorType *CanonCheck =
4582 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4583 assert(!CanonCheck &&
4584 "Dependent-sized vector_size canonical type broken");
4585 (void)CanonCheck;
4586 DependentVectorTypes.InsertNode(New, InsertPos);
4587 } else {
4588 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4589 SourceLocation(), VecKind);
4590 New = new (*this, alignof(DependentVectorType))
4591 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4592 }
4593 }
4594
4595 Types.push_back(New);
4596 return QualType(New, 0);
4597}
4598
4599/// getExtVectorType - Return the unique reference to an extended vector type of
4600/// the specified element type and size. VectorType must be a built-in type.
4602 unsigned NumElts) const {
4603 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4604 (vecType->isBitIntType() &&
4605 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4606 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits()) &&
4607 vecType->castAs<BitIntType>()->getNumBits() >= 8));
4608
4609 // Check if we've already instantiated a vector of this type.
4610 llvm::FoldingSetNodeID ID;
4611 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4613 void *InsertPos = nullptr;
4614 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4615 return QualType(VTP, 0);
4616
4617 // If the element type isn't canonical, this won't be a canonical type either,
4618 // so fill in the canonical type field.
4619 QualType Canonical;
4620 if (!vecType.isCanonical()) {
4621 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4622
4623 // Get the new insert position for the node we care about.
4624 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4625 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4626 }
4627 auto *New = new (*this, alignof(ExtVectorType))
4628 ExtVectorType(vecType, NumElts, Canonical);
4629 VectorTypes.InsertNode(New, InsertPos);
4630 Types.push_back(New);
4631 return QualType(New, 0);
4632}
4633
4636 Expr *SizeExpr,
4637 SourceLocation AttrLoc) const {
4638 llvm::FoldingSetNodeID ID;
4640 SizeExpr);
4641
4642 void *InsertPos = nullptr;
4644 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4646 if (Canon) {
4647 // We already have a canonical version of this array type; use it as
4648 // the canonical type for a newly-built type.
4649 New = new (*this, alignof(DependentSizedExtVectorType))
4650 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4651 AttrLoc);
4652 } else {
4653 QualType CanonVecTy = getCanonicalType(vecType);
4654 if (CanonVecTy == vecType) {
4655 New = new (*this, alignof(DependentSizedExtVectorType))
4656 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4657
4658 DependentSizedExtVectorType *CanonCheck
4659 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4660 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4661 (void)CanonCheck;
4662 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4663 } else {
4664 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4665 SourceLocation());
4666 New = new (*this, alignof(DependentSizedExtVectorType))
4667 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4668 }
4669 }
4670
4671 Types.push_back(New);
4672 return QualType(New, 0);
4673}
4674
4676 unsigned NumColumns) const {
4677 llvm::FoldingSetNodeID ID;
4678 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4679 Type::ConstantMatrix);
4680
4681 assert(MatrixType::isValidElementType(ElementTy) &&
4682 "need a valid element type");
4683 assert(ConstantMatrixType::isDimensionValid(NumRows) &&
4685 "need valid matrix dimensions");
4686 void *InsertPos = nullptr;
4687 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4688 return QualType(MTP, 0);
4689
4690 QualType Canonical;
4691 if (!ElementTy.isCanonical()) {
4692 Canonical =
4693 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4694
4695 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4696 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4697 (void)NewIP;
4698 }
4699
4700 auto *New = new (*this, alignof(ConstantMatrixType))
4701 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4702 MatrixTypes.InsertNode(New, InsertPos);
4703 Types.push_back(New);
4704 return QualType(New, 0);
4705}
4706
4708 Expr *RowExpr,
4709 Expr *ColumnExpr,
4710 SourceLocation AttrLoc) const {
4711 QualType CanonElementTy = getCanonicalType(ElementTy);
4712 llvm::FoldingSetNodeID ID;
4713 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4714 ColumnExpr);
4715
4716 void *InsertPos = nullptr;
4718 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4719
4720 if (!Canon) {
4721 Canon = new (*this, alignof(DependentSizedMatrixType))
4722 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4723 ColumnExpr, AttrLoc);
4724#ifndef NDEBUG
4725 DependentSizedMatrixType *CanonCheck =
4726 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4727 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4728#endif
4729 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4730 Types.push_back(Canon);
4731 }
4732
4733 // Already have a canonical version of the matrix type
4734 //
4735 // If it exactly matches the requested type, use it directly.
4736 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4737 Canon->getRowExpr() == ColumnExpr)
4738 return QualType(Canon, 0);
4739
4740 // Use Canon as the canonical type for newly-built type.
4741 DependentSizedMatrixType *New = new (*this, alignof(DependentSizedMatrixType))
4742 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4743 ColumnExpr, AttrLoc);
4744 Types.push_back(New);
4745 return QualType(New, 0);
4746}
4747
4749 Expr *AddrSpaceExpr,
4750 SourceLocation AttrLoc) const {
4751 assert(AddrSpaceExpr->isInstantiationDependent());
4752
4753 QualType canonPointeeType = getCanonicalType(PointeeType);
4754
4755 void *insertPos = nullptr;
4756 llvm::FoldingSetNodeID ID;
4757 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4758 AddrSpaceExpr);
4759
4760 DependentAddressSpaceType *canonTy =
4761 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4762
4763 if (!canonTy) {
4764 canonTy = new (*this, alignof(DependentAddressSpaceType))
4765 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
4766 AttrLoc);
4767 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4768 Types.push_back(canonTy);
4769 }
4770
4771 if (canonPointeeType == PointeeType &&
4772 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4773 return QualType(canonTy, 0);
4774
4775 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
4776 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
4777 AddrSpaceExpr, AttrLoc);
4778 Types.push_back(sugaredType);
4779 return QualType(sugaredType, 0);
4780}
4781
4782/// Determine whether \p T is canonical as the result type of a function.
4784 return T.isCanonical() &&
4785 (T.getObjCLifetime() == Qualifiers::OCL_None ||
4786 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4787}
4788
4789/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4792 const FunctionType::ExtInfo &Info) const {
4793 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
4794 // functionality creates a function without a prototype regardless of
4795 // language mode (so it makes them even in C++). Once the rewriter has been
4796 // fixed, this assertion can be enabled again.
4797 //assert(!LangOpts.requiresStrictPrototypes() &&
4798 // "strict prototypes are disabled");
4799
4800 // Unique functions, to guarantee there is only one function of a particular
4801 // structure.
4802 llvm::FoldingSetNodeID ID;
4803 FunctionNoProtoType::Profile(ID, ResultTy, Info);
4804
4805 void *InsertPos = nullptr;
4806 if (FunctionNoProtoType *FT =
4807 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4808 return QualType(FT, 0);
4809
4810 QualType Canonical;
4811 if (!isCanonicalResultType(ResultTy)) {
4812 Canonical =
4814
4815 // Get the new insert position for the node we care about.
4816 FunctionNoProtoType *NewIP =
4817 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4818 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4819 }
4820
4821 auto *New = new (*this, alignof(FunctionNoProtoType))
4822 FunctionNoProtoType(ResultTy, Canonical, Info);
4823 Types.push_back(New);
4824 FunctionNoProtoTypes.InsertNode(New, InsertPos);
4825 return QualType(New, 0);
4826}
4827
4830 CanQualType CanResultType = getCanonicalType(ResultType);
4831
4832 // Canonical result types do not have ARC lifetime qualifiers.
4833 if (CanResultType.getQualifiers().hasObjCLifetime()) {
4834 Qualifiers Qs = CanResultType.getQualifiers();
4835 Qs.removeObjCLifetime();
4837 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
4838 }
4839
4840 return CanResultType;
4841}
4842
4844 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
4845 if (ESI.Type == EST_None)
4846 return true;
4847 if (!NoexceptInType)
4848 return false;
4849
4850 // C++17 onwards: exception specification is part of the type, as a simple
4851 // boolean "can this function type throw".
4852 if (ESI.Type == EST_BasicNoexcept)
4853 return true;
4854
4855 // A noexcept(expr) specification is (possibly) canonical if expr is
4856 // value-dependent.
4857 if (ESI.Type == EST_DependentNoexcept)
4858 return true;
4859
4860 // A dynamic exception specification is canonical if it only contains pack
4861 // expansions (so we can't tell whether it's non-throwing) and all its
4862 // contained types are canonical.
4863 if (ESI.Type == EST_Dynamic) {
4864 bool AnyPackExpansions = false;
4865 for (QualType ET : ESI.Exceptions) {
4866 if (!ET.isCanonical())
4867 return false;
4868 if (ET->getAs<PackExpansionType>())
4869 AnyPackExpansions = true;
4870 }
4871 return AnyPackExpansions;
4872 }
4873
4874 return false;
4875}
4876
4877QualType ASTContext::getFunctionTypeInternal(
4878 QualType ResultTy, ArrayRef<QualType> ArgArray,
4879 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
4880 size_t NumArgs = ArgArray.size();
4881
4882 // Unique functions, to guarantee there is only one function of a particular
4883 // structure.
4884 llvm::FoldingSetNodeID ID;
4885 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
4886 *this, true);
4887
4888 QualType Canonical;
4889 bool Unique = false;
4890
4891 void *InsertPos = nullptr;
4892 if (FunctionProtoType *FPT =
4893 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4894 QualType Existing = QualType(FPT, 0);
4895
4896 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
4897 // it so long as our exception specification doesn't contain a dependent
4898 // noexcept expression, or we're just looking for a canonical type.
4899 // Otherwise, we're going to need to create a type
4900 // sugar node to hold the concrete expression.
4901 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
4902 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
4903 return Existing;
4904
4905 // We need a new type sugar node for this one, to hold the new noexcept
4906 // expression. We do no canonicalization here, but that's OK since we don't
4907 // expect to see the same noexcept expression much more than once.
4908 Canonical = getCanonicalType(Existing);
4909 Unique = true;
4910 }
4911
4912 bool NoexceptInType = getLangOpts().CPlusPlus17;
4913 bool IsCanonicalExceptionSpec =
4915
4916 // Determine whether the type being created is already canonical or not.
4917 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
4918 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
4919 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
4920 if (!ArgArray[i].isCanonicalAsParam())
4921 isCanonical = false;
4922
4923 if (OnlyWantCanonical)
4924 assert(isCanonical &&
4925 "given non-canonical parameters constructing canonical type");
4926
4927 // If this type isn't canonical, get the canonical version of it if we don't
4928 // already have it. The exception spec is only partially part of the
4929 // canonical type, and only in C++17 onwards.
4930 if (!isCanonical && Canonical.isNull()) {
4931 SmallVector<QualType, 16> CanonicalArgs;
4932 CanonicalArgs.reserve(NumArgs);
4933 for (unsigned i = 0; i != NumArgs; ++i)
4934 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
4935
4936 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
4937 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
4938 CanonicalEPI.HasTrailingReturn = false;
4939
4940 if (IsCanonicalExceptionSpec) {
4941 // Exception spec is already OK.
4942 } else if (NoexceptInType) {
4943 switch (EPI.ExceptionSpec.Type) {
4945 // We don't know yet. It shouldn't matter what we pick here; no-one
4946 // should ever look at this.
4947 [[fallthrough]];
4948 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
4949 CanonicalEPI.ExceptionSpec.Type = EST_None;
4950 break;
4951
4952 // A dynamic exception specification is almost always "not noexcept",
4953 // with the exception that a pack expansion might expand to no types.
4954 case EST_Dynamic: {
4955 bool AnyPacks = false;
4956 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
4957 if (ET->getAs<PackExpansionType>())
4958 AnyPacks = true;
4959 ExceptionTypeStorage.push_back(getCanonicalType(ET));
4960 }
4961 if (!AnyPacks)
4962 CanonicalEPI.ExceptionSpec.Type = EST_None;
4963 else {
4964 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
4965 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
4966 }
4967 break;
4968 }
4969
4970 case EST_DynamicNone:
4971 case EST_BasicNoexcept:
4972 case EST_NoexceptTrue:
4973 case EST_NoThrow:
4974 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
4975 break;
4976
4978 llvm_unreachable("dependent noexcept is already canonical");
4979 }
4980 } else {
4982 }
4983
4984 // Adjust the canonical function result type.
4985 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
4986 Canonical =
4987 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
4988
4989 // Get the new insert position for the node we care about.
4990 FunctionProtoType *NewIP =
4991 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4992 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4993 }
4994
4995 // Compute the needed size to hold this FunctionProtoType and the
4996 // various trailing objects.
4997 auto ESH = FunctionProtoType::getExceptionSpecSize(
4998 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
4999 size_t Size = FunctionProtoType::totalSizeToAlloc<
5005 EPI.requiresFunctionProtoTypeArmAttributes(), ESH.NumExceptionType,
5006 ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
5007 EPI.ExtParameterInfos ? NumArgs : 0,
5009 EPI.FunctionEffects.conditions().size());
5010
5011 auto *FTP = (FunctionProtoType *)Allocate(Size, alignof(FunctionProtoType));
5013 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
5014 Types.push_back(FTP);
5015 if (!Unique)
5016 FunctionProtoTypes.InsertNode(FTP, InsertPos);
5017 if (!EPI.FunctionEffects.empty())
5018 AnyFunctionEffects = true;
5019 return QualType(FTP, 0);
5020}
5021
5022QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
5023 llvm::FoldingSetNodeID ID;
5024 PipeType::Profile(ID, T, ReadOnly);
5025
5026 void *InsertPos = nullptr;
5027 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
5028 return QualType(PT, 0);
5029
5030 // If the pipe element type isn't canonical, this won't be a canonical type
5031 // either, so fill in the canonical type field.
5032 QualType Canonical;
5033 if (!T.isCanonical()) {
5034 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
5035
5036 // Get the new insert position for the node we care about.
5037 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
5038 assert(!NewIP && "Shouldn't be in the map!");
5039 (void)NewIP;
5040 }
5041 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
5042 Types.push_back(New);
5043 PipeTypes.InsertNode(New, InsertPos);
5044 return QualType(New, 0);
5045}
5046
5048 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
5049 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
5050 : Ty;
5051}
5052
5054 return getPipeType(T, true);
5055}
5056
5058 return getPipeType(T, false);
5059}
5060
5061QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
5062 llvm::FoldingSetNodeID ID;
5063 BitIntType::Profile(ID, IsUnsigned, NumBits);
5064
5065 void *InsertPos = nullptr;
5066 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5067 return QualType(EIT, 0);
5068
5069 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
5070 BitIntTypes.InsertNode(New, InsertPos);
5071 Types.push_back(New);
5072 return QualType(New, 0);
5073}
5074
5076 Expr *NumBitsExpr) const {
5077 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
5078 llvm::FoldingSetNodeID ID;
5079 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
5080
5081 void *InsertPos = nullptr;
5082 if (DependentBitIntType *Existing =
5083 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5084 return QualType(Existing, 0);
5085
5086 auto *New = new (*this, alignof(DependentBitIntType))
5087 DependentBitIntType(IsUnsigned, NumBitsExpr);
5088 DependentBitIntTypes.InsertNode(New, InsertPos);
5089
5090 Types.push_back(New);
5091 return QualType(New, 0);
5092}
5093
5094#ifndef NDEBUG
5096 if (!isa<CXXRecordDecl>(D)) return false;
5097 const auto *RD = cast<CXXRecordDecl>(D);
5098 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
5099 return true;
5100 if (RD->getDescribedClassTemplate() &&
5101 !isa<ClassTemplateSpecializationDecl>(RD))
5102 return true;
5103 return false;
5104}
5105#endif
5106
5107/// getInjectedClassNameType - Return the unique reference to the
5108/// injected class name type for the specified templated declaration.
5110 QualType TST) const {
5112 if (Decl->TypeForDecl) {
5113 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
5114 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
5115 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
5116 Decl->TypeForDecl = PrevDecl->TypeForDecl;
5117 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
5118 } else {
5119 Type *newType = new (*this, alignof(InjectedClassNameType))
5121 Decl->TypeForDecl = newType;
5122 Types.push_back(newType);
5123 }
5124 return QualType(Decl->TypeForDecl, 0);
5125}
5126
5127/// getTypeDeclType - Return the unique reference to the type for the
5128/// specified type declaration.
5129QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
5130 assert(Decl && "Passed null for Decl param");
5131 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
5132
5133 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
5134 return getTypedefType(Typedef);
5135
5136 assert(!isa<TemplateTypeParmDecl>(Decl) &&
5137 "Template type parameter types are always available.");
5138
5139 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
5140 assert(Record->isFirstDecl() && "struct/union has previous declaration");
5142 return getRecordType(Record);
5143 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
5144 assert(Enum->isFirstDecl() && "enum has previous declaration");
5145 return getEnumType(Enum);
5146 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
5147 return getUnresolvedUsingType(Using);
5148 } else
5149 llvm_unreachable("TypeDecl without a type?");
5150
5151 return QualType(Decl->TypeForDecl, 0);
5152}
5153
5154/// getTypedefType - Return the unique reference to the type for the
5155/// specified typedef name decl.
5157 QualType Underlying) const {
5158 if (!Decl->TypeForDecl) {
5159 if (Underlying.isNull())
5160 Underlying = Decl->getUnderlyingType();
5161 auto *NewType = new (*this, alignof(TypedefType)) TypedefType(
5162 Type::Typedef, Decl, QualType(), getCanonicalType(Underlying));
5163 Decl->TypeForDecl = NewType;
5164 Types.push_back(NewType);
5165 return QualType(NewType, 0);
5166 }
5167 if (Underlying.isNull() || Decl->getUnderlyingType() == Underlying)
5168 return QualType(Decl->TypeForDecl, 0);
5169 assert(hasSameType(Decl->getUnderlyingType(), Underlying));
5170
5171 llvm::FoldingSetNodeID ID;
5172 TypedefType::Profile(ID, Decl, Underlying);
5173
5174 void *InsertPos = nullptr;
5175 if (TypedefType *T = TypedefTypes.FindNodeOrInsertPos(ID, InsertPos)) {
5176 assert(!T->typeMatchesDecl() &&
5177 "non-divergent case should be handled with TypeDecl");
5178 return QualType(T, 0);
5179 }
5180
5181 void *Mem = Allocate(TypedefType::totalSizeToAlloc<QualType>(true),
5182 alignof(TypedefType));
5183 auto *NewType = new (Mem) TypedefType(Type::Typedef, Decl, Underlying,
5184 getCanonicalType(Underlying));
5185 TypedefTypes.InsertNode(NewType, InsertPos);
5186 Types.push_back(NewType);
5187 return QualType(NewType, 0);
5188}
5189
5191 QualType Underlying) const {
5192 llvm::FoldingSetNodeID ID;
5193 UsingType::Profile(ID, Found, Underlying);
5194
5195 void *InsertPos = nullptr;
5196 if (UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5197 return QualType(T, 0);
5198
5199 const Type *TypeForDecl =
5200 cast<TypeDecl>(Found->getTargetDecl())->getTypeForDecl();
5201
5202 assert(!Underlying.hasLocalQualifiers());
5203 QualType Canon = Underlying->getCanonicalTypeInternal();
5204 assert(TypeForDecl->getCanonicalTypeInternal() == Canon);
5205
5206 if (Underlying.getTypePtr() == TypeForDecl)
5207 Underlying = QualType();
5208 void *Mem =
5209 Allocate(UsingType::totalSizeToAlloc<QualType>(!Underlying.isNull()),
5210 alignof(UsingType));
5211 UsingType *NewType = new (Mem) UsingType(Found, Underlying, Canon);
5212 Types.push_back(NewType);
5213 UsingTypes.InsertNode(NewType, InsertPos);
5214 return QualType(NewType, 0);
5215}
5216
5218 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
5219
5220 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
5221 if (PrevDecl->TypeForDecl)
5222 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
5223
5224 auto *newType = new (*this, alignof(RecordType)) RecordType(Decl);
5225 Decl->TypeForDecl = newType;
5226 Types.push_back(newType);
5227 return QualType(newType, 0);
5228}
5229
5231 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
5232
5233 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
5234 if (PrevDecl->TypeForDecl)
5235 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
5236
5237 auto *newType = new (*this, alignof(EnumType)) EnumType(Decl);
5238 Decl->TypeForDecl = newType;
5239 Types.push_back(newType);
5240 return QualType(newType, 0);
5241}
5242
5243bool ASTContext::computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits,
5244 unsigned NumPositiveBits,
5245 QualType &BestType,
5246 QualType &BestPromotionType) {
5247 unsigned IntWidth = Target->getIntWidth();
5248 unsigned CharWidth = Target->getCharWidth();
5249 unsigned ShortWidth = Target->getShortWidth();
5250 bool EnumTooLarge = false;
5251 unsigned BestWidth;
5252 if (NumNegativeBits) {
5253 // If there is a negative value, figure out the smallest integer type (of
5254 // int/long/longlong) that fits.
5255 // If it's packed, check also if it fits a char or a short.
5256 if (IsPacked && NumNegativeBits <= CharWidth &&
5257 NumPositiveBits < CharWidth) {
5258 BestType = SignedCharTy;
5259 BestWidth = CharWidth;
5260 } else if (IsPacked && NumNegativeBits <= ShortWidth &&
5261 NumPositiveBits < ShortWidth) {
5262 BestType = ShortTy;
5263 BestWidth = ShortWidth;
5264 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5265 BestType = IntTy;
5266 BestWidth = IntWidth;
5267 } else {
5268 BestWidth = Target->getLongWidth();
5269
5270 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
5271 BestType = LongTy;
5272 } else {
5273 BestWidth = Target->getLongLongWidth();
5274
5275 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5276 EnumTooLarge = true;
5277 BestType = LongLongTy;
5278 }
5279 }
5280 BestPromotionType = (BestWidth <= IntWidth ? IntTy : BestType);
5281 } else {
5282 // If there is no negative value, figure out the smallest type that fits
5283 // all of the enumerator values.
5284 // If it's packed, check also if it fits a char or a short.
5285 if (IsPacked && NumPositiveBits <= CharWidth) {
5286 BestType = UnsignedCharTy;
5287 BestPromotionType = IntTy;
5288 BestWidth = CharWidth;
5289 } else if (IsPacked && NumPositiveBits <= ShortWidth) {
5290 BestType = UnsignedShortTy;
5291 BestPromotionType = IntTy;
5292 BestWidth = ShortWidth;
5293 } else if (NumPositiveBits <= IntWidth) {
5294 BestType = UnsignedIntTy;
5295 BestWidth = IntWidth;
5296 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5298 : IntTy;
5299 } else if (NumPositiveBits <= (BestWidth = Target->getLongWidth())) {
5300 BestType = UnsignedLongTy;
5301 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5303 : LongTy;
5304 } else {
5305 BestWidth = Target->getLongLongWidth();
5306 if (NumPositiveBits > BestWidth) {
5307 // This can happen with bit-precise integer types, but those are not
5308 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
5309 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
5310 // a 128-bit integer, we should consider doing the same.
5311 EnumTooLarge = true;
5312 }
5313 BestType = UnsignedLongLongTy;
5314 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5316 : LongLongTy;
5317 }
5318 }
5319 return EnumTooLarge;
5320}
5321
5323 const UnresolvedUsingTypenameDecl *Decl) const {
5324 if (Decl->TypeForDecl)
5325 return QualType(Decl->TypeForDecl, 0);
5326
5327 if (const UnresolvedUsingTypenameDecl *CanonicalDecl =
5329 if (CanonicalDecl->TypeForDecl)
5330 return QualType(Decl->TypeForDecl = CanonicalDecl->TypeForDecl, 0);
5331
5332 Type *newType =
5333 new (*this, alignof(UnresolvedUsingType)) UnresolvedUsingType(Decl);
5334 Decl->TypeForDecl = newType;
5335 Types.push_back(newType);
5336 return QualType(newType, 0);
5337}
5338
5340 QualType modifiedType,
5341 QualType equivalentType,
5342 const Attr *attr) const {
5343 llvm::FoldingSetNodeID id;
5344 AttributedType::Profile(id, attrKind, modifiedType, equivalentType, attr);
5345
5346 void *insertPos = nullptr;
5347 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
5348 if (type) return QualType(type, 0);
5349
5350 assert(!attr || attr->getKind() == attrKind);
5351
5352 QualType canon = getCanonicalType(equivalentType);
5353 type = new (*this, alignof(AttributedType))
5354 AttributedType(canon, attrKind, attr, modifiedType, equivalentType);
5355
5356 Types.push_back(type);
5357 AttributedTypes.InsertNode(type, insertPos);
5358
5359 return QualType(type, 0);
5360}
5361
5363 QualType equivalentType) const {
5364 return getAttributedType(attr->getKind(), modifiedType, equivalentType, attr);
5365}
5366
5368 QualType modifiedType,
5369 QualType equivalentType) {
5370 switch (nullability) {
5372 return getAttributedType(attr::TypeNonNull, modifiedType, equivalentType);
5373
5375 return getAttributedType(attr::TypeNullable, modifiedType, equivalentType);
5376
5378 return getAttributedType(attr::TypeNullableResult, modifiedType,
5379 equivalentType);
5380
5382 return getAttributedType(attr::TypeNullUnspecified, modifiedType,
5383 equivalentType);
5384 }
5385
5386 llvm_unreachable("Unknown nullability kind");
5387}
5388
5389QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
5390 QualType Wrapped) const {
5391 llvm::FoldingSetNodeID ID;
5392 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
5393
5394 void *InsertPos = nullptr;
5396 BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
5397 if (Ty)
5398 return QualType(Ty, 0);
5399
5400 QualType Canon = getCanonicalType(Wrapped);
5401 Ty = new (*this, alignof(BTFTagAttributedType))
5402 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
5403
5404 Types.push_back(Ty);
5405 BTFTagAttributedTypes.InsertNode(Ty, InsertPos);
5406
5407 return QualType(Ty, 0);
5408}
5409
5411 QualType Wrapped, QualType Contained,
5413
5414 llvm::FoldingSetNodeID ID;
5415 HLSLAttributedResourceType::Profile(ID, Wrapped, Contained, Attrs);
5416
5417 void *InsertPos = nullptr;
5419 HLSLAttributedResourceTypes.FindNodeOrInsertPos(ID, InsertPos);
5420 if (Ty)
5421 return QualType(Ty, 0);
5422
5423 Ty = new (*this, alignof(HLSLAttributedResourceType))
5424 HLSLAttributedResourceType(Wrapped, Contained, Attrs);
5425
5426 Types.push_back(Ty);
5427 HLSLAttributedResourceTypes.InsertNode(Ty, InsertPos);
5428
5429 return QualType(Ty, 0);
5430}
5431/// Retrieve a substitution-result type.
5433 QualType Replacement, Decl *AssociatedDecl, unsigned Index,
5434 std::optional<unsigned> PackIndex,
5435 SubstTemplateTypeParmTypeFlag Flag) const {
5436 llvm::FoldingSetNodeID ID;
5437 SubstTemplateTypeParmType::Profile(ID, Replacement, AssociatedDecl, Index,
5438 PackIndex, Flag);
5439 void *InsertPos = nullptr;
5440 SubstTemplateTypeParmType *SubstParm =
5441 SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5442
5443 if (!SubstParm) {
5444 void *Mem = Allocate(SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
5445 !Replacement.isCanonical()),
5446 alignof(SubstTemplateTypeParmType));
5447 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
5448 Index, PackIndex, Flag);
5449 Types.push_back(SubstParm);
5450 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
5451 }
5452
5453 return QualType(SubstParm, 0);
5454}
5455
5456/// Retrieve a
5459 unsigned Index, bool Final,
5460 const TemplateArgument &ArgPack) {
5461#ifndef NDEBUG
5462 for (const auto &P : ArgPack.pack_elements())
5463 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
5464#endif
5465
5466 llvm::FoldingSetNodeID ID;
5467 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
5468 ArgPack);
5469 void *InsertPos = nullptr;
5470 if (SubstTemplateTypeParmPackType *SubstParm =
5471 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
5472 return QualType(SubstParm, 0);
5473
5474 QualType Canon;
5475 {
5476 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5477 if (!AssociatedDecl->isCanonicalDecl() ||
5478 !CanonArgPack.structurallyEquals(ArgPack)) {
5480 AssociatedDecl->getCanonicalDecl(), Index, Final, CanonArgPack);
5481 [[maybe_unused]] const auto *Nothing =
5482 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
5483 assert(!Nothing);
5484 }
5485 }
5486
5487 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
5488 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
5489 ArgPack);
5490 Types.push_back(SubstParm);
5491 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
5492 return QualType(SubstParm, 0);
5493}
5494
5495/// Retrieve the template type parameter type for a template
5496/// parameter or parameter pack with the given depth, index, and (optionally)
5497/// name.
5498QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
5499 bool ParameterPack,
5500 TemplateTypeParmDecl *TTPDecl) const {
5501 llvm::FoldingSetNodeID ID;
5502 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
5503 void *InsertPos = nullptr;
5504 TemplateTypeParmType *TypeParm
5505 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5506
5507 if (TypeParm)
5508 return QualType(TypeParm, 0);
5509
5510 if (TTPDecl) {
5511 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
5512 TypeParm = new (*this, alignof(TemplateTypeParmType))
5513 TemplateTypeParmType(Depth, Index, ParameterPack, TTPDecl, Canon);
5514
5515 TemplateTypeParmType *TypeCheck
5516 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5517 assert(!TypeCheck && "Template type parameter canonical type broken");
5518 (void)TypeCheck;
5519 } else
5520 TypeParm = new (*this, alignof(TemplateTypeParmType)) TemplateTypeParmType(
5521 Depth, Index, ParameterPack, /*TTPDecl=*/nullptr, /*Canon=*/QualType());
5522
5523 Types.push_back(TypeParm);
5524 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
5525
5526 return QualType(TypeParm, 0);
5527}
5528
5531 SourceLocation NameLoc,
5532 const TemplateArgumentListInfo &Args,
5533 QualType Underlying) const {
5534 assert(!Name.getAsDependentTemplateName() &&
5535 "No dependent template names here!");
5536 QualType TST =
5537 getTemplateSpecializationType(Name, Args.arguments(), Underlying);
5538
5543 TL.setTemplateNameLoc(NameLoc);
5544 TL.setLAngleLoc(Args.getLAngleLoc());
5545 TL.setRAngleLoc(Args.getRAngleLoc());
5546 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5547 TL.setArgLocInfo(i, Args[i].getLocInfo());
5548 return DI;
5549}
5550
5554 QualType Underlying) const {
5555 assert(!Template.getAsDependentTemplateName() &&
5556 "No dependent template names here!");
5557
5559 ArgVec.reserve(Args.size());
5560 for (const TemplateArgumentLoc &Arg : Args)
5561 ArgVec.push_back(Arg.getArgument());
5562
5563 return getTemplateSpecializationType(Template, ArgVec, Underlying);
5564}
5565
5566#ifndef NDEBUG
5568 for (const TemplateArgument &Arg : Args)
5569 if (Arg.isPackExpansion())
5570 return true;
5571
5572 return true;
5573}
5574#endif
5575
5579 QualType Underlying) const {
5580 assert(!Template.getAsDependentTemplateName() &&
5581 "No dependent template names here!");
5582
5583 const auto *TD = Template.getAsTemplateDecl(/*IgnoreDeduced=*/true);
5584 bool IsTypeAlias = TD && TD->isTypeAlias();
5585 QualType CanonType;
5586 if (!Underlying.isNull())
5587 CanonType = getCanonicalType(Underlying);
5588 else {
5589 // We can get here with an alias template when the specialization contains
5590 // a pack expansion that does not match up with a parameter pack.
5591 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
5592 "Caller must compute aliased type");
5593 IsTypeAlias = false;
5594 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
5595 }
5596
5597 // Allocate the (non-canonical) template specialization type, but don't
5598 // try to unique it: these types typically have location information that
5599 // we don't unique and don't want to lose.
5600 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
5601 sizeof(TemplateArgument) * Args.size() +
5602 (IsTypeAlias ? sizeof(QualType) : 0),
5604 auto *Spec
5605 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
5606 IsTypeAlias ? Underlying : QualType());
5607
5608 Types.push_back(Spec);
5609 return QualType(Spec, 0);
5610}
5611
5613 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
5614 assert(!Template.getAsDependentTemplateName() &&
5615 "No dependent template names here!");
5616
5617 // Build the canonical template specialization type.
5618 // Any DeducedTemplateNames are ignored, because the effective name of a TST
5619 // accounts for the TST arguments laid over any default arguments contained in
5620 // its name.
5621 TemplateName CanonTemplate =
5622 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true);
5623
5624 bool AnyNonCanonArgs = false;
5625 auto CanonArgs =
5626 ::getCanonicalTemplateArguments(*this, Args, AnyNonCanonArgs);
5627
5628 // Determine whether this canonical template specialization type already
5629 // exists.
5630 llvm::FoldingSetNodeID ID;
5631 TemplateSpecializationType::Profile(ID, CanonTemplate,
5632 CanonArgs, *this);
5633
5634 void *InsertPos = nullptr;
5636 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5637
5638 if (!Spec) {
5639 // Allocate a new canonical template specialization type.
5640 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
5641 sizeof(TemplateArgument) * CanonArgs.size()),
5643 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
5644 CanonArgs,
5645 QualType(), QualType());
5646 Types.push_back(Spec);
5647 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
5648 }
5649
5650 assert(Spec->isDependentType() &&
5651 "Non-dependent template-id type must have a canonical type");
5652 return QualType(Spec, 0);
5653}
5654
5657 QualType NamedType,
5658 TagDecl *OwnedTagDecl) const {
5659 llvm::FoldingSetNodeID ID;
5660 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
5661
5662 void *InsertPos = nullptr;
5663 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
5664 if (T)
5665 return QualType(T, 0);
5666
5667 QualType Canon = NamedType;
5668 if (!Canon.isCanonical()) {
5669 Canon = getCanonicalType(NamedType);
5670 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
5671 assert(!CheckT && "Elaborated canonical type broken");
5672 (void)CheckT;
5673 }
5674
5675 void *Mem =
5676 Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
5677 alignof(ElaboratedType));
5678 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
5679
5680 Types.push_back(T);
5681 ElaboratedTypes.InsertNode(T, InsertPos);
5682 return QualType(T, 0);
5683}
5684
5687 llvm::FoldingSetNodeID ID;
5688 ParenType::Profile(ID, InnerType);
5689
5690 void *InsertPos = nullptr;
5691 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
5692 if (T)
5693 return QualType(T, 0);
5694
5695 QualType Canon = InnerType;
5696 if (!Canon.isCanonical()) {
5697 Canon = getCanonicalType(InnerType);
5698 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
5699 assert(!CheckT && "Paren canonical type broken");
5700 (void)CheckT;
5701 }
5702
5703 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
5704 Types.push_back(T);
5705 ParenTypes.InsertNode(T, InsertPos);
5706 return QualType(T, 0);
5707}
5708
5711 const IdentifierInfo *MacroII) const {
5712 QualType Canon = UnderlyingTy;
5713 if (!Canon.isCanonical())
5714 Canon = getCanonicalType(UnderlyingTy);
5715
5716 auto *newType = new (*this, alignof(MacroQualifiedType))
5717 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
5718 Types.push_back(newType);
5719 return QualType(newType, 0);
5720}
5721
5724 const IdentifierInfo *Name,
5725 QualType Canon) const {
5726 if (Canon.isNull()) {
5728 if (CanonNNS != NNS)
5729 Canon = getDependentNameType(Keyword, CanonNNS, Name);
5730 }
5731
5732 llvm::FoldingSetNodeID ID;
5733 DependentNameType::Profile(ID, Keyword, NNS, Name);
5734
5735 void *InsertPos = nullptr;
5737 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
5738 if (T)
5739 return QualType(T, 0);
5740
5741 T = new (*this, alignof(DependentNameType))
5742 DependentNameType(Keyword, NNS, Name, Canon);
5743 Types.push_back(T);
5744 DependentNameTypes.InsertNode(T, InsertPos);
5745 return QualType(T, 0);
5746}
5747
5750 const IdentifierInfo *Name, ArrayRef<TemplateArgumentLoc> Args) const {
5751 // TODO: avoid this copy
5753 for (unsigned I = 0, E = Args.size(); I != E; ++I)
5754 ArgCopy.push_back(Args[I].getArgument());
5755 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
5756}
5757
5760 ElaboratedTypeKeyword Keyword,
5762 const IdentifierInfo *Name,
5763 ArrayRef<TemplateArgument> Args) const {
5764 assert((!NNS || NNS->isDependent()) &&
5765 "nested-name-specifier must be dependent");
5766
5767 llvm::FoldingSetNodeID ID;
5768 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
5769 Name, Args);
5770
5771 void *InsertPos = nullptr;
5773 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5774 if (T)
5775 return QualType(T, 0);
5776
5778
5779 ElaboratedTypeKeyword CanonKeyword = Keyword;
5780 if (Keyword == ElaboratedTypeKeyword::None)
5781 CanonKeyword = ElaboratedTypeKeyword::Typename;
5782
5783 bool AnyNonCanonArgs = false;
5784 auto CanonArgs =
5785 ::getCanonicalTemplateArguments(*this, Args, AnyNonCanonArgs);
5786
5787 QualType Canon;
5788 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
5789 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
5790 Name,
5791 CanonArgs);
5792
5793 // Find the insert position again.
5794 [[maybe_unused]] auto *Nothing =
5795 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5796 assert(!Nothing && "canonical type broken");
5797 }
5798
5799 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
5800 sizeof(TemplateArgument) * Args.size()),
5802 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
5803 Name, Args, Canon);
5804 Types.push_back(T);
5805 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
5806 return QualType(T, 0);
5807}
5808
5810 TemplateArgument Arg;
5811 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
5812 QualType ArgType = getTypeDeclType(TTP);
5813 if (TTP->isParameterPack())
5814 ArgType = getPackExpansionType(ArgType, std::nullopt);
5815
5816 Arg = TemplateArgument(ArgType);
5817 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5818 QualType T =
5819 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
5820 // For class NTTPs, ensure we include the 'const' so the type matches that
5821 // of a real template argument.
5822 // FIXME: It would be more faithful to model this as something like an
5823 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
5824 ExprValueKind VK;
5825 if (T->isRecordType()) {
5826 // C++ [temp.param]p8: An id-expression naming a non-type
5827 // template-parameter of class type T denotes a static storage duration
5828 // object of type const T.
5829 T.addConst();
5830 VK = VK_LValue;
5831 } else {
5832 VK = Expr::getValueKindForType(NTTP->getType());
5833 }
5834 Expr *E = new (*this)
5835 DeclRefExpr(*this, NTTP, /*RefersToEnclosingVariableOrCapture=*/false,
5836 T, VK, NTTP->getLocation());
5837
5838 if (NTTP->isParameterPack())
5839 E = new (*this)
5840 PackExpansionExpr(DependentTy, E, NTTP->getLocation(), std::nullopt);
5841 Arg = TemplateArgument(E);
5842 } else {
5843 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
5845 nullptr, /*TemplateKeyword=*/false, TemplateName(TTP));
5846 if (TTP->isParameterPack())
5847 Arg = TemplateArgument(Name, std::optional<unsigned>());
5848 else
5849 Arg = TemplateArgument(Name);
5850 }
5851
5852 if (Param->isTemplateParameterPack())
5853 Arg =
5854 TemplateArgument::CreatePackCopy(const_cast<ASTContext &>(*this), Arg);
5855
5856 return Arg;
5857}
5858
5860 std::optional<unsigned> NumExpansions,
5861 bool ExpectPackInType) const {
5862 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
5863 "Pack expansions must expand one or more parameter packs");
5864
5865 llvm::FoldingSetNodeID ID;
5866 PackExpansionType::Profile(ID, Pattern, NumExpansions);
5867
5868 void *InsertPos = nullptr;
5869 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
5870 if (T)
5871 return QualType(T, 0);
5872
5873 QualType Canon;
5874 if (!Pattern.isCanonical()) {
5875 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
5876 /*ExpectPackInType=*/false);
5877
5878 // Find the insert position again, in case we inserted an element into
5879 // PackExpansionTypes and invalidated our insert position.
5880 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
5881 }
5882
5883 T = new (*this, alignof(PackExpansionType))
5884 PackExpansionType(Pattern, Canon, NumExpansions);
5885 Types.push_back(T);
5886 PackExpansionTypes.InsertNode(T, InsertPos);
5887 return QualType(T, 0);
5888}
5889
5890/// CmpProtocolNames - Comparison predicate for sorting protocols
5891/// alphabetically.
5892static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
5893 ObjCProtocolDecl *const *RHS) {
5894 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
5895}
5896
5898 if (Protocols.empty()) return true;
5899
5900 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
5901 return false;
5902
5903 for (unsigned i = 1; i != Protocols.size(); ++i)
5904 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
5905 Protocols[i]->getCanonicalDecl() != Protocols[i])
5906 return false;
5907 return true;
5908}
5909
5910static void
5912 // Sort protocols, keyed by name.
5913 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
5914
5915 // Canonicalize.
5916 for (ObjCProtocolDecl *&P : Protocols)
5917 P = P->getCanonicalDecl();
5918
5919 // Remove duplicates.
5920 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
5921 Protocols.erase(ProtocolsEnd, Protocols.end());
5922}
5923
5925 ObjCProtocolDecl * const *Protocols,
5926 unsigned NumProtocols) const {
5927 return getObjCObjectType(BaseType, {},
5928 llvm::ArrayRef(Protocols, NumProtocols),
5929 /*isKindOf=*/false);
5930}
5931
5933 QualType baseType,
5934 ArrayRef<QualType> typeArgs,
5936 bool isKindOf) const {
5937 // If the base type is an interface and there aren't any protocols or
5938 // type arguments to add, then the interface type will do just fine.
5939 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
5940 isa<ObjCInterfaceType>(baseType))
5941 return baseType;
5942
5943 // Look in the folding set for an existing type.
5944 llvm::FoldingSetNodeID ID;
5945 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
5946 void *InsertPos = nullptr;
5947 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
5948 return QualType(QT, 0);
5949
5950 // Determine the type arguments to be used for canonicalization,
5951 // which may be explicitly specified here or written on the base
5952 // type.
5953 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
5954 if (effectiveTypeArgs.empty()) {
5955 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
5956 effectiveTypeArgs = baseObject->getTypeArgs();
5957 }
5958
5959 // Build the canonical type, which has the canonical base type and a
5960 // sorted-and-uniqued list of protocols and the type arguments
5961 // canonicalized.
5962 QualType canonical;
5963 bool typeArgsAreCanonical = llvm::all_of(
5964 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
5965 bool protocolsSorted = areSortedAndUniqued(protocols);
5966 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
5967 // Determine the canonical type arguments.
5968 ArrayRef<QualType> canonTypeArgs;
5969 SmallVector<QualType, 4> canonTypeArgsVec;
5970 if (!typeArgsAreCanonical) {
5971 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
5972 for (auto typeArg : effectiveTypeArgs)
5973 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
5974 canonTypeArgs = canonTypeArgsVec;
5975 } else {
5976 canonTypeArgs = effectiveTypeArgs;
5977 }
5978
5979 ArrayRef<ObjCProtocolDecl *> canonProtocols;
5980 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
5981 if (!protocolsSorted) {
5982 canonProtocolsVec.append(protocols.begin(), protocols.end());
5983 SortAndUniqueProtocols(canonProtocolsVec);
5984 canonProtocols = canonProtocolsVec;
5985 } else {
5986 canonProtocols = protocols;
5987 }
5988
5989 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
5990 canonProtocols, isKindOf);
5991
5992 // Regenerate InsertPos.
5993 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
5994 }
5995
5996 unsigned size = sizeof(ObjCObjectTypeImpl);
5997 size += typeArgs.size() * sizeof(QualType);
5998 size += protocols.size() * sizeof(ObjCProtocolDecl *);
5999 void *mem = Allocate(size, alignof(ObjCObjectTypeImpl));
6000 auto *T =
6001 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
6002 isKindOf);
6003
6004 Types.push_back(T);
6005 ObjCObjectTypes.InsertNode(T, InsertPos);
6006 return QualType(T, 0);
6007}
6008
6009/// Apply Objective-C protocol qualifiers to the given type.
6010/// If this is for the canonical type of a type parameter, we can apply
6011/// protocol qualifiers on the ObjCObjectPointerType.
6014 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
6015 bool allowOnPointerType) const {
6016 hasError = false;
6017
6018 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
6019 return getObjCTypeParamType(objT->getDecl(), protocols);
6020 }
6021
6022 // Apply protocol qualifiers to ObjCObjectPointerType.
6023 if (allowOnPointerType) {
6024 if (const auto *objPtr =
6025 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
6026 const ObjCObjectType *objT = objPtr->getObjectType();
6027 // Merge protocol lists and construct ObjCObjectType.
6029 protocolsVec.append(objT->qual_begin(),
6030 objT->qual_end());
6031 protocolsVec.append(protocols.begin(), protocols.end());
6032 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
6034 objT->getBaseType(),
6035 objT->getTypeArgsAsWritten(),
6036 protocols,
6037 objT->isKindOfTypeAsWritten());
6039 }
6040 }
6041
6042 // Apply protocol qualifiers to ObjCObjectType.
6043 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
6044 // FIXME: Check for protocols to which the class type is already
6045 // known to conform.
6046
6047 return getObjCObjectType(objT->getBaseType(),
6048 objT->getTypeArgsAsWritten(),
6049 protocols,
6050 objT->isKindOfTypeAsWritten());
6051 }
6052
6053 // If the canonical type is ObjCObjectType, ...
6054 if (type->isObjCObjectType()) {
6055 // Silently overwrite any existing protocol qualifiers.
6056 // TODO: determine whether that's the right thing to do.
6057
6058 // FIXME: Check for protocols to which the class type is already
6059 // known to conform.
6060 return getObjCObjectType(type, {}, protocols, false);
6061 }
6062
6063 // id<protocol-list>
6064 if (type->isObjCIdType()) {
6065 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6066 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
6067 objPtr->isKindOfType());
6069 }
6070
6071 // Class<protocol-list>
6072 if (type->isObjCClassType()) {
6073 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6074 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
6075 objPtr->isKindOfType());
6077 }
6078
6079 hasError = true;
6080 return type;
6081}
6082
6085 ArrayRef<ObjCProtocolDecl *> protocols) const {
6086 // Look in the folding set for an existing type.
6087 llvm::FoldingSetNodeID ID;
6088 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
6089 void *InsertPos = nullptr;
6090 if (ObjCTypeParamType *TypeParam =
6091 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
6092 return QualType(TypeParam, 0);
6093
6094 // We canonicalize to the underlying type.
6095 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
6096 if (!protocols.empty()) {
6097 // Apply the protocol qualifers.
6098 bool hasError;
6100 Canonical, protocols, hasError, true /*allowOnPointerType*/));
6101 assert(!hasError && "Error when apply protocol qualifier to bound type");
6102 }
6103
6104 unsigned size = sizeof(ObjCTypeParamType);
6105 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6106 void *mem = Allocate(size, alignof(ObjCTypeParamType));
6107 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
6108
6109 Types.push_back(newType);
6110 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
6111 return QualType(newType, 0);
6112}
6113
6115 ObjCTypeParamDecl *New) const {
6117 // Update TypeForDecl after updating TypeSourceInfo.
6118 auto NewTypeParamTy = cast<ObjCTypeParamType>(New->getTypeForDecl());
6120 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
6121 QualType UpdatedTy = getObjCTypeParamType(New, protocols);
6122 New->setTypeForDecl(UpdatedTy.getTypePtr());
6123}
6124
6125/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
6126/// protocol list adopt all protocols in QT's qualified-id protocol
6127/// list.
6129 ObjCInterfaceDecl *IC) {
6130 if (!QT->isObjCQualifiedIdType())
6131 return false;
6132
6133 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
6134 // If both the right and left sides have qualifiers.
6135 for (auto *Proto : OPT->quals()) {
6136 if (!IC->ClassImplementsProtocol(Proto, false))
6137 return false;
6138 }
6139 return true;
6140 }
6141 return false;
6142}
6143
6144/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
6145/// QT's qualified-id protocol list adopt all protocols in IDecl's list
6146/// of protocols.
6148 ObjCInterfaceDecl *IDecl) {
6149 if (!QT->isObjCQualifiedIdType())
6150 return false;
6151 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
6152 if (!OPT)
6153 return false;
6154 if (!IDecl->hasDefinition())
6155 return false;
6157 CollectInheritedProtocols(IDecl, InheritedProtocols);
6158 if (InheritedProtocols.empty())
6159 return false;
6160 // Check that if every protocol in list of id<plist> conforms to a protocol
6161 // of IDecl's, then bridge casting is ok.
6162 bool Conforms = false;
6163 for (auto *Proto : OPT->quals()) {
6164 Conforms = false;
6165 for (auto *PI : InheritedProtocols) {
6166 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
6167 Conforms = true;
6168 break;
6169 }
6170 }
6171 if (!Conforms)
6172 break;
6173 }
6174 if (Conforms)
6175 return true;
6176
6177 for (auto *PI : InheritedProtocols) {
6178 // If both the right and left sides have qualifiers.
6179 bool Adopts = false;
6180 for (auto *Proto : OPT->quals()) {
6181 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
6182 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
6183 break;
6184 }
6185 if (!Adopts)
6186 return false;
6187 }
6188 return true;
6189}
6190
6191/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
6192/// the given object type.
6194 llvm::FoldingSetNodeID ID;
6195 ObjCObjectPointerType::Profile(ID, ObjectT);
6196
6197 void *InsertPos = nullptr;
6198 if (ObjCObjectPointerType *QT =
6199 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
6200 return QualType(QT, 0);
6201
6202 // Find the canonical object type.
6203 QualType Canonical;
6204 if (!ObjectT.isCanonical()) {
6205 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
6206
6207 // Regenerate InsertPos.
6208 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
6209 }
6210
6211 // No match.
6212 void *Mem =
6214 auto *QType =
6215 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
6216
6217 Types.push_back(QType);
6218 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
6219 return QualType(QType, 0);
6220}
6221
6222/// getObjCInterfaceType - Return the unique reference to the type for the
6223/// specified ObjC interface decl. The list of protocols is optional.
6225 ObjCInterfaceDecl *PrevDecl) const {
6226 if (Decl->TypeForDecl)
6227 return QualType(Decl->TypeForDecl, 0);
6228
6229 if (PrevDecl) {
6230 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
6231 Decl->TypeForDecl = PrevDecl->TypeForDecl;
6232 return QualType(PrevDecl->TypeForDecl, 0);
6233 }
6234
6235 // Prefer the definition, if there is one.
6236 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
6237 Decl = Def;
6238
6239 void *Mem = Allocate(sizeof(ObjCInterfaceType), alignof(ObjCInterfaceType));
6240 auto *T = new (Mem) ObjCInterfaceType(Decl);
6241 Decl->TypeForDecl = T;
6242 Types.push_back(T);
6243 return QualType(T, 0);
6244}
6245
6246/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
6247/// TypeOfExprType AST's (since expression's are never shared). For example,
6248/// multiple declarations that refer to "typeof(x)" all contain different
6249/// DeclRefExpr's. This doesn't effect the type checker, since it operates
6250/// on canonical type's (which are always unique).
6252 TypeOfExprType *toe;
6253 if (tofExpr->isTypeDependent()) {
6254 llvm::FoldingSetNodeID ID;
6255 DependentTypeOfExprType::Profile(ID, *this, tofExpr,
6256 Kind == TypeOfKind::Unqualified);
6257
6258 void *InsertPos = nullptr;
6260 DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
6261 if (Canon) {
6262 // We already have a "canonical" version of an identical, dependent
6263 // typeof(expr) type. Use that as our canonical type.
6264 toe = new (*this, alignof(TypeOfExprType)) TypeOfExprType(
6265 *this, tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
6266 } else {
6267 // Build a new, canonical typeof(expr) type.
6268 Canon = new (*this, alignof(DependentTypeOfExprType))
6269 DependentTypeOfExprType(*this, tofExpr, Kind);
6270 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
6271 toe = Canon;
6272 }
6273 } else {
6274 QualType Canonical = getCanonicalType(tofExpr->getType());
6275 toe = new (*this, alignof(TypeOfExprType))
6276 TypeOfExprType(*this, tofExpr, Kind, Canonical);
6277 }
6278 Types.push_back(toe);
6279 return QualType(toe, 0);
6280}
6281
6282/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
6283/// TypeOfType nodes. The only motivation to unique these nodes would be
6284/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
6285/// an issue. This doesn't affect the type checker, since it operates
6286/// on canonical types (which are always unique).
6288 QualType Canonical = getCanonicalType(tofType);
6289 auto *tot = new (*this, alignof(TypeOfType))
6290 TypeOfType(*this, tofType, Canonical, Kind);
6291 Types.push_back(tot);
6292 return QualType(tot, 0);
6293}
6294
6295/// getReferenceQualifiedType - Given an expr, will return the type for
6296/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
6297/// and class member access into account.
6299 // C++11 [dcl.type.simple]p4:
6300 // [...]
6301 QualType T = E->getType();
6302 switch (E->getValueKind()) {
6303 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6304 // type of e;
6305 case VK_XValue:
6306 return getRValueReferenceType(T);
6307 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6308 // type of e;
6309 case VK_LValue:
6310 return getLValueReferenceType(T);
6311 // - otherwise, decltype(e) is the type of e.
6312 case VK_PRValue:
6313 return T;
6314 }
6315 llvm_unreachable("Unknown value kind");
6316}
6317
6318/// Unlike many "get<Type>" functions, we don't unique DecltypeType
6319/// nodes. This would never be helpful, since each such type has its own
6320/// expression, and would not give a significant memory saving, since there
6321/// is an Expr tree under each such type.
6323 DecltypeType *dt;
6324
6325 // C++11 [temp.type]p2:
6326 // If an expression e involves a template parameter, decltype(e) denotes a
6327 // unique dependent type. Two such decltype-specifiers refer to the same
6328 // type only if their expressions are equivalent (14.5.6.1).
6329 if (e->isInstantiationDependent()) {
6330 llvm::FoldingSetNodeID ID;
6331 DependentDecltypeType::Profile(ID, *this, e);
6332
6333 void *InsertPos = nullptr;
6335 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
6336 if (!Canon) {
6337 // Build a new, canonical decltype(expr) type.
6338 Canon = new (*this, alignof(DependentDecltypeType))
6340 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
6341 }
6342 dt = new (*this, alignof(DecltypeType))
6343 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
6344 } else {
6345 dt = new (*this, alignof(DecltypeType))
6346 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
6347 }
6348 Types.push_back(dt);
6349 return QualType(dt, 0);
6350}
6351
6353 bool FullySubstituted,
6354 ArrayRef<QualType> Expansions,
6355 int Index) const {
6356 QualType Canonical;
6357 if (FullySubstituted && Index != -1) {
6358 Canonical = getCanonicalType(Expansions[Index]);
6359 } else {
6360 llvm::FoldingSetNodeID ID;
6361 PackIndexingType::Profile(ID, *this, Pattern.getCanonicalType(), IndexExpr,
6362 FullySubstituted);
6363 void *InsertPos = nullptr;
6364 PackIndexingType *Canon =
6365 DependentPackIndexingTypes.FindNodeOrInsertPos(ID, InsertPos);
6366 if (!Canon) {
6367 void *Mem = Allocate(
6368 PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6370 Canon = new (Mem)
6371 PackIndexingType(*this, QualType(), Pattern.getCanonicalType(),
6372 IndexExpr, FullySubstituted, Expansions);
6373 DependentPackIndexingTypes.InsertNode(Canon, InsertPos);
6374 }
6375 Canonical = QualType(Canon, 0);
6376 }
6377
6378 void *Mem =
6379 Allocate(PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6381 auto *T = new (Mem) PackIndexingType(*this, Canonical, Pattern, IndexExpr,
6382 FullySubstituted, Expansions);
6383 Types.push_back(T);
6384 return QualType(T, 0);
6385}
6386
6387/// getUnaryTransformationType - We don't unique these, since the memory
6388/// savings are minimal and these are rare.
6390 QualType UnderlyingType,
6392 const {
6393 UnaryTransformType *ut = nullptr;
6394
6395 if (BaseType->isDependentType()) {
6396 // Look in the folding set for an existing type.
6397 llvm::FoldingSetNodeID ID;
6399
6400 void *InsertPos = nullptr;
6402 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
6403
6404 if (!Canon) {
6405 // Build a new, canonical __underlying_type(type) type.
6406 Canon = new (*this, alignof(DependentUnaryTransformType))
6407 DependentUnaryTransformType(*this, getCanonicalType(BaseType), Kind);
6408 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
6409 }
6410 ut = new (*this, alignof(UnaryTransformType))
6411 UnaryTransformType(BaseType, QualType(), Kind, QualType(Canon, 0));
6412 } else {
6413 QualType CanonType = getCanonicalType(UnderlyingType);
6414 ut = new (*this, alignof(UnaryTransformType))
6415 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
6416 }
6417 Types.push_back(ut);
6418 return QualType(ut, 0);
6419}
6420
6421QualType ASTContext::getAutoTypeInternal(
6422 QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent,
6423 bool IsPack, ConceptDecl *TypeConstraintConcept,
6424 ArrayRef<TemplateArgument> TypeConstraintArgs, bool IsCanon) const {
6425 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
6426 !TypeConstraintConcept && !IsDependent)
6427 return getAutoDeductType();
6428
6429 // Look in the folding set for an existing type.
6430 llvm::FoldingSetNodeID ID;
6431 bool IsDeducedDependent =
6432 !DeducedType.isNull() && DeducedType->isDependentType();
6433 AutoType::Profile(ID, *this, DeducedType, Keyword,
6434 IsDependent || IsDeducedDependent, TypeConstraintConcept,
6435 TypeConstraintArgs);
6436 if (auto const AT_iter = AutoTypes.find(ID); AT_iter != AutoTypes.end())
6437 return QualType(AT_iter->getSecond(), 0);
6438
6439 QualType Canon;
6440 if (!IsCanon) {
6441 if (!DeducedType.isNull()) {
6442 Canon = DeducedType.getCanonicalType();
6443 } else if (TypeConstraintConcept) {
6444 bool AnyNonCanonArgs = false;
6445 ConceptDecl *CanonicalConcept = TypeConstraintConcept->getCanonicalDecl();
6446 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
6447 *this, TypeConstraintArgs, AnyNonCanonArgs);
6448 if (CanonicalConcept != TypeConstraintConcept || AnyNonCanonArgs) {
6449 Canon =
6450 getAutoTypeInternal(QualType(), Keyword, IsDependent, IsPack,
6451 CanonicalConcept, CanonicalConceptArgs, true);
6452 }
6453 }
6454 }
6455
6456 void *Mem = Allocate(sizeof(AutoType) +
6457 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
6458 alignof(AutoType));
6459 auto *AT = new (Mem) AutoType(
6460 DeducedType, Keyword,
6461 (IsDependent ? TypeDependence::DependentInstantiation
6462 : TypeDependence::None) |
6463 (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None),
6464 Canon, TypeConstraintConcept, TypeConstraintArgs);
6465#ifndef NDEBUG
6466 llvm::FoldingSetNodeID InsertedID;
6467 AT->Profile(InsertedID, *this);
6468 assert(InsertedID == ID && "ID does not match");
6469#endif
6470 Types.push_back(AT);
6471 AutoTypes.try_emplace(ID, AT);
6472 return QualType(AT, 0);
6473}
6474
6475/// getAutoType - Return the uniqued reference to the 'auto' type which has been
6476/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
6477/// canonical deduced-but-dependent 'auto' type.
6480 bool IsDependent, bool IsPack,
6481 ConceptDecl *TypeConstraintConcept,
6482 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
6483 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
6484 assert((!IsDependent || DeducedType.isNull()) &&
6485 "A dependent auto should be undeduced");
6486 return getAutoTypeInternal(DeducedType, Keyword, IsDependent, IsPack,
6487 TypeConstraintConcept, TypeConstraintArgs);
6488}
6489
6491 QualType CanonT = T.getNonPackExpansionType().getCanonicalType();
6492
6493 // Remove a type-constraint from a top-level auto or decltype(auto).
6494 if (auto *AT = CanonT->getAs<AutoType>()) {
6495 if (!AT->isConstrained())
6496 return T;
6497 return getQualifiedType(getAutoType(QualType(), AT->getKeyword(),
6498 AT->isDependentType(),
6499 AT->containsUnexpandedParameterPack()),
6500 T.getQualifiers());
6501 }
6502
6503 // FIXME: We only support constrained auto at the top level in the type of a
6504 // non-type template parameter at the moment. Once we lift that restriction,
6505 // we'll need to recursively build types containing auto here.
6506 assert(!CanonT->getContainedAutoType() ||
6507 !CanonT->getContainedAutoType()->isConstrained());
6508 return T;
6509}
6510
6511QualType ASTContext::getDeducedTemplateSpecializationTypeInternal(
6512 TemplateName Template, QualType DeducedType, bool IsDependent,
6513 QualType Canon) const {
6514 // Look in the folding set for an existing type.
6515 void *InsertPos = nullptr;
6516 llvm::FoldingSetNodeID ID;
6518 IsDependent);
6520 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6521 return QualType(DTST, 0);
6522
6523 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
6524 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent,
6525 Canon);
6526 llvm::FoldingSetNodeID TempID;
6527 DTST->Profile(TempID);
6528 assert(ID == TempID && "ID does not match");
6529 Types.push_back(DTST);
6530 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
6531 return QualType(DTST, 0);
6532}
6533
6534/// Return the uniqued reference to the deduced template specialization type
6535/// which has been deduced to the given type, or to the canonical undeduced
6536/// such type, or the canonical deduced-but-dependent such type.
6538 TemplateName Template, QualType DeducedType, bool IsDependent) const {
6539 QualType Canon = DeducedType.isNull()
6540 ? getDeducedTemplateSpecializationTypeInternal(
6542 IsDependent, QualType())
6543 : DeducedType.getCanonicalType();
6544 return getDeducedTemplateSpecializationTypeInternal(Template, DeducedType,
6545 IsDependent, Canon);
6546}
6547
6548/// getAtomicType - Return the uniqued reference to the atomic type for
6549/// the given value type.
6551 // Unique pointers, to guarantee there is only one pointer of a particular
6552 // structure.
6553 llvm::FoldingSetNodeID ID;
6555
6556 void *InsertPos = nullptr;
6557 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
6558 return QualType(AT, 0);
6559
6560 // If the atomic value type isn't canonical, this won't be a canonical type
6561 // either, so fill in the canonical type field.
6562 QualType Canonical;
6563 if (!T.isCanonical()) {
6564 Canonical = getAtomicType(getCanonicalType(T));
6565
6566 // Get the new insert position for the node we care about.
6567 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
6568 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
6569 }
6570 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
6571 Types.push_back(New);
6572 AtomicTypes.InsertNode(New, InsertPos);
6573 return QualType(New, 0);
6574}
6575
6576/// getAutoDeductType - Get type pattern for deducing against 'auto'.
6578 if (AutoDeductTy.isNull())
6579 AutoDeductTy = QualType(new (*this, alignof(AutoType))
6581 TypeDependence::None, QualType(),
6582 /*concept*/ nullptr, /*args*/ {}),
6583 0);
6584 return AutoDeductTy;
6585}
6586
6587/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
6591 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
6592 return AutoRRefDeductTy;
6593}
6594
6595/// getTagDeclType - Return the unique reference to the type for the
6596/// specified TagDecl (struct/union/class/enum) decl.
6598 assert(Decl);
6599 // FIXME: What is the design on getTagDeclType when it requires casting
6600 // away const? mutable?
6601 return getTypeDeclType(const_cast<TagDecl*>(Decl));
6602}
6603
6604/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
6605/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
6606/// needs to agree with the definition in <stddef.h>.
6608 return getFromTargetType(Target->getSizeType());
6609}
6610
6611/// Return the unique signed counterpart of the integer type
6612/// corresponding to size_t.
6614 return getFromTargetType(Target->getSignedSizeType());
6615}
6616
6617/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
6619 return getFromTargetType(Target->getIntMaxType());
6620}
6621
6622/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
6624 return getFromTargetType(Target->getUIntMaxType());
6625}
6626
6627/// getSignedWCharType - Return the type of "signed wchar_t".
6628/// Used when in C++, as a GCC extension.
6630 // FIXME: derive from "Target" ?
6631 return WCharTy;
6632}
6633
6634/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
6635/// Used when in C++, as a GCC extension.
6637 // FIXME: derive from "Target" ?
6638 return UnsignedIntTy;
6639}
6640
6642 return getFromTargetType(Target->getIntPtrType());
6643}
6644
6647}
6648
6649/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
6650/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
6652 return getFromTargetType(Target->getPtrDiffType(LangAS::Default));
6653}
6654
6655/// Return the unique unsigned counterpart of "ptrdiff_t"
6656/// integer type. The standard (C11 7.21.6.1p7) refers to this type
6657/// in the definition of %tu format specifier.
6659 return getFromTargetType(Target->getUnsignedPtrDiffType(LangAS::Default));
6660}
6661
6662/// Return the unique type for "pid_t" defined in
6663/// <sys/types.h>. We need this to compute the correct type for vfork().
6665 return getFromTargetType(Target->getProcessIDType());
6666}
6667
6668//===----------------------------------------------------------------------===//
6669// Type Operators
6670//===----------------------------------------------------------------------===//
6671
6673 // Push qualifiers into arrays, and then discard any remaining
6674 // qualifiers.
6675 T = getCanonicalType(T);
6677 const Type *Ty = T.getTypePtr();
6679 if (getLangOpts().HLSL && isa<ConstantArrayType>(Ty)) {
6681 } else if (isa<ArrayType>(Ty)) {
6683 } else if (isa<FunctionType>(Ty)) {
6684 Result = getPointerType(QualType(Ty, 0));
6685 } else {
6686 Result = QualType(Ty, 0);
6687 }
6688
6690}
6691
6693 Qualifiers &quals) const {
6694 SplitQualType splitType = type.getSplitUnqualifiedType();
6695
6696 // FIXME: getSplitUnqualifiedType() actually walks all the way to
6697 // the unqualified desugared type and then drops it on the floor.
6698 // We then have to strip that sugar back off with
6699 // getUnqualifiedDesugaredType(), which is silly.
6700 const auto *AT =
6701 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
6702
6703 // If we don't have an array, just use the results in splitType.
6704 if (!AT) {
6705 quals = splitType.Quals;
6706 return QualType(splitType.Ty, 0);
6707 }
6708
6709 // Otherwise, recurse on the array's element type.
6710 QualType elementType = AT->getElementType();
6711 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
6712
6713 // If that didn't change the element type, AT has no qualifiers, so we
6714 // can just use the results in splitType.
6715 if (elementType == unqualElementType) {
6716 assert(quals.empty()); // from the recursive call
6717 quals = splitType.Quals;
6718 return QualType(splitType.Ty, 0);
6719 }
6720
6721 // Otherwise, add in the qualifiers from the outermost type, then
6722 // build the type back up.
6723 quals.addConsistentQualifiers(splitType.Quals);
6724
6725 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
6726 return getConstantArrayType(unqualElementType, CAT->getSize(),
6727 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
6728 }
6729
6730 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
6731 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
6732 }
6733
6734 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
6735 return getVariableArrayType(unqualElementType,
6736 VAT->getSizeExpr(),
6737 VAT->getSizeModifier(),
6738 VAT->getIndexTypeCVRQualifiers(),
6739 VAT->getBracketsRange());
6740 }
6741
6742 const auto *DSAT = cast<DependentSizedArrayType>(AT);
6743 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
6744 DSAT->getSizeModifier(), 0,
6745 SourceRange());
6746}
6747
6748/// Attempt to unwrap two types that may both be array types with the same bound
6749/// (or both be array types of unknown bound) for the purpose of comparing the
6750/// cv-decomposition of two types per C++ [conv.qual].
6751///
6752/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
6753/// C++20 [conv.qual], if permitted by the current language mode.
6755 bool AllowPiMismatch) const {
6756 while (true) {
6757 auto *AT1 = getAsArrayType(T1);
6758 if (!AT1)
6759 return;
6760
6761 auto *AT2 = getAsArrayType(T2);
6762 if (!AT2)
6763 return;
6764
6765 // If we don't have two array types with the same constant bound nor two
6766 // incomplete array types, we've unwrapped everything we can.
6767 // C++20 also permits one type to be a constant array type and the other
6768 // to be an incomplete array type.
6769 // FIXME: Consider also unwrapping array of unknown bound and VLA.
6770 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
6771 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
6772 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
6773 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
6774 isa<IncompleteArrayType>(AT2))))
6775 return;
6776 } else if (isa<IncompleteArrayType>(AT1)) {
6777 if (!(isa<IncompleteArrayType>(AT2) ||
6778 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
6779 isa<ConstantArrayType>(AT2))))
6780 return;
6781 } else {
6782 return;
6783 }
6784
6785 T1 = AT1->getElementType();
6786 T2 = AT2->getElementType();
6787 }
6788}
6789
6790/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
6791///
6792/// If T1 and T2 are both pointer types of the same kind, or both array types
6793/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
6794/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
6795///
6796/// This function will typically be called in a loop that successively
6797/// "unwraps" pointer and pointer-to-member types to compare them at each
6798/// level.
6799///
6800/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
6801/// C++20 [conv.qual], if permitted by the current language mode.
6802///
6803/// \return \c true if a pointer type was unwrapped, \c false if we reached a
6804/// pair of types that can't be unwrapped further.
6806 bool AllowPiMismatch) const {
6807 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
6808
6809 const auto *T1PtrType = T1->getAs<PointerType>();
6810 const auto *T2PtrType = T2->getAs<PointerType>();
6811 if (T1PtrType && T2PtrType) {
6812 T1 = T1PtrType->getPointeeType();
6813 T2 = T2PtrType->getPointeeType();
6814 return true;
6815 }
6816
6817 const auto *T1MPType = T1->getAs<MemberPointerType>();
6818 const auto *T2MPType = T2->getAs<MemberPointerType>();
6819 if (T1MPType && T2MPType &&
6820 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
6821 QualType(T2MPType->getClass(), 0))) {
6822 T1 = T1MPType->getPointeeType();
6823 T2 = T2MPType->getPointeeType();
6824 return true;
6825 }
6826
6827 if (getLangOpts().ObjC) {
6828 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
6829 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
6830 if (T1OPType && T2OPType) {
6831 T1 = T1OPType->getPointeeType();
6832 T2 = T2OPType->getPointeeType();
6833 return true;
6834 }
6835 }
6836
6837 // FIXME: Block pointers, too?
6838
6839 return false;
6840}
6841
6843 while (true) {
6844 Qualifiers Quals;
6845 T1 = getUnqualifiedArrayType(T1, Quals);
6846 T2 = getUnqualifiedArrayType(T2, Quals);
6847 if (hasSameType(T1, T2))
6848 return true;
6849 if (!UnwrapSimilarTypes(T1, T2))
6850 return false;
6851 }
6852}
6853
6855 while (true) {
6856 Qualifiers Quals1, Quals2;
6857 T1 = getUnqualifiedArrayType(T1, Quals1);
6858 T2 = getUnqualifiedArrayType(T2, Quals2);
6859
6860 Quals1.removeCVRQualifiers();
6861 Quals2.removeCVRQualifiers();
6862 if (Quals1 != Quals2)
6863 return false;
6864
6865 if (hasSameType(T1, T2))
6866 return true;
6867
6868 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
6869 return false;
6870 }
6871}
6872
6875 SourceLocation NameLoc) const {
6876 switch (Name.getKind()) {
6879 // DNInfo work in progress: CHECKME: what about DNLoc?
6880 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
6881 NameLoc);
6882
6884 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
6885 // DNInfo work in progress: CHECKME: what about DNLoc?
6886 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
6887 }
6888
6890 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
6891 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
6892 }
6893
6895 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
6896 DeclarationName DName;
6897 if (DTN->isIdentifier()) {
6899 return DeclarationNameInfo(DName, NameLoc);
6900 } else {
6902 // DNInfo work in progress: FIXME: source locations?
6903 DeclarationNameLoc DNLoc =
6905 return DeclarationNameInfo(DName, NameLoc, DNLoc);
6906 }
6907 }
6908
6911 = Name.getAsSubstTemplateTemplateParm();
6912 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
6913 NameLoc);
6914 }
6915
6918 = Name.getAsSubstTemplateTemplateParmPack();
6920 NameLoc);
6921 }
6923 return DeclarationNameInfo(Name.getAsUsingShadowDecl()->getDeclName(),
6924 NameLoc);
6926 DeducedTemplateStorage *DTS = Name.getAsDeducedTemplateName();
6927 return getNameForTemplate(DTS->getUnderlying(), NameLoc);
6928 }
6929 }
6930
6931 llvm_unreachable("bad template name kind!");
6932}
6933
6934static const TemplateArgument *
6936 auto handleParam = [](auto *TP) -> const TemplateArgument * {
6937 if (!TP->hasDefaultArgument())
6938 return nullptr;
6939 return &TP->getDefaultArgument().getArgument();
6940 };
6941 switch (P->getKind()) {
6942 case NamedDecl::TemplateTypeParm:
6943 return handleParam(cast<TemplateTypeParmDecl>(P));
6944 case NamedDecl::NonTypeTemplateParm:
6945 return handleParam(cast<NonTypeTemplateParmDecl>(P));
6946 case NamedDecl::TemplateTemplateParm:
6947 return handleParam(cast<TemplateTemplateParmDecl>(P));
6948 default:
6949 llvm_unreachable("Unexpected template parameter kind");
6950 }
6951}
6952
6954 bool IgnoreDeduced) const {
6955 while (std::optional<TemplateName> UnderlyingOrNone =
6956 Name.desugar(IgnoreDeduced))
6957 Name = *UnderlyingOrNone;
6958
6959 switch (Name.getKind()) {
6961 TemplateDecl *Template = Name.getAsTemplateDecl();
6962 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
6963 Template = getCanonicalTemplateTemplateParmDecl(TTP);
6964
6965 // The canonical template name is the canonical template declaration.
6966 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
6967 }
6968
6971 llvm_unreachable("cannot canonicalize unresolved template");
6972
6974 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
6975 assert(DTN && "Non-dependent template names must refer to template decls.");
6976 return DTN->CanonicalTemplateName;
6977 }
6978
6981 Name.getAsSubstTemplateTemplateParmPack();
6982 TemplateArgument canonArgPack =
6985 canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
6986 subst->getFinal(), subst->getIndex());
6987 }
6989 assert(IgnoreDeduced == false);
6990 DeducedTemplateStorage *DTS = Name.getAsDeducedTemplateName();
6991 DefaultArguments DefArgs = DTS->getDefaultArguments();
6992 TemplateName Underlying = DTS->getUnderlying();
6993
6994 TemplateName CanonUnderlying =
6995 getCanonicalTemplateName(Underlying, /*IgnoreDeduced=*/true);
6996 bool NonCanonical = CanonUnderlying != Underlying;
6997 auto CanonArgs =
6998 getCanonicalTemplateArguments(*this, DefArgs.Args, NonCanonical);
6999
7000 ArrayRef<NamedDecl *> Params =
7001 CanonUnderlying.getAsTemplateDecl()->getTemplateParameters()->asArray();
7002 assert(CanonArgs.size() <= Params.size());
7003 // A deduced template name which deduces the same default arguments already
7004 // declared in the underlying template is the same template as the
7005 // underlying template. We need need to note any arguments which differ from
7006 // the corresponding declaration. If any argument differs, we must build a
7007 // deduced template name.
7008 for (int I = CanonArgs.size() - 1; I >= 0; --I) {
7010 if (!A)
7011 break;
7012 auto CanonParamDefArg = getCanonicalTemplateArgument(*A);
7013 TemplateArgument &CanonDefArg = CanonArgs[I];
7014 if (CanonDefArg.structurallyEquals(CanonParamDefArg))
7015 continue;
7016 // Keep popping from the back any deault arguments which are the same.
7017 if (I == int(CanonArgs.size() - 1))
7018 CanonArgs.pop_back();
7019 NonCanonical = true;
7020 }
7021 return NonCanonical ? getDeducedTemplateName(
7022 CanonUnderlying,
7023 /*DefaultArgs=*/{DefArgs.StartPos, CanonArgs})
7024 : Name;
7025 }
7029 llvm_unreachable("always sugar node");
7030 }
7031
7032 llvm_unreachable("bad template name!");
7033}
7034
7036 const TemplateName &Y,
7037 bool IgnoreDeduced) const {
7038 return getCanonicalTemplateName(X, IgnoreDeduced) ==
7039 getCanonicalTemplateName(Y, IgnoreDeduced);
7040}
7041
7042bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
7043 if (!XCE != !YCE)
7044 return false;
7045
7046 if (!XCE)
7047 return true;
7048
7049 llvm::FoldingSetNodeID XCEID, YCEID;
7050 XCE->Profile(XCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7051 YCE->Profile(YCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7052 return XCEID == YCEID;
7053}
7054
7056 const TypeConstraint *YTC) const {
7057 if (!XTC != !YTC)
7058 return false;
7059
7060 if (!XTC)
7061 return true;
7062
7063 auto *NCX = XTC->getNamedConcept();
7064 auto *NCY = YTC->getNamedConcept();
7065 if (!NCX || !NCY || !isSameEntity(NCX, NCY))
7066 return false;
7069 return false;
7071 if (XTC->getConceptReference()
7073 ->NumTemplateArgs !=
7075 return false;
7076
7077 // Compare slowly by profiling.
7078 //
7079 // We couldn't compare the profiling result for the template
7080 // args here. Consider the following example in different modules:
7081 //
7082 // template <__integer_like _Tp, C<_Tp> Sentinel>
7083 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
7084 // return __t;
7085 // }
7086 //
7087 // When we compare the profiling result for `C<_Tp>` in different
7088 // modules, it will compare the type of `_Tp` in different modules.
7089 // However, the type of `_Tp` in different modules refer to different
7090 // types here naturally. So we couldn't compare the profiling result
7091 // for the template args directly.
7094}
7095
7097 const NamedDecl *Y) const {
7098 if (X->getKind() != Y->getKind())
7099 return false;
7100
7101 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
7102 auto *TY = cast<TemplateTypeParmDecl>(Y);
7103 if (TX->isParameterPack() != TY->isParameterPack())
7104 return false;
7105 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
7106 return false;
7107 return isSameTypeConstraint(TX->getTypeConstraint(),
7108 TY->getTypeConstraint());
7109 }
7110
7111 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7112 auto *TY = cast<NonTypeTemplateParmDecl>(Y);
7113 return TX->isParameterPack() == TY->isParameterPack() &&
7114 TX->getASTContext().hasSameType(TX->getType(), TY->getType()) &&
7115 isSameConstraintExpr(TX->getPlaceholderTypeConstraint(),
7116 TY->getPlaceholderTypeConstraint());
7117 }
7118
7119 auto *TX = cast<TemplateTemplateParmDecl>(X);
7120 auto *TY = cast<TemplateTemplateParmDecl>(Y);
7121 return TX->isParameterPack() == TY->isParameterPack() &&
7122 isSameTemplateParameterList(TX->getTemplateParameters(),
7123 TY->getTemplateParameters());
7124}
7125
7127 const TemplateParameterList *X, const TemplateParameterList *Y) const {
7128 if (X->size() != Y->size())
7129 return false;
7130
7131 for (unsigned I = 0, N = X->size(); I != N; ++I)
7132 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
7133 return false;
7134
7135 return isSameConstraintExpr(X->getRequiresClause(), Y->getRequiresClause());
7136}
7137
7139 const NamedDecl *Y) const {
7140 // If the type parameter isn't the same already, we don't need to check the
7141 // default argument further.
7142 if (!isSameTemplateParameter(X, Y))
7143 return false;
7144
7145 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(X)) {
7146 auto *TTPY = cast<TemplateTypeParmDecl>(Y);
7147 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7148 return false;
7149
7150 return hasSameType(TTPX->getDefaultArgument().getArgument().getAsType(),
7151 TTPY->getDefaultArgument().getArgument().getAsType());
7152 }
7153
7154 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7155 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Y);
7156 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
7157 return false;
7158
7159 Expr *DefaultArgumentX =
7160 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7161 Expr *DefaultArgumentY =
7162 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7163 llvm::FoldingSetNodeID XID, YID;
7164 DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true);
7165 DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true);
7166 return XID == YID;
7167 }
7168
7169 auto *TTPX = cast<TemplateTemplateParmDecl>(X);
7170 auto *TTPY = cast<TemplateTemplateParmDecl>(Y);
7171
7172 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7173 return false;
7174
7175 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
7176 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
7177 return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate());
7178}
7179
7181 if (auto *NS = X->getAsNamespace())
7182 return NS;
7183 if (auto *NAS = X->getAsNamespaceAlias())
7184 return NAS->getNamespace();
7185 return nullptr;
7186}
7187
7189 const NestedNameSpecifier *Y) {
7190 if (auto *NSX = getNamespace(X)) {
7191 auto *NSY = getNamespace(Y);
7192 if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl())
7193 return false;
7194 } else if (X->getKind() != Y->getKind())
7195 return false;
7196
7197 // FIXME: For namespaces and types, we're permitted to check that the entity
7198 // is named via the same tokens. We should probably do so.
7199 switch (X->getKind()) {
7201 if (X->getAsIdentifier() != Y->getAsIdentifier())
7202 return false;
7203 break;
7206 // We've already checked that we named the same namespace.
7207 break;
7210 if (X->getAsType()->getCanonicalTypeInternal() !=
7212 return false;
7213 break;
7216 return true;
7217 }
7218
7219 // Recurse into earlier portion of NNS, if any.
7220 auto *PX = X->getPrefix();
7221 auto *PY = Y->getPrefix();
7222 if (PX && PY)
7223 return isSameQualifier(PX, PY);
7224 return !PX && !PY;
7225}
7226
7227/// Determine whether the attributes we can overload on are identical for A and
7228/// B. Will ignore any overloadable attrs represented in the type of A and B.
7230 const FunctionDecl *B) {
7231 // Note that pass_object_size attributes are represented in the function's
7232 // ExtParameterInfo, so we don't need to check them here.
7233
7234 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
7235 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
7236 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
7237
7238 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
7239 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
7240 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
7241
7242 // Return false if the number of enable_if attributes is different.
7243 if (!Cand1A || !Cand2A)
7244 return false;
7245
7246 Cand1ID.clear();
7247 Cand2ID.clear();
7248
7249 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
7250 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
7251
7252 // Return false if any of the enable_if expressions of A and B are
7253 // different.
7254 if (Cand1ID != Cand2ID)
7255 return false;
7256 }
7257 return true;
7258}
7259
7260bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
7261 // Caution: this function is called by the AST reader during deserialization,
7262 // so it cannot rely on AST invariants being met. Non-trivial accessors
7263 // should be avoided, along with any traversal of redeclaration chains.
7264
7265 if (X == Y)
7266 return true;
7267
7268 if (X->getDeclName() != Y->getDeclName())
7269 return false;
7270
7271 // Must be in the same context.
7272 //
7273 // Note that we can't use DeclContext::Equals here, because the DeclContexts
7274 // could be two different declarations of the same function. (We will fix the
7275 // semantic DC to refer to the primary definition after merging.)
7276 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
7277 cast<Decl>(Y->getDeclContext()->getRedeclContext())))
7278 return false;
7279
7280 // Two typedefs refer to the same entity if they have the same underlying
7281 // type.
7282 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
7283 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
7284 return hasSameType(TypedefX->getUnderlyingType(),
7285 TypedefY->getUnderlyingType());
7286
7287 // Must have the same kind.
7288 if (X->getKind() != Y->getKind())
7289 return false;
7290
7291 // Objective-C classes and protocols with the same name always match.
7292 if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
7293 return true;
7294
7295 if (isa<ClassTemplateSpecializationDecl>(X)) {
7296 // No need to handle these here: we merge them when adding them to the
7297 // template.
7298 return false;
7299 }
7300
7301 // Compatible tags match.
7302 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
7303 const auto *TagY = cast<TagDecl>(Y);
7304 return (TagX->getTagKind() == TagY->getTagKind()) ||
7305 ((TagX->getTagKind() == TagTypeKind::Struct ||
7306 TagX->getTagKind() == TagTypeKind::Class ||
7307 TagX->getTagKind() == TagTypeKind::Interface) &&
7308 (TagY->getTagKind() == TagTypeKind::Struct ||
7309 TagY->getTagKind() == TagTypeKind::Class ||
7310 TagY->getTagKind() == TagTypeKind::Interface));
7311 }
7312
7313 // Functions with the same type and linkage match.
7314 // FIXME: This needs to cope with merging of prototyped/non-prototyped
7315 // functions, etc.
7316 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
7317 const auto *FuncY = cast<FunctionDecl>(Y);
7318 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
7319 const auto *CtorY = cast<CXXConstructorDecl>(Y);
7320 if (CtorX->getInheritedConstructor() &&
7321 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
7322 CtorY->getInheritedConstructor().getConstructor()))
7323 return false;
7324 }
7325
7326 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
7327 return false;
7328
7329 // Multiversioned functions with different feature strings are represented
7330 // as separate declarations.
7331 if (FuncX->isMultiVersion()) {
7332 const auto *TAX = FuncX->getAttr<TargetAttr>();
7333 const auto *TAY = FuncY->getAttr<TargetAttr>();
7334 assert(TAX && TAY && "Multiversion Function without target attribute");
7335
7336 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
7337 return false;
7338 }
7339
7340 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
7341 // not the same entity if they are constrained.
7342 if ((FuncX->isMemberLikeConstrainedFriend() ||
7343 FuncY->isMemberLikeConstrainedFriend()) &&
7344 !FuncX->getLexicalDeclContext()->Equals(
7345 FuncY->getLexicalDeclContext())) {
7346 return false;
7347 }
7348
7349 if (!isSameConstraintExpr(FuncX->getTrailingRequiresClause(),
7350 FuncY->getTrailingRequiresClause()))
7351 return false;
7352
7353 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
7354 // Map to the first declaration that we've already merged into this one.
7355 // The TSI of redeclarations might not match (due to calling conventions
7356 // being inherited onto the type but not the TSI), but the TSI type of
7357 // the first declaration of the function should match across modules.
7358 FD = FD->getCanonicalDecl();
7359 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
7360 : FD->getType();
7361 };
7362 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
7363 if (!hasSameType(XT, YT)) {
7364 // We can get functions with different types on the redecl chain in C++17
7365 // if they have differing exception specifications and at least one of
7366 // the excpetion specs is unresolved.
7367 auto *XFPT = XT->getAs<FunctionProtoType>();
7368 auto *YFPT = YT->getAs<FunctionProtoType>();
7369 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
7370 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
7373 return true;
7374 return false;
7375 }
7376
7377 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
7378 hasSameOverloadableAttrs(FuncX, FuncY);
7379 }
7380
7381 // Variables with the same type and linkage match.
7382 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
7383 const auto *VarY = cast<VarDecl>(Y);
7384 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
7385 // During deserialization, we might compare variables before we load
7386 // their types. Assume the types will end up being the same.
7387 if (VarX->getType().isNull() || VarY->getType().isNull())
7388 return true;
7389
7390 if (hasSameType(VarX->getType(), VarY->getType()))
7391 return true;
7392
7393 // We can get decls with different types on the redecl chain. Eg.
7394 // template <typename T> struct S { static T Var[]; }; // #1
7395 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
7396 // Only? happens when completing an incomplete array type. In this case
7397 // when comparing #1 and #2 we should go through their element type.
7398 const ArrayType *VarXTy = getAsArrayType(VarX->getType());
7399 const ArrayType *VarYTy = getAsArrayType(VarY->getType());
7400 if (!VarXTy || !VarYTy)
7401 return false;
7402 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
7403 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
7404 }
7405 return false;
7406 }
7407
7408 // Namespaces with the same name and inlinedness match.
7409 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
7410 const auto *NamespaceY = cast<NamespaceDecl>(Y);
7411 return NamespaceX->isInline() == NamespaceY->isInline();
7412 }
7413
7414 // Identical template names and kinds match if their template parameter lists
7415 // and patterns match.
7416 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
7417 const auto *TemplateY = cast<TemplateDecl>(Y);
7418
7419 // ConceptDecl wouldn't be the same if their constraint expression differs.
7420 if (const auto *ConceptX = dyn_cast<ConceptDecl>(X)) {
7421 const auto *ConceptY = cast<ConceptDecl>(Y);
7422 if (!isSameConstraintExpr(ConceptX->getConstraintExpr(),
7423 ConceptY->getConstraintExpr()))
7424 return false;
7425 }
7426
7427 return isSameEntity(TemplateX->getTemplatedDecl(),
7428 TemplateY->getTemplatedDecl()) &&
7429 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
7430 TemplateY->getTemplateParameters());
7431 }
7432
7433 // Fields with the same name and the same type match.
7434 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
7435 const auto *FDY = cast<FieldDecl>(Y);
7436 // FIXME: Also check the bitwidth is odr-equivalent, if any.
7437 return hasSameType(FDX->getType(), FDY->getType());
7438 }
7439
7440 // Indirect fields with the same target field match.
7441 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
7442 const auto *IFDY = cast<IndirectFieldDecl>(Y);
7443 return IFDX->getAnonField()->getCanonicalDecl() ==
7444 IFDY->getAnonField()->getCanonicalDecl();
7445 }
7446
7447 // Enumerators with the same name match.
7448 if (isa<EnumConstantDecl>(X))
7449 // FIXME: Also check the value is odr-equivalent.
7450 return true;
7451
7452 // Using shadow declarations with the same target match.
7453 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
7454 const auto *USY = cast<UsingShadowDecl>(Y);
7455 return declaresSameEntity(USX->getTargetDecl(), USY->getTargetDecl());
7456 }
7457
7458 // Using declarations with the same qualifier match. (We already know that
7459 // the name matches.)
7460 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
7461 const auto *UY = cast<UsingDecl>(Y);
7462 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7463 UX->hasTypename() == UY->hasTypename() &&
7464 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7465 }
7466 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
7467 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
7468 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7469 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7470 }
7471 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
7472 return isSameQualifier(
7473 UX->getQualifier(),
7474 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
7475 }
7476
7477 // Using-pack declarations are only created by instantiation, and match if
7478 // they're instantiated from matching UnresolvedUsing...Decls.
7479 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
7480 return declaresSameEntity(
7481 UX->getInstantiatedFromUsingDecl(),
7482 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
7483 }
7484
7485 // Namespace alias definitions with the same target match.
7486 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
7487 const auto *NAY = cast<NamespaceAliasDecl>(Y);
7488 return NAX->getNamespace()->Equals(NAY->getNamespace());
7489 }
7490
7491 return false;
7492}
7493
7496 switch (Arg.getKind()) {
7498 return Arg;
7499
7501 return Arg;
7502
7504 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
7506 Arg.getIsDefaulted());
7507 }
7508
7511 /*isNullPtr*/ true, Arg.getIsDefaulted());
7512
7515 Arg.getIsDefaulted());
7516
7518 return TemplateArgument(
7521
7524
7526 return TemplateArgument(*this,
7529
7532 /*isNullPtr*/ false, Arg.getIsDefaulted());
7533
7535 bool AnyNonCanonArgs = false;
7536 auto CanonArgs = ::getCanonicalTemplateArguments(
7537 *this, Arg.pack_elements(), AnyNonCanonArgs);
7538 if (!AnyNonCanonArgs)
7539 return Arg;
7541 const_cast<ASTContext &>(*this), CanonArgs);
7542 NewArg.setIsDefaulted(Arg.getIsDefaulted());
7543 return NewArg;
7544 }
7545 }
7546
7547 // Silence GCC warning
7548 llvm_unreachable("Unhandled template argument kind");
7549}
7550
7553 if (!NNS)
7554 return nullptr;
7555
7556 switch (NNS->getKind()) {
7558 // Canonicalize the prefix but keep the identifier the same.
7559 return NestedNameSpecifier::Create(*this,
7561 NNS->getAsIdentifier());
7562
7564 // A namespace is canonical; build a nested-name-specifier with
7565 // this namespace and no prefix.
7566 return NestedNameSpecifier::Create(*this, nullptr,
7567 NNS->getAsNamespace()->getFirstDecl());
7568
7570 // A namespace is canonical; build a nested-name-specifier with
7571 // this namespace and no prefix.
7573 *this, nullptr,
7575
7576 // The difference between TypeSpec and TypeSpecWithTemplate is that the
7577 // latter will have the 'template' keyword when printed.
7580 const Type *T = getCanonicalType(NNS->getAsType());
7581
7582 // If we have some kind of dependent-named type (e.g., "typename T::type"),
7583 // break it apart into its prefix and identifier, then reconsititute those
7584 // as the canonical nested-name-specifier. This is required to canonicalize
7585 // a dependent nested-name-specifier involving typedefs of dependent-name
7586 // types, e.g.,
7587 // typedef typename T::type T1;
7588 // typedef typename T1::type T2;
7589 if (const auto *DNT = T->getAs<DependentNameType>())
7590 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
7591 DNT->getIdentifier());
7592 if (const auto *DTST = T->getAs<DependentTemplateSpecializationType>())
7593 return NestedNameSpecifier::Create(*this, DTST->getQualifier(), true, T);
7594
7595 // TODO: Set 'Template' parameter to true for other template types.
7596 return NestedNameSpecifier::Create(*this, nullptr, false, T);
7597 }
7598
7601 // The global specifier and __super specifer are canonical and unique.
7602 return NNS;
7603 }
7604
7605 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
7606}
7607
7609 // Handle the non-qualified case efficiently.
7610 if (!T.hasLocalQualifiers()) {
7611 // Handle the common positive case fast.
7612 if (const auto *AT = dyn_cast<ArrayType>(T))
7613 return AT;
7614 }
7615
7616 // Handle the common negative case fast.
7617 if (!isa<ArrayType>(T.getCanonicalType()))
7618 return nullptr;
7619
7620 // Apply any qualifiers from the array type to the element type. This
7621 // implements C99 6.7.3p8: "If the specification of an array type includes
7622 // any type qualifiers, the element type is so qualified, not the array type."
7623
7624 // If we get here, we either have type qualifiers on the type, or we have
7625 // sugar such as a typedef in the way. If we have type qualifiers on the type
7626 // we must propagate them down into the element type.
7627
7628 SplitQualType split = T.getSplitDesugaredType();
7629 Qualifiers qs = split.Quals;
7630
7631 // If we have a simple case, just return now.
7632 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
7633 if (!ATy || qs.empty())
7634 return ATy;
7635
7636 // Otherwise, we have an array and we have qualifiers on it. Push the
7637 // qualifiers into the array element type and return a new array type.
7638 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
7639
7640 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
7641 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
7642 CAT->getSizeExpr(),
7643 CAT->getSizeModifier(),
7644 CAT->getIndexTypeCVRQualifiers()));
7645 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
7646 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
7647 IAT->getSizeModifier(),
7648 IAT->getIndexTypeCVRQualifiers()));
7649
7650 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
7651 return cast<ArrayType>(
7653 DSAT->getSizeExpr(),
7654 DSAT->getSizeModifier(),
7655 DSAT->getIndexTypeCVRQualifiers(),
7656 DSAT->getBracketsRange()));
7657
7658 const auto *VAT = cast<VariableArrayType>(ATy);
7659 return cast<ArrayType>(getVariableArrayType(NewEltTy,
7660 VAT->getSizeExpr(),
7661 VAT->getSizeModifier(),
7662 VAT->getIndexTypeCVRQualifiers(),
7663 VAT->getBracketsRange()));
7664}
7665
7668 return getArrayParameterType(T);
7669 if (T->isArrayType() || T->isFunctionType())
7670 return getDecayedType(T);
7671 return T;
7672}
7673
7677 return T.getUnqualifiedType();
7678}
7679
7681 // C++ [except.throw]p3:
7682 // A throw-expression initializes a temporary object, called the exception
7683 // object, the type of which is determined by removing any top-level
7684 // cv-qualifiers from the static type of the operand of throw and adjusting
7685 // the type from "array of T" or "function returning T" to "pointer to T"
7686 // or "pointer to function returning T", [...]
7688 if (T->isArrayType() || T->isFunctionType())
7689 T = getDecayedType(T);
7690 return T.getUnqualifiedType();
7691}
7692
7693/// getArrayDecayedType - Return the properly qualified result of decaying the
7694/// specified array type to a pointer. This operation is non-trivial when
7695/// handling typedefs etc. The canonical type of "T" must be an array type,
7696/// this returns a pointer to a properly qualified element of the array.
7697///
7698/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
7700 // Get the element type with 'getAsArrayType' so that we don't lose any
7701 // typedefs in the element type of the array. This also handles propagation
7702 // of type qualifiers from the array type into the element type if present
7703 // (C99 6.7.3p8).
7704 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
7705 assert(PrettyArrayType && "Not an array type!");
7706
7707 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
7708
7709 // int x[restrict 4] -> int *restrict
7711 PrettyArrayType->getIndexTypeQualifiers());
7712
7713 // int x[_Nullable] -> int * _Nullable
7714 if (auto Nullability = Ty->getNullability()) {
7715 Result = const_cast<ASTContext *>(this)->getAttributedType(*Nullability,
7716 Result, Result);
7717 }
7718 return Result;
7719}
7720
7722 return getBaseElementType(array->getElementType());
7723}
7724
7726 Qualifiers qs;
7727 while (true) {
7728 SplitQualType split = type.getSplitDesugaredType();
7729 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
7730 if (!array) break;
7731
7732 type = array->getElementType();
7734 }
7735
7736 return getQualifiedType(type, qs);
7737}
7738
7739/// getConstantArrayElementCount - Returns number of constant array elements.
7740uint64_t
7742 uint64_t ElementCount = 1;
7743 do {
7744 ElementCount *= CA->getZExtSize();
7745 CA = dyn_cast_or_null<ConstantArrayType>(
7747 } while (CA);
7748 return ElementCount;
7749}
7750
7752 const ArrayInitLoopExpr *AILE) const {
7753 if (!AILE)
7754 return 0;
7755
7756 uint64_t ElementCount = 1;
7757
7758 do {
7759 ElementCount *= AILE->getArraySize().getZExtValue();
7760 AILE = dyn_cast<ArrayInitLoopExpr>(AILE->getSubExpr());
7761 } while (AILE);
7762
7763 return ElementCount;
7764}
7765
7766/// getFloatingRank - Return a relative rank for floating point types.
7767/// This routine will assert if passed a built-in type that isn't a float.
7769 if (const auto *CT = T->getAs<ComplexType>())
7770 return getFloatingRank(CT->getElementType());
7771
7772 switch (T->castAs<BuiltinType>()->getKind()) {
7773 default: llvm_unreachable("getFloatingRank(): not a floating type");
7774 case BuiltinType::Float16: return Float16Rank;
7775 case BuiltinType::Half: return HalfRank;
7776 case BuiltinType::Float: return FloatRank;
7777 case BuiltinType::Double: return DoubleRank;
7778 case BuiltinType::LongDouble: return LongDoubleRank;
7779 case BuiltinType::Float128: return Float128Rank;
7780 case BuiltinType::BFloat16: return BFloat16Rank;
7781 case BuiltinType::Ibm128: return Ibm128Rank;
7782 }
7783}
7784
7785/// getFloatingTypeOrder - Compare the rank of the two specified floating
7786/// point types, ignoring the domain of the type (i.e. 'double' ==
7787/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
7788/// LHS < RHS, return -1.
7790 FloatingRank LHSR = getFloatingRank(LHS);
7791 FloatingRank RHSR = getFloatingRank(RHS);
7792
7793 if (LHSR == RHSR)
7794 return 0;
7795 if (LHSR > RHSR)
7796 return 1;
7797 return -1;
7798}
7799
7802 return 0;
7803 return getFloatingTypeOrder(LHS, RHS);
7804}
7805
7806/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
7807/// routine will assert if passed a built-in type that isn't an integer or enum,
7808/// or if it is not canonicalized.
7809unsigned ASTContext::getIntegerRank(const Type *T) const {
7810 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
7811
7812 // Results in this 'losing' to any type of the same size, but winning if
7813 // larger.
7814 if (const auto *EIT = dyn_cast<BitIntType>(T))
7815 return 0 + (EIT->getNumBits() << 3);
7816
7817 switch (cast<BuiltinType>(T)->getKind()) {
7818 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
7819 case BuiltinType::Bool:
7820 return 1 + (getIntWidth(BoolTy) << 3);
7821 case BuiltinType::Char_S:
7822 case BuiltinType::Char_U:
7823 case BuiltinType::SChar:
7824 case BuiltinType::UChar:
7825 return 2 + (getIntWidth(CharTy) << 3);
7826 case BuiltinType::Short:
7827 case BuiltinType::UShort:
7828 return 3 + (getIntWidth(ShortTy) << 3);
7829 case BuiltinType::Int:
7830 case BuiltinType::UInt:
7831 return 4 + (getIntWidth(IntTy) << 3);
7832 case BuiltinType::Long:
7833 case BuiltinType::ULong:
7834 return 5 + (getIntWidth(LongTy) << 3);
7835 case BuiltinType::LongLong:
7836 case BuiltinType::ULongLong:
7837 return 6 + (getIntWidth(LongLongTy) << 3);
7838 case BuiltinType::Int128:
7839 case BuiltinType::UInt128:
7840 return 7 + (getIntWidth(Int128Ty) << 3);
7841
7842 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
7843 // their underlying types" [c++20 conv.rank]
7844 case BuiltinType::Char8:
7845 return getIntegerRank(UnsignedCharTy.getTypePtr());
7846 case BuiltinType::Char16:
7847 return getIntegerRank(
7848 getFromTargetType(Target->getChar16Type()).getTypePtr());
7849 case BuiltinType::Char32:
7850 return getIntegerRank(
7851 getFromTargetType(Target->getChar32Type()).getTypePtr());
7852 case BuiltinType::WChar_S:
7853 case BuiltinType::WChar_U:
7854 return getIntegerRank(
7855 getFromTargetType(Target->getWCharType()).getTypePtr());
7856 }
7857}
7858
7859/// Whether this is a promotable bitfield reference according
7860/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
7861///
7862/// \returns the type this bit-field will promote to, or NULL if no
7863/// promotion occurs.
7865 if (E->isTypeDependent() || E->isValueDependent())
7866 return {};
7867
7868 // C++ [conv.prom]p5:
7869 // If the bit-field has an enumerated type, it is treated as any other
7870 // value of that type for promotion purposes.
7872 return {};
7873
7874 // FIXME: We should not do this unless E->refersToBitField() is true. This
7875 // matters in C where getSourceBitField() will find bit-fields for various
7876 // cases where the source expression is not a bit-field designator.
7877
7878 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
7879 if (!Field)
7880 return {};
7881
7882 QualType FT = Field->getType();
7883
7884 uint64_t BitWidth = Field->getBitWidthValue();
7885 uint64_t IntSize = getTypeSize(IntTy);
7886 // C++ [conv.prom]p5:
7887 // A prvalue for an integral bit-field can be converted to a prvalue of type
7888 // int if int can represent all the values of the bit-field; otherwise, it
7889 // can be converted to unsigned int if unsigned int can represent all the
7890 // values of the bit-field. If the bit-field is larger yet, no integral
7891 // promotion applies to it.
7892 // C11 6.3.1.1/2:
7893 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
7894 // If an int can represent all values of the original type (as restricted by
7895 // the width, for a bit-field), the value is converted to an int; otherwise,
7896 // it is converted to an unsigned int.
7897 //
7898 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
7899 // We perform that promotion here to match GCC and C++.
7900 // FIXME: C does not permit promotion of an enum bit-field whose rank is
7901 // greater than that of 'int'. We perform that promotion to match GCC.
7902 //
7903 // C23 6.3.1.1p2:
7904 // The value from a bit-field of a bit-precise integer type is converted to
7905 // the corresponding bit-precise integer type. (The rest is the same as in
7906 // C11.)
7907 if (QualType QT = Field->getType(); QT->isBitIntType())
7908 return QT;
7909
7910 if (BitWidth < IntSize)
7911 return IntTy;
7912
7913 if (BitWidth == IntSize)
7914 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
7915
7916 // Bit-fields wider than int are not subject to promotions, and therefore act
7917 // like the base type. GCC has some weird bugs in this area that we
7918 // deliberately do not follow (GCC follows a pre-standard resolution to
7919 // C's DR315 which treats bit-width as being part of the type, and this leaks
7920 // into their semantics in some cases).
7921 return {};
7922}
7923
7924/// getPromotedIntegerType - Returns the type that Promotable will
7925/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
7926/// integer type.
7928 assert(!Promotable.isNull());
7929 assert(isPromotableIntegerType(Promotable));
7930 if (const auto *ET = Promotable->getAs<EnumType>())
7931 return ET->getDecl()->getPromotionType();
7932
7933 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
7934 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
7935 // (3.9.1) can be converted to a prvalue of the first of the following
7936 // types that can represent all the values of its underlying type:
7937 // int, unsigned int, long int, unsigned long int, long long int, or
7938 // unsigned long long int [...]
7939 // FIXME: Is there some better way to compute this?
7940 if (BT->getKind() == BuiltinType::WChar_S ||
7941 BT->getKind() == BuiltinType::WChar_U ||
7942 BT->getKind() == BuiltinType::Char8 ||
7943 BT->getKind() == BuiltinType::Char16 ||
7944 BT->getKind() == BuiltinType::Char32) {
7945 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
7946 uint64_t FromSize = getTypeSize(BT);
7947 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
7949 for (const auto &PT : PromoteTypes) {
7950 uint64_t ToSize = getTypeSize(PT);
7951 if (FromSize < ToSize ||
7952 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
7953 return PT;
7954 }
7955 llvm_unreachable("char type should fit into long long");
7956 }
7957 }
7958
7959 // At this point, we should have a signed or unsigned integer type.
7960 if (Promotable->isSignedIntegerType())
7961 return IntTy;
7962 uint64_t PromotableSize = getIntWidth(Promotable);
7963 uint64_t IntSize = getIntWidth(IntTy);
7964 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
7965 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
7966}
7967
7968/// Recurses in pointer/array types until it finds an objc retainable
7969/// type and returns its ownership.
7971 while (!T.isNull()) {
7972 if (T.getObjCLifetime() != Qualifiers::OCL_None)
7973 return T.getObjCLifetime();
7974 if (T->isArrayType())
7976 else if (const auto *PT = T->getAs<PointerType>())
7977 T = PT->getPointeeType();
7978 else if (const auto *RT = T->getAs<ReferenceType>())
7979 T = RT->getPointeeType();
7980 else
7981 break;
7982 }
7983
7984 return Qualifiers::OCL_None;
7985}
7986
7987static const Type *getIntegerTypeForEnum(const EnumType *ET) {
7988 // Incomplete enum types are not treated as integer types.
7989 // FIXME: In C++, enum types are never integer types.
7990 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
7991 return ET->getDecl()->getIntegerType().getTypePtr();
7992 return nullptr;
7993}
7994
7995/// getIntegerTypeOrder - Returns the highest ranked integer type:
7996/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
7997/// LHS < RHS, return -1.
7999 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
8000 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
8001
8002 // Unwrap enums to their underlying type.
8003 if (const auto *ET = dyn_cast<EnumType>(LHSC))
8004 LHSC = getIntegerTypeForEnum(ET);
8005 if (const auto *ET = dyn_cast<EnumType>(RHSC))
8006 RHSC = getIntegerTypeForEnum(ET);
8007
8008 if (LHSC == RHSC) return 0;
8009
8010 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
8011 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
8012
8013 unsigned LHSRank = getIntegerRank(LHSC);
8014 unsigned RHSRank = getIntegerRank(RHSC);
8015
8016 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
8017 if (LHSRank == RHSRank) return 0;
8018 return LHSRank > RHSRank ? 1 : -1;
8019 }
8020
8021 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
8022 if (LHSUnsigned) {
8023 // If the unsigned [LHS] type is larger, return it.
8024 if (LHSRank >= RHSRank)
8025 return 1;
8026
8027 // If the signed type can represent all values of the unsigned type, it
8028 // wins. Because we are dealing with 2's complement and types that are
8029 // powers of two larger than each other, this is always safe.
8030 return -1;
8031 }
8032
8033 // If the unsigned [RHS] type is larger, return it.
8034 if (RHSRank >= LHSRank)
8035 return -1;
8036
8037 // If the signed type can represent all values of the unsigned type, it
8038 // wins. Because we are dealing with 2's complement and types that are
8039 // powers of two larger than each other, this is always safe.
8040 return 1;
8041}
8042
8044 if (CFConstantStringTypeDecl)
8045 return CFConstantStringTypeDecl;
8046
8047 assert(!CFConstantStringTagDecl &&
8048 "tag and typedef should be initialized together");
8049 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
8050 CFConstantStringTagDecl->startDefinition();
8051
8052 struct {
8053 QualType Type;
8054 const char *Name;
8055 } Fields[5];
8056 unsigned Count = 0;
8057
8058 /// Objective-C ABI
8059 ///
8060 /// typedef struct __NSConstantString_tag {
8061 /// const int *isa;
8062 /// int flags;
8063 /// const char *str;
8064 /// long length;
8065 /// } __NSConstantString;
8066 ///
8067 /// Swift ABI (4.1, 4.2)
8068 ///
8069 /// typedef struct __NSConstantString_tag {
8070 /// uintptr_t _cfisa;
8071 /// uintptr_t _swift_rc;
8072 /// _Atomic(uint64_t) _cfinfoa;
8073 /// const char *_ptr;
8074 /// uint32_t _length;
8075 /// } __NSConstantString;
8076 ///
8077 /// Swift ABI (5.0)
8078 ///
8079 /// typedef struct __NSConstantString_tag {
8080 /// uintptr_t _cfisa;
8081 /// uintptr_t _swift_rc;
8082 /// _Atomic(uint64_t) _cfinfoa;
8083 /// const char *_ptr;
8084 /// uintptr_t _length;
8085 /// } __NSConstantString;
8086
8087 const auto CFRuntime = getLangOpts().CFRuntime;
8088 if (static_cast<unsigned>(CFRuntime) <
8089 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
8090 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
8091 Fields[Count++] = { IntTy, "flags" };
8092 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
8093 Fields[Count++] = { LongTy, "length" };
8094 } else {
8095 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
8096 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
8097 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
8098 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
8101 Fields[Count++] = { IntTy, "_ptr" };
8102 else
8103 Fields[Count++] = { getUIntPtrType(), "_ptr" };
8104 }
8105
8106 // Create fields
8107 for (unsigned i = 0; i < Count; ++i) {
8108 FieldDecl *Field =
8109 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
8110 SourceLocation(), &Idents.get(Fields[i].Name),
8111 Fields[i].Type, /*TInfo=*/nullptr,
8112 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8113 Field->setAccess(AS_public);
8114 CFConstantStringTagDecl->addDecl(Field);
8115 }
8116
8117 CFConstantStringTagDecl->completeDefinition();
8118 // This type is designed to be compatible with NSConstantString, but cannot
8119 // use the same name, since NSConstantString is an interface.
8120 auto tagType = getTagDeclType(CFConstantStringTagDecl);
8121 CFConstantStringTypeDecl =
8122 buildImplicitTypedef(tagType, "__NSConstantString");
8123
8124 return CFConstantStringTypeDecl;
8125}
8126
8128 if (!CFConstantStringTagDecl)
8129 getCFConstantStringDecl(); // Build the tag and the typedef.
8130 return CFConstantStringTagDecl;
8131}
8132
8133// getCFConstantStringType - Return the type used for constant CFStrings.
8136}
8137
8139 if (ObjCSuperType.isNull()) {
8140 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
8141 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
8142 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
8143 }
8144 return ObjCSuperType;
8145}
8146
8148 const auto *TD = T->castAs<TypedefType>();
8149 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
8150 const auto *TagType =
8151 CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>();
8152 CFConstantStringTagDecl = TagType->getDecl();
8153}
8154
8156 if (BlockDescriptorType)
8157 return getTagDeclType(BlockDescriptorType);
8158
8159 RecordDecl *RD;
8160 // FIXME: Needs the FlagAppleBlock bit.
8161 RD = buildImplicitRecord("__block_descriptor");
8162 RD->startDefinition();
8163
8164 QualType FieldTypes[] = {
8167 };
8168
8169 static const char *const FieldNames[] = {
8170 "reserved",
8171 "Size"
8172 };
8173
8174 for (size_t i = 0; i < 2; ++i) {
8176 *this, RD, SourceLocation(), SourceLocation(),
8177 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8178 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8179 Field->setAccess(AS_public);
8180 RD->addDecl(Field);
8181 }
8182
8183 RD->completeDefinition();
8184
8185 BlockDescriptorType = RD;
8186
8187 return getTagDeclType(BlockDescriptorType);
8188}
8189
8191 if (BlockDescriptorExtendedType)
8192 return getTagDeclType(BlockDescriptorExtendedType);
8193
8194 RecordDecl *RD;
8195 // FIXME: Needs the FlagAppleBlock bit.
8196 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
8197 RD->startDefinition();
8198
8199 QualType FieldTypes[] = {
8204 };
8205
8206 static const char *const FieldNames[] = {
8207 "reserved",
8208 "Size",
8209 "CopyFuncPtr",
8210 "DestroyFuncPtr"
8211 };
8212
8213 for (size_t i = 0; i < 4; ++i) {
8215 *this, RD, SourceLocation(), SourceLocation(),
8216 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8217 /*BitWidth=*/nullptr,
8218 /*Mutable=*/false, ICIS_NoInit);
8219 Field->setAccess(AS_public);
8220 RD->addDecl(Field);
8221 }
8222
8223 RD->completeDefinition();
8224
8225 BlockDescriptorExtendedType = RD;
8226 return getTagDeclType(BlockDescriptorExtendedType);
8227}
8228
8230 const auto *BT = dyn_cast<BuiltinType>(T);
8231
8232 if (!BT) {
8233 if (isa<PipeType>(T))
8234 return OCLTK_Pipe;
8235
8236 return OCLTK_Default;
8237 }
8238
8239 switch (BT->getKind()) {
8240#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8241 case BuiltinType::Id: \
8242 return OCLTK_Image;
8243#include "clang/Basic/OpenCLImageTypes.def"
8244
8245 case BuiltinType::OCLClkEvent:
8246 return OCLTK_ClkEvent;
8247
8248 case BuiltinType::OCLEvent:
8249 return OCLTK_Event;
8250
8251 case BuiltinType::OCLQueue:
8252 return OCLTK_Queue;
8253
8254 case BuiltinType::OCLReserveID:
8255 return OCLTK_ReserveID;
8256
8257 case BuiltinType::OCLSampler:
8258 return OCLTK_Sampler;
8259
8260 default:
8261 return OCLTK_Default;
8262 }
8263}
8264
8266 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
8267}
8268
8269/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
8270/// requires copy/dispose. Note that this must match the logic
8271/// in buildByrefHelpers.
8273 const VarDecl *D) {
8274 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
8275 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
8276 if (!copyExpr && record->hasTrivialDestructor()) return false;
8277
8278 return true;
8279 }
8280
8281 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
8282 // move or destroy.
8284 return true;
8285
8286 if (!Ty->isObjCRetainableType()) return false;
8287
8288 Qualifiers qs = Ty.getQualifiers();
8289
8290 // If we have lifetime, that dominates.
8291 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
8292 switch (lifetime) {
8293 case Qualifiers::OCL_None: llvm_unreachable("impossible");
8294
8295 // These are just bits as far as the runtime is concerned.
8298 return false;
8299
8300 // These cases should have been taken care of when checking the type's
8301 // non-triviality.
8304 llvm_unreachable("impossible");
8305 }
8306 llvm_unreachable("fell out of lifetime switch!");
8307 }
8308 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
8310}
8311
8313 Qualifiers::ObjCLifetime &LifeTime,
8314 bool &HasByrefExtendedLayout) const {
8315 if (!getLangOpts().ObjC ||
8316 getLangOpts().getGC() != LangOptions::NonGC)
8317 return false;
8318
8319 HasByrefExtendedLayout = false;
8320 if (Ty->isRecordType()) {
8321 HasByrefExtendedLayout = true;
8322 LifeTime = Qualifiers::OCL_None;
8323 } else if ((LifeTime = Ty.getObjCLifetime())) {
8324 // Honor the ARC qualifiers.
8325 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
8326 // The MRR rule.
8328 } else {
8329 LifeTime = Qualifiers::OCL_None;
8330 }
8331 return true;
8332}
8333
8335 assert(Target && "Expected target to be initialized");
8336 const llvm::Triple &T = Target->getTriple();
8337 // Windows is LLP64 rather than LP64
8338 if (T.isOSWindows() && T.isArch64Bit())
8339 return UnsignedLongLongTy;
8340 return UnsignedLongTy;
8341}
8342
8344 assert(Target && "Expected target to be initialized");
8345 const llvm::Triple &T = Target->getTriple();
8346 // Windows is LLP64 rather than LP64
8347 if (T.isOSWindows() && T.isArch64Bit())
8348 return LongLongTy;
8349 return LongTy;
8350}
8351
8353 if (!ObjCInstanceTypeDecl)
8354 ObjCInstanceTypeDecl =
8355 buildImplicitTypedef(getObjCIdType(), "instancetype");
8356 return ObjCInstanceTypeDecl;
8357}
8358
8359// This returns true if a type has been typedefed to BOOL:
8360// typedef <type> BOOL;
8362 if (const auto *TT = dyn_cast<TypedefType>(T))
8363 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
8364 return II->isStr("BOOL");
8365
8366 return false;
8367}
8368
8369/// getObjCEncodingTypeSize returns size of type for objective-c encoding
8370/// purpose.
8372 if (!type->isIncompleteArrayType() && type->isIncompleteType())
8373 return CharUnits::Zero();
8374
8376
8377 // Make all integer and enum types at least as large as an int
8378 if (sz.isPositive() && type->isIntegralOrEnumerationType())
8379 sz = std::max(sz, getTypeSizeInChars(IntTy));
8380 // Treat arrays as pointers, since that's how they're passed in.
8381 else if (type->isArrayType())
8383 return sz;
8384}
8385
8387 return getTargetInfo().getCXXABI().isMicrosoft() &&
8388 VD->isStaticDataMember() &&
8390 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
8391}
8392
8395 if (!VD->isInline())
8397
8398 // In almost all cases, it's a weak definition.
8399 auto *First = VD->getFirstDecl();
8400 if (First->isInlineSpecified() || !First->isStaticDataMember())
8402
8403 // If there's a file-context declaration in this translation unit, it's a
8404 // non-discardable definition.
8405 for (auto *D : VD->redecls())
8407 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
8409
8410 // If we've not seen one yet, we don't know.
8412}
8413
8414static std::string charUnitsToString(const CharUnits &CU) {
8415 return llvm::itostr(CU.getQuantity());
8416}
8417
8418/// getObjCEncodingForBlock - Return the encoded type for this block
8419/// declaration.
8421 std::string S;
8422
8423 const BlockDecl *Decl = Expr->getBlockDecl();
8424 QualType BlockTy =
8426 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
8427 // Encode result type.
8428 if (getLangOpts().EncodeExtendedBlockSig)
8430 true /*Extended*/);
8431 else
8432 getObjCEncodingForType(BlockReturnTy, S);
8433 // Compute size of all parameters.
8434 // Start with computing size of a pointer in number of bytes.
8435 // FIXME: There might(should) be a better way of doing this computation!
8437 CharUnits ParmOffset = PtrSize;
8438 for (auto *PI : Decl->parameters()) {
8439 QualType PType = PI->getType();
8441 if (sz.isZero())
8442 continue;
8443 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
8444 ParmOffset += sz;
8445 }
8446 // Size of the argument frame
8447 S += charUnitsToString(ParmOffset);
8448 // Block pointer and offset.
8449 S += "@?0";
8450
8451 // Argument types.
8452 ParmOffset = PtrSize;
8453 for (auto *PVDecl : Decl->parameters()) {
8454 QualType PType = PVDecl->getOriginalType();
8455 if (const auto *AT =
8456 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8457 // Use array's original type only if it has known number of
8458 // elements.
8459 if (!isa<ConstantArrayType>(AT))
8460 PType = PVDecl->getType();
8461 } else if (PType->isFunctionType())
8462 PType = PVDecl->getType();
8463 if (getLangOpts().EncodeExtendedBlockSig)
8465 S, true /*Extended*/);
8466 else
8467 getObjCEncodingForType(PType, S);
8468 S += charUnitsToString(ParmOffset);
8469 ParmOffset += getObjCEncodingTypeSize(PType);
8470 }
8471
8472 return S;
8473}
8474
8475std::string
8477 std::string S;
8478 // Encode result type.
8479 getObjCEncodingForType(Decl->getReturnType(), S);
8480 CharUnits ParmOffset;
8481 // Compute size of all parameters.
8482 for (auto *PI : Decl->parameters()) {
8483 QualType PType = PI->getType();
8485 if (sz.isZero())
8486 continue;
8487
8488 assert(sz.isPositive() &&
8489 "getObjCEncodingForFunctionDecl - Incomplete param type");
8490 ParmOffset += sz;
8491 }
8492 S += charUnitsToString(ParmOffset);
8493 ParmOffset = CharUnits::Zero();
8494
8495 // Argument types.
8496 for (auto *PVDecl : Decl->parameters()) {
8497 QualType PType = PVDecl->getOriginalType();
8498 if (const auto *AT =
8499 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8500 // Use array's original type only if it has known number of
8501 // elements.
8502 if (!isa<ConstantArrayType>(AT))
8503 PType = PVDecl->getType();
8504 } else if (PType->isFunctionType())
8505 PType = PVDecl->getType();
8506 getObjCEncodingForType(PType, S);
8507 S += charUnitsToString(ParmOffset);
8508 ParmOffset += getObjCEncodingTypeSize(PType);
8509 }
8510
8511 return S;
8512}
8513
8514/// getObjCEncodingForMethodParameter - Return the encoded type for a single
8515/// method parameter or return type. If Extended, include class names and
8516/// block object types.
8518 QualType T, std::string& S,
8519 bool Extended) const {
8520 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
8522 // Encode parameter type.
8523 ObjCEncOptions Options = ObjCEncOptions()
8524 .setExpandPointedToStructures()
8525 .setExpandStructures()
8526 .setIsOutermostType();
8527 if (Extended)
8528 Options.setEncodeBlockParameters().setEncodeClassNames();
8529 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
8530}
8531
8532/// getObjCEncodingForMethodDecl - Return the encoded type for this method
8533/// declaration.
8535 bool Extended) const {
8536 // FIXME: This is not very efficient.
8537 // Encode return type.
8538 std::string S;
8539 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
8540 Decl->getReturnType(), S, Extended);
8541 // Compute size of all parameters.
8542 // Start with computing size of a pointer in number of bytes.
8543 // FIXME: There might(should) be a better way of doing this computation!
8545 // The first two arguments (self and _cmd) are pointers; account for
8546 // their size.
8547 CharUnits ParmOffset = 2 * PtrSize;
8548 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8549 E = Decl->sel_param_end(); PI != E; ++PI) {
8550 QualType PType = (*PI)->getType();
8552 if (sz.isZero())
8553 continue;
8554
8555 assert(sz.isPositive() &&
8556 "getObjCEncodingForMethodDecl - Incomplete param type");
8557 ParmOffset += sz;
8558 }
8559 S += charUnitsToString(ParmOffset);
8560 S += "@0:";
8561 S += charUnitsToString(PtrSize);
8562
8563 // Argument types.
8564 ParmOffset = 2 * PtrSize;
8565 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8566 E = Decl->sel_param_end(); PI != E; ++PI) {
8567 const ParmVarDecl *PVDecl = *PI;
8568 QualType PType = PVDecl->getOriginalType();
8569 if (const auto *AT =
8570 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8571 // Use array's original type only if it has known number of
8572 // elements.
8573 if (!isa<ConstantArrayType>(AT))
8574 PType = PVDecl->getType();
8575 } else if (PType->isFunctionType())
8576 PType = PVDecl->getType();
8578 PType, S, Extended);
8579 S += charUnitsToString(ParmOffset);
8580 ParmOffset += getObjCEncodingTypeSize(PType);
8581 }
8582
8583 return S;
8584}
8585
8588 const ObjCPropertyDecl *PD,
8589 const Decl *Container) const {
8590 if (!Container)
8591 return nullptr;
8592 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
8593 for (auto *PID : CID->property_impls())
8594 if (PID->getPropertyDecl() == PD)
8595 return PID;
8596 } else {
8597 const auto *OID = cast<ObjCImplementationDecl>(Container);
8598 for (auto *PID : OID->property_impls())
8599 if (PID->getPropertyDecl() == PD)
8600 return PID;
8601 }
8602 return nullptr;
8603}
8604
8605/// getObjCEncodingForPropertyDecl - Return the encoded type for this
8606/// property declaration. If non-NULL, Container must be either an
8607/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
8608/// NULL when getting encodings for protocol properties.
8609/// Property attributes are stored as a comma-delimited C string. The simple
8610/// attributes readonly and bycopy are encoded as single characters. The
8611/// parametrized attributes, getter=name, setter=name, and ivar=name, are
8612/// encoded as single characters, followed by an identifier. Property types
8613/// are also encoded as a parametrized attribute. The characters used to encode
8614/// these attributes are defined by the following enumeration:
8615/// @code
8616/// enum PropertyAttributes {
8617/// kPropertyReadOnly = 'R', // property is read-only.
8618/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
8619/// kPropertyByref = '&', // property is a reference to the value last assigned
8620/// kPropertyDynamic = 'D', // property is dynamic
8621/// kPropertyGetter = 'G', // followed by getter selector name
8622/// kPropertySetter = 'S', // followed by setter selector name
8623/// kPropertyInstanceVariable = 'V' // followed by instance variable name
8624/// kPropertyType = 'T' // followed by old-style type encoding.
8625/// kPropertyWeak = 'W' // 'weak' property
8626/// kPropertyStrong = 'P' // property GC'able
8627/// kPropertyNonAtomic = 'N' // property non-atomic
8628/// kPropertyOptional = '?' // property optional
8629/// };
8630/// @endcode
8631std::string
8633 const Decl *Container) const {
8634 // Collect information from the property implementation decl(s).
8635 bool Dynamic = false;
8636 ObjCPropertyImplDecl *SynthesizePID = nullptr;
8637
8638 if (ObjCPropertyImplDecl *PropertyImpDecl =
8640 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
8641 Dynamic = true;
8642 else
8643 SynthesizePID = PropertyImpDecl;
8644 }
8645
8646 // FIXME: This is not very efficient.
8647 std::string S = "T";
8648
8649 // Encode result type.
8650 // GCC has some special rules regarding encoding of properties which
8651 // closely resembles encoding of ivars.
8653
8654 if (PD->isOptional())
8655 S += ",?";
8656
8657 if (PD->isReadOnly()) {
8658 S += ",R";
8660 S += ",C";
8662 S += ",&";
8664 S += ",W";
8665 } else {
8666 switch (PD->getSetterKind()) {
8667 case ObjCPropertyDecl::Assign: break;
8668 case ObjCPropertyDecl::Copy: S += ",C"; break;
8669 case ObjCPropertyDecl::Retain: S += ",&"; break;
8670 case ObjCPropertyDecl::Weak: S += ",W"; break;
8671 }
8672 }
8673
8674 // It really isn't clear at all what this means, since properties
8675 // are "dynamic by default".
8676 if (Dynamic)
8677 S += ",D";
8678
8680 S += ",N";
8681
8683 S += ",G";
8684 S += PD->getGetterName().getAsString();
8685 }
8686
8688 S += ",S";
8689 S += PD->getSetterName().getAsString();
8690 }
8691
8692 if (SynthesizePID) {
8693 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
8694 S += ",V";
8695 S += OID->getNameAsString();
8696 }
8697
8698 // FIXME: OBJCGC: weak & strong
8699 return S;
8700}
8701
8702/// getLegacyIntegralTypeEncoding -
8703/// Another legacy compatibility encoding: 32-bit longs are encoded as
8704/// 'l' or 'L' , but not always. For typedefs, we need to use
8705/// 'i' or 'I' instead if encoding a struct field, or a pointer!
8707 if (PointeeTy->getAs<TypedefType>()) {
8708 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
8709 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
8710 PointeeTy = UnsignedIntTy;
8711 else
8712 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
8713 PointeeTy = IntTy;
8714 }
8715 }
8716}
8717
8719 const FieldDecl *Field,
8720 QualType *NotEncodedT) const {
8721 // We follow the behavior of gcc, expanding structures which are
8722 // directly pointed to, and expanding embedded structures. Note that
8723 // these rules are sufficient to prevent recursive encoding of the
8724 // same type.
8725 getObjCEncodingForTypeImpl(T, S,
8726 ObjCEncOptions()
8727 .setExpandPointedToStructures()
8728 .setExpandStructures()
8729 .setIsOutermostType(),
8730 Field, NotEncodedT);
8731}
8732
8734 std::string& S) const {
8735 // Encode result type.
8736 // GCC has some special rules regarding encoding of properties which
8737 // closely resembles encoding of ivars.
8738 getObjCEncodingForTypeImpl(T, S,
8739 ObjCEncOptions()
8740 .setExpandPointedToStructures()
8741 .setExpandStructures()
8742 .setIsOutermostType()
8743 .setEncodingProperty(),
8744 /*Field=*/nullptr);
8745}
8746
8748 const BuiltinType *BT) {
8749 BuiltinType::Kind kind = BT->getKind();
8750 switch (kind) {
8751 case BuiltinType::Void: return 'v';
8752 case BuiltinType::Bool: return 'B';
8753 case BuiltinType::Char8:
8754 case BuiltinType::Char_U:
8755 case BuiltinType::UChar: return 'C';
8756 case BuiltinType::Char16:
8757 case BuiltinType::UShort: return 'S';
8758 case BuiltinType::Char32:
8759 case BuiltinType::UInt: return 'I';
8760 case BuiltinType::ULong:
8761 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
8762 case BuiltinType::UInt128: return 'T';
8763 case BuiltinType::ULongLong: return 'Q';
8764 case BuiltinType::Char_S:
8765 case BuiltinType::SChar: return 'c';
8766 case BuiltinType::Short: return 's';
8767 case BuiltinType::WChar_S:
8768 case BuiltinType::WChar_U:
8769 case BuiltinType::Int: return 'i';
8770 case BuiltinType::Long:
8771 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
8772 case BuiltinType::LongLong: return 'q';
8773 case BuiltinType::Int128: return 't';
8774 case BuiltinType::Float: return 'f';
8775 case BuiltinType::Double: return 'd';
8776 case BuiltinType::LongDouble: return 'D';
8777 case BuiltinType::NullPtr: return '*'; // like char*
8778
8779 case BuiltinType::BFloat16:
8780 case BuiltinType::Float16:
8781 case BuiltinType::Float128:
8782 case BuiltinType::Ibm128:
8783 case BuiltinType::Half:
8784 case BuiltinType::ShortAccum:
8785 case BuiltinType::Accum:
8786 case BuiltinType::LongAccum:
8787 case BuiltinType::UShortAccum:
8788 case BuiltinType::UAccum:
8789 case BuiltinType::ULongAccum:
8790 case BuiltinType::ShortFract:
8791 case BuiltinType::Fract:
8792 case BuiltinType::LongFract:
8793 case BuiltinType::UShortFract:
8794 case BuiltinType::UFract:
8795 case BuiltinType::ULongFract:
8796 case BuiltinType::SatShortAccum:
8797 case BuiltinType::SatAccum:
8798 case BuiltinType::SatLongAccum:
8799 case BuiltinType::SatUShortAccum:
8800 case BuiltinType::SatUAccum:
8801 case BuiltinType::SatULongAccum:
8802 case BuiltinType::SatShortFract:
8803 case BuiltinType::SatFract:
8804 case BuiltinType::SatLongFract:
8805 case BuiltinType::SatUShortFract:
8806 case BuiltinType::SatUFract:
8807 case BuiltinType::SatULongFract:
8808 // FIXME: potentially need @encodes for these!
8809 return ' ';
8810
8811#define SVE_TYPE(Name, Id, SingletonId) \
8812 case BuiltinType::Id:
8813#include "clang/Basic/AArch64SVEACLETypes.def"
8814#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
8815#include "clang/Basic/RISCVVTypes.def"
8816#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
8817#include "clang/Basic/WebAssemblyReferenceTypes.def"
8818#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
8819#include "clang/Basic/AMDGPUTypes.def"
8820 {
8821 DiagnosticsEngine &Diags = C->getDiagnostics();
8822 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
8823 "cannot yet @encode type %0");
8824 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
8825 return ' ';
8826 }
8827
8828 case BuiltinType::ObjCId:
8829 case BuiltinType::ObjCClass:
8830 case BuiltinType::ObjCSel:
8831 llvm_unreachable("@encoding ObjC primitive type");
8832
8833 // OpenCL and placeholder types don't need @encodings.
8834#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8835 case BuiltinType::Id:
8836#include "clang/Basic/OpenCLImageTypes.def"
8837#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
8838 case BuiltinType::Id:
8839#include "clang/Basic/OpenCLExtensionTypes.def"
8840 case BuiltinType::OCLEvent:
8841 case BuiltinType::OCLClkEvent:
8842 case BuiltinType::OCLQueue:
8843 case BuiltinType::OCLReserveID:
8844 case BuiltinType::OCLSampler:
8845 case BuiltinType::Dependent:
8846#define PPC_VECTOR_TYPE(Name, Id, Size) \
8847 case BuiltinType::Id:
8848#include "clang/Basic/PPCTypes.def"
8849#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
8850#include "clang/Basic/HLSLIntangibleTypes.def"
8851#define BUILTIN_TYPE(KIND, ID)
8852#define PLACEHOLDER_TYPE(KIND, ID) \
8853 case BuiltinType::KIND:
8854#include "clang/AST/BuiltinTypes.def"
8855 llvm_unreachable("invalid builtin type for @encode");
8856 }
8857 llvm_unreachable("invalid BuiltinType::Kind value");
8858}
8859
8860static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
8861 EnumDecl *Enum = ET->getDecl();
8862
8863 // The encoding of an non-fixed enum type is always 'i', regardless of size.
8864 if (!Enum->isFixed())
8865 return 'i';
8866
8867 // The encoding of a fixed enum type matches its fixed underlying type.
8868 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
8870}
8871
8872static void EncodeBitField(const ASTContext *Ctx, std::string& S,
8873 QualType T, const FieldDecl *FD) {
8874 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
8875 S += 'b';
8876 // The NeXT runtime encodes bit fields as b followed by the number of bits.
8877 // The GNU runtime requires more information; bitfields are encoded as b,
8878 // then the offset (in bits) of the first element, then the type of the
8879 // bitfield, then the size in bits. For example, in this structure:
8880 //
8881 // struct
8882 // {
8883 // int integer;
8884 // int flags:2;
8885 // };
8886 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
8887 // runtime, but b32i2 for the GNU runtime. The reason for this extra
8888 // information is not especially sensible, but we're stuck with it for
8889 // compatibility with GCC, although providing it breaks anything that
8890 // actually uses runtime introspection and wants to work on both runtimes...
8891 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
8892 uint64_t Offset;
8893
8894 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
8895 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
8896 IVD);
8897 } else {
8898 const RecordDecl *RD = FD->getParent();
8899 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
8900 Offset = RL.getFieldOffset(FD->getFieldIndex());
8901 }
8902
8903 S += llvm::utostr(Offset);
8904
8905 if (const auto *ET = T->getAs<EnumType>())
8906 S += ObjCEncodingForEnumType(Ctx, ET);
8907 else {
8908 const auto *BT = T->castAs<BuiltinType>();
8909 S += getObjCEncodingForPrimitiveType(Ctx, BT);
8910 }
8911 }
8912 S += llvm::utostr(FD->getBitWidthValue());
8913}
8914
8915// Helper function for determining whether the encoded type string would include
8916// a template specialization type.
8918 bool VisitBasesAndFields) {
8920
8921 if (auto *PT = T->getAs<PointerType>())
8923 PT->getPointeeType().getTypePtr(), false);
8924
8925 auto *CXXRD = T->getAsCXXRecordDecl();
8926
8927 if (!CXXRD)
8928 return false;
8929
8930 if (isa<ClassTemplateSpecializationDecl>(CXXRD))
8931 return true;
8932
8933 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
8934 return false;
8935
8936 for (const auto &B : CXXRD->bases())
8937 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
8938 true))
8939 return true;
8940
8941 for (auto *FD : CXXRD->fields())
8942 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
8943 true))
8944 return true;
8945
8946 return false;
8947}
8948
8949// FIXME: Use SmallString for accumulating string.
8950void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
8951 const ObjCEncOptions Options,
8952 const FieldDecl *FD,
8953 QualType *NotEncodedT) const {
8955 switch (CT->getTypeClass()) {
8956 case Type::Builtin:
8957 case Type::Enum:
8958 if (FD && FD->isBitField())
8959 return EncodeBitField(this, S, T, FD);
8960 if (const auto *BT = dyn_cast<BuiltinType>(CT))
8961 S += getObjCEncodingForPrimitiveType(this, BT);
8962 else
8963 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
8964 return;
8965
8966 case Type::Complex:
8967 S += 'j';
8968 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
8969 ObjCEncOptions(),
8970 /*Field=*/nullptr);
8971 return;
8972
8973 case Type::Atomic:
8974 S += 'A';
8975 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
8976 ObjCEncOptions(),
8977 /*Field=*/nullptr);
8978 return;
8979
8980 // encoding for pointer or reference types.
8981 case Type::Pointer:
8982 case Type::LValueReference:
8983 case Type::RValueReference: {
8984 QualType PointeeTy;
8985 if (isa<PointerType>(CT)) {
8986 const auto *PT = T->castAs<PointerType>();
8987 if (PT->isObjCSelType()) {
8988 S += ':';
8989 return;
8990 }
8991 PointeeTy = PT->getPointeeType();
8992 } else {
8993 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
8994 }
8995
8996 bool isReadOnly = false;
8997 // For historical/compatibility reasons, the read-only qualifier of the
8998 // pointee gets emitted _before_ the '^'. The read-only qualifier of
8999 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
9000 // Also, do not emit the 'r' for anything but the outermost type!
9001 if (T->getAs<TypedefType>()) {
9002 if (Options.IsOutermostType() && T.isConstQualified()) {
9003 isReadOnly = true;
9004 S += 'r';
9005 }
9006 } else if (Options.IsOutermostType()) {
9007 QualType P = PointeeTy;
9008 while (auto PT = P->getAs<PointerType>())
9009 P = PT->getPointeeType();
9010 if (P.isConstQualified()) {
9011 isReadOnly = true;
9012 S += 'r';
9013 }
9014 }
9015 if (isReadOnly) {
9016 // Another legacy compatibility encoding. Some ObjC qualifier and type
9017 // combinations need to be rearranged.
9018 // Rewrite "in const" from "nr" to "rn"
9019 if (StringRef(S).ends_with("nr"))
9020 S.replace(S.end()-2, S.end(), "rn");
9021 }
9022
9023 if (PointeeTy->isCharType()) {
9024 // char pointer types should be encoded as '*' unless it is a
9025 // type that has been typedef'd to 'BOOL'.
9026 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
9027 S += '*';
9028 return;
9029 }
9030 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
9031 // GCC binary compat: Need to convert "struct objc_class *" to "#".
9032 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
9033 S += '#';
9034 return;
9035 }
9036 // GCC binary compat: Need to convert "struct objc_object *" to "@".
9037 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
9038 S += '@';
9039 return;
9040 }
9041 // If the encoded string for the class includes template names, just emit
9042 // "^v" for pointers to the class.
9043 if (getLangOpts().CPlusPlus &&
9044 (!getLangOpts().EncodeCXXClassTemplateSpec &&
9046 RTy, Options.ExpandPointedToStructures()))) {
9047 S += "^v";
9048 return;
9049 }
9050 // fall through...
9051 }
9052 S += '^';
9054
9055 ObjCEncOptions NewOptions;
9056 if (Options.ExpandPointedToStructures())
9057 NewOptions.setExpandStructures();
9058 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
9059 /*Field=*/nullptr, NotEncodedT);
9060 return;
9061 }
9062
9063 case Type::ConstantArray:
9064 case Type::IncompleteArray:
9065 case Type::VariableArray: {
9066 const auto *AT = cast<ArrayType>(CT);
9067
9068 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
9069 // Incomplete arrays are encoded as a pointer to the array element.
9070 S += '^';
9071
9072 getObjCEncodingForTypeImpl(
9073 AT->getElementType(), S,
9074 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
9075 } else {
9076 S += '[';
9077
9078 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
9079 S += llvm::utostr(CAT->getZExtSize());
9080 else {
9081 //Variable length arrays are encoded as a regular array with 0 elements.
9082 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
9083 "Unknown array type!");
9084 S += '0';
9085 }
9086
9087 getObjCEncodingForTypeImpl(
9088 AT->getElementType(), S,
9089 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
9090 NotEncodedT);
9091 S += ']';
9092 }
9093 return;
9094 }
9095
9096 case Type::FunctionNoProto:
9097 case Type::FunctionProto:
9098 S += '?';
9099 return;
9100
9101 case Type::Record: {
9102 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
9103 S += RDecl->isUnion() ? '(' : '{';
9104 // Anonymous structures print as '?'
9105 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
9106 S += II->getName();
9107 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
9108 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
9109 llvm::raw_string_ostream OS(S);
9110 printTemplateArgumentList(OS, TemplateArgs.asArray(),
9112 }
9113 } else {
9114 S += '?';
9115 }
9116 if (Options.ExpandStructures()) {
9117 S += '=';
9118 if (!RDecl->isUnion()) {
9119 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
9120 } else {
9121 for (const auto *Field : RDecl->fields()) {
9122 if (FD) {
9123 S += '"';
9124 S += Field->getNameAsString();
9125 S += '"';
9126 }
9127
9128 // Special case bit-fields.
9129 if (Field->isBitField()) {
9130 getObjCEncodingForTypeImpl(Field->getType(), S,
9131 ObjCEncOptions().setExpandStructures(),
9132 Field);
9133 } else {
9134 QualType qt = Field->getType();
9136 getObjCEncodingForTypeImpl(
9137 qt, S,
9138 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
9139 NotEncodedT);
9140 }
9141 }
9142 }
9143 }
9144 S += RDecl->isUnion() ? ')' : '}';
9145 return;
9146 }
9147
9148 case Type::BlockPointer: {
9149 const auto *BT = T->castAs<BlockPointerType>();
9150 S += "@?"; // Unlike a pointer-to-function, which is "^?".
9151 if (Options.EncodeBlockParameters()) {
9152 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
9153
9154 S += '<';
9155 // Block return type
9156 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
9157 Options.forComponentType(), FD, NotEncodedT);
9158 // Block self
9159 S += "@?";
9160 // Block parameters
9161 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
9162 for (const auto &I : FPT->param_types())
9163 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
9164 NotEncodedT);
9165 }
9166 S += '>';
9167 }
9168 return;
9169 }
9170
9171 case Type::ObjCObject: {
9172 // hack to match legacy encoding of *id and *Class
9174 if (Ty->isObjCIdType()) {
9175 S += "{objc_object=}";
9176 return;
9177 }
9178 else if (Ty->isObjCClassType()) {
9179 S += "{objc_class=}";
9180 return;
9181 }
9182 // TODO: Double check to make sure this intentionally falls through.
9183 [[fallthrough]];
9184 }
9185
9186 case Type::ObjCInterface: {
9187 // Ignore protocol qualifiers when mangling at this level.
9188 // @encode(class_name)
9189 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
9190 S += '{';
9191 S += OI->getObjCRuntimeNameAsString();
9192 if (Options.ExpandStructures()) {
9193 S += '=';
9195 DeepCollectObjCIvars(OI, true, Ivars);
9196 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
9197 const FieldDecl *Field = Ivars[i];
9198 if (Field->isBitField())
9199 getObjCEncodingForTypeImpl(Field->getType(), S,
9200 ObjCEncOptions().setExpandStructures(),
9201 Field);
9202 else
9203 getObjCEncodingForTypeImpl(Field->getType(), S,
9204 ObjCEncOptions().setExpandStructures(), FD,
9205 NotEncodedT);
9206 }
9207 }
9208 S += '}';
9209 return;
9210 }
9211
9212 case Type::ObjCObjectPointer: {
9213 const auto *OPT = T->castAs<ObjCObjectPointerType>();
9214 if (OPT->isObjCIdType()) {
9215 S += '@';
9216 return;
9217 }
9218
9219 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
9220 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
9221 // Since this is a binary compatibility issue, need to consult with
9222 // runtime folks. Fortunately, this is a *very* obscure construct.
9223 S += '#';
9224 return;
9225 }
9226
9227 if (OPT->isObjCQualifiedIdType()) {
9228 getObjCEncodingForTypeImpl(
9229 getObjCIdType(), S,
9230 Options.keepingOnly(ObjCEncOptions()
9231 .setExpandPointedToStructures()
9232 .setExpandStructures()),
9233 FD);
9234 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
9235 // Note that we do extended encoding of protocol qualifier list
9236 // Only when doing ivar or property encoding.
9237 S += '"';
9238 for (const auto *I : OPT->quals()) {
9239 S += '<';
9240 S += I->getObjCRuntimeNameAsString();
9241 S += '>';
9242 }
9243 S += '"';
9244 }
9245 return;
9246 }
9247
9248 S += '@';
9249 if (OPT->getInterfaceDecl() &&
9250 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
9251 S += '"';
9252 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
9253 for (const auto *I : OPT->quals()) {
9254 S += '<';
9255 S += I->getObjCRuntimeNameAsString();
9256 S += '>';
9257 }
9258 S += '"';
9259 }
9260 return;
9261 }
9262
9263 // gcc just blithely ignores member pointers.
9264 // FIXME: we should do better than that. 'M' is available.
9265 case Type::MemberPointer:
9266 // This matches gcc's encoding, even though technically it is insufficient.
9267 //FIXME. We should do a better job than gcc.
9268 case Type::Vector:
9269 case Type::ExtVector:
9270 // Until we have a coherent encoding of these three types, issue warning.
9271 if (NotEncodedT)
9272 *NotEncodedT = T;
9273 return;
9274
9275 case Type::ConstantMatrix:
9276 if (NotEncodedT)
9277 *NotEncodedT = T;
9278 return;
9279
9280 case Type::BitInt:
9281 if (NotEncodedT)
9282 *NotEncodedT = T;
9283 return;
9284
9285 // We could see an undeduced auto type here during error recovery.
9286 // Just ignore it.
9287 case Type::Auto:
9288 case Type::DeducedTemplateSpecialization:
9289 return;
9290
9291 case Type::HLSLAttributedResource:
9292 llvm_unreachable("unexpected type");
9293
9294 case Type::ArrayParameter:
9295 case Type::Pipe:
9296#define ABSTRACT_TYPE(KIND, BASE)
9297#define TYPE(KIND, BASE)
9298#define DEPENDENT_TYPE(KIND, BASE) \
9299 case Type::KIND:
9300#define NON_CANONICAL_TYPE(KIND, BASE) \
9301 case Type::KIND:
9302#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
9303 case Type::KIND:
9304#include "clang/AST/TypeNodes.inc"
9305 llvm_unreachable("@encode for dependent type!");
9306 }
9307 llvm_unreachable("bad type kind!");
9308}
9309
9310void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
9311 std::string &S,
9312 const FieldDecl *FD,
9313 bool includeVBases,
9314 QualType *NotEncodedT) const {
9315 assert(RDecl && "Expected non-null RecordDecl");
9316 assert(!RDecl->isUnion() && "Should not be called for unions");
9317 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
9318 return;
9319
9320 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
9321 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
9322 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
9323
9324 if (CXXRec) {
9325 for (const auto &BI : CXXRec->bases()) {
9326 if (!BI.isVirtual()) {
9327 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9328 if (base->isEmpty())
9329 continue;
9330 uint64_t offs = toBits(layout.getBaseClassOffset(base));
9331 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9332 std::make_pair(offs, base));
9333 }
9334 }
9335 }
9336
9337 for (FieldDecl *Field : RDecl->fields()) {
9338 if (!Field->isZeroLengthBitField() && Field->isZeroSize(*this))
9339 continue;
9340 uint64_t offs = layout.getFieldOffset(Field->getFieldIndex());
9341 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9342 std::make_pair(offs, Field));
9343 }
9344
9345 if (CXXRec && includeVBases) {
9346 for (const auto &BI : CXXRec->vbases()) {
9347 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9348 if (base->isEmpty())
9349 continue;
9350 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
9351 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
9352 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
9353 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
9354 std::make_pair(offs, base));
9355 }
9356 }
9357
9358 CharUnits size;
9359 if (CXXRec) {
9360 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
9361 } else {
9362 size = layout.getSize();
9363 }
9364
9365#ifndef NDEBUG
9366 uint64_t CurOffs = 0;
9367#endif
9368 std::multimap<uint64_t, NamedDecl *>::iterator
9369 CurLayObj = FieldOrBaseOffsets.begin();
9370
9371 if (CXXRec && CXXRec->isDynamicClass() &&
9372 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
9373 if (FD) {
9374 S += "\"_vptr$";
9375 std::string recname = CXXRec->getNameAsString();
9376 if (recname.empty()) recname = "?";
9377 S += recname;
9378 S += '"';
9379 }
9380 S += "^^?";
9381#ifndef NDEBUG
9382 CurOffs += getTypeSize(VoidPtrTy);
9383#endif
9384 }
9385
9386 if (!RDecl->hasFlexibleArrayMember()) {
9387 // Mark the end of the structure.
9388 uint64_t offs = toBits(size);
9389 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9390 std::make_pair(offs, nullptr));
9391 }
9392
9393 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
9394#ifndef NDEBUG
9395 assert(CurOffs <= CurLayObj->first);
9396 if (CurOffs < CurLayObj->first) {
9397 uint64_t padding = CurLayObj->first - CurOffs;
9398 // FIXME: There doesn't seem to be a way to indicate in the encoding that
9399 // packing/alignment of members is different that normal, in which case
9400 // the encoding will be out-of-sync with the real layout.
9401 // If the runtime switches to just consider the size of types without
9402 // taking into account alignment, we could make padding explicit in the
9403 // encoding (e.g. using arrays of chars). The encoding strings would be
9404 // longer then though.
9405 CurOffs += padding;
9406 }
9407#endif
9408
9409 NamedDecl *dcl = CurLayObj->second;
9410 if (!dcl)
9411 break; // reached end of structure.
9412
9413 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
9414 // We expand the bases without their virtual bases since those are going
9415 // in the initial structure. Note that this differs from gcc which
9416 // expands virtual bases each time one is encountered in the hierarchy,
9417 // making the encoding type bigger than it really is.
9418 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
9419 NotEncodedT);
9420 assert(!base->isEmpty());
9421#ifndef NDEBUG
9422 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
9423#endif
9424 } else {
9425 const auto *field = cast<FieldDecl>(dcl);
9426 if (FD) {
9427 S += '"';
9428 S += field->getNameAsString();
9429 S += '"';
9430 }
9431
9432 if (field->isBitField()) {
9433 EncodeBitField(this, S, field->getType(), field);
9434#ifndef NDEBUG
9435 CurOffs += field->getBitWidthValue();
9436#endif
9437 } else {
9438 QualType qt = field->getType();
9440 getObjCEncodingForTypeImpl(
9441 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
9442 FD, NotEncodedT);
9443#ifndef NDEBUG
9444 CurOffs += getTypeSize(field->getType());
9445#endif
9446 }
9447 }
9448 }
9449}
9450
9452 std::string& S) const {
9453 if (QT & Decl::OBJC_TQ_In)
9454 S += 'n';
9455 if (QT & Decl::OBJC_TQ_Inout)
9456 S += 'N';
9457 if (QT & Decl::OBJC_TQ_Out)
9458 S += 'o';
9459 if (QT & Decl::OBJC_TQ_Bycopy)
9460 S += 'O';
9461 if (QT & Decl::OBJC_TQ_Byref)
9462 S += 'R';
9463 if (QT & Decl::OBJC_TQ_Oneway)
9464 S += 'V';
9465}
9466
9468 if (!ObjCIdDecl) {
9471 ObjCIdDecl = buildImplicitTypedef(T, "id");
9472 }
9473 return ObjCIdDecl;
9474}
9475
9477 if (!ObjCSelDecl) {
9479 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
9480 }
9481 return ObjCSelDecl;
9482}
9483
9485 if (!ObjCClassDecl) {
9488 ObjCClassDecl = buildImplicitTypedef(T, "Class");
9489 }
9490 return ObjCClassDecl;
9491}
9492
9494 if (!ObjCProtocolClassDecl) {
9495 ObjCProtocolClassDecl
9498 &Idents.get("Protocol"),
9499 /*typeParamList=*/nullptr,
9500 /*PrevDecl=*/nullptr,
9501 SourceLocation(), true);
9502 }
9503
9504 return ObjCProtocolClassDecl;
9505}
9506
9507//===----------------------------------------------------------------------===//
9508// __builtin_va_list Construction Functions
9509//===----------------------------------------------------------------------===//
9510
9512 StringRef Name) {
9513 // typedef char* __builtin[_ms]_va_list;
9514 QualType T = Context->getPointerType(Context->CharTy);
9515 return Context->buildImplicitTypedef(T, Name);
9516}
9517
9519 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
9520}
9521
9523 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
9524}
9525
9527 // typedef void* __builtin_va_list;
9528 QualType T = Context->getPointerType(Context->VoidTy);
9529 return Context->buildImplicitTypedef(T, "__builtin_va_list");
9530}
9531
9532static TypedefDecl *
9534 // struct __va_list
9535 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
9536 if (Context->getLangOpts().CPlusPlus) {
9537 // namespace std { struct __va_list {
9538 auto *NS = NamespaceDecl::Create(
9539 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
9540 /*Inline=*/false, SourceLocation(), SourceLocation(),
9541 &Context->Idents.get("std"),
9542 /*PrevDecl=*/nullptr, /*Nested=*/false);
9543 NS->setImplicit();
9544 VaListTagDecl->setDeclContext(NS);
9545 }
9546
9547 VaListTagDecl->startDefinition();
9548
9549 const size_t NumFields = 5;
9550 QualType FieldTypes[NumFields];
9551 const char *FieldNames[NumFields];
9552
9553 // void *__stack;
9554 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
9555 FieldNames[0] = "__stack";
9556
9557 // void *__gr_top;
9558 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
9559 FieldNames[1] = "__gr_top";
9560
9561 // void *__vr_top;
9562 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9563 FieldNames[2] = "__vr_top";
9564
9565 // int __gr_offs;
9566 FieldTypes[3] = Context->IntTy;
9567 FieldNames[3] = "__gr_offs";
9568
9569 // int __vr_offs;
9570 FieldTypes[4] = Context->IntTy;
9571 FieldNames[4] = "__vr_offs";
9572
9573 // Create fields
9574 for (unsigned i = 0; i < NumFields; ++i) {
9575 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9576 VaListTagDecl,
9579 &Context->Idents.get(FieldNames[i]),
9580 FieldTypes[i], /*TInfo=*/nullptr,
9581 /*BitWidth=*/nullptr,
9582 /*Mutable=*/false,
9583 ICIS_NoInit);
9584 Field->setAccess(AS_public);
9585 VaListTagDecl->addDecl(Field);
9586 }
9587 VaListTagDecl->completeDefinition();
9588 Context->VaListTagDecl = VaListTagDecl;
9589 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9590
9591 // } __builtin_va_list;
9592 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
9593}
9594
9596 // typedef struct __va_list_tag {
9597 RecordDecl *VaListTagDecl;
9598
9599 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9600 VaListTagDecl->startDefinition();
9601
9602 const size_t NumFields = 5;
9603 QualType FieldTypes[NumFields];
9604 const char *FieldNames[NumFields];
9605
9606 // unsigned char gpr;
9607 FieldTypes[0] = Context->UnsignedCharTy;
9608 FieldNames[0] = "gpr";
9609
9610 // unsigned char fpr;
9611 FieldTypes[1] = Context->UnsignedCharTy;
9612 FieldNames[1] = "fpr";
9613
9614 // unsigned short reserved;
9615 FieldTypes[2] = Context->UnsignedShortTy;
9616 FieldNames[2] = "reserved";
9617
9618 // void* overflow_arg_area;
9619 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
9620 FieldNames[3] = "overflow_arg_area";
9621
9622 // void* reg_save_area;
9623 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
9624 FieldNames[4] = "reg_save_area";
9625
9626 // Create fields
9627 for (unsigned i = 0; i < NumFields; ++i) {
9628 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
9631 &Context->Idents.get(FieldNames[i]),
9632 FieldTypes[i], /*TInfo=*/nullptr,
9633 /*BitWidth=*/nullptr,
9634 /*Mutable=*/false,
9635 ICIS_NoInit);
9636 Field->setAccess(AS_public);
9637 VaListTagDecl->addDecl(Field);
9638 }
9639 VaListTagDecl->completeDefinition();
9640 Context->VaListTagDecl = VaListTagDecl;
9641 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9642
9643 // } __va_list_tag;
9644 TypedefDecl *VaListTagTypedefDecl =
9645 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
9646
9647 QualType VaListTagTypedefType =
9648 Context->getTypedefType(VaListTagTypedefDecl);
9649
9650 // typedef __va_list_tag __builtin_va_list[1];
9651 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9652 QualType VaListTagArrayType = Context->getConstantArrayType(
9653 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
9654 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9655}
9656
9657static TypedefDecl *
9659 // struct __va_list_tag {
9660 RecordDecl *VaListTagDecl;
9661 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9662 VaListTagDecl->startDefinition();
9663
9664 const size_t NumFields = 4;
9665 QualType FieldTypes[NumFields];
9666 const char *FieldNames[NumFields];
9667
9668 // unsigned gp_offset;
9669 FieldTypes[0] = Context->UnsignedIntTy;
9670 FieldNames[0] = "gp_offset";
9671
9672 // unsigned fp_offset;
9673 FieldTypes[1] = Context->UnsignedIntTy;
9674 FieldNames[1] = "fp_offset";
9675
9676 // void* overflow_arg_area;
9677 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9678 FieldNames[2] = "overflow_arg_area";
9679
9680 // void* reg_save_area;
9681 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
9682 FieldNames[3] = "reg_save_area";
9683
9684 // Create fields
9685 for (unsigned i = 0; i < NumFields; ++i) {
9686 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9687 VaListTagDecl,
9690 &Context->Idents.get(FieldNames[i]),
9691 FieldTypes[i], /*TInfo=*/nullptr,
9692 /*BitWidth=*/nullptr,
9693 /*Mutable=*/false,
9694 ICIS_NoInit);
9695 Field->setAccess(AS_public);
9696 VaListTagDecl->addDecl(Field);
9697 }
9698 VaListTagDecl->completeDefinition();
9699 Context->VaListTagDecl = VaListTagDecl;
9700 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9701
9702 // };
9703
9704 // typedef struct __va_list_tag __builtin_va_list[1];
9705 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9706 QualType VaListTagArrayType = Context->getConstantArrayType(
9707 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
9708 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9709}
9710
9712 // typedef int __builtin_va_list[4];
9713 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
9714 QualType IntArrayType = Context->getConstantArrayType(
9715 Context->IntTy, Size, nullptr, ArraySizeModifier::Normal, 0);
9716 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
9717}
9718
9719static TypedefDecl *
9721 // struct __va_list
9722 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
9723 if (Context->getLangOpts().CPlusPlus) {
9724 // namespace std { struct __va_list {
9725 NamespaceDecl *NS;
9726 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
9727 Context->getTranslationUnitDecl(),
9728 /*Inline=*/false, SourceLocation(),
9729 SourceLocation(), &Context->Idents.get("std"),
9730 /*PrevDecl=*/nullptr, /*Nested=*/false);
9731 NS->setImplicit();
9732 VaListDecl->setDeclContext(NS);
9733 }
9734
9735 VaListDecl->startDefinition();
9736
9737 // void * __ap;
9738 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9739 VaListDecl,
9742 &Context->Idents.get("__ap"),
9743 Context->getPointerType(Context->VoidTy),
9744 /*TInfo=*/nullptr,
9745 /*BitWidth=*/nullptr,
9746 /*Mutable=*/false,
9747 ICIS_NoInit);
9748 Field->setAccess(AS_public);
9749 VaListDecl->addDecl(Field);
9750
9751 // };
9752 VaListDecl->completeDefinition();
9753 Context->VaListTagDecl = VaListDecl;
9754
9755 // typedef struct __va_list __builtin_va_list;
9756 QualType T = Context->getRecordType(VaListDecl);
9757 return Context->buildImplicitTypedef(T, "__builtin_va_list");
9758}
9759
9760static TypedefDecl *
9762 // struct __va_list_tag {
9763 RecordDecl *VaListTagDecl;
9764 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9765 VaListTagDecl->startDefinition();
9766
9767 const size_t NumFields = 4;
9768 QualType FieldTypes[NumFields];
9769 const char *FieldNames[NumFields];
9770
9771 // long __gpr;
9772 FieldTypes[0] = Context->LongTy;
9773 FieldNames[0] = "__gpr";
9774
9775 // long __fpr;
9776 FieldTypes[1] = Context->LongTy;
9777 FieldNames[1] = "__fpr";
9778
9779 // void *__overflow_arg_area;
9780 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9781 FieldNames[2] = "__overflow_arg_area";
9782
9783 // void *__reg_save_area;
9784 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
9785 FieldNames[3] = "__reg_save_area";
9786
9787 // Create fields
9788 for (unsigned i = 0; i < NumFields; ++i) {
9789 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9790 VaListTagDecl,
9793 &Context->Idents.get(FieldNames[i]),
9794 FieldTypes[i], /*TInfo=*/nullptr,
9795 /*BitWidth=*/nullptr,
9796 /*Mutable=*/false,
9797 ICIS_NoInit);
9798 Field->setAccess(AS_public);
9799 VaListTagDecl->addDecl(Field);
9800 }
9801 VaListTagDecl->completeDefinition();
9802 Context->VaListTagDecl = VaListTagDecl;
9803 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9804
9805 // };
9806
9807 // typedef __va_list_tag __builtin_va_list[1];
9808 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9809 QualType VaListTagArrayType = Context->getConstantArrayType(
9810 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
9811
9812 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9813}
9814
9816 // typedef struct __va_list_tag {
9817 RecordDecl *VaListTagDecl;
9818 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9819 VaListTagDecl->startDefinition();
9820
9821 const size_t NumFields = 3;
9822 QualType FieldTypes[NumFields];
9823 const char *FieldNames[NumFields];
9824
9825 // void *CurrentSavedRegisterArea;
9826 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
9827 FieldNames[0] = "__current_saved_reg_area_pointer";
9828
9829 // void *SavedRegAreaEnd;
9830 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
9831 FieldNames[1] = "__saved_reg_area_end_pointer";
9832
9833 // void *OverflowArea;
9834 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9835 FieldNames[2] = "__overflow_area_pointer";
9836
9837 // Create fields
9838 for (unsigned i = 0; i < NumFields; ++i) {
9840 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
9841 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
9842 /*TInfo=*/nullptr,
9843 /*BitWidth=*/nullptr,
9844 /*Mutable=*/false, ICIS_NoInit);
9845 Field->setAccess(AS_public);
9846 VaListTagDecl->addDecl(Field);
9847 }
9848 VaListTagDecl->completeDefinition();
9849 Context->VaListTagDecl = VaListTagDecl;
9850 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9851
9852 // } __va_list_tag;
9853 TypedefDecl *VaListTagTypedefDecl =
9854 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
9855
9856 QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl);
9857
9858 // typedef __va_list_tag __builtin_va_list[1];
9859 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9860 QualType VaListTagArrayType = Context->getConstantArrayType(
9861 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
9862
9863 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9864}
9865
9866static TypedefDecl *
9868 // typedef struct __va_list_tag {
9869 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9870
9871 VaListTagDecl->startDefinition();
9872
9873 // int* __va_stk;
9874 // int* __va_reg;
9875 // int __va_ndx;
9876 constexpr size_t NumFields = 3;
9877 QualType FieldTypes[NumFields] = {Context->getPointerType(Context->IntTy),
9878 Context->getPointerType(Context->IntTy),
9879 Context->IntTy};
9880 const char *FieldNames[NumFields] = {"__va_stk", "__va_reg", "__va_ndx"};
9881
9882 // Create fields
9883 for (unsigned i = 0; i < NumFields; ++i) {
9885 *Context, VaListTagDecl, SourceLocation(), SourceLocation(),
9886 &Context->Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
9887 /*BitWidth=*/nullptr,
9888 /*Mutable=*/false, ICIS_NoInit);
9889 Field->setAccess(AS_public);
9890 VaListTagDecl->addDecl(Field);
9891 }
9892 VaListTagDecl->completeDefinition();
9893 Context->VaListTagDecl = VaListTagDecl;
9894 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9895
9896 // } __va_list_tag;
9897 TypedefDecl *VaListTagTypedefDecl =
9898 Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
9899
9900 return VaListTagTypedefDecl;
9901}
9902
9905 switch (Kind) {
9907 return CreateCharPtrBuiltinVaListDecl(Context);
9909 return CreateVoidPtrBuiltinVaListDecl(Context);
9911 return CreateAArch64ABIBuiltinVaListDecl(Context);
9913 return CreatePowerABIBuiltinVaListDecl(Context);
9915 return CreateX86_64ABIBuiltinVaListDecl(Context);
9917 return CreatePNaClABIBuiltinVaListDecl(Context);
9919 return CreateAAPCSABIBuiltinVaListDecl(Context);
9921 return CreateSystemZBuiltinVaListDecl(Context);
9923 return CreateHexagonBuiltinVaListDecl(Context);
9925 return CreateXtensaABIBuiltinVaListDecl(Context);
9926 }
9927
9928 llvm_unreachable("Unhandled __builtin_va_list type kind");
9929}
9930
9932 if (!BuiltinVaListDecl) {
9933 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
9934 assert(BuiltinVaListDecl->isImplicit());
9935 }
9936
9937 return BuiltinVaListDecl;
9938}
9939
9941 // Force the creation of VaListTagDecl by building the __builtin_va_list
9942 // declaration.
9943 if (!VaListTagDecl)
9944 (void)getBuiltinVaListDecl();
9945
9946 return VaListTagDecl;
9947}
9948
9950 if (!BuiltinMSVaListDecl)
9951 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
9952
9953 return BuiltinMSVaListDecl;
9954}
9955
9957 // Allow redecl custom type checking builtin for HLSL.
9958 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
9960 return true;
9962}
9963
9965 assert(ObjCConstantStringType.isNull() &&
9966 "'NSConstantString' type already set!");
9967
9968 ObjCConstantStringType = getObjCInterfaceType(Decl);
9969}
9970
9971/// Retrieve the template name that corresponds to a non-empty
9972/// lookup.
9975 UnresolvedSetIterator End) const {
9976 unsigned size = End - Begin;
9977 assert(size > 1 && "set is not overloaded!");
9978
9979 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
9980 size * sizeof(FunctionTemplateDecl*));
9981 auto *OT = new (memory) OverloadedTemplateStorage(size);
9982
9983 NamedDecl **Storage = OT->getStorage();
9984 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
9985 NamedDecl *D = *I;
9986 assert(isa<FunctionTemplateDecl>(D) ||
9987 isa<UnresolvedUsingValueDecl>(D) ||
9988 (isa<UsingShadowDecl>(D) &&
9989 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
9990 *Storage++ = D;
9991 }
9992
9993 return TemplateName(OT);
9994}
9995
9996/// Retrieve a template name representing an unqualified-id that has been
9997/// assumed to name a template for ADL purposes.
9999 auto *OT = new (*this) AssumedTemplateStorage(Name);
10000 return TemplateName(OT);
10001}
10002
10003/// Retrieve the template name that represents a qualified
10004/// template name such as \c std::vector.
10006 bool TemplateKeyword,
10007 TemplateName Template) const {
10008 assert(Template.getKind() == TemplateName::Template ||
10009 Template.getKind() == TemplateName::UsingTemplate);
10010
10011 // FIXME: Canonicalization?
10012 llvm::FoldingSetNodeID ID;
10013 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
10014
10015 void *InsertPos = nullptr;
10017 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
10018 if (!QTN) {
10019 QTN = new (*this, alignof(QualifiedTemplateName))
10020 QualifiedTemplateName(NNS, TemplateKeyword, Template);
10021 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
10022 }
10023
10024 return TemplateName(QTN);
10025}
10026
10027/// Retrieve the template name that represents a dependent
10028/// template name such as \c MetaFun::template apply.
10031 const IdentifierInfo *Name) const {
10032 assert((!NNS || NNS->isDependent()) &&
10033 "Nested name specifier must be dependent");
10034
10035 llvm::FoldingSetNodeID ID;
10036 DependentTemplateName::Profile(ID, NNS, Name);
10037
10038 void *InsertPos = nullptr;
10040 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
10041
10042 if (QTN)
10043 return TemplateName(QTN);
10044
10046 if (CanonNNS == NNS) {
10047 QTN = new (*this, alignof(DependentTemplateName))
10048 DependentTemplateName(NNS, Name);
10049 } else {
10050 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
10051 QTN = new (*this, alignof(DependentTemplateName))
10052 DependentTemplateName(NNS, Name, Canon);
10053 DependentTemplateName *CheckQTN =
10054 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
10055 assert(!CheckQTN && "Dependent type name canonicalization broken");
10056 (void)CheckQTN;
10057 }
10058
10059 DependentTemplateNames.InsertNode(QTN, InsertPos);
10060 return TemplateName(QTN);
10061}
10062
10063/// Retrieve the template name that represents a dependent
10064/// template name such as \c MetaFun::template operator+.
10067 OverloadedOperatorKind Operator) const {
10068 assert((!NNS || NNS->isDependent()) &&
10069 "Nested name specifier must be dependent");
10070
10071 llvm::FoldingSetNodeID ID;
10072 DependentTemplateName::Profile(ID, NNS, Operator);
10073
10074 void *InsertPos = nullptr;
10076 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
10077
10078 if (QTN)
10079 return TemplateName(QTN);
10080
10082 if (CanonNNS == NNS) {
10083 QTN = new (*this, alignof(DependentTemplateName))
10084 DependentTemplateName(NNS, Operator);
10085 } else {
10086 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
10087 QTN = new (*this, alignof(DependentTemplateName))
10088 DependentTemplateName(NNS, Operator, Canon);
10089
10090 DependentTemplateName *CheckQTN
10091 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
10092 assert(!CheckQTN && "Dependent template name canonicalization broken");
10093 (void)CheckQTN;
10094 }
10095
10096 DependentTemplateNames.InsertNode(QTN, InsertPos);
10097 return TemplateName(QTN);
10098}
10099
10101 TemplateName Replacement, Decl *AssociatedDecl, unsigned Index,
10102 std::optional<unsigned> PackIndex) const {
10103 llvm::FoldingSetNodeID ID;
10104 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
10105 Index, PackIndex);
10106
10107 void *insertPos = nullptr;
10109 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
10110
10111 if (!subst) {
10112 subst = new (*this) SubstTemplateTemplateParmStorage(
10113 Replacement, AssociatedDecl, Index, PackIndex);
10114 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
10115 }
10116
10117 return TemplateName(subst);
10118}
10119
10122 Decl *AssociatedDecl,
10123 unsigned Index, bool Final) const {
10124 auto &Self = const_cast<ASTContext &>(*this);
10125 llvm::FoldingSetNodeID ID;
10127 AssociatedDecl, Index, Final);
10128
10129 void *InsertPos = nullptr;
10131 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
10132
10133 if (!Subst) {
10134 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
10135 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
10136 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
10137 }
10138
10139 return TemplateName(Subst);
10140}
10141
10142/// Retrieve the template name that represents a template name
10143/// deduced from a specialization.
10146 DefaultArguments DefaultArgs) const {
10147 if (!DefaultArgs)
10148 return Underlying;
10149
10150 llvm::FoldingSetNodeID ID;
10151 DeducedTemplateStorage::Profile(ID, *this, Underlying, DefaultArgs);
10152
10153 void *InsertPos = nullptr;
10155 DeducedTemplates.FindNodeOrInsertPos(ID, InsertPos);
10156 if (!DTS) {
10157 void *Mem = Allocate(sizeof(DeducedTemplateStorage) +
10158 sizeof(TemplateArgument) * DefaultArgs.Args.size(),
10159 alignof(DeducedTemplateStorage));
10160 DTS = new (Mem) DeducedTemplateStorage(Underlying, DefaultArgs);
10161 DeducedTemplates.InsertNode(DTS, InsertPos);
10162 }
10163 return TemplateName(DTS);
10164}
10165
10166/// getFromTargetType - Given one of the integer types provided by
10167/// TargetInfo, produce the corresponding type. The unsigned @p Type
10168/// is actually a value of type @c TargetInfo::IntType.
10169CanQualType ASTContext::getFromTargetType(unsigned Type) const {
10170 switch (Type) {
10171 case TargetInfo::NoInt: return {};
10174 case TargetInfo::SignedShort: return ShortTy;
10176 case TargetInfo::SignedInt: return IntTy;
10178 case TargetInfo::SignedLong: return LongTy;
10182 }
10183
10184 llvm_unreachable("Unhandled TargetInfo::IntType value");
10185}
10186
10187//===----------------------------------------------------------------------===//
10188// Type Predicates.
10189//===----------------------------------------------------------------------===//
10190
10191/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
10192/// garbage collection attribute.
10193///
10195 if (getLangOpts().getGC() == LangOptions::NonGC)
10196 return Qualifiers::GCNone;
10197
10198 assert(getLangOpts().ObjC);
10199 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
10200
10201 // Default behaviour under objective-C's gc is for ObjC pointers
10202 // (or pointers to them) be treated as though they were declared
10203 // as __strong.
10204 if (GCAttrs == Qualifiers::GCNone) {
10206 return Qualifiers::Strong;
10207 else if (Ty->isPointerType())
10209 } else {
10210 // It's not valid to set GC attributes on anything that isn't a
10211 // pointer.
10212#ifndef NDEBUG
10214 while (const auto *AT = dyn_cast<ArrayType>(CT))
10215 CT = AT->getElementType();
10216 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
10217#endif
10218 }
10219 return GCAttrs;
10220}
10221
10222//===----------------------------------------------------------------------===//
10223// Type Compatibility Testing
10224//===----------------------------------------------------------------------===//
10225
10226/// areCompatVectorTypes - Return true if the two specified vector types are
10227/// compatible.
10228static bool areCompatVectorTypes(const VectorType *LHS,
10229 const VectorType *RHS) {
10230 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10231 return LHS->getElementType() == RHS->getElementType() &&
10232 LHS->getNumElements() == RHS->getNumElements();
10233}
10234
10235/// areCompatMatrixTypes - Return true if the two specified matrix types are
10236/// compatible.
10238 const ConstantMatrixType *RHS) {
10239 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10240 return LHS->getElementType() == RHS->getElementType() &&
10241 LHS->getNumRows() == RHS->getNumRows() &&
10242 LHS->getNumColumns() == RHS->getNumColumns();
10243}
10244
10246 QualType SecondVec) {
10247 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
10248 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
10249
10250 if (hasSameUnqualifiedType(FirstVec, SecondVec))
10251 return true;
10252
10253 // Treat Neon vector types and most AltiVec vector types as if they are the
10254 // equivalent GCC vector types.
10255 const auto *First = FirstVec->castAs<VectorType>();
10256 const auto *Second = SecondVec->castAs<VectorType>();
10257 if (First->getNumElements() == Second->getNumElements() &&
10258 hasSameType(First->getElementType(), Second->getElementType()) &&
10259 First->getVectorKind() != VectorKind::AltiVecPixel &&
10260 First->getVectorKind() != VectorKind::AltiVecBool &&
10263 First->getVectorKind() != VectorKind::SveFixedLengthData &&
10264 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10267 First->getVectorKind() != VectorKind::RVVFixedLengthData &&
10269 First->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10271 First->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10273 First->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10275 First->getVectorKind() != VectorKind::RVVFixedLengthMask_4 &&
10277 return true;
10278
10279 return false;
10280}
10281
10282/// getSVETypeSize - Return SVE vector or predicate register size.
10283static uint64_t getSVETypeSize(ASTContext &Context, const BuiltinType *Ty) {
10284 assert(Ty->isSveVLSBuiltinType() && "Invalid SVE Type");
10285 if (Ty->getKind() == BuiltinType::SveBool ||
10286 Ty->getKind() == BuiltinType::SveCount)
10287 return (Context.getLangOpts().VScaleMin * 128) / Context.getCharWidth();
10288 return Context.getLangOpts().VScaleMin * 128;
10289}
10290
10292 QualType SecondType) {
10293 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10294 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10295 if (const auto *VT = SecondType->getAs<VectorType>()) {
10296 // Predicates have the same representation as uint8 so we also have to
10297 // check the kind to make these types incompatible.
10298 if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
10299 return BT->getKind() == BuiltinType::SveBool;
10300 else if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
10301 return VT->getElementType().getCanonicalType() ==
10302 FirstType->getSveEltType(*this);
10303 else if (VT->getVectorKind() == VectorKind::Generic)
10304 return getTypeSize(SecondType) == getSVETypeSize(*this, BT) &&
10305 hasSameType(VT->getElementType(),
10306 getBuiltinVectorTypeInfo(BT).ElementType);
10307 }
10308 }
10309 return false;
10310 };
10311
10312 return IsValidCast(FirstType, SecondType) ||
10313 IsValidCast(SecondType, FirstType);
10314}
10315
10317 QualType SecondType) {
10318 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10319 const auto *BT = FirstType->getAs<BuiltinType>();
10320 if (!BT)
10321 return false;
10322
10323 const auto *VecTy = SecondType->getAs<VectorType>();
10324 if (VecTy && (VecTy->getVectorKind() == VectorKind::SveFixedLengthData ||
10325 VecTy->getVectorKind() == VectorKind::Generic)) {
10327 getLangOpts().getLaxVectorConversions();
10328
10329 // Can not convert between sve predicates and sve vectors because of
10330 // different size.
10331 if (BT->getKind() == BuiltinType::SveBool &&
10332 VecTy->getVectorKind() == VectorKind::SveFixedLengthData)
10333 return false;
10334
10335 // If __ARM_FEATURE_SVE_BITS != N do not allow GNU vector lax conversion.
10336 // "Whenever __ARM_FEATURE_SVE_BITS==N, GNUT implicitly
10337 // converts to VLAT and VLAT implicitly converts to GNUT."
10338 // ACLE Spec Version 00bet6, 3.7.3.2. Behavior common to vectors and
10339 // predicates.
10340 if (VecTy->getVectorKind() == VectorKind::Generic &&
10341 getTypeSize(SecondType) != getSVETypeSize(*this, BT))
10342 return false;
10343
10344 // If -flax-vector-conversions=all is specified, the types are
10345 // certainly compatible.
10347 return true;
10348
10349 // If -flax-vector-conversions=integer is specified, the types are
10350 // compatible if the elements are integer types.
10352 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10353 FirstType->getSveEltType(*this)->isIntegerType();
10354 }
10355
10356 return false;
10357 };
10358
10359 return IsLaxCompatible(FirstType, SecondType) ||
10360 IsLaxCompatible(SecondType, FirstType);
10361}
10362
10363/// getRVVTypeSize - Return RVV vector register size.
10364static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
10365 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
10366 auto VScale = Context.getTargetInfo().getVScaleRange(Context.getLangOpts());
10367 if (!VScale)
10368 return 0;
10369
10371
10372 uint64_t EltSize = Context.getTypeSize(Info.ElementType);
10373 if (Info.ElementType == Context.BoolTy)
10374 EltSize = 1;
10375
10376 uint64_t MinElts = Info.EC.getKnownMinValue();
10377 return VScale->first * MinElts * EltSize;
10378}
10379
10381 QualType SecondType) {
10382 assert(
10383 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10384 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10385 "Expected RVV builtin type and vector type!");
10386
10387 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10388 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10389 if (const auto *VT = SecondType->getAs<VectorType>()) {
10390 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10392 return FirstType->isRVVVLSBuiltinType() &&
10393 Info.ElementType == BoolTy &&
10394 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)));
10395 }
10396 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1) {
10398 return FirstType->isRVVVLSBuiltinType() &&
10399 Info.ElementType == BoolTy &&
10400 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT) * 8));
10401 }
10402 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2) {
10404 return FirstType->isRVVVLSBuiltinType() &&
10405 Info.ElementType == BoolTy &&
10406 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 4);
10407 }
10408 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10410 return FirstType->isRVVVLSBuiltinType() &&
10411 Info.ElementType == BoolTy &&
10412 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 2);
10413 }
10414 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
10415 VT->getVectorKind() == VectorKind::Generic)
10416 return FirstType->isRVVVLSBuiltinType() &&
10417 getTypeSize(SecondType) == getRVVTypeSize(*this, BT) &&
10418 hasSameType(VT->getElementType(),
10419 getBuiltinVectorTypeInfo(BT).ElementType);
10420 }
10421 }
10422 return false;
10423 };
10424
10425 return IsValidCast(FirstType, SecondType) ||
10426 IsValidCast(SecondType, FirstType);
10427}
10428
10430 QualType SecondType) {
10431 assert(
10432 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10433 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10434 "Expected RVV builtin type and vector type!");
10435
10436 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10437 const auto *BT = FirstType->getAs<BuiltinType>();
10438 if (!BT)
10439 return false;
10440
10441 if (!BT->isRVVVLSBuiltinType())
10442 return false;
10443
10444 const auto *VecTy = SecondType->getAs<VectorType>();
10445 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
10447 getLangOpts().getLaxVectorConversions();
10448
10449 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
10450 if (getTypeSize(SecondType) != getRVVTypeSize(*this, BT))
10451 return false;
10452
10453 // If -flax-vector-conversions=all is specified, the types are
10454 // certainly compatible.
10456 return true;
10457
10458 // If -flax-vector-conversions=integer is specified, the types are
10459 // compatible if the elements are integer types.
10461 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10462 FirstType->getRVVEltType(*this)->isIntegerType();
10463 }
10464
10465 return false;
10466 };
10467
10468 return IsLaxCompatible(FirstType, SecondType) ||
10469 IsLaxCompatible(SecondType, FirstType);
10470}
10471
10473 while (true) {
10474 // __strong id
10475 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
10476 if (Attr->getAttrKind() == attr::ObjCOwnership)
10477 return true;
10478
10479 Ty = Attr->getModifiedType();
10480
10481 // X *__strong (...)
10482 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
10483 Ty = Paren->getInnerType();
10484
10485 // We do not want to look through typedefs, typeof(expr),
10486 // typeof(type), or any other way that the type is somehow
10487 // abstracted.
10488 } else {
10489 return false;
10490 }
10491 }
10492}
10493
10494//===----------------------------------------------------------------------===//
10495// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
10496//===----------------------------------------------------------------------===//
10497
10498/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
10499/// inheritance hierarchy of 'rProto'.
10500bool
10502 ObjCProtocolDecl *rProto) const {
10503 if (declaresSameEntity(lProto, rProto))
10504 return true;
10505 for (auto *PI : rProto->protocols())
10506 if (ProtocolCompatibleWithProtocol(lProto, PI))
10507 return true;
10508 return false;
10509}
10510
10511/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
10512/// Class<pr1, ...>.
10514 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
10515 for (auto *lhsProto : lhs->quals()) {
10516 bool match = false;
10517 for (auto *rhsProto : rhs->quals()) {
10518 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
10519 match = true;
10520 break;
10521 }
10522 }
10523 if (!match)
10524 return false;
10525 }
10526 return true;
10527}
10528
10529/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
10530/// ObjCQualifiedIDType.
10532 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
10533 bool compare) {
10534 // Allow id<P..> and an 'id' in all cases.
10535 if (lhs->isObjCIdType() || rhs->isObjCIdType())
10536 return true;
10537
10538 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
10539 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
10541 return false;
10542
10543 if (lhs->isObjCQualifiedIdType()) {
10544 if (rhs->qual_empty()) {
10545 // If the RHS is a unqualified interface pointer "NSString*",
10546 // make sure we check the class hierarchy.
10547 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10548 for (auto *I : lhs->quals()) {
10549 // when comparing an id<P> on lhs with a static type on rhs,
10550 // see if static class implements all of id's protocols, directly or
10551 // through its super class and categories.
10552 if (!rhsID->ClassImplementsProtocol(I, true))
10553 return false;
10554 }
10555 }
10556 // If there are no qualifiers and no interface, we have an 'id'.
10557 return true;
10558 }
10559 // Both the right and left sides have qualifiers.
10560 for (auto *lhsProto : lhs->quals()) {
10561 bool match = false;
10562
10563 // when comparing an id<P> on lhs with a static type on rhs,
10564 // see if static class implements all of id's protocols, directly or
10565 // through its super class and categories.
10566 for (auto *rhsProto : rhs->quals()) {
10567 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10568 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10569 match = true;
10570 break;
10571 }
10572 }
10573 // If the RHS is a qualified interface pointer "NSString<P>*",
10574 // make sure we check the class hierarchy.
10575 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10576 for (auto *I : lhs->quals()) {
10577 // when comparing an id<P> on lhs with a static type on rhs,
10578 // see if static class implements all of id's protocols, directly or
10579 // through its super class and categories.
10580 if (rhsID->ClassImplementsProtocol(I, true)) {
10581 match = true;
10582 break;
10583 }
10584 }
10585 }
10586 if (!match)
10587 return false;
10588 }
10589
10590 return true;
10591 }
10592
10593 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
10594
10595 if (lhs->getInterfaceType()) {
10596 // If both the right and left sides have qualifiers.
10597 for (auto *lhsProto : lhs->quals()) {
10598 bool match = false;
10599
10600 // when comparing an id<P> on rhs with a static type on lhs,
10601 // see if static class implements all of id's protocols, directly or
10602 // through its super class and categories.
10603 // First, lhs protocols in the qualifier list must be found, direct
10604 // or indirect in rhs's qualifier list or it is a mismatch.
10605 for (auto *rhsProto : rhs->quals()) {
10606 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10607 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10608 match = true;
10609 break;
10610 }
10611 }
10612 if (!match)
10613 return false;
10614 }
10615
10616 // Static class's protocols, or its super class or category protocols
10617 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
10618 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
10619 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
10620 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
10621 // This is rather dubious but matches gcc's behavior. If lhs has
10622 // no type qualifier and its class has no static protocol(s)
10623 // assume that it is mismatch.
10624 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
10625 return false;
10626 for (auto *lhsProto : LHSInheritedProtocols) {
10627 bool match = false;
10628 for (auto *rhsProto : rhs->quals()) {
10629 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10630 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10631 match = true;
10632 break;
10633 }
10634 }
10635 if (!match)
10636 return false;
10637 }
10638 }
10639 return true;
10640 }
10641 return false;
10642}
10643
10644/// canAssignObjCInterfaces - Return true if the two interface types are
10645/// compatible for assignment from RHS to LHS. This handles validation of any
10646/// protocol qualifiers on the LHS or RHS.
10648 const ObjCObjectPointerType *RHSOPT) {
10649 const ObjCObjectType* LHS = LHSOPT->getObjectType();
10650 const ObjCObjectType* RHS = RHSOPT->getObjectType();
10651
10652 // If either type represents the built-in 'id' type, return true.
10653 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
10654 return true;
10655
10656 // Function object that propagates a successful result or handles
10657 // __kindof types.
10658 auto finish = [&](bool succeeded) -> bool {
10659 if (succeeded)
10660 return true;
10661
10662 if (!RHS->isKindOfType())
10663 return false;
10664
10665 // Strip off __kindof and protocol qualifiers, then check whether
10666 // we can assign the other way.
10668 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
10669 };
10670
10671 // Casts from or to id<P> are allowed when the other side has compatible
10672 // protocols.
10673 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
10674 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
10675 }
10676
10677 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
10678 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
10679 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
10680 }
10681
10682 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
10683 if (LHS->isObjCClass() && RHS->isObjCClass()) {
10684 return true;
10685 }
10686
10687 // If we have 2 user-defined types, fall into that path.
10688 if (LHS->getInterface() && RHS->getInterface()) {
10689 return finish(canAssignObjCInterfaces(LHS, RHS));
10690 }
10691
10692 return false;
10693}
10694
10695/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
10696/// for providing type-safety for objective-c pointers used to pass/return
10697/// arguments in block literals. When passed as arguments, passing 'A*' where
10698/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
10699/// not OK. For the return type, the opposite is not OK.
10701 const ObjCObjectPointerType *LHSOPT,
10702 const ObjCObjectPointerType *RHSOPT,
10703 bool BlockReturnType) {
10704
10705 // Function object that propagates a successful result or handles
10706 // __kindof types.
10707 auto finish = [&](bool succeeded) -> bool {
10708 if (succeeded)
10709 return true;
10710
10711 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
10712 if (!Expected->isKindOfType())
10713 return false;
10714
10715 // Strip off __kindof and protocol qualifiers, then check whether
10716 // we can assign the other way.
10718 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
10719 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
10720 BlockReturnType);
10721 };
10722
10723 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
10724 return true;
10725
10726 if (LHSOPT->isObjCBuiltinType()) {
10727 return finish(RHSOPT->isObjCBuiltinType() ||
10728 RHSOPT->isObjCQualifiedIdType());
10729 }
10730
10731 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
10732 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
10733 // Use for block parameters previous type checking for compatibility.
10734 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
10735 // Or corrected type checking as in non-compat mode.
10736 (!BlockReturnType &&
10737 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
10738 else
10740 (BlockReturnType ? LHSOPT : RHSOPT),
10741 (BlockReturnType ? RHSOPT : LHSOPT), false));
10742 }
10743
10744 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
10745 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
10746 if (LHS && RHS) { // We have 2 user-defined types.
10747 if (LHS != RHS) {
10748 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
10749 return finish(BlockReturnType);
10750 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
10751 return finish(!BlockReturnType);
10752 }
10753 else
10754 return true;
10755 }
10756 return false;
10757}
10758
10759/// Comparison routine for Objective-C protocols to be used with
10760/// llvm::array_pod_sort.
10762 ObjCProtocolDecl * const *rhs) {
10763 return (*lhs)->getName().compare((*rhs)->getName());
10764}
10765
10766/// getIntersectionOfProtocols - This routine finds the intersection of set
10767/// of protocols inherited from two distinct objective-c pointer objects with
10768/// the given common base.
10769/// It is used to build composite qualifier list of the composite type of
10770/// the conditional expression involving two objective-c pointer objects.
10771static
10773 const ObjCInterfaceDecl *CommonBase,
10774 const ObjCObjectPointerType *LHSOPT,
10775 const ObjCObjectPointerType *RHSOPT,
10776 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
10777
10778 const ObjCObjectType* LHS = LHSOPT->getObjectType();
10779 const ObjCObjectType* RHS = RHSOPT->getObjectType();
10780 assert(LHS->getInterface() && "LHS must have an interface base");
10781 assert(RHS->getInterface() && "RHS must have an interface base");
10782
10783 // Add all of the protocols for the LHS.
10785
10786 // Start with the protocol qualifiers.
10787 for (auto *proto : LHS->quals()) {
10788 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
10789 }
10790
10791 // Also add the protocols associated with the LHS interface.
10792 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
10793
10794 // Add all of the protocols for the RHS.
10796
10797 // Start with the protocol qualifiers.
10798 for (auto *proto : RHS->quals()) {
10799 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
10800 }
10801
10802 // Also add the protocols associated with the RHS interface.
10803 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
10804
10805 // Compute the intersection of the collected protocol sets.
10806 for (auto *proto : LHSProtocolSet) {
10807 if (RHSProtocolSet.count(proto))
10808 IntersectionSet.push_back(proto);
10809 }
10810
10811 // Compute the set of protocols that is implied by either the common type or
10812 // the protocols within the intersection.
10814 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
10815
10816 // Remove any implied protocols from the list of inherited protocols.
10817 if (!ImpliedProtocols.empty()) {
10818 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
10819 return ImpliedProtocols.contains(proto);
10820 });
10821 }
10822
10823 // Sort the remaining protocols by name.
10824 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
10826}
10827
10828/// Determine whether the first type is a subtype of the second.
10830 QualType rhs) {
10831 // Common case: two object pointers.
10832 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
10833 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
10834 if (lhsOPT && rhsOPT)
10835 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
10836
10837 // Two block pointers.
10838 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
10839 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
10840 if (lhsBlock && rhsBlock)
10841 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
10842
10843 // If either is an unqualified 'id' and the other is a block, it's
10844 // acceptable.
10845 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
10846 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
10847 return true;
10848
10849 return false;
10850}
10851
10852// Check that the given Objective-C type argument lists are equivalent.
10854 const ObjCInterfaceDecl *iface,
10855 ArrayRef<QualType> lhsArgs,
10856 ArrayRef<QualType> rhsArgs,
10857 bool stripKindOf) {
10858 if (lhsArgs.size() != rhsArgs.size())
10859 return false;
10860
10861 ObjCTypeParamList *typeParams = iface->getTypeParamList();
10862 if (!typeParams)
10863 return false;
10864
10865 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
10866 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
10867 continue;
10868
10869 switch (typeParams->begin()[i]->getVariance()) {
10871 if (!stripKindOf ||
10872 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
10873 rhsArgs[i].stripObjCKindOfType(ctx))) {
10874 return false;
10875 }
10876 break;
10877
10879 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
10880 return false;
10881 break;
10882
10884 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
10885 return false;
10886 break;
10887 }
10888 }
10889
10890 return true;
10891}
10892
10894 const ObjCObjectPointerType *Lptr,
10895 const ObjCObjectPointerType *Rptr) {
10896 const ObjCObjectType *LHS = Lptr->getObjectType();
10897 const ObjCObjectType *RHS = Rptr->getObjectType();
10898 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
10899 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
10900
10901 if (!LDecl || !RDecl)
10902 return {};
10903
10904 // When either LHS or RHS is a kindof type, we should return a kindof type.
10905 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
10906 // kindof(A).
10907 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
10908
10909 // Follow the left-hand side up the class hierarchy until we either hit a
10910 // root or find the RHS. Record the ancestors in case we don't find it.
10911 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
10912 LHSAncestors;
10913 while (true) {
10914 // Record this ancestor. We'll need this if the common type isn't in the
10915 // path from the LHS to the root.
10916 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
10917
10918 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
10919 // Get the type arguments.
10920 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
10921 bool anyChanges = false;
10922 if (LHS->isSpecialized() && RHS->isSpecialized()) {
10923 // Both have type arguments, compare them.
10924 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
10925 LHS->getTypeArgs(), RHS->getTypeArgs(),
10926 /*stripKindOf=*/true))
10927 return {};
10928 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
10929 // If only one has type arguments, the result will not have type
10930 // arguments.
10931 LHSTypeArgs = {};
10932 anyChanges = true;
10933 }
10934
10935 // Compute the intersection of protocols.
10937 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
10938 Protocols);
10939 if (!Protocols.empty())
10940 anyChanges = true;
10941
10942 // If anything in the LHS will have changed, build a new result type.
10943 // If we need to return a kindof type but LHS is not a kindof type, we
10944 // build a new result type.
10945 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
10947 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
10948 anyKindOf || LHS->isKindOfType());
10950 }
10951
10952 return getObjCObjectPointerType(QualType(LHS, 0));
10953 }
10954
10955 // Find the superclass.
10956 QualType LHSSuperType = LHS->getSuperClassType();
10957 if (LHSSuperType.isNull())
10958 break;
10959
10960 LHS = LHSSuperType->castAs<ObjCObjectType>();
10961 }
10962
10963 // We didn't find anything by following the LHS to its root; now check
10964 // the RHS against the cached set of ancestors.
10965 while (true) {
10966 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
10967 if (KnownLHS != LHSAncestors.end()) {
10968 LHS = KnownLHS->second;
10969
10970 // Get the type arguments.
10971 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
10972 bool anyChanges = false;
10973 if (LHS->isSpecialized() && RHS->isSpecialized()) {
10974 // Both have type arguments, compare them.
10975 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
10976 LHS->getTypeArgs(), RHS->getTypeArgs(),
10977 /*stripKindOf=*/true))
10978 return {};
10979 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
10980 // If only one has type arguments, the result will not have type
10981 // arguments.
10982 RHSTypeArgs = {};
10983 anyChanges = true;
10984 }
10985
10986 // Compute the intersection of protocols.
10988 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
10989 Protocols);
10990 if (!Protocols.empty())
10991 anyChanges = true;
10992
10993 // If we need to return a kindof type but RHS is not a kindof type, we
10994 // build a new result type.
10995 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
10997 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
10998 anyKindOf || RHS->isKindOfType());
11000 }
11001
11002 return getObjCObjectPointerType(QualType(RHS, 0));
11003 }
11004
11005 // Find the superclass of the RHS.
11006 QualType RHSSuperType = RHS->getSuperClassType();
11007 if (RHSSuperType.isNull())
11008 break;
11009
11010 RHS = RHSSuperType->castAs<ObjCObjectType>();
11011 }
11012
11013 return {};
11014}
11015
11017 const ObjCObjectType *RHS) {
11018 assert(LHS->getInterface() && "LHS is not an interface type");
11019 assert(RHS->getInterface() && "RHS is not an interface type");
11020
11021 // Verify that the base decls are compatible: the RHS must be a subclass of
11022 // the LHS.
11023 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
11024 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
11025 if (!IsSuperClass)
11026 return false;
11027
11028 // If the LHS has protocol qualifiers, determine whether all of them are
11029 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
11030 // LHS).
11031 if (LHS->getNumProtocols() > 0) {
11032 // OK if conversion of LHS to SuperClass results in narrowing of types
11033 // ; i.e., SuperClass may implement at least one of the protocols
11034 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
11035 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
11036 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
11037 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
11038 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
11039 // qualifiers.
11040 for (auto *RHSPI : RHS->quals())
11041 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
11042 // If there is no protocols associated with RHS, it is not a match.
11043 if (SuperClassInheritedProtocols.empty())
11044 return false;
11045
11046 for (const auto *LHSProto : LHS->quals()) {
11047 bool SuperImplementsProtocol = false;
11048 for (auto *SuperClassProto : SuperClassInheritedProtocols)
11049 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
11050 SuperImplementsProtocol = true;
11051 break;
11052 }
11053 if (!SuperImplementsProtocol)
11054 return false;
11055 }
11056 }
11057
11058 // If the LHS is specialized, we may need to check type arguments.
11059 if (LHS->isSpecialized()) {
11060 // Follow the superclass chain until we've matched the LHS class in the
11061 // hierarchy. This substitutes type arguments through.
11062 const ObjCObjectType *RHSSuper = RHS;
11063 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
11064 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
11065
11066 // If the RHS is specializd, compare type arguments.
11067 if (RHSSuper->isSpecialized() &&
11068 !sameObjCTypeArgs(*this, LHS->getInterface(),
11069 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
11070 /*stripKindOf=*/true)) {
11071 return false;
11072 }
11073 }
11074
11075 return true;
11076}
11077
11079 // get the "pointed to" types
11080 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
11081 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
11082
11083 if (!LHSOPT || !RHSOPT)
11084 return false;
11085
11086 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
11087 canAssignObjCInterfaces(RHSOPT, LHSOPT);
11088}
11089
11092 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
11093 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
11094}
11095
11096/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
11097/// both shall have the identically qualified version of a compatible type.
11098/// C99 6.2.7p1: Two types have compatible types if their types are the
11099/// same. See 6.7.[2,3,5] for additional rules.
11101 bool CompareUnqualified) {
11102 if (getLangOpts().CPlusPlus)
11103 return hasSameType(LHS, RHS);
11104
11105 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
11106}
11107
11109 return typesAreCompatible(LHS, RHS);
11110}
11111
11113 return !mergeTypes(LHS, RHS, true).isNull();
11114}
11115
11116/// mergeTransparentUnionType - if T is a transparent union type and a member
11117/// of T is compatible with SubType, return the merged type, else return
11118/// QualType()
11120 bool OfBlockPointer,
11121 bool Unqualified) {
11122 if (const RecordType *UT = T->getAsUnionType()) {
11123 RecordDecl *UD = UT->getDecl();
11124 if (UD->hasAttr<TransparentUnionAttr>()) {
11125 for (const auto *I : UD->fields()) {
11126 QualType ET = I->getType().getUnqualifiedType();
11127 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
11128 if (!MT.isNull())
11129 return MT;
11130 }
11131 }
11132 }
11133
11134 return {};
11135}
11136
11137/// mergeFunctionParameterTypes - merge two types which appear as function
11138/// parameter types
11140 bool OfBlockPointer,
11141 bool Unqualified) {
11142 // GNU extension: two types are compatible if they appear as a function
11143 // argument, one of the types is a transparent union type and the other
11144 // type is compatible with a union member
11145 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
11146 Unqualified);
11147 if (!lmerge.isNull())
11148 return lmerge;
11149
11150 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
11151 Unqualified);
11152 if (!rmerge.isNull())
11153 return rmerge;
11154
11155 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
11156}
11157
11159 bool OfBlockPointer, bool Unqualified,
11160 bool AllowCXX,
11161 bool IsConditionalOperator) {
11162 const auto *lbase = lhs->castAs<FunctionType>();
11163 const auto *rbase = rhs->castAs<FunctionType>();
11164 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
11165 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
11166 bool allLTypes = true;
11167 bool allRTypes = true;
11168
11169 // Check return type
11170 QualType retType;
11171 if (OfBlockPointer) {
11172 QualType RHS = rbase->getReturnType();
11173 QualType LHS = lbase->getReturnType();
11174 bool UnqualifiedResult = Unqualified;
11175 if (!UnqualifiedResult)
11176 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
11177 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
11178 }
11179 else
11180 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
11181 Unqualified);
11182 if (retType.isNull())
11183 return {};
11184
11185 if (Unqualified)
11186 retType = retType.getUnqualifiedType();
11187
11188 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
11189 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
11190 if (Unqualified) {
11191 LRetType = LRetType.getUnqualifiedType();
11192 RRetType = RRetType.getUnqualifiedType();
11193 }
11194
11195 if (getCanonicalType(retType) != LRetType)
11196 allLTypes = false;
11197 if (getCanonicalType(retType) != RRetType)
11198 allRTypes = false;
11199
11200 // FIXME: double check this
11201 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
11202 // rbase->getRegParmAttr() != 0 &&
11203 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
11204 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
11205 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
11206
11207 // Compatible functions must have compatible calling conventions
11208 if (lbaseInfo.getCC() != rbaseInfo.getCC())
11209 return {};
11210
11211 // Regparm is part of the calling convention.
11212 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
11213 return {};
11214 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
11215 return {};
11216
11217 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
11218 return {};
11219 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
11220 return {};
11221 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
11222 return {};
11223
11224 // When merging declarations, it's common for supplemental information like
11225 // attributes to only be present in one of the declarations, and we generally
11226 // want type merging to preserve the union of information. So a merged
11227 // function type should be noreturn if it was noreturn in *either* operand
11228 // type.
11229 //
11230 // But for the conditional operator, this is backwards. The result of the
11231 // operator could be either operand, and its type should conservatively
11232 // reflect that. So a function type in a composite type is noreturn only
11233 // if it's noreturn in *both* operand types.
11234 //
11235 // Arguably, noreturn is a kind of subtype, and the conditional operator
11236 // ought to produce the most specific common supertype of its operand types.
11237 // That would differ from this rule in contravariant positions. However,
11238 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
11239 // as a practical matter, it would only affect C code that does abstraction of
11240 // higher-order functions (taking noreturn callbacks!), which is uncommon to
11241 // say the least. So we use the simpler rule.
11242 bool NoReturn = IsConditionalOperator
11243 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
11244 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
11245 if (lbaseInfo.getNoReturn() != NoReturn)
11246 allLTypes = false;
11247 if (rbaseInfo.getNoReturn() != NoReturn)
11248 allRTypes = false;
11249
11250 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
11251
11252 std::optional<FunctionEffectSet> MergedFX;
11253
11254 if (lproto && rproto) { // two C99 style function prototypes
11255 assert((AllowCXX ||
11256 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
11257 "C++ shouldn't be here");
11258 // Compatible functions must have the same number of parameters
11259 if (lproto->getNumParams() != rproto->getNumParams())
11260 return {};
11261
11262 // Variadic and non-variadic functions aren't compatible
11263 if (lproto->isVariadic() != rproto->isVariadic())
11264 return {};
11265
11266 if (lproto->getMethodQuals() != rproto->getMethodQuals())
11267 return {};
11268
11269 // Function effects are handled similarly to noreturn, see above.
11270 FunctionEffectsRef LHSFX = lproto->getFunctionEffects();
11271 FunctionEffectsRef RHSFX = rproto->getFunctionEffects();
11272 if (LHSFX != RHSFX) {
11273 if (IsConditionalOperator)
11274 MergedFX = FunctionEffectSet::getIntersection(LHSFX, RHSFX);
11275 else {
11277 MergedFX = FunctionEffectSet::getUnion(LHSFX, RHSFX, Errs);
11278 // Here we're discarding a possible error due to conflicts in the effect
11279 // sets. But we're not in a context where we can report it. The
11280 // operation does however guarantee maintenance of invariants.
11281 }
11282 if (*MergedFX != LHSFX)
11283 allLTypes = false;
11284 if (*MergedFX != RHSFX)
11285 allRTypes = false;
11286 }
11287
11289 bool canUseLeft, canUseRight;
11290 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
11291 newParamInfos))
11292 return {};
11293
11294 if (!canUseLeft)
11295 allLTypes = false;
11296 if (!canUseRight)
11297 allRTypes = false;
11298
11299 // Check parameter type compatibility
11301 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
11302 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
11303 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
11305 lParamType, rParamType, OfBlockPointer, Unqualified);
11306 if (paramType.isNull())
11307 return {};
11308
11309 if (Unqualified)
11310 paramType = paramType.getUnqualifiedType();
11311
11312 types.push_back(paramType);
11313 if (Unqualified) {
11314 lParamType = lParamType.getUnqualifiedType();
11315 rParamType = rParamType.getUnqualifiedType();
11316 }
11317
11318 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
11319 allLTypes = false;
11320 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
11321 allRTypes = false;
11322 }
11323
11324 if (allLTypes) return lhs;
11325 if (allRTypes) return rhs;
11326
11327 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
11328 EPI.ExtInfo = einfo;
11329 EPI.ExtParameterInfos =
11330 newParamInfos.empty() ? nullptr : newParamInfos.data();
11331 if (MergedFX)
11332 EPI.FunctionEffects = *MergedFX;
11333 return getFunctionType(retType, types, EPI);
11334 }
11335
11336 if (lproto) allRTypes = false;
11337 if (rproto) allLTypes = false;
11338
11339 const FunctionProtoType *proto = lproto ? lproto : rproto;
11340 if (proto) {
11341 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
11342 if (proto->isVariadic())
11343 return {};
11344 // Check that the types are compatible with the types that
11345 // would result from default argument promotions (C99 6.7.5.3p15).
11346 // The only types actually affected are promotable integer
11347 // types and floats, which would be passed as a different
11348 // type depending on whether the prototype is visible.
11349 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
11350 QualType paramTy = proto->getParamType(i);
11351
11352 // Look at the converted type of enum types, since that is the type used
11353 // to pass enum values.
11354 if (const auto *Enum = paramTy->getAs<EnumType>()) {
11355 paramTy = Enum->getDecl()->getIntegerType();
11356 if (paramTy.isNull())
11357 return {};
11358 }
11359
11360 if (isPromotableIntegerType(paramTy) ||
11361 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
11362 return {};
11363 }
11364
11365 if (allLTypes) return lhs;
11366 if (allRTypes) return rhs;
11367
11369 EPI.ExtInfo = einfo;
11370 if (MergedFX)
11371 EPI.FunctionEffects = *MergedFX;
11372 return getFunctionType(retType, proto->getParamTypes(), EPI);
11373 }
11374
11375 if (allLTypes) return lhs;
11376 if (allRTypes) return rhs;
11377 return getFunctionNoProtoType(retType, einfo);
11378}
11379
11380/// Given that we have an enum type and a non-enum type, try to merge them.
11382 QualType other, bool isBlockReturnType) {
11383 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
11384 // a signed integer type, or an unsigned integer type.
11385 // Compatibility is based on the underlying type, not the promotion
11386 // type.
11387 QualType underlyingType = ET->getDecl()->getIntegerType();
11388 if (underlyingType.isNull())
11389 return {};
11390 if (Context.hasSameType(underlyingType, other))
11391 return other;
11392
11393 // In block return types, we're more permissive and accept any
11394 // integral type of the same size.
11395 if (isBlockReturnType && other->isIntegerType() &&
11396 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
11397 return other;
11398
11399 return {};
11400}
11401
11402QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
11403 bool Unqualified, bool BlockReturnType,
11404 bool IsConditionalOperator) {
11405 // For C++ we will not reach this code with reference types (see below),
11406 // for OpenMP variant call overloading we might.
11407 //
11408 // C++ [expr]: If an expression initially has the type "reference to T", the
11409 // type is adjusted to "T" prior to any further analysis, the expression
11410 // designates the object or function denoted by the reference, and the
11411 // expression is an lvalue unless the reference is an rvalue reference and
11412 // the expression is a function call (possibly inside parentheses).
11413 auto *LHSRefTy = LHS->getAs<ReferenceType>();
11414 auto *RHSRefTy = RHS->getAs<ReferenceType>();
11415 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
11416 LHS->getTypeClass() == RHS->getTypeClass())
11417 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
11418 OfBlockPointer, Unqualified, BlockReturnType);
11419 if (LHSRefTy || RHSRefTy)
11420 return {};
11421
11422 if (Unqualified) {
11423 LHS = LHS.getUnqualifiedType();
11424 RHS = RHS.getUnqualifiedType();
11425 }
11426
11427 QualType LHSCan = getCanonicalType(LHS),
11428 RHSCan = getCanonicalType(RHS);
11429
11430 // If two types are identical, they are compatible.
11431 if (LHSCan == RHSCan)
11432 return LHS;
11433
11434 // If the qualifiers are different, the types aren't compatible... mostly.
11435 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11436 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11437 if (LQuals != RQuals) {
11438 // If any of these qualifiers are different, we have a type
11439 // mismatch.
11440 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11441 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
11442 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
11443 LQuals.hasUnaligned() != RQuals.hasUnaligned())
11444 return {};
11445
11446 // Exactly one GC qualifier difference is allowed: __strong is
11447 // okay if the other type has no GC qualifier but is an Objective
11448 // C object pointer (i.e. implicitly strong by default). We fix
11449 // this by pretending that the unqualified type was actually
11450 // qualified __strong.
11451 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11452 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11453 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11454
11455 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11456 return {};
11457
11458 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
11460 }
11461 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
11463 }
11464 return {};
11465 }
11466
11467 // Okay, qualifiers are equal.
11468
11469 Type::TypeClass LHSClass = LHSCan->getTypeClass();
11470 Type::TypeClass RHSClass = RHSCan->getTypeClass();
11471
11472 // We want to consider the two function types to be the same for these
11473 // comparisons, just force one to the other.
11474 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
11475 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
11476
11477 // Same as above for arrays
11478 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
11479 LHSClass = Type::ConstantArray;
11480 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
11481 RHSClass = Type::ConstantArray;
11482
11483 // ObjCInterfaces are just specialized ObjCObjects.
11484 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
11485 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
11486
11487 // Canonicalize ExtVector -> Vector.
11488 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
11489 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
11490
11491 // If the canonical type classes don't match.
11492 if (LHSClass != RHSClass) {
11493 // Note that we only have special rules for turning block enum
11494 // returns into block int returns, not vice-versa.
11495 if (const auto *ETy = LHS->getAs<EnumType>()) {
11496 return mergeEnumWithInteger(*this, ETy, RHS, false);
11497 }
11498 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
11499 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
11500 }
11501 // allow block pointer type to match an 'id' type.
11502 if (OfBlockPointer && !BlockReturnType) {
11503 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
11504 return LHS;
11505 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
11506 return RHS;
11507 }
11508 // Allow __auto_type to match anything; it merges to the type with more
11509 // information.
11510 if (const auto *AT = LHS->getAs<AutoType>()) {
11511 if (!AT->isDeduced() && AT->isGNUAutoType())
11512 return RHS;
11513 }
11514 if (const auto *AT = RHS->getAs<AutoType>()) {
11515 if (!AT->isDeduced() && AT->isGNUAutoType())
11516 return LHS;
11517 }
11518 return {};
11519 }
11520
11521 // The canonical type classes match.
11522 switch (LHSClass) {
11523#define TYPE(Class, Base)
11524#define ABSTRACT_TYPE(Class, Base)
11525#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
11526#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
11527#define DEPENDENT_TYPE(Class, Base) case Type::Class:
11528#include "clang/AST/TypeNodes.inc"
11529 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
11530
11531 case Type::Auto:
11532 case Type::DeducedTemplateSpecialization:
11533 case Type::LValueReference:
11534 case Type::RValueReference:
11535 case Type::MemberPointer:
11536 llvm_unreachable("C++ should never be in mergeTypes");
11537
11538 case Type::ObjCInterface:
11539 case Type::IncompleteArray:
11540 case Type::VariableArray:
11541 case Type::FunctionProto:
11542 case Type::ExtVector:
11543 llvm_unreachable("Types are eliminated above");
11544
11545 case Type::Pointer:
11546 {
11547 // Merge two pointer types, while trying to preserve typedef info
11548 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
11549 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
11550 if (Unqualified) {
11551 LHSPointee = LHSPointee.getUnqualifiedType();
11552 RHSPointee = RHSPointee.getUnqualifiedType();
11553 }
11554 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
11555 Unqualified);
11556 if (ResultType.isNull())
11557 return {};
11558 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11559 return LHS;
11560 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
11561 return RHS;
11562 return getPointerType(ResultType);
11563 }
11564 case Type::BlockPointer:
11565 {
11566 // Merge two block pointer types, while trying to preserve typedef info
11567 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
11568 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
11569 if (Unqualified) {
11570 LHSPointee = LHSPointee.getUnqualifiedType();
11571 RHSPointee = RHSPointee.getUnqualifiedType();
11572 }
11573 if (getLangOpts().OpenCL) {
11574 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
11575 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
11576 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
11577 // 6.12.5) thus the following check is asymmetric.
11578 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual, *this))
11579 return {};
11580 LHSPteeQual.removeAddressSpace();
11581 RHSPteeQual.removeAddressSpace();
11582 LHSPointee =
11583 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
11584 RHSPointee =
11585 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
11586 }
11587 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
11588 Unqualified);
11589 if (ResultType.isNull())
11590 return {};
11591 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11592 return LHS;
11593 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
11594 return RHS;
11595 return getBlockPointerType(ResultType);
11596 }
11597 case Type::Atomic:
11598 {
11599 // Merge two pointer types, while trying to preserve typedef info
11600 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
11601 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
11602 if (Unqualified) {
11603 LHSValue = LHSValue.getUnqualifiedType();
11604 RHSValue = RHSValue.getUnqualifiedType();
11605 }
11606 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
11607 Unqualified);
11608 if (ResultType.isNull())
11609 return {};
11610 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
11611 return LHS;
11612 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
11613 return RHS;
11614 return getAtomicType(ResultType);
11615 }
11616 case Type::ConstantArray:
11617 {
11618 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
11619 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
11620 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
11621 return {};
11622
11623 QualType LHSElem = getAsArrayType(LHS)->getElementType();
11624 QualType RHSElem = getAsArrayType(RHS)->getElementType();
11625 if (Unqualified) {
11626 LHSElem = LHSElem.getUnqualifiedType();
11627 RHSElem = RHSElem.getUnqualifiedType();
11628 }
11629
11630 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
11631 if (ResultType.isNull())
11632 return {};
11633
11634 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
11635 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
11636
11637 // If either side is a variable array, and both are complete, check whether
11638 // the current dimension is definite.
11639 if (LVAT || RVAT) {
11640 auto SizeFetch = [this](const VariableArrayType* VAT,
11641 const ConstantArrayType* CAT)
11642 -> std::pair<bool,llvm::APInt> {
11643 if (VAT) {
11644 std::optional<llvm::APSInt> TheInt;
11645 Expr *E = VAT->getSizeExpr();
11646 if (E && (TheInt = E->getIntegerConstantExpr(*this)))
11647 return std::make_pair(true, *TheInt);
11648 return std::make_pair(false, llvm::APSInt());
11649 }
11650 if (CAT)
11651 return std::make_pair(true, CAT->getSize());
11652 return std::make_pair(false, llvm::APInt());
11653 };
11654
11655 bool HaveLSize, HaveRSize;
11656 llvm::APInt LSize, RSize;
11657 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
11658 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
11659 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
11660 return {}; // Definite, but unequal, array dimension
11661 }
11662
11663 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
11664 return LHS;
11665 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
11666 return RHS;
11667 if (LCAT)
11668 return getConstantArrayType(ResultType, LCAT->getSize(),
11669 LCAT->getSizeExpr(), ArraySizeModifier(), 0);
11670 if (RCAT)
11671 return getConstantArrayType(ResultType, RCAT->getSize(),
11672 RCAT->getSizeExpr(), ArraySizeModifier(), 0);
11673 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
11674 return LHS;
11675 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
11676 return RHS;
11677 if (LVAT) {
11678 // FIXME: This isn't correct! But tricky to implement because
11679 // the array's size has to be the size of LHS, but the type
11680 // has to be different.
11681 return LHS;
11682 }
11683 if (RVAT) {
11684 // FIXME: This isn't correct! But tricky to implement because
11685 // the array's size has to be the size of RHS, but the type
11686 // has to be different.
11687 return RHS;
11688 }
11689 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
11690 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
11691 return getIncompleteArrayType(ResultType, ArraySizeModifier(), 0);
11692 }
11693 case Type::FunctionNoProto:
11694 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified,
11695 /*AllowCXX=*/false, IsConditionalOperator);
11696 case Type::Record:
11697 case Type::Enum:
11698 return {};
11699 case Type::Builtin:
11700 // Only exactly equal builtin types are compatible, which is tested above.
11701 return {};
11702 case Type::Complex:
11703 // Distinct complex types are incompatible.
11704 return {};
11705 case Type::Vector:
11706 // FIXME: The merged type should be an ExtVector!
11707 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
11708 RHSCan->castAs<VectorType>()))
11709 return LHS;
11710 return {};
11711 case Type::ConstantMatrix:
11713 RHSCan->castAs<ConstantMatrixType>()))
11714 return LHS;
11715 return {};
11716 case Type::ObjCObject: {
11717 // Check if the types are assignment compatible.
11718 // FIXME: This should be type compatibility, e.g. whether
11719 // "LHS x; RHS x;" at global scope is legal.
11721 RHS->castAs<ObjCObjectType>()))
11722 return LHS;
11723 return {};
11724 }
11725 case Type::ObjCObjectPointer:
11726 if (OfBlockPointer) {
11729 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
11730 return LHS;
11731 return {};
11732 }
11735 return LHS;
11736 return {};
11737 case Type::Pipe:
11738 assert(LHS != RHS &&
11739 "Equivalent pipe types should have already been handled!");
11740 return {};
11741 case Type::ArrayParameter:
11742 assert(LHS != RHS &&
11743 "Equivalent ArrayParameter types should have already been handled!");
11744 return {};
11745 case Type::BitInt: {
11746 // Merge two bit-precise int types, while trying to preserve typedef info.
11747 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
11748 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
11749 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
11750 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
11751
11752 // Like unsigned/int, shouldn't have a type if they don't match.
11753 if (LHSUnsigned != RHSUnsigned)
11754 return {};
11755
11756 if (LHSBits != RHSBits)
11757 return {};
11758 return LHS;
11759 }
11760 case Type::HLSLAttributedResource: {
11761 const HLSLAttributedResourceType *LHSTy =
11763 const HLSLAttributedResourceType *RHSTy =
11765 assert(LHSTy->getWrappedType() == RHSTy->getWrappedType() &&
11766 LHSTy->getWrappedType()->isHLSLResourceType() &&
11767 "HLSLAttributedResourceType should always wrap __hlsl_resource_t");
11768
11769 if (LHSTy->getAttrs() == RHSTy->getAttrs() &&
11770 LHSTy->getContainedType() == RHSTy->getContainedType())
11771 return LHS;
11772 return {};
11773 }
11774 }
11775
11776 llvm_unreachable("Invalid Type::Class!");
11777}
11778
11780 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
11781 bool &CanUseFirst, bool &CanUseSecond,
11783 assert(NewParamInfos.empty() && "param info list not empty");
11784 CanUseFirst = CanUseSecond = true;
11785 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
11786 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
11787
11788 // Fast path: if the first type doesn't have ext parameter infos,
11789 // we match if and only if the second type also doesn't have them.
11790 if (!FirstHasInfo && !SecondHasInfo)
11791 return true;
11792
11793 bool NeedParamInfo = false;
11794 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
11795 : SecondFnType->getExtParameterInfos().size();
11796
11797 for (size_t I = 0; I < E; ++I) {
11798 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
11799 if (FirstHasInfo)
11800 FirstParam = FirstFnType->getExtParameterInfo(I);
11801 if (SecondHasInfo)
11802 SecondParam = SecondFnType->getExtParameterInfo(I);
11803
11804 // Cannot merge unless everything except the noescape flag matches.
11805 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
11806 return false;
11807
11808 bool FirstNoEscape = FirstParam.isNoEscape();
11809 bool SecondNoEscape = SecondParam.isNoEscape();
11810 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
11811 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
11812 if (NewParamInfos.back().getOpaqueValue())
11813 NeedParamInfo = true;
11814 if (FirstNoEscape != IsNoEscape)
11815 CanUseFirst = false;
11816 if (SecondNoEscape != IsNoEscape)
11817 CanUseSecond = false;
11818 }
11819
11820 if (!NeedParamInfo)
11821 NewParamInfos.clear();
11822
11823 return true;
11824}
11825
11827 ObjCLayouts[CD] = nullptr;
11828}
11829
11830/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
11831/// 'RHS' attributes and returns the merged version; including for function
11832/// return types.
11834 QualType LHSCan = getCanonicalType(LHS),
11835 RHSCan = getCanonicalType(RHS);
11836 // If two types are identical, they are compatible.
11837 if (LHSCan == RHSCan)
11838 return LHS;
11839 if (RHSCan->isFunctionType()) {
11840 if (!LHSCan->isFunctionType())
11841 return {};
11842 QualType OldReturnType =
11843 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
11844 QualType NewReturnType =
11845 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
11846 QualType ResReturnType =
11847 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
11848 if (ResReturnType.isNull())
11849 return {};
11850 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
11851 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
11852 // In either case, use OldReturnType to build the new function type.
11853 const auto *F = LHS->castAs<FunctionType>();
11854 if (const auto *FPT = cast<FunctionProtoType>(F)) {
11855 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11856 EPI.ExtInfo = getFunctionExtInfo(LHS);
11857 QualType ResultType =
11858 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
11859 return ResultType;
11860 }
11861 }
11862 return {};
11863 }
11864
11865 // If the qualifiers are different, the types can still be merged.
11866 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11867 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11868 if (LQuals != RQuals) {
11869 // If any of these qualifiers are different, we have a type mismatch.
11870 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11871 LQuals.getAddressSpace() != RQuals.getAddressSpace())
11872 return {};
11873
11874 // Exactly one GC qualifier difference is allowed: __strong is
11875 // okay if the other type has no GC qualifier but is an Objective
11876 // C object pointer (i.e. implicitly strong by default). We fix
11877 // this by pretending that the unqualified type was actually
11878 // qualified __strong.
11879 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11880 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11881 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11882
11883 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11884 return {};
11885
11886 if (GC_L == Qualifiers::Strong)
11887 return LHS;
11888 if (GC_R == Qualifiers::Strong)
11889 return RHS;
11890 return {};
11891 }
11892
11893 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
11894 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
11895 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
11896 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
11897 if (ResQT == LHSBaseQT)
11898 return LHS;
11899 if (ResQT == RHSBaseQT)
11900 return RHS;
11901 }
11902 return {};
11903}
11904
11905//===----------------------------------------------------------------------===//
11906// Integer Predicates
11907//===----------------------------------------------------------------------===//
11908
11910 if (const auto *ET = T->getAs<EnumType>())
11911 T = ET->getDecl()->getIntegerType();
11912 if (T->isBooleanType())
11913 return 1;
11914 if (const auto *EIT = T->getAs<BitIntType>())
11915 return EIT->getNumBits();
11916 // For builtin types, just use the standard type sizing method
11917 return (unsigned)getTypeSize(T);
11918}
11919
11921 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
11922 T->isFixedPointType()) &&
11923 "Unexpected type");
11924
11925 // Turn <4 x signed int> -> <4 x unsigned int>
11926 if (const auto *VTy = T->getAs<VectorType>())
11927 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
11928 VTy->getNumElements(), VTy->getVectorKind());
11929
11930 // For _BitInt, return an unsigned _BitInt with same width.
11931 if (const auto *EITy = T->getAs<BitIntType>())
11932 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
11933
11934 // For enums, get the underlying integer type of the enum, and let the general
11935 // integer type signchanging code handle it.
11936 if (const auto *ETy = T->getAs<EnumType>())
11937 T = ETy->getDecl()->getIntegerType();
11938
11939 switch (T->castAs<BuiltinType>()->getKind()) {
11940 case BuiltinType::Char_U:
11941 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
11942 case BuiltinType::Char_S:
11943 case BuiltinType::SChar:
11944 case BuiltinType::Char8:
11945 return UnsignedCharTy;
11946 case BuiltinType::Short:
11947 return UnsignedShortTy;
11948 case BuiltinType::Int:
11949 return UnsignedIntTy;
11950 case BuiltinType::Long:
11951 return UnsignedLongTy;
11952 case BuiltinType::LongLong:
11953 return UnsignedLongLongTy;
11954 case BuiltinType::Int128:
11955 return UnsignedInt128Ty;
11956 // wchar_t is special. It is either signed or not, but when it's signed,
11957 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
11958 // version of its underlying type instead.
11959 case BuiltinType::WChar_S:
11960 return getUnsignedWCharType();
11961
11962 case BuiltinType::ShortAccum:
11963 return UnsignedShortAccumTy;
11964 case BuiltinType::Accum:
11965 return UnsignedAccumTy;
11966 case BuiltinType::LongAccum:
11967 return UnsignedLongAccumTy;
11968 case BuiltinType::SatShortAccum:
11970 case BuiltinType::SatAccum:
11971 return SatUnsignedAccumTy;
11972 case BuiltinType::SatLongAccum:
11974 case BuiltinType::ShortFract:
11975 return UnsignedShortFractTy;
11976 case BuiltinType::Fract:
11977 return UnsignedFractTy;
11978 case BuiltinType::LongFract:
11979 return UnsignedLongFractTy;
11980 case BuiltinType::SatShortFract:
11982 case BuiltinType::SatFract:
11983 return SatUnsignedFractTy;
11984 case BuiltinType::SatLongFract:
11986 default:
11989 "Unexpected signed integer or fixed point type");
11990 return T;
11991 }
11992}
11993
11995 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
11996 T->isFixedPointType()) &&
11997 "Unexpected type");
11998
11999 // Turn <4 x unsigned int> -> <4 x signed int>
12000 if (const auto *VTy = T->getAs<VectorType>())
12001 return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
12002 VTy->getNumElements(), VTy->getVectorKind());
12003
12004 // For _BitInt, return a signed _BitInt with same width.
12005 if (const auto *EITy = T->getAs<BitIntType>())
12006 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
12007
12008 // For enums, get the underlying integer type of the enum, and let the general
12009 // integer type signchanging code handle it.
12010 if (const auto *ETy = T->getAs<EnumType>())
12011 T = ETy->getDecl()->getIntegerType();
12012
12013 switch (T->castAs<BuiltinType>()->getKind()) {
12014 case BuiltinType::Char_S:
12015 // Plain `char` is mapped to `signed char` even if it's already signed
12016 case BuiltinType::Char_U:
12017 case BuiltinType::UChar:
12018 case BuiltinType::Char8:
12019 return SignedCharTy;
12020 case BuiltinType::UShort:
12021 return ShortTy;
12022 case BuiltinType::UInt:
12023 return IntTy;
12024 case BuiltinType::ULong:
12025 return LongTy;
12026 case BuiltinType::ULongLong:
12027 return LongLongTy;
12028 case BuiltinType::UInt128:
12029 return Int128Ty;
12030 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
12031 // there's no matching "signed wchar_t". Therefore we return the signed
12032 // version of its underlying type instead.
12033 case BuiltinType::WChar_U:
12034 return getSignedWCharType();
12035
12036 case BuiltinType::UShortAccum:
12037 return ShortAccumTy;
12038 case BuiltinType::UAccum:
12039 return AccumTy;
12040 case BuiltinType::ULongAccum:
12041 return LongAccumTy;
12042 case BuiltinType::SatUShortAccum:
12043 return SatShortAccumTy;
12044 case BuiltinType::SatUAccum:
12045 return SatAccumTy;
12046 case BuiltinType::SatULongAccum:
12047 return SatLongAccumTy;
12048 case BuiltinType::UShortFract:
12049 return ShortFractTy;
12050 case BuiltinType::UFract:
12051 return FractTy;
12052 case BuiltinType::ULongFract:
12053 return LongFractTy;
12054 case BuiltinType::SatUShortFract:
12055 return SatShortFractTy;
12056 case BuiltinType::SatUFract:
12057 return SatFractTy;
12058 case BuiltinType::SatULongFract:
12059 return SatLongFractTy;
12060 default:
12061 assert(
12063 "Unexpected signed integer or fixed point type");
12064 return T;
12065 }
12066}
12067
12069
12071 QualType ReturnType) {}
12072
12073//===----------------------------------------------------------------------===//
12074// Builtin Type Computation
12075//===----------------------------------------------------------------------===//
12076
12077/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
12078/// pointer over the consumed characters. This returns the resultant type. If
12079/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
12080/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
12081/// a vector of "i*".
12082///
12083/// RequiresICE is filled in on return to indicate whether the value is required
12084/// to be an Integer Constant Expression.
12085static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
12087 bool &RequiresICE,
12088 bool AllowTypeModifiers) {
12089 // Modifiers.
12090 int HowLong = 0;
12091 bool Signed = false, Unsigned = false;
12092 RequiresICE = false;
12093
12094 // Read the prefixed modifiers first.
12095 bool Done = false;
12096 #ifndef NDEBUG
12097 bool IsSpecial = false;
12098 #endif
12099 while (!Done) {
12100 switch (*Str++) {
12101 default: Done = true; --Str; break;
12102 case 'I':
12103 RequiresICE = true;
12104 break;
12105 case 'S':
12106 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
12107 assert(!Signed && "Can't use 'S' modifier multiple times!");
12108 Signed = true;
12109 break;
12110 case 'U':
12111 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
12112 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
12113 Unsigned = true;
12114 break;
12115 case 'L':
12116 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
12117 assert(HowLong <= 2 && "Can't have LLLL modifier");
12118 ++HowLong;
12119 break;
12120 case 'N':
12121 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
12122 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12123 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
12124 #ifndef NDEBUG
12125 IsSpecial = true;
12126 #endif
12127 if (Context.getTargetInfo().getLongWidth() == 32)
12128 ++HowLong;
12129 break;
12130 case 'W':
12131 // This modifier represents int64 type.
12132 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12133 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
12134 #ifndef NDEBUG
12135 IsSpecial = true;
12136 #endif
12137 switch (Context.getTargetInfo().getInt64Type()) {
12138 default:
12139 llvm_unreachable("Unexpected integer type");
12141 HowLong = 1;
12142 break;
12144 HowLong = 2;
12145 break;
12146 }
12147 break;
12148 case 'Z':
12149 // This modifier represents int32 type.
12150 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12151 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
12152 #ifndef NDEBUG
12153 IsSpecial = true;
12154 #endif
12155 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
12156 default:
12157 llvm_unreachable("Unexpected integer type");
12159 HowLong = 0;
12160 break;
12162 HowLong = 1;
12163 break;
12165 HowLong = 2;
12166 break;
12167 }
12168 break;
12169 case 'O':
12170 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12171 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
12172 #ifndef NDEBUG
12173 IsSpecial = true;
12174 #endif
12175 if (Context.getLangOpts().OpenCL)
12176 HowLong = 1;
12177 else
12178 HowLong = 2;
12179 break;
12180 }
12181 }
12182
12183 QualType Type;
12184
12185 // Read the base type.
12186 switch (*Str++) {
12187 default: llvm_unreachable("Unknown builtin type letter!");
12188 case 'x':
12189 assert(HowLong == 0 && !Signed && !Unsigned &&
12190 "Bad modifiers used with 'x'!");
12191 Type = Context.Float16Ty;
12192 break;
12193 case 'y':
12194 assert(HowLong == 0 && !Signed && !Unsigned &&
12195 "Bad modifiers used with 'y'!");
12196 Type = Context.BFloat16Ty;
12197 break;
12198 case 'v':
12199 assert(HowLong == 0 && !Signed && !Unsigned &&
12200 "Bad modifiers used with 'v'!");
12201 Type = Context.VoidTy;
12202 break;
12203 case 'h':
12204 assert(HowLong == 0 && !Signed && !Unsigned &&
12205 "Bad modifiers used with 'h'!");
12206 Type = Context.HalfTy;
12207 break;
12208 case 'f':
12209 assert(HowLong == 0 && !Signed && !Unsigned &&
12210 "Bad modifiers used with 'f'!");
12211 Type = Context.FloatTy;
12212 break;
12213 case 'd':
12214 assert(HowLong < 3 && !Signed && !Unsigned &&
12215 "Bad modifiers used with 'd'!");
12216 if (HowLong == 1)
12217 Type = Context.LongDoubleTy;
12218 else if (HowLong == 2)
12219 Type = Context.Float128Ty;
12220 else
12221 Type = Context.DoubleTy;
12222 break;
12223 case 's':
12224 assert(HowLong == 0 && "Bad modifiers used with 's'!");
12225 if (Unsigned)
12226 Type = Context.UnsignedShortTy;
12227 else
12228 Type = Context.ShortTy;
12229 break;
12230 case 'i':
12231 if (HowLong == 3)
12232 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
12233 else if (HowLong == 2)
12234 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
12235 else if (HowLong == 1)
12236 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
12237 else
12238 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
12239 break;
12240 case 'c':
12241 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
12242 if (Signed)
12243 Type = Context.SignedCharTy;
12244 else if (Unsigned)
12245 Type = Context.UnsignedCharTy;
12246 else
12247 Type = Context.CharTy;
12248 break;
12249 case 'b': // boolean
12250 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
12251 Type = Context.BoolTy;
12252 break;
12253 case 'z': // size_t.
12254 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
12255 Type = Context.getSizeType();
12256 break;
12257 case 'w': // wchar_t.
12258 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
12259 Type = Context.getWideCharType();
12260 break;
12261 case 'F':
12262 Type = Context.getCFConstantStringType();
12263 break;
12264 case 'G':
12265 Type = Context.getObjCIdType();
12266 break;
12267 case 'H':
12268 Type = Context.getObjCSelType();
12269 break;
12270 case 'M':
12271 Type = Context.getObjCSuperType();
12272 break;
12273 case 'a':
12274 Type = Context.getBuiltinVaListType();
12275 assert(!Type.isNull() && "builtin va list type not initialized!");
12276 break;
12277 case 'A':
12278 // This is a "reference" to a va_list; however, what exactly
12279 // this means depends on how va_list is defined. There are two
12280 // different kinds of va_list: ones passed by value, and ones
12281 // passed by reference. An example of a by-value va_list is
12282 // x86, where va_list is a char*. An example of by-ref va_list
12283 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
12284 // we want this argument to be a char*&; for x86-64, we want
12285 // it to be a __va_list_tag*.
12286 Type = Context.getBuiltinVaListType();
12287 assert(!Type.isNull() && "builtin va list type not initialized!");
12288 if (Type->isArrayType())
12289 Type = Context.getArrayDecayedType(Type);
12290 else
12291 Type = Context.getLValueReferenceType(Type);
12292 break;
12293 case 'q': {
12294 char *End;
12295 unsigned NumElements = strtoul(Str, &End, 10);
12296 assert(End != Str && "Missing vector size");
12297 Str = End;
12298
12299 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12300 RequiresICE, false);
12301 assert(!RequiresICE && "Can't require vector ICE");
12302
12303 Type = Context.getScalableVectorType(ElementType, NumElements);
12304 break;
12305 }
12306 case 'Q': {
12307 switch (*Str++) {
12308 case 'a': {
12309 Type = Context.SveCountTy;
12310 break;
12311 }
12312 case 'b': {
12313 Type = Context.AMDGPUBufferRsrcTy;
12314 break;
12315 }
12316 default:
12317 llvm_unreachable("Unexpected target builtin type");
12318 }
12319 break;
12320 }
12321 case 'V': {
12322 char *End;
12323 unsigned NumElements = strtoul(Str, &End, 10);
12324 assert(End != Str && "Missing vector size");
12325 Str = End;
12326
12327 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12328 RequiresICE, false);
12329 assert(!RequiresICE && "Can't require vector ICE");
12330
12331 // TODO: No way to make AltiVec vectors in builtins yet.
12332 Type = Context.getVectorType(ElementType, NumElements, VectorKind::Generic);
12333 break;
12334 }
12335 case 'E': {
12336 char *End;
12337
12338 unsigned NumElements = strtoul(Str, &End, 10);
12339 assert(End != Str && "Missing vector size");
12340
12341 Str = End;
12342
12343 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12344 false);
12345 Type = Context.getExtVectorType(ElementType, NumElements);
12346 break;
12347 }
12348 case 'X': {
12349 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12350 false);
12351 assert(!RequiresICE && "Can't require complex ICE");
12352 Type = Context.getComplexType(ElementType);
12353 break;
12354 }
12355 case 'Y':
12356 Type = Context.getPointerDiffType();
12357 break;
12358 case 'P':
12359 Type = Context.getFILEType();
12360 if (Type.isNull()) {
12362 return {};
12363 }
12364 break;
12365 case 'J':
12366 if (Signed)
12367 Type = Context.getsigjmp_bufType();
12368 else
12369 Type = Context.getjmp_bufType();
12370
12371 if (Type.isNull()) {
12373 return {};
12374 }
12375 break;
12376 case 'K':
12377 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
12378 Type = Context.getucontext_tType();
12379
12380 if (Type.isNull()) {
12382 return {};
12383 }
12384 break;
12385 case 'p':
12386 Type = Context.getProcessIDType();
12387 break;
12388 case 'm':
12389 Type = Context.MFloat8Ty;
12390 break;
12391 }
12392
12393 // If there are modifiers and if we're allowed to parse them, go for it.
12394 Done = !AllowTypeModifiers;
12395 while (!Done) {
12396 switch (char c = *Str++) {
12397 default: Done = true; --Str; break;
12398 case '*':
12399 case '&': {
12400 // Both pointers and references can have their pointee types
12401 // qualified with an address space.
12402 char *End;
12403 unsigned AddrSpace = strtoul(Str, &End, 10);
12404 if (End != Str) {
12405 // Note AddrSpace == 0 is not the same as an unspecified address space.
12406 Type = Context.getAddrSpaceQualType(
12407 Type,
12408 Context.getLangASForBuiltinAddressSpace(AddrSpace));
12409 Str = End;
12410 }
12411 if (c == '*')
12412 Type = Context.getPointerType(Type);
12413 else
12414 Type = Context.getLValueReferenceType(Type);
12415 break;
12416 }
12417 // FIXME: There's no way to have a built-in with an rvalue ref arg.
12418 case 'C':
12419 Type = Type.withConst();
12420 break;
12421 case 'D':
12422 Type = Context.getVolatileType(Type);
12423 break;
12424 case 'R':
12425 Type = Type.withRestrict();
12426 break;
12427 }
12428 }
12429
12430 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
12431 "Integer constant 'I' type must be an integer");
12432
12433 return Type;
12434}
12435
12436// On some targets such as PowerPC, some of the builtins are defined with custom
12437// type descriptors for target-dependent types. These descriptors are decoded in
12438// other functions, but it may be useful to be able to fall back to default
12439// descriptor decoding to define builtins mixing target-dependent and target-
12440// independent types. This function allows decoding one type descriptor with
12441// default decoding.
12442QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
12443 GetBuiltinTypeError &Error, bool &RequireICE,
12444 bool AllowTypeModifiers) const {
12445 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
12446}
12447
12448/// GetBuiltinType - Return the type for the specified builtin.
12450 GetBuiltinTypeError &Error,
12451 unsigned *IntegerConstantArgs) const {
12452 const char *TypeStr = BuiltinInfo.getTypeString(Id);
12453 if (TypeStr[0] == '\0') {
12454 Error = GE_Missing_type;
12455 return {};
12456 }
12457
12458 SmallVector<QualType, 8> ArgTypes;
12459
12460 bool RequiresICE = false;
12461 Error = GE_None;
12462 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
12463 RequiresICE, true);
12464 if (Error != GE_None)
12465 return {};
12466
12467 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
12468
12469 while (TypeStr[0] && TypeStr[0] != '.') {
12470 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
12471 if (Error != GE_None)
12472 return {};
12473
12474 // If this argument is required to be an IntegerConstantExpression and the
12475 // caller cares, fill in the bitmask we return.
12476 if (RequiresICE && IntegerConstantArgs)
12477 *IntegerConstantArgs |= 1 << ArgTypes.size();
12478
12479 // Do array -> pointer decay. The builtin should use the decayed type.
12480 if (Ty->isArrayType())
12481 Ty = getArrayDecayedType(Ty);
12482
12483 ArgTypes.push_back(Ty);
12484 }
12485
12486 if (Id == Builtin::BI__GetExceptionInfo)
12487 return {};
12488
12489 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
12490 "'.' should only occur at end of builtin type list!");
12491
12492 bool Variadic = (TypeStr[0] == '.');
12493
12495 Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
12496 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
12497
12498
12499 // We really shouldn't be making a no-proto type here.
12500 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
12501 return getFunctionNoProtoType(ResType, EI);
12502
12504 EPI.ExtInfo = EI;
12505 EPI.Variadic = Variadic;
12507 EPI.ExceptionSpec.Type =
12509
12510 return getFunctionType(ResType, ArgTypes, EPI);
12511}
12512
12514 const FunctionDecl *FD) {
12515 if (!FD->isExternallyVisible())
12516 return GVA_Internal;
12517
12518 // Non-user-provided functions get emitted as weak definitions with every
12519 // use, no matter whether they've been explicitly instantiated etc.
12520 if (!FD->isUserProvided())
12521 return GVA_DiscardableODR;
12522
12524 switch (FD->getTemplateSpecializationKind()) {
12525 case TSK_Undeclared:
12528 break;
12529
12531 return GVA_StrongODR;
12532
12533 // C++11 [temp.explicit]p10:
12534 // [ Note: The intent is that an inline function that is the subject of
12535 // an explicit instantiation declaration will still be implicitly
12536 // instantiated when used so that the body can be considered for
12537 // inlining, but that no out-of-line copy of the inline function would be
12538 // generated in the translation unit. -- end note ]
12541
12544 break;
12545 }
12546
12547 if (!FD->isInlined())
12548 return External;
12549
12550 if ((!Context.getLangOpts().CPlusPlus &&
12551 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12552 !FD->hasAttr<DLLExportAttr>()) ||
12553 FD->hasAttr<GNUInlineAttr>()) {
12554 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
12555
12556 // GNU or C99 inline semantics. Determine whether this symbol should be
12557 // externally visible.
12559 return External;
12560
12561 // C99 inline semantics, where the symbol is not externally visible.
12563 }
12564
12565 // Functions specified with extern and inline in -fms-compatibility mode
12566 // forcibly get emitted. While the body of the function cannot be later
12567 // replaced, the function definition cannot be discarded.
12568 if (FD->isMSExternInline())
12569 return GVA_StrongODR;
12570
12571 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12572 isa<CXXConstructorDecl>(FD) &&
12573 cast<CXXConstructorDecl>(FD)->isInheritingConstructor())
12574 // Our approach to inheriting constructors is fundamentally different from
12575 // that used by the MS ABI, so keep our inheriting constructor thunks
12576 // internal rather than trying to pick an unambiguous mangling for them.
12577 return GVA_Internal;
12578
12579 return GVA_DiscardableODR;
12580}
12581
12583 const Decl *D, GVALinkage L) {
12584 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
12585 // dllexport/dllimport on inline functions.
12586 if (D->hasAttr<DLLImportAttr>()) {
12587 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
12589 } else if (D->hasAttr<DLLExportAttr>()) {
12590 if (L == GVA_DiscardableODR)
12591 return GVA_StrongODR;
12592 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
12593 // Device-side functions with __global__ attribute must always be
12594 // visible externally so they can be launched from host.
12595 if (D->hasAttr<CUDAGlobalAttr>() &&
12596 (L == GVA_DiscardableODR || L == GVA_Internal))
12597 return GVA_StrongODR;
12598 // Single source offloading languages like CUDA/HIP need to be able to
12599 // access static device variables from host code of the same compilation
12600 // unit. This is done by externalizing the static variable with a shared
12601 // name between the host and device compilation which is the same for the
12602 // same compilation unit whereas different among different compilation
12603 // units.
12604 if (Context.shouldExternalize(D))
12605 return GVA_StrongExternal;
12606 }
12607 return L;
12608}
12609
12610/// Adjust the GVALinkage for a declaration based on what an external AST source
12611/// knows about whether there can be other definitions of this declaration.
12612static GVALinkage
12614 GVALinkage L) {
12615 ExternalASTSource *Source = Ctx.getExternalSource();
12616 if (!Source)
12617 return L;
12618
12619 switch (Source->hasExternalDefinitions(D)) {
12621 // Other translation units rely on us to provide the definition.
12622 if (L == GVA_DiscardableODR)
12623 return GVA_StrongODR;
12624 break;
12625
12628
12630 break;
12631 }
12632 return L;
12633}
12634
12638 basicGVALinkageForFunction(*this, FD)));
12639}
12640
12642 const VarDecl *VD) {
12643 // As an extension for interactive REPLs, make sure constant variables are
12644 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
12645 // marking them as internal.
12646 if (Context.getLangOpts().CPlusPlus &&
12647 Context.getLangOpts().IncrementalExtensions &&
12648 VD->getType().isConstQualified() &&
12649 !VD->getType().isVolatileQualified() && !VD->isInline() &&
12650 !isa<VarTemplateSpecializationDecl>(VD) && !VD->getDescribedVarTemplate())
12651 return GVA_DiscardableODR;
12652
12653 if (!VD->isExternallyVisible())
12654 return GVA_Internal;
12655
12656 if (VD->isStaticLocal()) {
12657 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
12658 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
12659 LexicalContext = LexicalContext->getLexicalParent();
12660
12661 // ObjC Blocks can create local variables that don't have a FunctionDecl
12662 // LexicalContext.
12663 if (!LexicalContext)
12664 return GVA_DiscardableODR;
12665
12666 // Otherwise, let the static local variable inherit its linkage from the
12667 // nearest enclosing function.
12668 auto StaticLocalLinkage =
12669 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
12670
12671 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
12672 // be emitted in any object with references to the symbol for the object it
12673 // contains, whether inline or out-of-line."
12674 // Similar behavior is observed with MSVC. An alternative ABI could use
12675 // StrongODR/AvailableExternally to match the function, but none are
12676 // known/supported currently.
12677 if (StaticLocalLinkage == GVA_StrongODR ||
12678 StaticLocalLinkage == GVA_AvailableExternally)
12679 return GVA_DiscardableODR;
12680 return StaticLocalLinkage;
12681 }
12682
12683 // MSVC treats in-class initialized static data members as definitions.
12684 // By giving them non-strong linkage, out-of-line definitions won't
12685 // cause link errors.
12687 return GVA_DiscardableODR;
12688
12689 // Most non-template variables have strong linkage; inline variables are
12690 // linkonce_odr or (occasionally, for compatibility) weak_odr.
12691 GVALinkage StrongLinkage;
12692 switch (Context.getInlineVariableDefinitionKind(VD)) {
12694 StrongLinkage = GVA_StrongExternal;
12695 break;
12698 StrongLinkage = GVA_DiscardableODR;
12699 break;
12701 StrongLinkage = GVA_StrongODR;
12702 break;
12703 }
12704
12705 switch (VD->getTemplateSpecializationKind()) {
12706 case TSK_Undeclared:
12707 return StrongLinkage;
12708
12710 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12711 VD->isStaticDataMember()
12713 : StrongLinkage;
12714
12716 return GVA_StrongODR;
12717
12720
12722 return GVA_DiscardableODR;
12723 }
12724
12725 llvm_unreachable("Invalid Linkage!");
12726}
12727
12731 basicGVALinkageForVariable(*this, VD)));
12732}
12733
12735 if (const auto *VD = dyn_cast<VarDecl>(D)) {
12736 if (!VD->isFileVarDecl())
12737 return false;
12738 // Global named register variables (GNU extension) are never emitted.
12739 if (VD->getStorageClass() == SC_Register)
12740 return false;
12741 if (VD->getDescribedVarTemplate() ||
12742 isa<VarTemplatePartialSpecializationDecl>(VD))
12743 return false;
12744 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
12745 // We never need to emit an uninstantiated function template.
12746 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12747 return false;
12748 } else if (isa<PragmaCommentDecl>(D))
12749 return true;
12750 else if (isa<PragmaDetectMismatchDecl>(D))
12751 return true;
12752 else if (isa<OMPRequiresDecl>(D))
12753 return true;
12754 else if (isa<OMPThreadPrivateDecl>(D))
12755 return !D->getDeclContext()->isDependentContext();
12756 else if (isa<OMPAllocateDecl>(D))
12757 return !D->getDeclContext()->isDependentContext();
12758 else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D))
12759 return !D->getDeclContext()->isDependentContext();
12760 else if (isa<ImportDecl>(D))
12761 return true;
12762 else
12763 return false;
12764
12765 // If this is a member of a class template, we do not need to emit it.
12767 return false;
12768
12769 // Weak references don't produce any output by themselves.
12770 if (D->hasAttr<WeakRefAttr>())
12771 return false;
12772
12773 // Aliases and used decls are required.
12774 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
12775 return true;
12776
12777 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
12778 // Forward declarations aren't required.
12779 if (!FD->doesThisDeclarationHaveABody())
12780 return FD->doesDeclarationForceExternallyVisibleDefinition();
12781
12782 // Constructors and destructors are required.
12783 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
12784 return true;
12785
12786 // The key function for a class is required. This rule only comes
12787 // into play when inline functions can be key functions, though.
12788 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
12789 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
12790 const CXXRecordDecl *RD = MD->getParent();
12791 if (MD->isOutOfLine() && RD->isDynamicClass()) {
12792 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
12793 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
12794 return true;
12795 }
12796 }
12797 }
12798
12800
12801 // static, static inline, always_inline, and extern inline functions can
12802 // always be deferred. Normal inline functions can be deferred in C99/C++.
12803 // Implicit template instantiations can also be deferred in C++.
12805 }
12806
12807 const auto *VD = cast<VarDecl>(D);
12808 assert(VD->isFileVarDecl() && "Expected file scoped var");
12809
12810 // If the decl is marked as `declare target to`, it should be emitted for the
12811 // host and for the device.
12812 if (LangOpts.OpenMP &&
12813 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
12814 return true;
12815
12816 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
12818 return false;
12819
12820 if (VD->shouldEmitInExternalSource())
12821 return false;
12822
12823 // Variables that can be needed in other TUs are required.
12826 return true;
12827
12828 // We never need to emit a variable that is available in another TU.
12830 return false;
12831
12832 // Variables that have destruction with side-effects are required.
12833 if (VD->needsDestruction(*this))
12834 return true;
12835
12836 // Variables that have initialization with side-effects are required.
12837 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
12838 // We can get a value-dependent initializer during error recovery.
12839 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
12840 return true;
12841
12842 // Likewise, variables with tuple-like bindings are required if their
12843 // bindings have side-effects.
12844 if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
12845 for (const auto *BD : DD->bindings())
12846 if (const auto *BindingVD = BD->getHoldingVar())
12847 if (DeclMustBeEmitted(BindingVD))
12848 return true;
12849
12850 return false;
12851}
12852
12854 const FunctionDecl *FD,
12855 llvm::function_ref<void(FunctionDecl *)> Pred) const {
12856 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
12857 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
12858 FD = FD->getMostRecentDecl();
12859 // FIXME: The order of traversal here matters and depends on the order of
12860 // lookup results, which happens to be (mostly) oldest-to-newest, but we
12861 // shouldn't rely on that.
12862 for (auto *CurDecl :
12864 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
12865 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
12866 SeenDecls.insert(CurFD).second) {
12867 Pred(CurFD);
12868 }
12869 }
12870}
12871
12873 bool IsCXXMethod,
12874 bool IsBuiltin) const {
12875 // Pass through to the C++ ABI object
12876 if (IsCXXMethod)
12877 return ABI->getDefaultMethodCallConv(IsVariadic);
12878
12879 // Builtins ignore user-specified default calling convention and remain the
12880 // Target's default calling convention.
12881 if (!IsBuiltin) {
12882 switch (LangOpts.getDefaultCallingConv()) {
12884 break;
12886 return CC_C;
12888 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
12889 return CC_X86FastCall;
12890 break;
12892 if (!IsVariadic)
12893 return CC_X86StdCall;
12894 break;
12896 // __vectorcall cannot be applied to variadic functions.
12897 if (!IsVariadic)
12898 return CC_X86VectorCall;
12899 break;
12901 // __regcall cannot be applied to variadic functions.
12902 if (!IsVariadic)
12903 return CC_X86RegCall;
12904 break;
12906 if (!IsVariadic)
12907 return CC_M68kRTD;
12908 break;
12909 }
12910 }
12911 return Target->getDefaultCallingConv();
12912}
12913
12915 // Pass through to the C++ ABI object
12916 return ABI->isNearlyEmpty(RD);
12917}
12918
12920 if (!VTContext.get()) {
12921 auto ABI = Target->getCXXABI();
12922 if (ABI.isMicrosoft())
12923 VTContext.reset(new MicrosoftVTableContext(*this));
12924 else {
12925 auto ComponentLayout = getLangOpts().RelativeCXXABIVTables
12928 VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout));
12929 }
12930 }
12931 return VTContext.get();
12932}
12933
12935 if (!T)
12936 T = Target;
12937 switch (T->getCXXABI().getKind()) {
12938 case TargetCXXABI::AppleARM64:
12939 case TargetCXXABI::Fuchsia:
12940 case TargetCXXABI::GenericAArch64:
12941 case TargetCXXABI::GenericItanium:
12942 case TargetCXXABI::GenericARM:
12943 case TargetCXXABI::GenericMIPS:
12944 case TargetCXXABI::iOS:
12945 case TargetCXXABI::WebAssembly:
12946 case TargetCXXABI::WatchOS:
12947 case TargetCXXABI::XL:
12949 case TargetCXXABI::Microsoft:
12951 }
12952 llvm_unreachable("Unsupported ABI");
12953}
12954
12956 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
12957 "Device mangle context does not support Microsoft mangling.");
12958 switch (T.getCXXABI().getKind()) {
12959 case TargetCXXABI::AppleARM64:
12960 case TargetCXXABI::Fuchsia:
12961 case TargetCXXABI::GenericAArch64:
12962 case TargetCXXABI::GenericItanium:
12963 case TargetCXXABI::GenericARM:
12964 case TargetCXXABI::GenericMIPS:
12965 case TargetCXXABI::iOS:
12966 case TargetCXXABI::WebAssembly:
12967 case TargetCXXABI::WatchOS:
12968 case TargetCXXABI::XL:
12970 *this, getDiagnostics(),
12971 [](ASTContext &, const NamedDecl *ND) -> std::optional<unsigned> {
12972 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
12973 return RD->getDeviceLambdaManglingNumber();
12974 return std::nullopt;
12975 },
12976 /*IsAux=*/true);
12977 case TargetCXXABI::Microsoft:
12979 /*IsAux=*/true);
12980 }
12981 llvm_unreachable("Unsupported ABI");
12982}
12983
12984CXXABI::~CXXABI() = default;
12985
12987 return ASTRecordLayouts.getMemorySize() +
12988 llvm::capacity_in_bytes(ObjCLayouts) +
12989 llvm::capacity_in_bytes(KeyFunctions) +
12990 llvm::capacity_in_bytes(ObjCImpls) +
12991 llvm::capacity_in_bytes(BlockVarCopyInits) +
12992 llvm::capacity_in_bytes(DeclAttrs) +
12993 llvm::capacity_in_bytes(TemplateOrInstantiation) +
12994 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
12995 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
12996 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
12997 llvm::capacity_in_bytes(OverriddenMethods) +
12998 llvm::capacity_in_bytes(Types) +
12999 llvm::capacity_in_bytes(VariableArrayTypes);
13000}
13001
13002/// getIntTypeForBitwidth -
13003/// sets integer QualTy according to specified details:
13004/// bitwidth, signed/unsigned.
13005/// Returns empty type if there is no appropriate target types.
13007 unsigned Signed) const {
13009 CanQualType QualTy = getFromTargetType(Ty);
13010 if (!QualTy && DestWidth == 128)
13011 return Signed ? Int128Ty : UnsignedInt128Ty;
13012 return QualTy;
13013}
13014
13015/// getRealTypeForBitwidth -
13016/// sets floating point QualTy according to specified bitwidth.
13017/// Returns empty type if there is no appropriate target types.
13019 FloatModeKind ExplicitType) const {
13020 FloatModeKind Ty =
13021 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
13022 switch (Ty) {
13024 return HalfTy;
13026 return FloatTy;
13028 return DoubleTy;
13030 return LongDoubleTy;
13032 return Float128Ty;
13034 return Ibm128Ty;
13036 return {};
13037 }
13038
13039 llvm_unreachable("Unhandled TargetInfo::RealType value");
13040}
13041
13042void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
13043 if (Number <= 1)
13044 return;
13045
13046 MangleNumbers[ND] = Number;
13047
13048 if (Listener)
13049 Listener->AddedManglingNumber(ND, Number);
13050}
13051
13053 bool ForAuxTarget) const {
13054 auto I = MangleNumbers.find(ND);
13055 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
13056 // CUDA/HIP host compilation encodes host and device mangling numbers
13057 // as lower and upper half of 32 bit integer.
13058 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
13059 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
13060 } else {
13061 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
13062 "number for aux target");
13063 }
13064 return Res > 1 ? Res : 1;
13065}
13066
13067void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
13068 if (Number <= 1)
13069 return;
13070
13071 StaticLocalNumbers[VD] = Number;
13072
13073 if (Listener)
13074 Listener->AddedStaticLocalNumbers(VD, Number);
13075}
13076
13078 auto I = StaticLocalNumbers.find(VD);
13079 return I != StaticLocalNumbers.end() ? I->second : 1;
13080}
13081
13084 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13085 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
13086 if (!MCtx)
13088 return *MCtx;
13089}
13090
13093 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13094 std::unique_ptr<MangleNumberingContext> &MCtx =
13095 ExtraMangleNumberingContexts[D];
13096 if (!MCtx)
13098 return *MCtx;
13099}
13100
13101std::unique_ptr<MangleNumberingContext>
13103 return ABI->createMangleNumberingContext();
13104}
13105
13106const CXXConstructorDecl *
13108 return ABI->getCopyConstructorForExceptionObject(
13109 cast<CXXRecordDecl>(RD->getFirstDecl()));
13110}
13111
13113 CXXConstructorDecl *CD) {
13114 return ABI->addCopyConstructorForExceptionObject(
13115 cast<CXXRecordDecl>(RD->getFirstDecl()),
13116 cast<CXXConstructorDecl>(CD->getFirstDecl()));
13117}
13118
13120 TypedefNameDecl *DD) {
13121 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
13122}
13123
13126 return ABI->getTypedefNameForUnnamedTagDecl(TD);
13127}
13128
13130 DeclaratorDecl *DD) {
13131 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
13132}
13133
13135 return ABI->getDeclaratorForUnnamedTagDecl(TD);
13136}
13137
13138void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
13139 ParamIndices[D] = index;
13140}
13141
13143 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
13144 assert(I != ParamIndices.end() &&
13145 "ParmIndices lacks entry set by ParmVarDecl");
13146 return I->second;
13147}
13148
13150 unsigned Length) const {
13151 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
13152 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
13153 EltTy = EltTy.withConst();
13154
13155 EltTy = adjustStringLiteralBaseType(EltTy);
13156
13157 // Get an array type for the string, according to C99 6.4.5. This includes
13158 // the null terminator character.
13159 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
13160 ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
13161}
13162
13165 StringLiteral *&Result = StringLiteralCache[Key];
13166 if (!Result)
13168 *this, Key, StringLiteralKind::Ordinary,
13169 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
13170 SourceLocation());
13171 return Result;
13172}
13173
13174MSGuidDecl *
13176 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
13177
13178 llvm::FoldingSetNodeID ID;
13179 MSGuidDecl::Profile(ID, Parts);
13180
13181 void *InsertPos;
13182 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
13183 return Existing;
13184
13185 QualType GUIDType = getMSGuidType().withConst();
13186 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
13187 MSGuidDecls.InsertNode(New, InsertPos);
13188 return New;
13189}
13190
13193 const APValue &APVal) const {
13194 llvm::FoldingSetNodeID ID;
13196
13197 void *InsertPos;
13198 if (UnnamedGlobalConstantDecl *Existing =
13199 UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos))
13200 return Existing;
13201
13203 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
13204 UnnamedGlobalConstantDecls.InsertNode(New, InsertPos);
13205 return New;
13206}
13207
13210 assert(T->isRecordType() && "template param object of unexpected type");
13211
13212 // C++ [temp.param]p8:
13213 // [...] a static storage duration object of type 'const T' [...]
13214 T.addConst();
13215
13216 llvm::FoldingSetNodeID ID;
13218
13219 void *InsertPos;
13220 if (TemplateParamObjectDecl *Existing =
13221 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
13222 return Existing;
13223
13224 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
13225 TemplateParamObjectDecls.InsertNode(New, InsertPos);
13226 return New;
13227}
13228
13230 const llvm::Triple &T = getTargetInfo().getTriple();
13231 if (!T.isOSDarwin())
13232 return false;
13233
13234 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
13235 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
13236 return false;
13237
13238 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
13239 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
13240 uint64_t Size = sizeChars.getQuantity();
13241 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
13242 unsigned Align = alignChars.getQuantity();
13243 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
13244 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
13245}
13246
13247bool
13249 const ObjCMethodDecl *MethodImpl) {
13250 // No point trying to match an unavailable/deprecated mothod.
13251 if (MethodDecl->hasAttr<UnavailableAttr>()
13252 || MethodDecl->hasAttr<DeprecatedAttr>())
13253 return false;
13254 if (MethodDecl->getObjCDeclQualifier() !=
13255 MethodImpl->getObjCDeclQualifier())
13256 return false;
13257 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
13258 return false;
13259
13260 if (MethodDecl->param_size() != MethodImpl->param_size())
13261 return false;
13262
13263 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
13264 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
13265 EF = MethodDecl->param_end();
13266 IM != EM && IF != EF; ++IM, ++IF) {
13267 const ParmVarDecl *DeclVar = (*IF);
13268 const ParmVarDecl *ImplVar = (*IM);
13269 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
13270 return false;
13271 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
13272 return false;
13273 }
13274
13275 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
13276}
13277
13279 LangAS AS;
13281 AS = LangAS::Default;
13282 else
13283 AS = QT->getPointeeType().getAddressSpace();
13284
13286}
13287
13290}
13291
13292bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
13293 if (X == Y)
13294 return true;
13295 if (!X || !Y)
13296 return false;
13297 llvm::FoldingSetNodeID IDX, IDY;
13298 X->Profile(IDX, *this, /*Canonical=*/true);
13299 Y->Profile(IDY, *this, /*Canonical=*/true);
13300 return IDX == IDY;
13301}
13302
13303// The getCommon* helpers return, for given 'same' X and Y entities given as
13304// inputs, another entity which is also the 'same' as the inputs, but which
13305// is closer to the canonical form of the inputs, each according to a given
13306// criteria.
13307// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
13308// the regular ones.
13309
13311 if (!declaresSameEntity(X, Y))
13312 return nullptr;
13313 for (const Decl *DX : X->redecls()) {
13314 // If we reach Y before reaching the first decl, that means X is older.
13315 if (DX == Y)
13316 return X;
13317 // If we reach the first decl, then Y is older.
13318 if (DX->isFirstDecl())
13319 return Y;
13320 }
13321 llvm_unreachable("Corrupt redecls chain");
13322}
13323
13324template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13325static T *getCommonDecl(T *X, T *Y) {
13326 return cast_or_null<T>(
13327 getCommonDecl(const_cast<Decl *>(cast_or_null<Decl>(X)),
13328 const_cast<Decl *>(cast_or_null<Decl>(Y))));
13329}
13330
13331template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13332static T *getCommonDeclChecked(T *X, T *Y) {
13333 return cast<T>(getCommonDecl(const_cast<Decl *>(cast<Decl>(X)),
13334 const_cast<Decl *>(cast<Decl>(Y))));
13335}
13336
13338 TemplateName Y,
13339 bool IgnoreDeduced = false) {
13340 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
13341 return X;
13342 // FIXME: There are cases here where we could find a common template name
13343 // with more sugar. For example one could be a SubstTemplateTemplate*
13344 // replacing the other.
13345 TemplateName CX = Ctx.getCanonicalTemplateName(X, IgnoreDeduced);
13346 if (CX.getAsVoidPointer() !=
13348 return TemplateName();
13349 return CX;
13350}
13351
13354 bool IgnoreDeduced) {
13355 TemplateName R = getCommonTemplateName(Ctx, X, Y, IgnoreDeduced);
13356 assert(R.getAsVoidPointer() != nullptr);
13357 return R;
13358}
13359
13361 ArrayRef<QualType> Ys, bool Unqualified = false) {
13362 assert(Xs.size() == Ys.size());
13363 SmallVector<QualType, 8> Rs(Xs.size());
13364 for (size_t I = 0; I < Rs.size(); ++I)
13365 Rs[I] = Ctx.getCommonSugaredType(Xs[I], Ys[I], Unqualified);
13366 return Rs;
13367}
13368
13369template <class T>
13370static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
13371 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
13372 : SourceLocation();
13373}
13374
13376 const TemplateArgument &X,
13377 const TemplateArgument &Y) {
13378 if (X.getKind() != Y.getKind())
13379 return TemplateArgument();
13380
13381 switch (X.getKind()) {
13383 if (!Ctx.hasSameType(X.getAsType(), Y.getAsType()))
13384 return TemplateArgument();
13385 return TemplateArgument(
13386 Ctx.getCommonSugaredType(X.getAsType(), Y.getAsType()));
13388 if (!Ctx.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
13389 return TemplateArgument();
13390 return TemplateArgument(
13391 Ctx.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
13392 /*Unqualified=*/true);
13394 if (!Ctx.hasSameType(X.getAsExpr()->getType(), Y.getAsExpr()->getType()))
13395 return TemplateArgument();
13396 // FIXME: Try to keep the common sugar.
13397 return X;
13399 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
13400 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13401 if (!CTN.getAsVoidPointer())
13402 return TemplateArgument();
13403 return TemplateArgument(CTN);
13404 }
13406 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
13408 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13409 if (!CTN.getAsVoidPointer())
13410 return TemplateName();
13411 auto NExpX = X.getNumTemplateExpansions();
13412 assert(NExpX == Y.getNumTemplateExpansions());
13413 return TemplateArgument(CTN, NExpX);
13414 }
13415 default:
13416 // FIXME: Handle the other argument kinds.
13417 return X;
13418 }
13419}
13420
13425 if (Xs.size() != Ys.size())
13426 return true;
13427 R.resize(Xs.size());
13428 for (size_t I = 0; I < R.size(); ++I) {
13429 R[I] = getCommonTemplateArgument(Ctx, Xs[I], Ys[I]);
13430 if (R[I].isNull())
13431 return true;
13432 }
13433 return false;
13434}
13435
13440 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
13441 assert(!Different);
13442 (void)Different;
13443 return R;
13444}
13445
13446template <class T>
13448 return X->getKeyword() == Y->getKeyword() ? X->getKeyword()
13450}
13451
13452template <class T>
13454 const T *Y) {
13455 // FIXME: Try to keep the common NNS sugar.
13456 return X->getQualifier() == Y->getQualifier()
13457 ? X->getQualifier()
13458 : Ctx.getCanonicalNestedNameSpecifier(X->getQualifier());
13459}
13460
13461template <class T>
13462static QualType getCommonElementType(ASTContext &Ctx, const T *X, const T *Y) {
13463 return Ctx.getCommonSugaredType(X->getElementType(), Y->getElementType());
13464}
13465
13466template <class T>
13468 Qualifiers &QX, const T *Y,
13469 Qualifiers &QY) {
13470 QualType EX = X->getElementType(), EY = Y->getElementType();
13471 QualType R = Ctx.getCommonSugaredType(EX, EY,
13472 /*Unqualified=*/true);
13473 Qualifiers RQ = R.getQualifiers();
13474 QX += EX.getQualifiers() - RQ;
13475 QY += EY.getQualifiers() - RQ;
13476 return R;
13477}
13478
13479template <class T>
13480static QualType getCommonPointeeType(ASTContext &Ctx, const T *X, const T *Y) {
13481 return Ctx.getCommonSugaredType(X->getPointeeType(), Y->getPointeeType());
13482}
13483
13484template <class T> static auto *getCommonSizeExpr(ASTContext &Ctx, T *X, T *Y) {
13485 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
13486 return X->getSizeExpr();
13487}
13488
13489static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
13490 assert(X->getSizeModifier() == Y->getSizeModifier());
13491 return X->getSizeModifier();
13492}
13493
13495 const ArrayType *Y) {
13496 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
13497 return X->getIndexTypeCVRQualifiers();
13498}
13499
13500// Merges two type lists such that the resulting vector will contain
13501// each type (in a canonical sense) only once, in the order they appear
13502// from X to Y. If they occur in both X and Y, the result will contain
13503// the common sugared type between them.
13506 llvm::DenseMap<QualType, unsigned> Found;
13507 for (auto Ts : {X, Y}) {
13508 for (QualType T : Ts) {
13509 auto Res = Found.try_emplace(Ctx.getCanonicalType(T), Out.size());
13510 if (!Res.second) {
13511 QualType &U = Out[Res.first->second];
13512 U = Ctx.getCommonSugaredType(U, T);
13513 } else {
13514 Out.emplace_back(T);
13515 }
13516 }
13517 }
13518}
13519
13523 SmallVectorImpl<QualType> &ExceptionTypeStorage,
13524 bool AcceptDependent) {
13525 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
13526
13527 // If either of them can throw anything, that is the result.
13528 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
13529 if (EST1 == I)
13530 return ESI1;
13531 if (EST2 == I)
13532 return ESI2;
13533 }
13534
13535 // If either of them is non-throwing, the result is the other.
13536 for (auto I :
13538 if (EST1 == I)
13539 return ESI2;
13540 if (EST2 == I)
13541 return ESI1;
13542 }
13543
13544 // If we're left with value-dependent computed noexcept expressions, we're
13545 // stuck. Before C++17, we can just drop the exception specification entirely,
13546 // since it's not actually part of the canonical type. And this should never
13547 // happen in C++17, because it would mean we were computing the composite
13548 // pointer type of dependent types, which should never happen.
13549 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
13550 assert(AcceptDependent &&
13551 "computing composite pointer type of dependent types");
13553 }
13554
13555 // Switch over the possibilities so that people adding new values know to
13556 // update this function.
13557 switch (EST1) {
13558 case EST_None:
13559 case EST_DynamicNone:
13560 case EST_MSAny:
13561 case EST_BasicNoexcept:
13563 case EST_NoexceptFalse:
13564 case EST_NoexceptTrue:
13565 case EST_NoThrow:
13566 llvm_unreachable("These ESTs should be handled above");
13567
13568 case EST_Dynamic: {
13569 // This is the fun case: both exception specifications are dynamic. Form
13570 // the union of the two lists.
13571 assert(EST2 == EST_Dynamic && "other cases should already be handled");
13572 mergeTypeLists(*this, ExceptionTypeStorage, ESI1.Exceptions,
13573 ESI2.Exceptions);
13575 Result.Exceptions = ExceptionTypeStorage;
13576 return Result;
13577 }
13578
13579 case EST_Unevaluated:
13580 case EST_Uninstantiated:
13581 case EST_Unparsed:
13582 llvm_unreachable("shouldn't see unresolved exception specifications here");
13583 }
13584
13585 llvm_unreachable("invalid ExceptionSpecificationType");
13586}
13587
13589 Qualifiers &QX, const Type *Y,
13590 Qualifiers &QY) {
13591 Type::TypeClass TC = X->getTypeClass();
13592 assert(TC == Y->getTypeClass());
13593 switch (TC) {
13594#define UNEXPECTED_TYPE(Class, Kind) \
13595 case Type::Class: \
13596 llvm_unreachable("Unexpected " Kind ": " #Class);
13597
13598#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
13599#define TYPE(Class, Base)
13600#include "clang/AST/TypeNodes.inc"
13601
13602#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
13603 SUGAR_FREE_TYPE(Builtin)
13604 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
13605 SUGAR_FREE_TYPE(DependentBitInt)
13608 SUGAR_FREE_TYPE(ObjCInterface)
13610 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
13611 SUGAR_FREE_TYPE(UnresolvedUsing)
13612 SUGAR_FREE_TYPE(HLSLAttributedResource)
13613#undef SUGAR_FREE_TYPE
13614#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
13615 NON_UNIQUE_TYPE(TypeOfExpr)
13616 NON_UNIQUE_TYPE(VariableArray)
13617#undef NON_UNIQUE_TYPE
13618
13619 UNEXPECTED_TYPE(TypeOf, "sugar")
13620
13621#undef UNEXPECTED_TYPE
13622
13623 case Type::Auto: {
13624 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
13625 assert(AX->getDeducedType().isNull());
13626 assert(AY->getDeducedType().isNull());
13627 assert(AX->getKeyword() == AY->getKeyword());
13628 assert(AX->isInstantiationDependentType() ==
13629 AY->isInstantiationDependentType());
13630 auto As = getCommonTemplateArguments(Ctx, AX->getTypeConstraintArguments(),
13631 AY->getTypeConstraintArguments());
13632 return Ctx.getAutoType(QualType(), AX->getKeyword(),
13634 AX->containsUnexpandedParameterPack(),
13635 getCommonDeclChecked(AX->getTypeConstraintConcept(),
13636 AY->getTypeConstraintConcept()),
13637 As);
13638 }
13639 case Type::IncompleteArray: {
13640 const auto *AX = cast<IncompleteArrayType>(X),
13641 *AY = cast<IncompleteArrayType>(Y);
13642 return Ctx.getIncompleteArrayType(
13643 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
13645 }
13646 case Type::DependentSizedArray: {
13647 const auto *AX = cast<DependentSizedArrayType>(X),
13648 *AY = cast<DependentSizedArrayType>(Y);
13649 return Ctx.getDependentSizedArrayType(
13650 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
13651 getCommonSizeExpr(Ctx, AX, AY), getCommonSizeModifier(AX, AY),
13653 AX->getBracketsRange() == AY->getBracketsRange()
13654 ? AX->getBracketsRange()
13655 : SourceRange());
13656 }
13657 case Type::ConstantArray: {
13658 const auto *AX = cast<ConstantArrayType>(X),
13659 *AY = cast<ConstantArrayType>(Y);
13660 assert(AX->getSize() == AY->getSize());
13661 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
13662 ? AX->getSizeExpr()
13663 : nullptr;
13664 return Ctx.getConstantArrayType(
13665 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
13667 }
13668 case Type::ArrayParameter: {
13669 const auto *AX = cast<ArrayParameterType>(X),
13670 *AY = cast<ArrayParameterType>(Y);
13671 assert(AX->getSize() == AY->getSize());
13672 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
13673 ? AX->getSizeExpr()
13674 : nullptr;
13675 auto ArrayTy = Ctx.getConstantArrayType(
13676 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
13678 return Ctx.getArrayParameterType(ArrayTy);
13679 }
13680 case Type::Atomic: {
13681 const auto *AX = cast<AtomicType>(X), *AY = cast<AtomicType>(Y);
13682 return Ctx.getAtomicType(
13683 Ctx.getCommonSugaredType(AX->getValueType(), AY->getValueType()));
13684 }
13685 case Type::Complex: {
13686 const auto *CX = cast<ComplexType>(X), *CY = cast<ComplexType>(Y);
13687 return Ctx.getComplexType(getCommonArrayElementType(Ctx, CX, QX, CY, QY));
13688 }
13689 case Type::Pointer: {
13690 const auto *PX = cast<PointerType>(X), *PY = cast<PointerType>(Y);
13691 return Ctx.getPointerType(getCommonPointeeType(Ctx, PX, PY));
13692 }
13693 case Type::BlockPointer: {
13694 const auto *PX = cast<BlockPointerType>(X), *PY = cast<BlockPointerType>(Y);
13695 return Ctx.getBlockPointerType(getCommonPointeeType(Ctx, PX, PY));
13696 }
13697 case Type::ObjCObjectPointer: {
13698 const auto *PX = cast<ObjCObjectPointerType>(X),
13699 *PY = cast<ObjCObjectPointerType>(Y);
13700 return Ctx.getObjCObjectPointerType(getCommonPointeeType(Ctx, PX, PY));
13701 }
13702 case Type::MemberPointer: {
13703 const auto *PX = cast<MemberPointerType>(X),
13704 *PY = cast<MemberPointerType>(Y);
13705 return Ctx.getMemberPointerType(
13706 getCommonPointeeType(Ctx, PX, PY),
13707 Ctx.getCommonSugaredType(QualType(PX->getClass(), 0),
13708 QualType(PY->getClass(), 0))
13709 .getTypePtr());
13710 }
13711 case Type::LValueReference: {
13712 const auto *PX = cast<LValueReferenceType>(X),
13713 *PY = cast<LValueReferenceType>(Y);
13714 // FIXME: Preserve PointeeTypeAsWritten.
13715 return Ctx.getLValueReferenceType(getCommonPointeeType(Ctx, PX, PY),
13716 PX->isSpelledAsLValue() ||
13717 PY->isSpelledAsLValue());
13718 }
13719 case Type::RValueReference: {
13720 const auto *PX = cast<RValueReferenceType>(X),
13721 *PY = cast<RValueReferenceType>(Y);
13722 // FIXME: Preserve PointeeTypeAsWritten.
13723 return Ctx.getRValueReferenceType(getCommonPointeeType(Ctx, PX, PY));
13724 }
13725 case Type::DependentAddressSpace: {
13726 const auto *PX = cast<DependentAddressSpaceType>(X),
13727 *PY = cast<DependentAddressSpaceType>(Y);
13728 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
13729 return Ctx.getDependentAddressSpaceType(getCommonPointeeType(Ctx, PX, PY),
13730 PX->getAddrSpaceExpr(),
13731 getCommonAttrLoc(PX, PY));
13732 }
13733 case Type::FunctionNoProto: {
13734 const auto *FX = cast<FunctionNoProtoType>(X),
13735 *FY = cast<FunctionNoProtoType>(Y);
13736 assert(FX->getExtInfo() == FY->getExtInfo());
13737 return Ctx.getFunctionNoProtoType(
13738 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType()),
13739 FX->getExtInfo());
13740 }
13741 case Type::FunctionProto: {
13742 const auto *FX = cast<FunctionProtoType>(X),
13743 *FY = cast<FunctionProtoType>(Y);
13744 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
13745 EPIY = FY->getExtProtoInfo();
13746 assert(EPIX.ExtInfo == EPIY.ExtInfo);
13747 assert(EPIX.ExtParameterInfos == EPIY.ExtParameterInfos);
13748 assert(EPIX.RefQualifier == EPIY.RefQualifier);
13749 assert(EPIX.TypeQuals == EPIY.TypeQuals);
13750 assert(EPIX.Variadic == EPIY.Variadic);
13751
13752 // FIXME: Can we handle an empty EllipsisLoc?
13753 // Use emtpy EllipsisLoc if X and Y differ.
13754
13755 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
13756
13757 QualType R =
13758 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType());
13759 auto P = getCommonTypes(Ctx, FX->param_types(), FY->param_types(),
13760 /*Unqualified=*/true);
13761
13762 SmallVector<QualType, 8> Exceptions;
13764 EPIX.ExceptionSpec, EPIY.ExceptionSpec, Exceptions, true);
13765 return Ctx.getFunctionType(R, P, EPIX);
13766 }
13767 case Type::ObjCObject: {
13768 const auto *OX = cast<ObjCObjectType>(X), *OY = cast<ObjCObjectType>(Y);
13769 assert(
13770 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
13771 OY->getProtocols().begin(), OY->getProtocols().end(),
13772 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
13773 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
13774 }) &&
13775 "protocol lists must be the same");
13776 auto TAs = getCommonTypes(Ctx, OX->getTypeArgsAsWritten(),
13777 OY->getTypeArgsAsWritten());
13778 return Ctx.getObjCObjectType(
13779 Ctx.getCommonSugaredType(OX->getBaseType(), OY->getBaseType()), TAs,
13780 OX->getProtocols(),
13781 OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
13782 }
13783 case Type::ConstantMatrix: {
13784 const auto *MX = cast<ConstantMatrixType>(X),
13785 *MY = cast<ConstantMatrixType>(Y);
13786 assert(MX->getNumRows() == MY->getNumRows());
13787 assert(MX->getNumColumns() == MY->getNumColumns());
13788 return Ctx.getConstantMatrixType(getCommonElementType(Ctx, MX, MY),
13789 MX->getNumRows(), MX->getNumColumns());
13790 }
13791 case Type::DependentSizedMatrix: {
13792 const auto *MX = cast<DependentSizedMatrixType>(X),
13793 *MY = cast<DependentSizedMatrixType>(Y);
13794 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
13795 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
13796 return Ctx.getDependentSizedMatrixType(
13797 getCommonElementType(Ctx, MX, MY), MX->getRowExpr(),
13798 MX->getColumnExpr(), getCommonAttrLoc(MX, MY));
13799 }
13800 case Type::Vector: {
13801 const auto *VX = cast<VectorType>(X), *VY = cast<VectorType>(Y);
13802 assert(VX->getNumElements() == VY->getNumElements());
13803 assert(VX->getVectorKind() == VY->getVectorKind());
13804 return Ctx.getVectorType(getCommonElementType(Ctx, VX, VY),
13805 VX->getNumElements(), VX->getVectorKind());
13806 }
13807 case Type::ExtVector: {
13808 const auto *VX = cast<ExtVectorType>(X), *VY = cast<ExtVectorType>(Y);
13809 assert(VX->getNumElements() == VY->getNumElements());
13810 return Ctx.getExtVectorType(getCommonElementType(Ctx, VX, VY),
13811 VX->getNumElements());
13812 }
13813 case Type::DependentSizedExtVector: {
13814 const auto *VX = cast<DependentSizedExtVectorType>(X),
13815 *VY = cast<DependentSizedExtVectorType>(Y);
13817 getCommonSizeExpr(Ctx, VX, VY),
13818 getCommonAttrLoc(VX, VY));
13819 }
13820 case Type::DependentVector: {
13821 const auto *VX = cast<DependentVectorType>(X),
13822 *VY = cast<DependentVectorType>(Y);
13823 assert(VX->getVectorKind() == VY->getVectorKind());
13824 return Ctx.getDependentVectorType(
13825 getCommonElementType(Ctx, VX, VY), getCommonSizeExpr(Ctx, VX, VY),
13826 getCommonAttrLoc(VX, VY), VX->getVectorKind());
13827 }
13828 case Type::InjectedClassName: {
13829 const auto *IX = cast<InjectedClassNameType>(X),
13830 *IY = cast<InjectedClassNameType>(Y);
13831 return Ctx.getInjectedClassNameType(
13832 getCommonDeclChecked(IX->getDecl(), IY->getDecl()),
13833 Ctx.getCommonSugaredType(IX->getInjectedSpecializationType(),
13834 IY->getInjectedSpecializationType()));
13835 }
13836 case Type::TemplateSpecialization: {
13837 const auto *TX = cast<TemplateSpecializationType>(X),
13838 *TY = cast<TemplateSpecializationType>(Y);
13839 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
13840 TY->template_arguments());
13842 ::getCommonTemplateNameChecked(Ctx, TX->getTemplateName(),
13843 TY->getTemplateName(),
13844 /*IgnoreDeduced=*/true),
13845 As, X->getCanonicalTypeInternal());
13846 }
13847 case Type::Decltype: {
13848 const auto *DX = cast<DecltypeType>(X);
13849 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Y);
13850 assert(DX->isDependentType());
13851 assert(DY->isDependentType());
13852 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
13853 // As Decltype is not uniqued, building a common type would be wasteful.
13854 return QualType(DX, 0);
13855 }
13856 case Type::PackIndexing: {
13857 const auto *DX = cast<PackIndexingType>(X);
13858 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Y);
13859 assert(DX->isDependentType());
13860 assert(DY->isDependentType());
13861 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
13862 return QualType(DX, 0);
13863 }
13864 case Type::DependentName: {
13865 const auto *NX = cast<DependentNameType>(X),
13866 *NY = cast<DependentNameType>(Y);
13867 assert(NX->getIdentifier() == NY->getIdentifier());
13868 return Ctx.getDependentNameType(
13869 getCommonTypeKeyword(NX, NY), getCommonNNS(Ctx, NX, NY),
13870 NX->getIdentifier(), NX->getCanonicalTypeInternal());
13871 }
13872 case Type::DependentTemplateSpecialization: {
13873 const auto *TX = cast<DependentTemplateSpecializationType>(X),
13874 *TY = cast<DependentTemplateSpecializationType>(Y);
13875 assert(TX->getIdentifier() == TY->getIdentifier());
13876 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
13877 TY->template_arguments());
13879 getCommonTypeKeyword(TX, TY), getCommonNNS(Ctx, TX, TY),
13880 TX->getIdentifier(), As);
13881 }
13882 case Type::UnaryTransform: {
13883 const auto *TX = cast<UnaryTransformType>(X),
13884 *TY = cast<UnaryTransformType>(Y);
13885 assert(TX->getUTTKind() == TY->getUTTKind());
13886 return Ctx.getUnaryTransformType(
13887 Ctx.getCommonSugaredType(TX->getBaseType(), TY->getBaseType()),
13888 Ctx.getCommonSugaredType(TX->getUnderlyingType(),
13889 TY->getUnderlyingType()),
13890 TX->getUTTKind());
13891 }
13892 case Type::PackExpansion: {
13893 const auto *PX = cast<PackExpansionType>(X),
13894 *PY = cast<PackExpansionType>(Y);
13895 assert(PX->getNumExpansions() == PY->getNumExpansions());
13896 return Ctx.getPackExpansionType(
13897 Ctx.getCommonSugaredType(PX->getPattern(), PY->getPattern()),
13898 PX->getNumExpansions(), false);
13899 }
13900 case Type::Pipe: {
13901 const auto *PX = cast<PipeType>(X), *PY = cast<PipeType>(Y);
13902 assert(PX->isReadOnly() == PY->isReadOnly());
13903 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
13905 return (Ctx.*MP)(getCommonElementType(Ctx, PX, PY));
13906 }
13907 case Type::TemplateTypeParm: {
13908 const auto *TX = cast<TemplateTypeParmType>(X),
13909 *TY = cast<TemplateTypeParmType>(Y);
13910 assert(TX->getDepth() == TY->getDepth());
13911 assert(TX->getIndex() == TY->getIndex());
13912 assert(TX->isParameterPack() == TY->isParameterPack());
13913 return Ctx.getTemplateTypeParmType(
13914 TX->getDepth(), TX->getIndex(), TX->isParameterPack(),
13915 getCommonDecl(TX->getDecl(), TY->getDecl()));
13916 }
13917 }
13918 llvm_unreachable("Unknown Type Class");
13919}
13920
13922 const Type *Y,
13923 SplitQualType Underlying) {
13924 Type::TypeClass TC = X->getTypeClass();
13925 if (TC != Y->getTypeClass())
13926 return QualType();
13927 switch (TC) {
13928#define UNEXPECTED_TYPE(Class, Kind) \
13929 case Type::Class: \
13930 llvm_unreachable("Unexpected " Kind ": " #Class);
13931#define TYPE(Class, Base)
13932#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
13933#include "clang/AST/TypeNodes.inc"
13934
13935#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
13938 CANONICAL_TYPE(BlockPointer)
13939 CANONICAL_TYPE(Builtin)
13941 CANONICAL_TYPE(ConstantArray)
13942 CANONICAL_TYPE(ArrayParameter)
13943 CANONICAL_TYPE(ConstantMatrix)
13945 CANONICAL_TYPE(ExtVector)
13946 CANONICAL_TYPE(FunctionNoProto)
13947 CANONICAL_TYPE(FunctionProto)
13948 CANONICAL_TYPE(IncompleteArray)
13949 CANONICAL_TYPE(HLSLAttributedResource)
13950 CANONICAL_TYPE(LValueReference)
13951 CANONICAL_TYPE(MemberPointer)
13952 CANONICAL_TYPE(ObjCInterface)
13953 CANONICAL_TYPE(ObjCObject)
13954 CANONICAL_TYPE(ObjCObjectPointer)
13958 CANONICAL_TYPE(RValueReference)
13959 CANONICAL_TYPE(VariableArray)
13961#undef CANONICAL_TYPE
13962
13963#undef UNEXPECTED_TYPE
13964
13965 case Type::Adjusted: {
13966 const auto *AX = cast<AdjustedType>(X), *AY = cast<AdjustedType>(Y);
13967 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
13968 if (!Ctx.hasSameType(OX, OY))
13969 return QualType();
13970 // FIXME: It's inefficient to have to unify the original types.
13971 return Ctx.getAdjustedType(Ctx.getCommonSugaredType(OX, OY),
13972 Ctx.getQualifiedType(Underlying));
13973 }
13974 case Type::Decayed: {
13975 const auto *DX = cast<DecayedType>(X), *DY = cast<DecayedType>(Y);
13976 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
13977 if (!Ctx.hasSameType(OX, OY))
13978 return QualType();
13979 // FIXME: It's inefficient to have to unify the original types.
13980 return Ctx.getDecayedType(Ctx.getCommonSugaredType(OX, OY),
13981 Ctx.getQualifiedType(Underlying));
13982 }
13983 case Type::Attributed: {
13984 const auto *AX = cast<AttributedType>(X), *AY = cast<AttributedType>(Y);
13985 AttributedType::Kind Kind = AX->getAttrKind();
13986 if (Kind != AY->getAttrKind())
13987 return QualType();
13988 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
13989 if (!Ctx.hasSameType(MX, MY))
13990 return QualType();
13991 // FIXME: It's inefficient to have to unify the modified types.
13992 return Ctx.getAttributedType(Kind, Ctx.getCommonSugaredType(MX, MY),
13993 Ctx.getQualifiedType(Underlying),
13994 AX->getAttr());
13995 }
13996 case Type::BTFTagAttributed: {
13997 const auto *BX = cast<BTFTagAttributedType>(X);
13998 const BTFTypeTagAttr *AX = BX->getAttr();
13999 // The attribute is not uniqued, so just compare the tag.
14000 if (AX->getBTFTypeTag() !=
14001 cast<BTFTagAttributedType>(Y)->getAttr()->getBTFTypeTag())
14002 return QualType();
14003 return Ctx.getBTFTagAttributedType(AX, Ctx.getQualifiedType(Underlying));
14004 }
14005 case Type::Auto: {
14006 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14007
14008 AutoTypeKeyword KW = AX->getKeyword();
14009 if (KW != AY->getKeyword())
14010 return QualType();
14011
14012 ConceptDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(),
14013 AY->getTypeConstraintConcept());
14015 if (CD &&
14016 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
14017 AY->getTypeConstraintArguments())) {
14018 CD = nullptr; // The arguments differ, so make it unconstrained.
14019 As.clear();
14020 }
14021
14022 // Both auto types can't be dependent, otherwise they wouldn't have been
14023 // sugar. This implies they can't contain unexpanded packs either.
14024 return Ctx.getAutoType(Ctx.getQualifiedType(Underlying), AX->getKeyword(),
14025 /*IsDependent=*/false, /*IsPack=*/false, CD, As);
14026 }
14027 case Type::PackIndexing:
14028 case Type::Decltype:
14029 return QualType();
14030 case Type::DeducedTemplateSpecialization:
14031 // FIXME: Try to merge these.
14032 return QualType();
14033
14034 case Type::Elaborated: {
14035 const auto *EX = cast<ElaboratedType>(X), *EY = cast<ElaboratedType>(Y);
14036 return Ctx.getElaboratedType(
14037 ::getCommonTypeKeyword(EX, EY), ::getCommonNNS(Ctx, EX, EY),
14038 Ctx.getQualifiedType(Underlying),
14039 ::getCommonDecl(EX->getOwnedTagDecl(), EY->getOwnedTagDecl()));
14040 }
14041 case Type::MacroQualified: {
14042 const auto *MX = cast<MacroQualifiedType>(X),
14043 *MY = cast<MacroQualifiedType>(Y);
14044 const IdentifierInfo *IX = MX->getMacroIdentifier();
14045 if (IX != MY->getMacroIdentifier())
14046 return QualType();
14047 return Ctx.getMacroQualifiedType(Ctx.getQualifiedType(Underlying), IX);
14048 }
14049 case Type::SubstTemplateTypeParm: {
14050 const auto *SX = cast<SubstTemplateTypeParmType>(X),
14051 *SY = cast<SubstTemplateTypeParmType>(Y);
14052 Decl *CD =
14053 ::getCommonDecl(SX->getAssociatedDecl(), SY->getAssociatedDecl());
14054 if (!CD)
14055 return QualType();
14056 unsigned Index = SX->getIndex();
14057 if (Index != SY->getIndex())
14058 return QualType();
14059 auto PackIndex = SX->getPackIndex();
14060 if (PackIndex != SY->getPackIndex())
14061 return QualType();
14062 return Ctx.getSubstTemplateTypeParmType(Ctx.getQualifiedType(Underlying),
14063 CD, Index, PackIndex);
14064 }
14065 case Type::ObjCTypeParam:
14066 // FIXME: Try to merge these.
14067 return QualType();
14068 case Type::Paren:
14069 return Ctx.getParenType(Ctx.getQualifiedType(Underlying));
14070
14071 case Type::TemplateSpecialization: {
14072 const auto *TX = cast<TemplateSpecializationType>(X),
14073 *TY = cast<TemplateSpecializationType>(Y);
14074 TemplateName CTN =
14075 ::getCommonTemplateName(Ctx, TX->getTemplateName(),
14076 TY->getTemplateName(), /*IgnoreDeduced=*/true);
14077 if (!CTN.getAsVoidPointer())
14078 return QualType();
14080 if (getCommonTemplateArguments(Ctx, Args, TX->template_arguments(),
14081 TY->template_arguments()))
14082 return QualType();
14083 return Ctx.getTemplateSpecializationType(CTN, Args,
14084 Ctx.getQualifiedType(Underlying));
14085 }
14086 case Type::Typedef: {
14087 const auto *TX = cast<TypedefType>(X), *TY = cast<TypedefType>(Y);
14088 const TypedefNameDecl *CD = ::getCommonDecl(TX->getDecl(), TY->getDecl());
14089 if (!CD)
14090 return QualType();
14091 return Ctx.getTypedefType(CD, Ctx.getQualifiedType(Underlying));
14092 }
14093 case Type::TypeOf: {
14094 // The common sugar between two typeof expressions, where one is
14095 // potentially a typeof_unqual and the other is not, we unify to the
14096 // qualified type as that retains the most information along with the type.
14097 // We only return a typeof_unqual type when both types are unqual types.
14099 if (cast<TypeOfType>(X)->getKind() == cast<TypeOfType>(Y)->getKind() &&
14100 cast<TypeOfType>(X)->getKind() == TypeOfKind::Unqualified)
14102 return Ctx.getTypeOfType(Ctx.getQualifiedType(Underlying), Kind);
14103 }
14104 case Type::TypeOfExpr:
14105 return QualType();
14106
14107 case Type::UnaryTransform: {
14108 const auto *UX = cast<UnaryTransformType>(X),
14109 *UY = cast<UnaryTransformType>(Y);
14110 UnaryTransformType::UTTKind KX = UX->getUTTKind();
14111 if (KX != UY->getUTTKind())
14112 return QualType();
14113 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
14114 if (!Ctx.hasSameType(BX, BY))
14115 return QualType();
14116 // FIXME: It's inefficient to have to unify the base types.
14117 return Ctx.getUnaryTransformType(Ctx.getCommonSugaredType(BX, BY),
14118 Ctx.getQualifiedType(Underlying), KX);
14119 }
14120 case Type::Using: {
14121 const auto *UX = cast<UsingType>(X), *UY = cast<UsingType>(Y);
14122 const UsingShadowDecl *CD =
14123 ::getCommonDecl(UX->getFoundDecl(), UY->getFoundDecl());
14124 if (!CD)
14125 return QualType();
14126 return Ctx.getUsingType(CD, Ctx.getQualifiedType(Underlying));
14127 }
14128 case Type::CountAttributed: {
14129 const auto *DX = cast<CountAttributedType>(X),
14130 *DY = cast<CountAttributedType>(Y);
14131 if (DX->isCountInBytes() != DY->isCountInBytes())
14132 return QualType();
14133 if (DX->isOrNull() != DY->isOrNull())
14134 return QualType();
14135 Expr *CEX = DX->getCountExpr();
14136 Expr *CEY = DY->getCountExpr();
14137 llvm::ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
14138 if (Ctx.hasSameExpr(CEX, CEY))
14139 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14140 DX->isCountInBytes(), DX->isOrNull(),
14141 CDX);
14142 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
14143 return QualType();
14144 // Two declarations with the same integer constant may still differ in their
14145 // expression pointers, so we need to evaluate them.
14146 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
14147 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
14148 if (VX != VY)
14149 return QualType();
14150 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14151 DX->isCountInBytes(), DX->isOrNull(),
14152 CDX);
14153 }
14154 }
14155 llvm_unreachable("Unhandled Type Class");
14156}
14157
14158static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
14160 while (true) {
14161 QTotal.addConsistentQualifiers(T.Quals);
14163 if (NT == QualType(T.Ty, 0))
14164 break;
14165 R.push_back(T);
14166 T = NT.split();
14167 }
14168 return R;
14169}
14170
14172 bool Unqualified) {
14173 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
14174 if (X == Y)
14175 return X;
14176 if (!Unqualified) {
14177 if (X.isCanonical())
14178 return X;
14179 if (Y.isCanonical())
14180 return Y;
14181 }
14182
14183 SplitQualType SX = X.split(), SY = Y.split();
14184 Qualifiers QX, QY;
14185 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
14186 // until we reach their underlying "canonical nodes". Note these are not
14187 // necessarily canonical types, as they may still have sugared properties.
14188 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
14189 auto Xs = ::unwrapSugar(SX, QX), Ys = ::unwrapSugar(SY, QY);
14190 if (SX.Ty != SY.Ty) {
14191 // The canonical nodes differ. Build a common canonical node out of the two,
14192 // unifying their sugar. This may recurse back here.
14193 SX.Ty =
14194 ::getCommonNonSugarTypeNode(*this, SX.Ty, QX, SY.Ty, QY).getTypePtr();
14195 } else {
14196 // The canonical nodes were identical: We may have desugared too much.
14197 // Add any common sugar back in.
14198 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
14199 QX -= SX.Quals;
14200 QY -= SY.Quals;
14201 SX = Xs.pop_back_val();
14202 SY = Ys.pop_back_val();
14203 }
14204 }
14205 if (Unqualified)
14207 else
14208 assert(QX == QY);
14209
14210 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
14211 // related. Walk up these nodes, unifying them and adding the result.
14212 while (!Xs.empty() && !Ys.empty()) {
14213 auto Underlying = SplitQualType(
14214 SX.Ty, Qualifiers::removeCommonQualifiers(SX.Quals, SY.Quals));
14215 SX = Xs.pop_back_val();
14216 SY = Ys.pop_back_val();
14217 SX.Ty = ::getCommonSugarTypeNode(*this, SX.Ty, SY.Ty, Underlying)
14219 // Stop at the first pair which is unrelated.
14220 if (!SX.Ty) {
14221 SX.Ty = Underlying.Ty;
14222 break;
14223 }
14224 QX -= Underlying.Quals;
14225 };
14226
14227 // Add back the missing accumulated qualifiers, which were stripped off
14228 // with the sugar nodes we could not unify.
14229 QualType R = getQualifiedType(SX.Ty, QX);
14230 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
14231 return R;
14232}
14233
14235 assert(Ty->isFixedPointType());
14236
14238 return Ty;
14239
14240 switch (Ty->castAs<BuiltinType>()->getKind()) {
14241 default:
14242 llvm_unreachable("Not a saturated fixed point type!");
14243 case BuiltinType::SatShortAccum:
14244 return ShortAccumTy;
14245 case BuiltinType::SatAccum:
14246 return AccumTy;
14247 case BuiltinType::SatLongAccum:
14248 return LongAccumTy;
14249 case BuiltinType::SatUShortAccum:
14250 return UnsignedShortAccumTy;
14251 case BuiltinType::SatUAccum:
14252 return UnsignedAccumTy;
14253 case BuiltinType::SatULongAccum:
14254 return UnsignedLongAccumTy;
14255 case BuiltinType::SatShortFract:
14256 return ShortFractTy;
14257 case BuiltinType::SatFract:
14258 return FractTy;
14259 case BuiltinType::SatLongFract:
14260 return LongFractTy;
14261 case BuiltinType::SatUShortFract:
14262 return UnsignedShortFractTy;
14263 case BuiltinType::SatUFract:
14264 return UnsignedFractTy;
14265 case BuiltinType::SatULongFract:
14266 return UnsignedLongFractTy;
14267 }
14268}
14269
14271 assert(Ty->isFixedPointType());
14272
14273 if (Ty->isSaturatedFixedPointType()) return Ty;
14274
14275 switch (Ty->castAs<BuiltinType>()->getKind()) {
14276 default:
14277 llvm_unreachable("Not a fixed point type!");
14278 case BuiltinType::ShortAccum:
14279 return SatShortAccumTy;
14280 case BuiltinType::Accum:
14281 return SatAccumTy;
14282 case BuiltinType::LongAccum:
14283 return SatLongAccumTy;
14284 case BuiltinType::UShortAccum:
14286 case BuiltinType::UAccum:
14287 return SatUnsignedAccumTy;
14288 case BuiltinType::ULongAccum:
14290 case BuiltinType::ShortFract:
14291 return SatShortFractTy;
14292 case BuiltinType::Fract:
14293 return SatFractTy;
14294 case BuiltinType::LongFract:
14295 return SatLongFractTy;
14296 case BuiltinType::UShortFract:
14298 case BuiltinType::UFract:
14299 return SatUnsignedFractTy;
14300 case BuiltinType::ULongFract:
14302 }
14303}
14304
14306 if (LangOpts.OpenCL)
14308
14309 if (LangOpts.CUDA)
14311
14312 return getLangASFromTargetAS(AS);
14313}
14314
14315// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
14316// doesn't include ASTContext.h
14317template
14319 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
14321 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
14322 const clang::ASTContext &Ctx, Decl *Value);
14323
14325 assert(Ty->isFixedPointType());
14326
14327 const TargetInfo &Target = getTargetInfo();
14328 switch (Ty->castAs<BuiltinType>()->getKind()) {
14329 default:
14330 llvm_unreachable("Not a fixed point type!");
14331 case BuiltinType::ShortAccum:
14332 case BuiltinType::SatShortAccum:
14333 return Target.getShortAccumScale();
14334 case BuiltinType::Accum:
14335 case BuiltinType::SatAccum:
14336 return Target.getAccumScale();
14337 case BuiltinType::LongAccum:
14338 case BuiltinType::SatLongAccum:
14339 return Target.getLongAccumScale();
14340 case BuiltinType::UShortAccum:
14341 case BuiltinType::SatUShortAccum:
14342 return Target.getUnsignedShortAccumScale();
14343 case BuiltinType::UAccum:
14344 case BuiltinType::SatUAccum:
14345 return Target.getUnsignedAccumScale();
14346 case BuiltinType::ULongAccum:
14347 case BuiltinType::SatULongAccum:
14348 return Target.getUnsignedLongAccumScale();
14349 case BuiltinType::ShortFract:
14350 case BuiltinType::SatShortFract:
14351 return Target.getShortFractScale();
14352 case BuiltinType::Fract:
14353 case BuiltinType::SatFract:
14354 return Target.getFractScale();
14355 case BuiltinType::LongFract:
14356 case BuiltinType::SatLongFract:
14357 return Target.getLongFractScale();
14358 case BuiltinType::UShortFract:
14359 case BuiltinType::SatUShortFract:
14360 return Target.getUnsignedShortFractScale();
14361 case BuiltinType::UFract:
14362 case BuiltinType::SatUFract:
14363 return Target.getUnsignedFractScale();
14364 case BuiltinType::ULongFract:
14365 case BuiltinType::SatULongFract:
14366 return Target.getUnsignedLongFractScale();
14367 }
14368}
14369
14371 assert(Ty->isFixedPointType());
14372
14373 const TargetInfo &Target = getTargetInfo();
14374 switch (Ty->castAs<BuiltinType>()->getKind()) {
14375 default:
14376 llvm_unreachable("Not a fixed point type!");
14377 case BuiltinType::ShortAccum:
14378 case BuiltinType::SatShortAccum:
14379 return Target.getShortAccumIBits();
14380 case BuiltinType::Accum:
14381 case BuiltinType::SatAccum:
14382 return Target.getAccumIBits();
14383 case BuiltinType::LongAccum:
14384 case BuiltinType::SatLongAccum:
14385 return Target.getLongAccumIBits();
14386 case BuiltinType::UShortAccum:
14387 case BuiltinType::SatUShortAccum:
14388 return Target.getUnsignedShortAccumIBits();
14389 case BuiltinType::UAccum:
14390 case BuiltinType::SatUAccum:
14391 return Target.getUnsignedAccumIBits();
14392 case BuiltinType::ULongAccum:
14393 case BuiltinType::SatULongAccum:
14394 return Target.getUnsignedLongAccumIBits();
14395 case BuiltinType::ShortFract:
14396 case BuiltinType::SatShortFract:
14397 case BuiltinType::Fract:
14398 case BuiltinType::SatFract:
14399 case BuiltinType::LongFract:
14400 case BuiltinType::SatLongFract:
14401 case BuiltinType::UShortFract:
14402 case BuiltinType::SatUShortFract:
14403 case BuiltinType::UFract:
14404 case BuiltinType::SatUFract:
14405 case BuiltinType::ULongFract:
14406 case BuiltinType::SatULongFract:
14407 return 0;
14408 }
14409}
14410
14411llvm::FixedPointSemantics
14413 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
14414 "Can only get the fixed point semantics for a "
14415 "fixed point or integer type.");
14416 if (Ty->isIntegerType())
14417 return llvm::FixedPointSemantics::GetIntegerSemantics(
14418 getIntWidth(Ty), Ty->isSignedIntegerType());
14419
14420 bool isSigned = Ty->isSignedFixedPointType();
14421 return llvm::FixedPointSemantics(
14422 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
14424 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
14425}
14426
14427llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
14428 assert(Ty->isFixedPointType());
14429 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
14430}
14431
14432llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
14433 assert(Ty->isFixedPointType());
14434 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
14435}
14436
14438 assert(Ty->isUnsignedFixedPointType() &&
14439 "Expected unsigned fixed point type");
14440
14441 switch (Ty->castAs<BuiltinType>()->getKind()) {
14442 case BuiltinType::UShortAccum:
14443 return ShortAccumTy;
14444 case BuiltinType::UAccum:
14445 return AccumTy;
14446 case BuiltinType::ULongAccum:
14447 return LongAccumTy;
14448 case BuiltinType::SatUShortAccum:
14449 return SatShortAccumTy;
14450 case BuiltinType::SatUAccum:
14451 return SatAccumTy;
14452 case BuiltinType::SatULongAccum:
14453 return SatLongAccumTy;
14454 case BuiltinType::UShortFract:
14455 return ShortFractTy;
14456 case BuiltinType::UFract:
14457 return FractTy;
14458 case BuiltinType::ULongFract:
14459 return LongFractTy;
14460 case BuiltinType::SatUShortFract:
14461 return SatShortFractTy;
14462 case BuiltinType::SatUFract:
14463 return SatFractTy;
14464 case BuiltinType::SatULongFract:
14465 return SatLongFractTy;
14466 default:
14467 llvm_unreachable("Unexpected unsigned fixed point type");
14468 }
14469}
14470
14471// Given a list of FMV features, return a concatenated list of the
14472// corresponding backend features (which may contain duplicates).
14473static std::vector<std::string> getFMVBackendFeaturesFor(
14474 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) {
14475 std::vector<std::string> BackendFeats;
14476 llvm::AArch64::ExtensionSet FeatureBits;
14477 for (StringRef F : FMVFeatStrings)
14478 if (auto FMVExt = llvm::AArch64::parseFMVExtension(F))
14479 if (FMVExt->ID)
14480 FeatureBits.enable(*FMVExt->ID);
14481 FeatureBits.toLLVMFeatureList(BackendFeats);
14482 return BackendFeats;
14483}
14484
14486ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
14487 assert(TD != nullptr);
14488 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TD->getFeaturesStr());
14489
14490 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
14491 return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
14492 });
14493 return ParsedAttr;
14494}
14495
14496void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
14497 const FunctionDecl *FD) const {
14498 if (FD)
14499 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
14500 else
14501 Target->initFeatureMap(FeatureMap, getDiagnostics(),
14502 Target->getTargetOpts().CPU,
14503 Target->getTargetOpts().Features);
14504}
14505
14506// Fills in the supplied string map with the set of target features for the
14507// passed in function.
14508void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
14509 GlobalDecl GD) const {
14510 StringRef TargetCPU = Target->getTargetOpts().CPU;
14511 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
14512 if (const auto *TD = FD->getAttr<TargetAttr>()) {
14514
14515 // Make a copy of the features as passed on the command line into the
14516 // beginning of the additional features from the function to override.
14517 // AArch64 handles command line option features in parseTargetAttr().
14518 if (!Target->getTriple().isAArch64())
14519 ParsedAttr.Features.insert(
14520 ParsedAttr.Features.begin(),
14521 Target->getTargetOpts().FeaturesAsWritten.begin(),
14522 Target->getTargetOpts().FeaturesAsWritten.end());
14523
14524 if (ParsedAttr.CPU != "" && Target->isValidCPUName(ParsedAttr.CPU))
14525 TargetCPU = ParsedAttr.CPU;
14526
14527 // Now populate the feature map, first with the TargetCPU which is either
14528 // the default or a new one from the target attribute string. Then we'll use
14529 // the passed in features (FeaturesAsWritten) along with the new ones from
14530 // the attribute.
14531 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
14532 ParsedAttr.Features);
14533 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
14535 Target->getCPUSpecificCPUDispatchFeatures(
14536 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
14537 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
14538 Features.insert(Features.begin(),
14539 Target->getTargetOpts().FeaturesAsWritten.begin(),
14540 Target->getTargetOpts().FeaturesAsWritten.end());
14541 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14542 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
14543 if (Target->getTriple().isAArch64()) {
14545 TC->getFeatures(Feats, GD.getMultiVersionIndex());
14546 std::vector<std::string> Features = getFMVBackendFeaturesFor(Feats);
14547 Features.insert(Features.begin(),
14548 Target->getTargetOpts().FeaturesAsWritten.begin(),
14549 Target->getTargetOpts().FeaturesAsWritten.end());
14550 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14551 } else if (Target->getTriple().isRISCV()) {
14552 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
14553 std::vector<std::string> Features;
14554 if (VersionStr != "default") {
14555 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(VersionStr);
14556 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
14557 ParsedAttr.Features.end());
14558 }
14559 Features.insert(Features.begin(),
14560 Target->getTargetOpts().FeaturesAsWritten.begin(),
14561 Target->getTargetOpts().FeaturesAsWritten.end());
14562 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14563 } else {
14564 std::vector<std::string> Features;
14565 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
14566 if (VersionStr.starts_with("arch="))
14567 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
14568 else if (VersionStr != "default")
14569 Features.push_back((StringRef{"+"} + VersionStr).str());
14570 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14571 }
14572 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
14573 std::vector<std::string> Features;
14574 if (Target->getTriple().isRISCV()) {
14575 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TV->getName());
14576 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
14577 ParsedAttr.Features.end());
14578 } else {
14579 assert(Target->getTriple().isAArch64());
14581 TV->getFeatures(Feats);
14582 Features = getFMVBackendFeaturesFor(Feats);
14583 }
14584 Features.insert(Features.begin(),
14585 Target->getTargetOpts().FeaturesAsWritten.begin(),
14586 Target->getTargetOpts().FeaturesAsWritten.end());
14587 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14588 } else {
14589 FeatureMap = Target->getTargetOpts().FeatureMap;
14590 }
14591}
14592
14594 const FunctionDecl *FD) {
14595 return {KernelNameType, FD};
14596}
14597
14599 // If the function declaration to register is invalid or dependent, the
14600 // registration attempt is ignored.
14601 if (FD->isInvalidDecl() || FD->isTemplated())
14602 return;
14603
14604 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
14605 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
14606
14607 // Be tolerant of multiple registration attempts so long as each attempt
14608 // is for the same entity. Callers are obligated to detect and diagnose
14609 // conflicting kernel names prior to calling this function.
14610 CanQualType KernelNameType = getCanonicalType(SKEPAttr->getKernelName());
14611 auto IT = SYCLKernels.find(KernelNameType);
14612 assert((IT == SYCLKernels.end() ||
14613 declaresSameEntity(FD, IT->second.getKernelEntryPointDecl())) &&
14614 "SYCL kernel name conflict");
14615 (void)IT;
14616 SYCLKernels.insert(
14617 std::make_pair(KernelNameType, BuildSYCLKernelInfo(KernelNameType, FD)));
14618}
14619
14621 CanQualType KernelNameType = getCanonicalType(T);
14622 return SYCLKernels.at(KernelNameType);
14623}
14624
14626 CanQualType KernelNameType = getCanonicalType(T);
14627 auto IT = SYCLKernels.find(KernelNameType);
14628 if (IT != SYCLKernels.end())
14629 return &IT->second;
14630 return nullptr;
14631}
14632
14634 OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
14635 return *OMPTraitInfoVector.back();
14636}
14637
14640 const ASTContext::SectionInfo &Section) {
14641 if (Section.Decl)
14642 return DB << Section.Decl;
14643 return DB << "a prior #pragma section";
14644}
14645
14647 bool IsInternalVar =
14648 isa<VarDecl>(D) &&
14649 basicGVALinkageForVariable(*this, cast<VarDecl>(D)) == GVA_Internal;
14650 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
14651 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
14652 (D->hasAttr<CUDAConstantAttr>() &&
14653 !D->getAttr<CUDAConstantAttr>()->isImplicit());
14654 // CUDA/HIP: managed variables need to be externalized since it is
14655 // a declaration in IR, therefore cannot have internal linkage. Kernels in
14656 // anonymous name space needs to be externalized to avoid duplicate symbols.
14657 return (IsInternalVar &&
14658 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
14659 (D->hasAttr<CUDAGlobalAttr>() &&
14660 basicGVALinkageForFunction(*this, cast<FunctionDecl>(D)) ==
14661 GVA_Internal);
14662}
14663
14665 return mayExternalize(D) &&
14666 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
14667 CUDADeviceVarODRUsedByHost.count(cast<VarDecl>(D)));
14668}
14669
14670StringRef ASTContext::getCUIDHash() const {
14671 if (!CUIDHash.empty())
14672 return CUIDHash;
14673 if (LangOpts.CUID.empty())
14674 return StringRef();
14675 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
14676 return CUIDHash;
14677}
14678
14679const CXXRecordDecl *
14681 assert(ThisClass);
14682 assert(ThisClass->isPolymorphic());
14683 const CXXRecordDecl *PrimaryBase = ThisClass;
14684 while (1) {
14685 assert(PrimaryBase);
14686 assert(PrimaryBase->isPolymorphic());
14687 auto &Layout = getASTRecordLayout(PrimaryBase);
14688 auto Base = Layout.getPrimaryBase();
14689 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
14690 break;
14691 PrimaryBase = Base;
14692 }
14693 return PrimaryBase;
14694}
14695
14697 StringRef MangledName) {
14698 auto *Method = cast<CXXMethodDecl>(VirtualMethodDecl.getDecl());
14699 assert(Method->isVirtual());
14700 bool DefaultIncludesPointerAuth =
14701 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics;
14702
14703 if (!DefaultIncludesPointerAuth)
14704 return true;
14705
14706 auto Existing = ThunksToBeAbbreviated.find(VirtualMethodDecl);
14707 if (Existing != ThunksToBeAbbreviated.end())
14708 return Existing->second.contains(MangledName.str());
14709
14710 std::unique_ptr<MangleContext> Mangler(createMangleContext());
14711 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks;
14712 auto VtableContext = getVTableContext();
14713 if (const auto *ThunkInfos = VtableContext->getThunkInfo(VirtualMethodDecl)) {
14714 auto *Destructor = dyn_cast<CXXDestructorDecl>(Method);
14715 for (const auto &Thunk : *ThunkInfos) {
14716 SmallString<256> ElidedName;
14717 llvm::raw_svector_ostream ElidedNameStream(ElidedName);
14718 if (Destructor)
14719 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
14720 Thunk, /* elideOverrideInfo */ true,
14721 ElidedNameStream);
14722 else
14723 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ true,
14724 ElidedNameStream);
14725 SmallString<256> MangledName;
14726 llvm::raw_svector_ostream mangledNameStream(MangledName);
14727 if (Destructor)
14728 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
14729 Thunk, /* elideOverrideInfo */ false,
14730 mangledNameStream);
14731 else
14732 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ false,
14733 mangledNameStream);
14734
14735 Thunks[ElidedName].push_back(std::string(MangledName));
14736 }
14737 }
14738 llvm::StringSet<> SimplifiedThunkNames;
14739 for (auto &ThunkList : Thunks) {
14740 llvm::sort(ThunkList.second);
14741 SimplifiedThunkNames.insert(ThunkList.second[0]);
14742 }
14743 bool Result = SimplifiedThunkNames.contains(MangledName);
14744 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames);
14745 return Result;
14746}
This file provides AST data structures related to concepts.
static void SortAndUniqueProtocols(SmallVectorImpl< ObjCProtocolDecl * > &Protocols)
static bool isCanonicalExceptionSpecification(const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType)
static SourceLocation getCommonAttrLoc(const T *X, const T *Y)
static auto getCommonTypes(ASTContext &Ctx, ArrayRef< QualType > Xs, ArrayRef< QualType > Ys, bool Unqualified=false)
static auto getCanonicalTemplateArguments(const ASTContext &C, ArrayRef< TemplateArgument > Args, bool &AnyNonCanonArgs)
static char getObjCEncodingForPrimitiveType(const ASTContext *C, const BuiltinType *BT)
static bool NeedsInjectedClassNameType(const RecordDecl *D)
static bool unionHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD, bool CheckIfTriviallyCopyable)
static NamespaceDecl * getNamespace(const NestedNameSpecifier *X)
static TypedefDecl * CreateHexagonBuiltinVaListDecl(const ASTContext *Context)
#define CANONICAL_TYPE(Class)
static NestedNameSpecifier * getCommonNNS(ASTContext &Ctx, const T *X, const T *Y)
static Decl * getCommonDecl(Decl *X, Decl *Y)
static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, const Decl *D, GVALinkage L)
static bool isTypeTypedefedAsBOOL(QualType T)
static void EncodeBitField(const ASTContext *Ctx, std::string &S, QualType T, const FieldDecl *FD)
static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, const VarDecl *VD)
static const TemplateArgument * getDefaultTemplateArgumentOrNone(const NamedDecl *P)
static uint64_t getSVETypeSize(ASTContext &Context, const BuiltinType *Ty)
getSVETypeSize - Return SVE vector or predicate register size.
#define SUGAR_FREE_TYPE(Class)
static bool getCommonTemplateArguments(ASTContext &Ctx, SmallVectorImpl< TemplateArgument > &R, ArrayRef< TemplateArgument > Xs, ArrayRef< TemplateArgument > Ys)
static bool hasTemplateSpecializationInEncodedString(const Type *T, bool VisitBasesAndFields)
static void getIntersectionOfProtocols(ASTContext &Context, const ObjCInterfaceDecl *CommonBase, const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT, SmallVectorImpl< ObjCProtocolDecl * > &IntersectionSet)
getIntersectionOfProtocols - This routine finds the intersection of set of protocols inherited from t...
static bool areCompatMatrixTypes(const ConstantMatrixType *LHS, const ConstantMatrixType *RHS)
areCompatMatrixTypes - Return true if the two specified matrix types are compatible.
static TypedefDecl * CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context)
static bool sameObjCTypeArgs(ASTContext &ctx, const ObjCInterfaceDecl *iface, ArrayRef< QualType > lhsArgs, ArrayRef< QualType > rhsArgs, bool stripKindOf)
static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs, QualType rhs)
Determine whether the first type is a subtype of the second.
static const Type * getIntegerTypeForEnum(const EnumType *ET)
static const Decl & adjustDeclToTemplate(const Decl &D)
If we have a 'templated' declaration for a template, adjust 'D' to refer to the actual template.
Definition: ASTContext.cpp:355
static int CmpProtocolNames(ObjCProtocolDecl *const *LHS, ObjCProtocolDecl *const *RHS)
CmpProtocolNames - Comparison predicate for sorting protocols alphabetically.
static QualType getCommonElementType(ASTContext &Ctx, const T *X, const T *Y)
static TypedefDecl * CreatePowerABIBuiltinVaListDecl(const ASTContext *Context)
static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y)
static std::optional< int64_t > structHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD, bool CheckIfTriviallyCopyable)
static bool hasSameOverloadableAttrs(const FunctionDecl *A, const FunctionDecl *B)
Determine whether the attributes we can overload on are identical for A and B.
static T * getCommonDeclChecked(T *X, T *Y)
static TypedefDecl * CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context)
static int64_t getSubobjectOffset(const FieldDecl *Field, const ASTContext &Context, const clang::ASTRecordLayout &)
static TypedefDecl * CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context)
static TypedefDecl * CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context)
static TemplateName getCommonTemplateNameChecked(ASTContext &Ctx, TemplateName X, TemplateName Y, bool IgnoreDeduced)
static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, QualType other, bool isBlockReturnType)
Given that we have an enum type and a non-enum type, try to merge them.
static GVALinkage adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D, GVALinkage L)
Adjust the GVALinkage for a declaration based on what an external AST source knows about whether ther...
static TypedefDecl * CreateSystemZBuiltinVaListDecl(const ASTContext *Context)
static std::optional< int64_t > getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context, bool CheckIfTriviallyCopyable)
static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, const FunctionDecl *FD)
#define NON_UNIQUE_TYPE(Class)
static TypedefDecl * CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context)
static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI, const LangOptions &LangOpts)
Definition: ASTContext.cpp:900
static auto getCommonIndexTypeCVRQualifiers(const ArrayType *X, const ArrayType *Y)
static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, ASTContext::GetBuiltinTypeError &Error, bool &RequiresICE, bool AllowTypeModifiers)
DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the pointer over the consume...
FloatingRank
Definition: ASTContext.cpp:104
@ FloatRank
Definition: ASTContext.cpp:108
@ LongDoubleRank
Definition: ASTContext.cpp:110
@ Float16Rank
Definition: ASTContext.cpp:106
@ Ibm128Rank
Definition: ASTContext.cpp:112
@ Float128Rank
Definition: ASTContext.cpp:111
@ BFloat16Rank
Definition: ASTContext.cpp:105
@ HalfRank
Definition: ASTContext.cpp:107
@ DoubleRank
Definition: ASTContext.cpp:109
static TypedefDecl * CreateCharPtrBuiltinVaListDecl(const ASTContext *Context)
static void mergeTypeLists(ASTContext &Ctx, SmallVectorImpl< QualType > &Out, ArrayRef< QualType > X, ArrayRef< QualType > Y)
static bool areSortedAndUniqued(ArrayRef< ObjCProtocolDecl * > Protocols)
static TypeInfoChars getConstantArrayInfoInChars(const ASTContext &Context, const ConstantArrayType *CAT)
getConstantArrayInfoInChars - Performing the computation in CharUnits instead of in bits prevents ove...
static FloatingRank getFloatingRank(QualType T)
getFloatingRank - Return a relative rank for floating point types.
static TypedefDecl * CreateXtensaABIBuiltinVaListDecl(const ASTContext *Context)
static TemplateArgument getCommonTemplateArgument(ASTContext &Ctx, const TemplateArgument &X, const TemplateArgument &Y)
static auto * getCommonSizeExpr(ASTContext &Ctx, T *X, T *Y)
static void encodeTypeForFunctionPointerAuth(const ASTContext &Ctx, raw_ostream &OS, QualType QT)
Encode a function type for use in the discriminator of a function pointer type.
static std::optional< int64_t > structSubobjectsHaveUniqueObjectRepresentations(const RangeT &Subobjects, int64_t CurOffsetInBits, const ASTContext &Context, const clang::ASTRecordLayout &Layout, bool CheckIfTriviallyCopyable)
static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET)
static QualType getCommonArrayElementType(ASTContext &Ctx, const T *X, Qualifiers &QX, const T *Y, Qualifiers &QY)
static QualType getCommonPointeeType(ASTContext &Ctx, const T *X, const T *Y)
static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty)
getRVVTypeSize - Return RVV vector register size.
static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal)
static SYCLKernelInfo BuildSYCLKernelInfo(CanQualType KernelNameType, const FunctionDecl *FD)
static int compareObjCProtocolsByName(ObjCProtocolDecl *const *lhs, ObjCProtocolDecl *const *rhs)
Comparison routine for Objective-C protocols to be used with llvm::array_pod_sort.
static QualType getCommonNonSugarTypeNode(ASTContext &Ctx, const Type *X, Qualifiers &QX, const Type *Y, Qualifiers &QY)
static QualType getCommonSugarTypeNode(ASTContext &Ctx, const Type *X, const Type *Y, SplitQualType Underlying)
static bool isSameQualifier(const NestedNameSpecifier *X, const NestedNameSpecifier *Y)
static std::string charUnitsToString(const CharUnits &CU)
static bool hasAnyPackExpansions(ArrayRef< TemplateArgument > Args)
static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod, SmallVectorImpl< const NamedDecl * > &Redeclared)
Definition: ASTContext.cpp:513
static SmallVector< SourceLocation, 2 > getDeclLocsForCommentSearch(const Decl *D, SourceManager &SourceMgr)
Definition: ASTContext.cpp:139
static TemplateName getCommonTemplateName(ASTContext &Ctx, TemplateName X, TemplateName Y, bool IgnoreDeduced=false)
static bool isCanonicalResultType(QualType T)
Determine whether T is canonical as the result type of a function.
static TypedefDecl * CreateMSVaListDecl(const ASTContext *Context)
static bool areCompatVectorTypes(const VectorType *LHS, const VectorType *RHS)
areCompatVectorTypes - Return true if the two specified vector types are compatible.
static TypedefDecl * CreateCharPtrNamedVaListDecl(const ASTContext *Context, StringRef Name)
#define UNEXPECTED_TYPE(Class, Kind)
static TypedefDecl * CreateVaListDecl(const ASTContext *Context, TargetInfo::BuiltinVaListKind Kind)
static std::vector< std::string > getFMVBackendFeaturesFor(const llvm::SmallVectorImpl< StringRef > &FMVFeatStrings)
static ElaboratedTypeKeyword getCommonTypeKeyword(const T *X, const T *Y)
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3460
NodeId Parent
Definition: ASTDiff.cpp:191
StringRef P
Provides definitions for the various language-specific address spaces.
static bool isUnsigned(SValBuilder &SVB, NonLoc Value)
#define SM(sm)
Definition: Cuda.cpp:85
static constexpr Builtin::Info BuiltinInfo[]
Definition: Builtins.cpp:32
Defines enum values for all the target-independent builtin functions.
static bool CanThrow(Expr *E, ASTContext &Ctx)
Definition: CFG.cpp:2686
const Decl * D
IndirectLocalPath & Path
Expr * E
Defines the clang::CommentOptions interface.
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1181
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines OpenMP nodes for declarative directives.
Defines the C++ template declaration subclasses.
Defines the ExceptionSpecificationType enumeration and various utility functions.
Defines the clang::Expr interface and subclasses for C++ expressions.
StringRef Text
Definition: Format.cpp:3054
unsigned Iter
Definition: HTMLLogger.cpp:153
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
static const Decl * getCanonicalDecl(const Decl *D)
#define X(type, name)
Definition: Value.h:144
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
llvm::MachO::Target Target
Definition: MachO.h:51
llvm::MachO::Record Record
Definition: MachO.h:31
static bool hasFeature(StringRef Feature, const LangOptions &LangOpts, const TargetInfo &Target)
Determine whether a translation unit built using the current language options has the given feature.
Definition: Module.cpp:96
Defines the clang::Module class, which describes a module in the source code.
Defines types useful for describing an Objective-C runtime.
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
static QualType getUnderlyingType(const SubRegion *R)
uint32_t Id
Definition: SemaARM.cpp:1136
SourceRange Range
Definition: SemaObjC.cpp:758
SourceLocation Loc
Definition: SemaObjC.cpp:759
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
static QualType getPointeeType(const MemRegion *R)
Defines the TargetCXXABI class, which abstracts details of the C++ ABI that we're targeting.
Defines the clang::TypeLoc interface and its subclasses.
static const TemplateArgument & getArgument(const TemplateArgument &A)
C Language Family Type Representation.
SourceLocation Begin
__device__ __2f16 float c
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
bool isMemberPointerToDerivedMember() const
Definition: APValue.cpp:1074
const ValueDecl * getMemberPointerDecl() const
Definition: APValue.cpp:1067
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition: APValue.cpp:1081
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
bool getByrefLifetime(QualType Ty, Qualifiers::ObjCLifetime &Lifetime, bool &HasByrefExtendedLayout) const
Returns true, if given type has a known lifetime.
MSGuidDecl * getMSGuidDecl(MSGuidDeclParts Parts) const
Return a declaration for the global GUID object representing the given GUID value.
QualType getUsingType(const UsingShadowDecl *Found, QualType Underlying) const
CanQualType AccumTy
Definition: ASTContext.h:1173
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, const ObjCMethodDecl *MethodImp)
CanQualType ObjCBuiltinSelTy
Definition: ASTContext.h:1192
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1141
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2922
CanQualType getCanonicalFunctionResultType(QualType ResultType) const
Adjust the given function result type.
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
llvm::PointerUnion< VarTemplateDecl *, MemberSpecializationInfo * > TemplateOrSpecializationInfo
A type synonym for the TemplateOrInstantiation mapping.
Definition: ASTContext.h:508
LangAS getOpenCLTypeAddrSpace(const Type *T) const
Get address space for OpenCL type.
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
void InitBuiltinTypes(const TargetInfo &Target, const TargetInfo *AuxTarget=nullptr)
Initialize built-in types.
ParentMapContext & getParentMapContext()
Returns the dynamic AST node parent map context.
Definition: ASTContext.cpp:894
QualType getParenType(QualType NamedType) const
size_t getSideTableAllocatedMemory() const
Return the total memory used for various side tables.
MemberSpecializationInfo * getInstantiatedFromStaticDataMember(const VarDecl *Var)
If this variable is an instantiated static data member of a class template specialization,...
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
CanQualType ARCUnbridgedCastTy
Definition: ASTContext.h:1191
QualType getDependentSizedMatrixType(QualType ElementType, Expr *RowExpr, Expr *ColumnExpr, SourceLocation AttrLoc) const
Return the unique reference to the matrix type of the specified element type and size.
QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr, QualType Wrapped) const
llvm::DenseMap< const Decl *, comments::FullComment * > ParsedComments
Mapping from declarations to parsed comments attached to any redeclaration.
Definition: ASTContext.h:896
BuiltinTemplateDecl * getBuiltinCommonTypeDecl() const
unsigned getManglingNumber(const NamedDecl *ND, bool ForAuxTarget=false) const
CanQualType LongTy
Definition: ASTContext.h:1169
unsigned getIntWidth(QualType T) const
CanQualType getCanonicalParamType(QualType T) const
Return the canonical parameter type corresponding to the specific potentially non-canonical one.
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
TemplateOrSpecializationInfo getTemplateOrSpecializationInfo(const VarDecl *Var)
CanQualType WIntTy
Definition: ASTContext.h:1165
@ Weak
Weak definition of inline variable.
@ WeakUnknown
Weak for now, might become strong later in this TU.
void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl)
TypedefDecl * getObjCClassDecl() const
Retrieve the typedef declaration corresponding to the predefined Objective-C 'Class' type.
TypedefNameDecl * getTypedefNameForUnnamedTagDecl(const TagDecl *TD)
TypedefDecl * getCFConstantStringDecl() const
CanQualType Int128Ty
Definition: ASTContext.h:1169
CanQualType SatUnsignedFractTy
Definition: ASTContext.h:1182
BuiltinTemplateDecl * getMakeIntegerSeqDecl() const
void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern)
Remember that the using decl Inst is an instantiation of the using decl Pattern of a class template.
bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an RISC-V vector builtin type and a VectorType that is a fixed-len...
ExternCContextDecl * getExternCContextDecl() const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD) const
Parses the target attributes passed in, and returns only the ones that are valid feature names.
QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent, bool IsPack=false, ConceptDecl *TypeConstraintConcept=nullptr, ArrayRef< TemplateArgument > TypeConstraintArgs={}) const
C++11 deduced auto type.
QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
TypedefDecl * getObjCSelDecl() const
Retrieve the typedef corresponding to the predefined 'SEL' type in Objective-C.
CanQualType UnsignedShortAccumTy
Definition: ASTContext.h:1175
TypedefDecl * getObjCInstanceTypeDecl()
Retrieve the typedef declaration corresponding to the Objective-C "instancetype" type.
uint64_t getFieldOffset(const ValueDecl *FD) const
Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, ArrayRef< TemplateArgumentLoc > Args) const
QualType adjustFunctionResultType(QualType FunctionType, QualType NewResultType)
Change the result type of a function type, preserving sugar such as attributed types.
void setTemplateOrSpecializationInfo(VarDecl *Inst, TemplateOrSpecializationInfo TSI)
bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, ObjCProtocolDecl *rProto) const
ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the inheritance hierarchy of 'rProto...
TypedefDecl * buildImplicitTypedef(QualType T, StringRef Name) const
Create a new implicit TU-level typedef declaration.
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl.
void adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig, ObjCTypeParamDecl *New) const
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
QualType getAutoRRefDeductType() const
C++11 deduction pattern for 'auto &&' type.
TypedefDecl * getBuiltinMSVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_ms_va_list type.
bool ObjCQualifiedIdTypesAreCompatible(const ObjCObjectPointerType *LHS, const ObjCObjectPointerType *RHS, bool ForCompare)
ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an ObjCQualifiedIDType.
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
QualType getBuiltinVaListType() const
Retrieve the type of the __builtin_va_list type.
Definition: ASTContext.h:2258
QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool AllowCXX=false, bool IsConditionalOperator=false)
NamedDecl * getInstantiatedFromUsingDecl(NamedDecl *Inst)
If the given using decl Inst is an instantiation of another (possibly unresolved) using decl,...
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:684
comments::FullComment * cloneFullComment(comments::FullComment *FC, const Decl *D) const
Definition: ASTContext.cpp:592
QualType getUnresolvedUsingType(const UnresolvedUsingTypenameDecl *Decl) const
CharUnits getObjCEncodingTypeSize(QualType T) const
Return the size of type T for Objective-C encoding purpose, in characters.
int getIntegerTypeOrder(QualType LHS, QualType RHS) const
Return the highest ranked integer type, see C99 6.3.1.8p1.
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType, const Attr *attr=nullptr) const
TypedefDecl * getObjCIdDecl() const
Retrieve the typedef corresponding to the predefined id type in Objective-C.
void setCurrentNamedModule(Module *M)
Set the (C++20) module we are building.
QualType getProcessIDType() const
Return the unique type for "pid_t" defined in <sys/types.h>.
CharUnits getMemberPointerPathAdjustment(const APValue &MP) const
Find the 'this' offset for the member path in a pointer-to-member APValue.
bool mayExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel may be externalized.
QualType getTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args, QualType Canon=QualType()) const
std::unique_ptr< MangleNumberingContext > createMangleNumberingContext() const
CanQualType SatAccumTy
Definition: ASTContext.h:1178
QualType getUnsignedPointerDiffType() const
Return the unique unsigned counterpart of "ptrdiff_t" integer type.
QualType getucontext_tType() const
Retrieve the C ucontext_t type.
Definition: ASTContext.h:2132
QualType getRecordType(const RecordDecl *Decl) const
QualType getScalableVectorType(QualType EltTy, unsigned NumElts, unsigned NumFields=1) const
Return the unique reference to a scalable vector type of the specified element type and scalable numb...
bool hasSameExpr(const Expr *X, const Expr *Y) const
Determine whether the given expressions X and Y are equivalent.
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
MangleContext * createMangleContext(const TargetInfo *T=nullptr)
If T is null pointer, assume the target in ASTContext.
QualType getRealTypeForBitwidth(unsigned DestWidth, FloatModeKind ExplicitType) const
getRealTypeForBitwidth - sets floating point QualTy according to specified bitwidth.
QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const
getInjectedClassNameType - Return the unique reference to the injected class name type for the specif...
QualType getVariableArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals, SourceRange Brackets) const
Return a non-unique reference to the type for a variable array of the specified element type.
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
CanQualType ShortAccumTy
Definition: ASTContext.h:1173
ASTMutationListener * getASTMutationListener() const
Retrieve a pointer to the AST mutation listener associated with this AST context, if any.
Definition: ASTContext.h:1289
IdentifierInfo * getBuiltinCommonTypeName() const
Definition: ASTContext.h:2076
unsigned NumImplicitCopyAssignmentOperatorsDeclared
The number of implicitly-declared copy assignment operators for which declarations were built.
Definition: ASTContext.h:3410
uint64_t getTargetNullPointerValue(QualType QT) const
Get target-dependent integer value for null pointer which is used for constant folding.
unsigned getTypeUnadjustedAlign(QualType T) const
Return the ABI-specified natural alignment of a (complete) type T, before alignment adjustments,...
Definition: ASTContext.h:2528
unsigned char getFixedPointIBits(QualType Ty) const
QualType getCorrespondingSignedFixedPointType(QualType Ty) const
CanQualType FloatTy
Definition: ASTContext.h:1172
QualType getArrayParameterType(QualType Ty) const
Return the uniqued reference to a specified array parameter type from the original array type.
QualType getCountAttributedType(QualType T, Expr *CountExpr, bool CountInBytes, bool OrNull, ArrayRef< TypeCoupledDeclRefInfo > DependentDecls) const
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2723
unsigned NumImplicitDestructorsDeclared
The number of implicitly-declared destructors for which declarations were built.
Definition: ASTContext.h:3424
bool mergeExtParameterInfo(const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, bool &CanUseFirst, bool &CanUseSecond, SmallVectorImpl< FunctionProtoType::ExtParameterInfo > &NewParamInfos)
This function merges the ExtParameterInfo lists of two functions.
bool ObjCQualifiedClassTypesAreCompatible(const ObjCObjectPointerType *LHS, const ObjCObjectPointerType *RHS)
ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and Class<pr1, ...>.
bool shouldExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel should be externalized.
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2739
bool propertyTypesAreCompatible(QualType, QualType)
void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, UsingShadowDecl *Pattern)
CanQualType DoubleTy
Definition: ASTContext.h:1172
TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
QualType getDependentVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc, VectorKind VecKind) const
Return the unique reference to the type for a dependently sized vector of the specified element type.
CanQualType SatLongAccumTy
Definition: ASTContext.h:1178
CanQualType getIntMaxType() const
Return the unique type for "intmax_t" (C99 7.18.1.5), defined in <stdint.h>.
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
OpenCLTypeKind getOpenCLTypeKind(const Type *T) const
Map an AST Type to an OpenCLTypeKind enum value.
QualType getFILEType() const
Retrieve the C FILE type.
Definition: ASTContext.h:2096
ArrayRef< Decl * > getModuleInitializers(Module *M)
Get the initializations to perform when importing a module, if any.
void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, std::string &S) const
Put the string version of the type qualifiers QT into S.
unsigned getPreferredTypeAlign(QualType T) const
Return the "preferred" alignment of the specified type T for the current target, in bits.
Definition: ASTContext.h:2580
std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, bool Extended=false) const
Emit the encoded type for the method declaration Decl into S.
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
CanQualType LongDoubleTy
Definition: ASTContext.h:1172
CanQualType OMPArrayShapingTy
Definition: ASTContext.h:1201
ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents, SelectorTable &sels, Builtin::Context &builtins, TranslationUnitKind TUKind)
Definition: ASTContext.cpp:913
QualType getReadPipeType(QualType T) const
Return a read_only pipe type for the specified type.
std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
getObjCEncodingForPropertyDecl - Return the encoded type for this method declaration.
CanQualType Char16Ty
Definition: ASTContext.h:1167
TemplateName getCanonicalTemplateName(TemplateName Name, bool IgnoreDeduced=false) const
Retrieves the "canonical" template name that refers to a given template.
unsigned getStaticLocalNumber(const VarDecl *VD) const
void addComment(const RawComment &RC)
Definition: ASTContext.cpp:346
void getLegacyIntegralTypeEncoding(QualType &t) const
getLegacyIntegralTypeEncoding - Another legacy compatibility encoding: 32-bit longs are encoded as 'l...
bool isSameTypeConstraint(const TypeConstraint *XTC, const TypeConstraint *YTC) const
Determine whether two type contraint are similar enough that they could used in declarations of the s...
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
RecordDecl * buildImplicitRecord(StringRef Name, RecordDecl::TagKind TK=RecordDecl::TagKind::Struct) const
Create a new implicit TU-level CXXRecordDecl or RecordDecl declaration.
QualType getSubstTemplateTypeParmType(QualType Replacement, Decl *AssociatedDecl, unsigned Index, std::optional< unsigned > PackIndex, SubstTemplateTypeParmTypeFlag Flag=SubstTemplateTypeParmTypeFlag::None) const
Retrieve a substitution-result type.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
QualType getMSGuidType() const
Retrieve the implicitly-predeclared 'struct _GUID' type.
Definition: ASTContext.h:2280
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or nullptr if there isn't on...
const ASTRecordLayout & getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const
Get or compute information about the layout of the specified Objective-C implementation.
CanQualType UnsignedLongFractTy
Definition: ASTContext.h:1177
QualType getEnumType(const EnumDecl *Decl) const
overridden_method_range overridden_methods(const CXXMethodDecl *Method) const
QualType getDependentBitIntType(bool Unsigned, Expr *BitsExpr) const
Return a dependent bit-precise integer type with the specified signedness and bit count.
void setObjCImplementation(ObjCInterfaceDecl *IFaceD, ObjCImplementationDecl *ImplD)
Set the implementation of ObjCInterfaceDecl.
StringRef getCUIDHash() const
bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const
Returns true if this is an inline-initialized static data member which is treated as a definition for...
bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
canAssignObjCInterfaces - Return true if the two interface types are compatible for assignment from R...
CanQualType VoidPtrTy
Definition: ASTContext.h:1187
QualType getReferenceQualifiedType(const Expr *e) const
getReferenceQualifiedType - Given an expr, will return the type for that expression,...
bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const
Determine whether two function types are the same, ignoring exception specifications in cases where t...
QualType getBlockDescriptorExtendedType() const
Gets the struct used to keep track of the extended descriptor for pointer to blocks.
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
Definition: ASTContext.h:1188
IdentifierInfo * getMakeIntegerSeqName() const
Definition: ASTContext.h:2064
bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT, ObjCInterfaceDecl *IDecl)
QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in QT's qualified-id protocol list adopt...
void addLazyModuleInitializers(Module *M, ArrayRef< GlobalDeclID > IDs)
bool isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const
Determine whether two 'requires' expressions are similar enough that they may be used in re-declarati...
IdentifierInfo * getTypePackElementName() const
Definition: ASTContext.h:2070
bool BlockRequiresCopying(QualType Ty, const VarDecl *D)
Returns true iff we need copy/dispose helpers for the given type.
CanQualType NullPtrTy
Definition: ASTContext.h:1187
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1703
CanQualType WideCharTy
Definition: ASTContext.h:1164
CanQualType OMPIteratorTy
Definition: ASTContext.h:1201
IdentifierTable & Idents
Definition: ASTContext.h:680
TemplateName getSubstTemplateTemplateParm(TemplateName replacement, Decl *AssociatedDecl, unsigned Index, std::optional< unsigned > PackIndex) const
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:682
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
void addModuleInitializer(Module *M, Decl *Init)
Add a declaration to the list of declarations that are initialized for a module.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:834
QualType getFunctionTypeWithoutPtrSizes(QualType T)
Get a function type and produce the equivalent function type where pointer size address spaces in the...
llvm::iterator_range< overridden_cxx_method_iterator > overridden_method_range
Definition: ASTContext.h:1063
bool isTypeIgnoredBySanitizer(const SanitizerMask &Mask, const QualType &Ty) const
Check if a type can have its sanitizer instrumentation elided based on its presence within an ignorel...
Definition: ASTContext.cpp:854
unsigned getMinGlobalAlignOfVar(uint64_t Size, const VarDecl *VD) const
Return the minimum alignement as specified by the target.
RawCommentList Comments
All comments in this translation unit.
Definition: ASTContext.h:867
bool isSameDefaultTemplateArgument(const NamedDecl *X, const NamedDecl *Y) const
Determine whether two default template arguments are similar enough that they may be used in declarat...
QualType applyObjCProtocolQualifiers(QualType type, ArrayRef< ObjCProtocolDecl * > protocols, bool &hasError, bool allowOnPointerType=false) const
Apply Objective-C protocol qualifiers to the given type.
QualType getMacroQualifiedType(QualType UnderlyingTy, const IdentifierInfo *MacroII) const
QualType removePtrSizeAddrSpace(QualType T) const
Remove the existing address space on the type if it is a pointer size address space and return the ty...
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
CanQualType SatShortFractTy
Definition: ASTContext.h:1181
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
bool canBindObjCObjectType(QualType To, QualType From)
int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const
Compare the rank of two floating point types as above, but compare equal if both types have the same ...
QualType getUIntPtrType() const
Return a type compatible with "uintptr_t" (C99 7.18.1.4), as defined by the target.
void setParameterIndex(const ParmVarDecl *D, unsigned index)
Used by ParmVarDecl to store on the side the index of the parameter when it exceeds the size of the n...
QualType getFunctionTypeWithExceptionSpec(QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const
Get a function type and produce the equivalent function type with the specified exception specificati...
Qualifiers::GC getObjCGCAttrKind(QualType Ty) const
Return one of the GCNone, Weak or Strong Objective-C garbage collection attributes.
CanQualType Ibm128Ty
Definition: ASTContext.h:1172
bool hasUniqueObjectRepresentations(QualType Ty, bool CheckIfTriviallyCopyable=true) const
Return true if the specified type has unique object representations according to (C++17 [meta....
bool typesAreBlockPointerCompatible(QualType, QualType)
CanQualType SatUnsignedAccumTy
Definition: ASTContext.h:1179
bool useAbbreviatedThunkName(GlobalDecl VirtualMethodDecl, StringRef MangledName)
const ASTRecordLayout & getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const
Get or compute information about the layout of the specified Objective-C interface.
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
void setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst, UsingEnumDecl *Pattern)
Remember that the using enum decl Inst is an instantiation of the using enum decl Pattern of a class ...
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
QualType getSignatureParameterType(QualType T) const
Retrieve the parameter type as adjusted for use in the signature of a function, decaying array and fu...
CanQualType ArraySectionTy
Definition: ASTContext.h:1200
QualType getCanonicalTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args) const
CanQualType ObjCBuiltinIdTy
Definition: ASTContext.h:1192
overridden_cxx_method_iterator overridden_methods_end(const CXXMethodDecl *Method) const
VTableContextBase * getVTableContext()
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const
ObjCPropertyImplDecl * getObjCPropertyImplDeclForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
bool isNearlyEmpty(const CXXRecordDecl *RD) const
QualType AutoDeductTy
Definition: ASTContext.h:1223
CanQualType BoolTy
Definition: ASTContext.h:1161
void cacheRawCommentForDecl(const Decl &OriginalD, const RawComment &Comment) const
Attaches Comment to OriginalD and to its redeclaration chain and removes the redeclaration chain from...
Definition: ASTContext.cpp:504
void attachCommentsToJustParsedDecls(ArrayRef< Decl * > Decls, const Preprocessor *PP)
Searches existing comments for doc comments that should be attached to Decls.
Definition: ASTContext.cpp:530
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth,...
void setStaticLocalNumber(const VarDecl *VD, unsigned Number)
QualType getCFConstantStringType() const
Return the C structure type used to represent constant CFStrings.
void eraseDeclAttrs(const Decl *D)
Erase the attributes corresponding to the given declaration.
UsingEnumDecl * getInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst)
If the given using-enum decl Inst is an instantiation of another using-enum decl, return it.
RecordDecl * getCFConstantStringTagDecl() const
QualType getObjCSelType() const
Retrieve the type that corresponds to the predefined Objective-C 'SEL' type.
Definition: ASTContext.h:2213
QualType getDeducedTemplateSpecializationType(TemplateName Template, QualType DeducedType, bool IsDependent) const
C++17 deduced class template specialization type.
std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const
Emit the encoded type for the function Decl into S.
QualType getTemplateTypeParmType(unsigned Depth, unsigned Index, bool ParameterPack, TemplateTypeParmDecl *ParmDecl=nullptr) const
Retrieve the template type parameter type for a template parameter or parameter pack with the given d...
CanQualType UnsignedFractTy
Definition: ASTContext.h:1177
QualType getjmp_bufType() const
Retrieve the C jmp_buf type.
Definition: ASTContext.h:2108
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
QualType mergeFunctionParameterTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false)
mergeFunctionParameterTypes - merge two types which appear as function parameter types
QualType getsigjmp_bufType() const
Retrieve the C sigjmp_buf type.
Definition: ASTContext.h:2120
void addOverriddenMethod(const CXXMethodDecl *Method, const CXXMethodDecl *Overridden)
Note that the given C++ Method overrides the given Overridden method.
CanQualType Float128Ty
Definition: ASTContext.h:1172
CanQualType ObjCBuiltinClassTy
Definition: ASTContext.h:1192
unsigned NumImplicitDefaultConstructorsDeclared
The number of implicitly-declared default constructors for which declarations were built.
Definition: ASTContext.h:3389
CanQualType UnresolvedTemplateTy
Definition: ASTContext.h:1188
OMPTraitInfo & getNewOMPTraitInfo()
Return a new OMPTraitInfo object owned by this context.
CanQualType UnsignedLongTy
Definition: ASTContext.h:1170
void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass, SmallVectorImpl< const ObjCIvarDecl * > &Ivars) const
DeepCollectObjCIvars - This routine first collects all declared, but not synthesized,...
bool computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits, unsigned NumPositiveBits, QualType &BestType, QualType &BestPromotionType)
Compute BestType and BestPromotionType for an enum based on the highest number of negative and positi...
llvm::APFixedPoint getFixedPointMin(QualType Ty) const
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
QualType adjustType(QualType OldType, llvm::function_ref< QualType(QualType)> Adjust) const
Rebuild a type, preserving any existing type sugar.
void addedLocalImportDecl(ImportDecl *Import)
Notify the AST context that a new import declaration has been parsed or implicitly created within thi...
CanQualType UnsignedLongAccumTy
Definition: ASTContext.h:1175
QualType AutoRRefDeductTy
Definition: ASTContext.h:1224
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
CanQualType ShortFractTy
Definition: ASTContext.h:1176
QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const
Return a type for a constant array for a string literal of the specified element type and length.
QualType getCorrespondingSaturatedType(QualType Ty) const
bool isSameEntity(const NamedDecl *X, const NamedDecl *Y) const
Determine whether the two declarations refer to the same entity.
TypeSourceInfo * getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc, const TemplateArgumentListInfo &Args, QualType Canon=QualType()) const
QualType getSubstTemplateTypeParmPackType(Decl *AssociatedDecl, unsigned Index, bool Final, const TemplateArgument &ArgPack)
Retrieve a.
CanQualType BoundMemberTy
Definition: ASTContext.h:1188
CanQualType SatUnsignedShortFractTy
Definition: ASTContext.h:1182
CanQualType CharTy
Definition: ASTContext.h:1162
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
bool hasSameFunctionTypeIgnoringParamABI(QualType T, QualType U) const
Determine if two function types are the same, ignoring parameter ABI annotations.
TypedefDecl * getInt128Decl() const
Retrieve the declaration for the 128-bit signed integer type.
unsigned getOpenMPDefaultSimdAlign(QualType T) const
Get default simd alignment of the specified complete type in bits.
QualType getObjCSuperType() const
Returns the C struct type for objc_super.
QualType getBlockDescriptorType() const
Gets the struct used to keep track of the descriptor for pointer to blocks.
bool CommentsLoaded
True if comments are already loaded from ExternalASTSource.
Definition: ASTContext.h:870
BlockVarCopyInit getBlockVarCopyInit(const VarDecl *VD) const
Get the copy initialization expression of the VarDecl VD, or nullptr if none exists.
unsigned NumImplicitMoveConstructorsDeclared
The number of implicitly-declared move constructors for which declarations were built.
Definition: ASTContext.h:3403
unsigned NumImplicitCopyConstructorsDeclared
The number of implicitly-declared copy constructors for which declarations were built.
Definition: ASTContext.h:3396
CanQualType IntTy
Definition: ASTContext.h:1169
llvm::DenseSet< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
Definition: ASTContext.h:1237
CanQualType PseudoObjectTy
Definition: ASTContext.h:1191
QualType getWebAssemblyExternrefType() const
Return a WebAssembly externref type.
void setTraversalScope(const std::vector< Decl * > &)
Definition: ASTContext.cpp:980
CharUnits getTypeUnadjustedAlignInChars(QualType T) const
getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a type, in characters,...
QualType getAdjustedType(QualType Orig, QualType New) const
Return the uniqued reference to a type adjusted from the original type to a new type.
void PrintStats() const
Definition: ASTContext.cpp:994
unsigned getAlignOfGlobalVar(QualType T, const VarDecl *VD) const
Return the alignment in bits that should be given to a global variable with type T.
TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
comments::FullComment * getLocalCommentForDeclUncached(const Decl *D) const
Return parsed documentation comment attached to a given declaration.
Definition: ASTContext.cpp:607
unsigned NumImplicitDestructors
The number of implicitly-declared destructors.
Definition: ASTContext.h:3420
CanQualType Float16Ty
Definition: ASTContext.h:1186
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2296
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
bool isAlignmentRequired(const Type *T) const
Determine if the alignment the type has was required using an alignment attribute.
TagDecl * MSGuidTagDecl
Definition: ASTContext.h:1231
bool areComparableObjCPointerTypes(QualType LHS, QualType RHS)
MangleContext * createDeviceMangleContext(const TargetInfo &T)
Creates a device mangle context to correctly mangle lambdas in a mixed architecture compile by settin...
CharUnits getExnObjectAlignment() const
Return the alignment (in bytes) of the thrown exception object.
CanQualType SignedCharTy
Definition: ASTContext.h:1169
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
ASTMutationListener * Listener
Definition: ASTContext.h:686
QualType getPackExpansionType(QualType Pattern, std::optional< unsigned > NumExpansions, bool ExpectPackInType=true) const
Form a pack expansion type with the given pattern.
CanQualType ObjCBuiltinBoolTy
Definition: ASTContext.h:1193
TypeInfoChars getTypeInfoInChars(const Type *T) const
QualType getObjCObjectType(QualType Base, ObjCProtocolDecl *const *Protocols, unsigned NumProtocols) const
Legacy interface: cannot provide type arguments or __kindof.
TemplateParamObjectDecl * getTemplateParamObjectDecl(QualType T, const APValue &V) const
Return the template parameter object of the given type with the given value.
CanQualType OverloadTy
Definition: ASTContext.h:1188
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
CanQualType OCLClkEventTy
Definition: ASTContext.h:1197
void adjustExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, bool AsWritten=false)
Change the exception specification on a function once it is delay-parsed, instantiated,...
TypedefDecl * getUInt128Decl() const
Retrieve the declaration for the 128-bit unsigned integer type.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:733
ArrayRef< Module * > getModulesWithMergedDefinition(const NamedDecl *Def)
Get the additional modules in which the definition Def has been merged.
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals, SourceRange Brackets) const
Return a non-unique reference to the type for a dependently-sized array of the specified element type...
uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID, const ObjCImplementationDecl *ID, const ObjCIvarDecl *Ivar) const
Get the offset of an ObjCIvarDecl in bits.
CanQualType SatUnsignedShortAccumTy
Definition: ASTContext.h:1179
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false, bool IsConditionalOperator=false)
const RawComment * getRawCommentForAnyRedecl(const Decl *D, const Decl **OriginalDecl=nullptr) const
Return the documentation comment attached to a given declaration.
Definition: ASTContext.cpp:422
CharUnits getAlignOfGlobalVarInChars(QualType T, const VarDecl *VD) const
Return the alignment in characters that should be given to a global variable with type T.
const ObjCMethodDecl * getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const
Get the duplicate declaration of a ObjCMethod in the same interface, or null if none exists.
static bool isObjCNSObjectType(QualType Ty)
Return true if this is an NSObject object with its NSObject attribute set.
Definition: ASTContext.h:2469
GVALinkage GetGVALinkageForVariable(const VarDecl *VD) const
UsingShadowDecl * getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst)
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2203
Decl * getVaListTagDecl() const
Retrieve the C type declaration corresponding to the predefined __va_list_tag type used to help defin...
QualType getUnsignedWCharType() const
Return the type of "unsigned wchar_t".
QualType getFunctionTypeWithoutParamABIs(QualType T) const
Get or construct a function type that is equivalent to the input type except that the parameter ABI a...
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2770
QualType getCorrespondingUnsaturatedType(QualType Ty) const
comments::FullComment * getCommentForDecl(const Decl *D, const Preprocessor *PP) const
Return parsed documentation comment attached to a given declaration.
Definition: ASTContext.cpp:612
FunctionProtoType::ExceptionSpecInfo mergeExceptionSpecs(FunctionProtoType::ExceptionSpecInfo ESI1, FunctionProtoType::ExceptionSpecInfo ESI2, SmallVectorImpl< QualType > &ExceptionTypeStorage, bool AcceptDependent)
TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl) const
unsigned getTargetDefaultAlignForAttributeAligned() const
Return the default alignment for attribute((aligned)) on this target, to be used if no alignment valu...
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
llvm::DenseMap< CanQualType, SYCLKernelInfo > SYCLKernels
Map of SYCL kernels indexed by the unique type used to name the kernel.
Definition: ASTContext.h:1250
bool isSameTemplateParameterList(const TemplateParameterList *X, const TemplateParameterList *Y) const
Determine whether two template parameter lists are similar enough that they may be used in declaratio...
QualType getWritePipeType(QualType T) const
Return a write_only pipe type for the specified type.
const CXXRecordDecl * baseForVTableAuthentication(const CXXRecordDecl *ThisClass)
Resolve the root record to be used to derive the vtable pointer authentication policy for the specifi...
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2489
CanQualType UnsignedInt128Ty
Definition: ASTContext.h:1171
CanQualType BuiltinFnTy
Definition: ASTContext.h:1190
ObjCInterfaceDecl * getObjCProtocolDecl() const
Retrieve the Objective-C class declaration corresponding to the predefined Protocol class.
unsigned NumImplicitDefaultConstructors
The number of implicitly-declared default constructors.
Definition: ASTContext.h:3385
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
unsigned NumImplicitMoveAssignmentOperatorsDeclared
The number of implicitly-declared move assignment operators for which declarations were built.
Definition: ASTContext.h:3417
void setManglingNumber(const NamedDecl *ND, unsigned Number)
llvm::DenseMap< const Decl *, const RawComment * > DeclRawComments
Mapping from declaration to directly attached comment.
Definition: ASTContext.h:876
CanQualType OCLSamplerTy
Definition: ASTContext.h:1197
TypedefDecl * getBuiltinVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_va_list type.
CanQualType VoidTy
Definition: ASTContext.h:1160
CanQualType UnsignedCharTy
Definition: ASTContext.h:1170
CanQualType UnsignedShortFractTy
Definition: ASTContext.h:1177
BuiltinTemplateDecl * buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, const IdentifierInfo *II) const
void * Allocate(size_t Size, unsigned Align=8) const
Definition: ASTContext.h:754
bool canBuiltinBeRedeclared(const FunctionDecl *) const
Return whether a declaration to a builtin is allowed to be overloaded/redeclared.
CanQualType UnsignedIntTy
Definition: ASTContext.h:1170
TemplateName getDependentTemplateName(NestedNameSpecifier *NNS, const IdentifierInfo *Name) const
Retrieve the template name that represents a dependent template name such as MetaFun::template apply.
unsigned NumImplicitMoveConstructors
The number of implicitly-declared move constructors.
Definition: ASTContext.h:3399
QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl, ArrayRef< ObjCProtocolDecl * > protocols) const
QualType getVolatileType(QualType T) const
Return the uniqued reference to the type for a volatile qualified type.
Definition: ASTContext.h:1381
void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, QualType T, std::string &S, bool Extended) const
getObjCEncodingForMethodParameter - Return the encoded type for a single method parameter or return t...
void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD)
unsigned overridden_methods_size(const CXXMethodDecl *Method) const
std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const
Return the encoded type for this block declaration.
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
QualType getExceptionObjectType(QualType T) const
CanQualType UnknownAnyTy
Definition: ASTContext.h:1189
void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
Note that the static data member Inst is an instantiation of the static data member template Tmpl of ...
FieldDecl * getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const
DeclaratorDecl * getDeclaratorForUnnamedTagDecl(const TagDecl *TD)
bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl)
ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's protocol list adopt all protocols in Q...
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1171
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
QualType getCommonSugaredType(QualType X, QualType Y, bool Unqualified=false)
CanQualType OCLReserveIDTy
Definition: ASTContext.h:1198
bool isSameTemplateParameter(const NamedDecl *X, const NamedDecl *Y) const
Determine whether two template parameters are similar enough that they may be used in declarations of...
void registerSYCLEntryPointFunction(FunctionDecl *FD)
Generates and stores SYCL kernel metadata for the provided SYCL kernel entry point function.
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
overridden_cxx_method_iterator overridden_methods_begin(const CXXMethodDecl *Method) const
CanQualType UnsignedShortTy
Definition: ASTContext.h:1170
unsigned getTypeAlignIfKnown(QualType T, bool NeedsPreferredAlignment=false) const
Return the alignment of a type, in bits, or 0 if the type is incomplete and we cannot determine the a...
void UnwrapSimilarArrayTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true) const
Attempt to unwrap two types that may both be array types with the same bound (or both be array types ...
bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1681
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
const SYCLKernelInfo & getSYCLKernelInfo(QualType T) const
Given a type used as a SYCL kernel name, returns a reference to the metadata generated from the corre...
bool canAssignObjCInterfacesInBlockPointer(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT, bool BlockReturnType)
canAssignObjCInterfacesInBlockPointer - This routine is specifically written for providing type-safet...
CanQualType SatUnsignedLongFractTy
Definition: ASTContext.h:1183
const CXXConstructorDecl * getCopyConstructorForExceptionObject(CXXRecordDecl *RD)
QualType getDependentAddressSpaceType(QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttrLoc) const
QualType getPackIndexingType(QualType Pattern, Expr *IndexExpr, bool FullySubstituted=false, ArrayRef< QualType > Expansions={}, int Index=-1) const
RawComment * getRawCommentForDeclNoCache(const Decl *D) const
Return the documentation comment attached to a given declaration, without looking into cache.
Definition: ASTContext.cpp:313
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
const VariableArrayType * getAsVariableArrayType(QualType T) const
Definition: ASTContext.h:2925
QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType, UnaryTransformType::UTTKind UKind) const
Unary type transforms.
void setExternalSource(IntrusiveRefCntPtr< ExternalASTSource > Source)
Attach an external AST source to the AST context.
Definition: ASTContext.cpp:990
const ObjCInterfaceDecl * getObjContainingInterface(const NamedDecl *ND) const
Returns the Objective-C interface that ND belongs to if it is an Objective-C method/property/ivar etc...
CanQualType ShortTy
Definition: ASTContext.h:1169
StringLiteral * getPredefinedStringLiteralFromCache(StringRef Key) const
Return a string representing the human readable name for the specified function declaration or file n...
bool hasSimilarType(QualType T1, QualType T2) const
Determine if two types are similar, according to the C++ rules.
llvm::APFixedPoint getFixedPointMax(QualType Ty) const
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type.
bool areCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an SVE builtin and a VectorType that is a fixed-length representat...
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
CanQualType FractTy
Definition: ASTContext.h:1176
Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const
Recurses in pointer/array types until it finds an Objective-C retainable type and returns its ownersh...
void addCopyConstructorForExceptionObject(CXXRecordDecl *RD, CXXConstructorDecl *CD)
DiagnosticsEngine & getDiagnostics() const
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
void ResetObjCLayout(const ObjCContainerDecl *CD)
CanQualType LongAccumTy
Definition: ASTContext.h:1174
interp::Context & getInterpContext()
Returns the clang bytecode interpreter context.
Definition: ASTContext.cpp:887
CanQualType Char32Ty
Definition: ASTContext.h:1168
UnnamedGlobalConstantDecl * getUnnamedGlobalConstantDecl(QualType Ty, const APValue &Value) const
Return a declaration for a uniquified anonymous global constant corresponding to a given APValue.
CanQualType SatFractTy
Definition: ASTContext.h:1181
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec)
Return true if the given vector types are of the same unqualified type or if they are equivalent to t...
void getOverriddenMethods(const NamedDecl *Method, SmallVectorImpl< const NamedDecl * > &Overridden) const
Return C++ or ObjC overridden methods for the given Method.
DeclarationNameInfo getNameForTemplate(TemplateName Name, SourceLocation NameLoc) const
bool hasSameTemplateName(const TemplateName &X, const TemplateName &Y, bool IgnoreDeduced=false) const
Determine whether the given template names refer to the same template.
CanQualType SatLongFractTy
Definition: ASTContext.h:1181
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:799
void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl)
CanQualType OCLQueueTy
Definition: ASTContext.h:1198
CanQualType LongFractTy
Definition: ASTContext.h:1176
CanQualType SatShortAccumTy
Definition: ASTContext.h:1178
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CanQualType BFloat16Ty
Definition: ASTContext.h:1185
unsigned NumImplicitCopyConstructors
The number of implicitly-declared copy constructors.
Definition: ASTContext.h:3392
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType IncompleteMatrixIdxTy
Definition: ASTContext.h:1199
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
CanQualType getNSIntegerType() const
QualType getCorrespondingUnsignedType(QualType T) const
void setBlockVarCopyInit(const VarDecl *VD, Expr *CopyExpr, bool CanThrow)
Set the copy initialization expression of a block var decl.
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const
Retrieve the template name that corresponds to a non-empty lookup.
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
TemplateName getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack, Decl *AssociatedDecl, unsigned Index, bool Final) const
TargetCXXABI::Kind getCXXABIKind() const
Return the C++ ABI kind that should be used.
Definition: ASTContext.cpp:861
QualType getHLSLAttributedResourceType(QualType Wrapped, QualType Contained, const HLSLAttributedResourceType::Attributes &Attrs)
bool UnwrapSimilarTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true) const
Attempt to unwrap two types that may be similar (C++ [conv.qual]).
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
Definition: ASTContext.h:1274
uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const
Return number of constant array elements.
BuiltinTemplateDecl * getTypePackElementDecl() const
CanQualType SatUnsignedLongAccumTy
Definition: ASTContext.h:1180
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
CanQualType LongLongTy
Definition: ASTContext.h:1169
QualType getTypeOfType(QualType QT, TypeOfKind Kind) const
getTypeOfType - Unlike many "get<Type>" functions, we don't unique TypeOfType nodes.
QualType getCorrespondingSignedType(QualType T) const
QualType mergeObjCGCQualifiers(QualType, QualType)
mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 'RHS' attributes and ret...
llvm::DenseMap< const Decl *, const Decl * > CommentlessRedeclChains
Keeps track of redeclaration chains that don't have any comment attached.
Definition: ASTContext.h:892
uint64_t getArrayInitLoopExprElementCount(const ArrayInitLoopExpr *AILE) const
Return number of elements initialized in an ArrayInitLoopExpr.
void deduplicateMergedDefinitonsFor(NamedDecl *ND)
Clean up the merged definition list.
unsigned getTargetAddressSpace(LangAS AS) const
QualType getWideCharType() const
Return the type of wide characters.
Definition: ASTContext.h:1927
QualType getIntPtrType() const
Return a type compatible with "intptr_t" (C99 7.18.1.4), as defined by the target.
void mergeDefinitionIntoModule(NamedDecl *ND, Module *M, bool NotifyListeners=true)
Note that the definition ND has been merged into module M, and should be visible whenever M is visibl...
void addTranslationUnitDecl()
Definition: ASTContext.h:1144
CanQualType WCharTy
Definition: ASTContext.h:1163
void getObjCEncodingForPropertyType(QualType T, std::string &S) const
Emit the Objective-C property type encoding for the given type T into S.
unsigned NumImplicitCopyAssignmentOperators
The number of implicitly-declared copy assignment operators.
Definition: ASTContext.h:3406
void CollectInheritedProtocols(const Decl *CDecl, llvm::SmallPtrSet< ObjCProtocolDecl *, 8 > &Protocols)
CollectInheritedProtocols - Collect all protocols in current class and those inherited by it.
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
llvm::DenseMap< const Decl *, const Decl * > RedeclChainComments
Mapping from canonical declaration to the first redeclaration in chain that has a comment attached.
Definition: ASTContext.h:883
CanQualType getSignedSizeType() const
Return the unique signed counterpart of the integer type corresponding to size_t.
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const
Return the uniqued reference to the type for an Objective-C gc-qualified type.
QualType getDecltypeType(Expr *e, QualType UnderlyingType) const
C++11 decltype.
NestedNameSpecifier * getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const
Retrieves the "canonical" nested name specifier for a given nested name specifier.
QualType getTypedefType(const TypedefNameDecl *Decl, QualType Underlying=QualType()) const
Return the unique reference to the type for the specified typedef-name decl.
InlineVariableDefinitionKind getInlineVariableDefinitionKind(const VarDecl *VD) const
Determine whether a definition of this inline variable should be treated as a weak or strong definiti...
CanQualType getUIntMaxType() const
Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in <stdint.h>.
uint16_t getPointerAuthVTablePointerDiscriminator(const CXXRecordDecl *RD)
Return the "other" discriminator used for the pointer auth schema used for vtable pointers in instanc...
CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const
Loading virtual member pointers using the virtual inheritance model always results in an adjustment u...
LangAS getLangASForBuiltinAddressSpace(unsigned AS) const
bool hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U)
Determine whether two function types are the same, ignoring pointer sizes in the return type and para...
unsigned char getFixedPointScale(QualType Ty) const
QualType getIncompleteArrayType(QualType EltTy, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a unique reference to the type for an incomplete array of the specified element type.
QualType getDependentSizedExtVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc) const
QualType DecodeTypeStr(const char *&Str, const ASTContext &Context, ASTContext::GetBuiltinTypeError &Error, bool &RequireICE, bool AllowTypeModifiers) const
TemplateName getAssumedTemplateName(DeclarationName Name) const
Retrieve a template name representing an unqualified-id that has been assumed to name a template for ...
@ GE_None
No error.
Definition: ASTContext.h:2391
@ GE_Missing_stdio
Missing a type from <stdio.h>
Definition: ASTContext.h:2397
@ GE_Missing_type
Missing a type.
Definition: ASTContext.h:2394
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
Definition: ASTContext.h:2403
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
Definition: ASTContext.h:2400
QualType adjustStringLiteralBaseType(QualType StrLTy) const
uint16_t getPointerAuthTypeDiscriminator(QualType T)
Return the "other" type-specific discriminator for the given type.
QualType getTypeOfExprType(Expr *E, TypeOfKind Kind) const
C23 feature and GCC extension.
CanQualType Char8Ty
Definition: ASTContext.h:1166
QualType getSignedWCharType() const
Return the type of "signed wchar_t".
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
bool hasCvrSimilarType(QualType T1, QualType T2)
Determine if two types are similar, ignoring only CVR qualifiers.
TemplateName getDeducedTemplateName(TemplateName Underlying, DefaultArguments DefaultArgs) const
Represents a TemplateName which had some of its default arguments deduced.
ObjCImplementationDecl * getObjCImplementation(ObjCInterfaceDecl *D)
Get the implementation of the ObjCInterfaceDecl D, or nullptr if none exists.
CanQualType HalfTy
Definition: ASTContext.h:1184
CanQualType UnsignedAccumTy
Definition: ASTContext.h:1175
void setObjCMethodRedeclaration(const ObjCMethodDecl *MD, const ObjCMethodDecl *Redecl)
void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND)
QualType getConstantMatrixType(QualType ElementType, unsigned NumRows, unsigned NumColumns) const
Return the unique reference to the matrix type of the specified element type and size.
QualType getVariableArrayDecayedType(QualType Ty) const
Returns a vla type where known sizes are replaced with [*].
bool isInSameModule(const Module *M1, const Module *M2)
If the two module M1 and M2 are in the same module.
void setCFConstantStringType(QualType T)
const SYCLKernelInfo * findSYCLKernelInfo(QualType T) const
Returns a pointer to the metadata generated from the corresponding SYCLkernel entry point if the prov...
unsigned getParameterIndex(const ParmVarDecl *D) const
Used by ParmVarDecl to retrieve on the side the index of the parameter when it exceeds the size of th...
CanQualType OCLEventTy
Definition: ASTContext.h:1197
void AddDeallocation(void(*Callback)(void *), void *Data) const
Add a deallocation callback that will be invoked when the ASTContext is destroyed.
Definition: ASTContext.cpp:985
AttrVec & getDeclAttrs(const Decl *D)
Retrieve the attributes for the given declaration.
CXXMethodVector::const_iterator overridden_cxx_method_iterator
Definition: ASTContext.h:1053
RawComment * getRawCommentForDeclNoCacheImpl(const Decl *D, const SourceLocation RepresentativeLocForDecl, const std::map< unsigned, RawComment * > &CommentsInFile) const
Definition: ASTContext.cpp:235
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
Definition: ASTContext.h:2520
QualType mergeTransparentUnionType(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false)
mergeTransparentUnionType - if T is a transparent union type and a member of T is compatible with Sub...
QualType isPromotableBitField(Expr *E) const
Whether this is a promotable bitfield reference according to C99 6.3.1.1p2, bullet 2 (and GCC extensi...
bool isSentinelNullExpr(const Expr *E)
CanQualType getNSUIntegerType() const
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2493
QualType getBitIntType(bool Unsigned, unsigned NumBits) const
Return a bit-precise integer type with the specified signedness and bit count.
unsigned NumImplicitMoveAssignmentOperators
The number of implicitly-declared move assignment operators.
Definition: ASTContext.h:3413
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
virtual void AddedStaticLocalNumbers(const Decl *D, unsigned Number)
An static local number was added to a Decl.
virtual void RedefinedHiddenDefinition(const NamedDecl *D, Module *M)
A definition has been made visible by being redefined locally.
virtual void AddedManglingNumber(const Decl *D, unsigned Number)
An mangling number was added to a Decl.
virtual void DeducedReturnType(const FunctionDecl *FD, QualType ReturnType)
A function's return type has been deduced.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
CharUnits getAlignment() const
getAlignment - Get the record alignment in characters.
Definition: RecordLayout.h:182
const CXXRecordDecl * getBaseSharingVBPtr() const
Definition: RecordLayout.h:329
CharUnits getSize() const
getSize - Get the record size in characters.
Definition: RecordLayout.h:193
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:200
CharUnits getDataSize() const
getDataSize() - Get the record data size, which is the record size without tail padding,...
Definition: RecordLayout.h:206
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:249
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:259
CharUnits getNonVirtualSize() const
getNonVirtualSize - Get the non-virtual size (in chars) of an object, which is the size of the object...
Definition: RecordLayout.h:210
CharUnits getUnadjustedAlignment() const
getUnadjustedAlignment - Get the record alignment in characters, before alignment adjustement.
Definition: RecordLayout.h:190
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition: Type.h:3358
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3377
Represents a loop initializing the elements of an array.
Definition: Expr.h:5752
llvm::APInt getArraySize() const
Definition: Expr.h:5774
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition: Expr.h:5772
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition: Type.h:3748
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3578
ArraySizeModifier getSizeModifier() const
Definition: Type.h:3592
Qualifiers getIndexTypeQualifiers() const
Definition: Type.h:3596
QualType getElementType() const
Definition: Type.h:3590
unsigned getIndexTypeCVRQualifiers() const
Definition: Type.h:3600
A structure for storing the information associated with a name that has been assumed to be a template...
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition: Expr.h:6678
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:7767
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7772
Attr - This represents one attribute.
Definition: Attr.h:43
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:6133
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6205
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:6562
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.cpp:5202
bool isConstrained() const
Definition: Type.h:6581
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6242
A fixed int type of a specified bitwidth.
Definition: Type.h:7820
void Profile(llvm::FoldingSetNodeID &ID) const
Definition: Type.h:7837
unsigned getNumBits() const
Definition: Type.h:7832
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4496
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6414
Pointer to a block type.
Definition: Type.h:3409
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3426
Represents the builtin template declaration which is used to implement __make_integer_seq and other b...
static BuiltinTemplateDecl * Create(const ASTContext &C, DeclContext *DC, DeclarationName Name, BuiltinTemplateKind BTK)
This class is used for builtin types like 'int'.
Definition: Type.h:3035
Kind getKind() const
Definition: Type.h:3083
StringRef getName(const PrintingPolicy &Policy) const
Definition: Type.cpp:3326
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition: Builtins.h:85
const char * getTypeString(unsigned ID) const
Get the type descriptor string for the specified builtin.
Definition: Builtins.h:109
bool hasCustomTypechecking(unsigned ID) const
Determines whether this builtin has custom typechecking.
Definition: Builtins.h:197
bool canBeRedeclared(unsigned ID) const
Returns true if this is a builtin that can be redeclared.
Definition: Builtins.cpp:246
bool isNoReturn(unsigned ID) const
Return true if we know this builtin never returns.
Definition: Builtins.h:133
bool isNoThrow(unsigned ID) const
Return true if we know this builtin never throws an exception.
Definition: Builtins.h:128
Implements C++ ABI-specific semantic analysis functions.
Definition: CXXABI.h:29
virtual ~CXXABI()
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2553
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2078
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2174
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition: DeclCXX.h:1226
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr, bool DelayTypeCreation=false)
Definition: DeclCXX.cpp:132
bool isDynamicClass() const
Definition: DeclCXX.h:586
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition: DeclCXX.h:1198
SplitQualType split() const
static CanQual< Type > CreateUnsafe(QualType Other)
Builds a canonical type from a QualType.
QualType withConst() const
Retrieves a version of this type with const applied.
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
bool isNull() const
Definition: CanonicalType.h:98
Qualifiers getQualifiers() const
Retrieve all qualifiers.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:84
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
bool isPositive() const
isPositive - Test whether the quantity is greater than zero.
Definition: CharUnits.h:128
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:53
Declaration of a class template.
llvm::PointerUnion< ClassTemplateDecl *, ClassTemplatePartialSpecializationDecl * > getSpecializedTemplateOrPartial() const
Retrieve the class template or class template partial specialization which was specialized by this.
Complex values, per C99 6.2.5p11.
Definition: Type.h:3146
QualType getElementType() const
Definition: Type.h:3156
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3161
Declaration of a C++20 concept.
ConceptDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
bool hasExplicitTemplateArgs() const
Whether or not template arguments were explicitly specified in the concept reference (they might not ...
Definition: ASTConcept.h:209
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Definition: ASTConcept.h:203
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3616
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition: Type.h:3712
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3672
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.h:3731
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition: Type.h:3692
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:4233
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition: Type.h:4254
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4271
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition: Type.h:4251
static constexpr bool isDimensionValid(size_t NumElements)
Returns true if NumElements is a valid matrix dimension.
Definition: Type.h:4262
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition: Type.h:3307
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3343
Represents a pointer type decayed from an array or function type.
Definition: Type.h:3392
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1439
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2104
bool isFileContext() const
Definition: DeclBase.h:2175
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1345
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:2120
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1866
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:2010
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1780
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1054
const DeclContext * getParentFunctionOrMethod(bool LexicalParent=false) const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext,...
Definition: DeclBase.cpp:322
T * getAttr() const
Definition: DeclBase.h:576
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:528
void addAttr(Attr *A)
Definition: DeclBase.cpp:1019
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:596
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition: DeclBase.cpp:542
static Decl * castFromDeclContext(const DeclContext *)
Definition: DeclBase.cpp:1047
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition: DeclBase.cpp:289
bool isCanonicalDecl() const
Whether this particular Decl is a canonical one.
Definition: DeclBase.h:977
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:254
ObjCDeclQualifier
ObjCDeclQualifier - 'Qualifiers' written next to the return and parameter types in method declaration...
Definition: DeclBase.h:198
@ OBJC_TQ_Byref
Definition: DeclBase.h:204
@ OBJC_TQ_Oneway
Definition: DeclBase.h:205
@ OBJC_TQ_Bycopy
Definition: DeclBase.h:203
@ OBJC_TQ_None
Definition: DeclBase.h:199
@ OBJC_TQ_Inout
Definition: DeclBase.h:201
bool isInvalidDecl() const
Definition: DeclBase.h:591
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:562
SourceLocation getLocation() const
Definition: DeclBase.h:442
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition: DeclBase.cpp:237
void setImplicit(bool I=true)
Definition: DeclBase.h:597
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: DeclBase.h:1042
DeclContext * getDeclContext()
Definition: DeclBase.h:451
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:434
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:363
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:911
bool hasAttr() const
Definition: DeclBase.h:580
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:971
Kind getKind() const
Definition: DeclBase.h:445
DeclarationNameLoc - Additional source/type location info for a declaration name.
static DeclarationNameLoc makeCXXOperatorNameLoc(SourceLocation BeginLoc, SourceLocation EndLoc)
Construct location information for a non-literal C++ operator.
DeclarationName getIdentifier(const IdentifierInfo *ID)
Create a declaration name that is a simple identifier.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
The name of a declaration.
static int compare(DeclarationName LHS, DeclarationName RHS)
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:735
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:764
Represents the type decltype(expr) (C++11).
Definition: Type.h:5880
Represents a C++17 deduced template specialization type.
Definition: Type.h:6610
void Profile(llvm::FoldingSetNodeID &ID) const
Definition: Type.h:6631
TemplateName getUnderlying() const
Definition: TemplateName.h:458
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) const
DefaultArguments getDefaultArguments() const
Definition: TemplateName.h:460
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:6528
Represents an extended address space qualifier where the input address space value is dependent.
Definition: Type.h:3921
Expr * getAddrSpaceExpr() const
Definition: Type.h:3932
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:3943
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:7865
Internal representation of canonical, dependent decltype(expr) types.
Definition: Type.h:5908
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:5912
Represents a qualified type name for which the type name is dependent.
Definition: Type.h:7030
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7062
Represents an array type in C++ whose size is a value-dependent expression.
Definition: Type.h:3863
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:3900
Expr * getSizeExpr() const
Definition: Type.h:3883
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3961
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:3986
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition: Type.h:4292
Expr * getRowExpr() const
Definition: Type.h:4304
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:4312
Represents a dependent template name that cannot be resolved prior to template instantiation.
Definition: TemplateName.h:548
OverloadedOperatorKind getOperator() const
Return the overloaded operator to which this template name refers.
Definition: TemplateName.h:620
bool isIdentifier() const
Determine whether this template name refers to an identifier.
Definition: TemplateName.h:607
const IdentifierInfo * getIdentifier() const
Returns the identifier to which this template name refers.
Definition: TemplateName.h:610
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TemplateName.h:626
Represents a template specialization type whose template cannot be resolved, e.g.
Definition: Type.h:7082
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:7109
Internal representation of canonical, dependent typeof(expr) types.
Definition: Type.h:5837
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:5842
Internal representation of canonical, dependent __underlying_type(type) types.
Definition: Type.h:6038
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6043
Represents a vector type where either the type or size is dependent.
Definition: Type.h:4087
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:4112
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:231
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1493
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition: Diagnostic.h:896
Wrap a function effect's condition expression in another struct so that FunctionProtoType's TrailingO...
Definition: Type.h:4829
Represents a type that was referred to using an elaborated type keyword, e.g., struct S,...
Definition: Type.h:6949
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7002
Represents an enum.
Definition: Decl.h:3861
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4066
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:4080
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4021
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:4981
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:6104
EnumDecl * getDecl() const
Definition: Type.h:6111
This represents one expression.
Definition: Expr.h:110
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3102
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:437
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition: Expr.cpp:4131
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:826
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition: Expr.h:221
bool isIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3077
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition: Expr.cpp:3970
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
QualType getType() const
Definition: Expr.h:142
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition: Expr.h:427
We can encode up to four bits in the low bits of a type pointer, but there are many more type qualifi...
Definition: Type.h:1703
void Profile(llvm::FoldingSetNodeID &ID) const
Definition: Type.h:1750
ExtVectorType - Extended vector type.
Definition: Type.h:4127
Declaration context for names declared as extern "C" in C++.
Definition: Decl.h:226
static ExternCContextDecl * Create(const ASTContext &C, TranslationUnitDecl *TU)
Definition: Decl.cpp:5377
Abstract interface for external sources of AST nodes.
virtual ExtKind hasExternalDefinitions(const Decl *D)
virtual void ReadComments()
Loads comment ranges.
virtual void CompleteRedeclChain(const Decl *D)
Gives the external AST source an opportunity to complete the redeclaration chain for a declaration.
virtual void PrintStats()
Print any statistics that have been gathered regarding the external AST source.
Represents a member of a struct/union/class.
Definition: Decl.h:3033
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3136
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition: Decl.cpp:4620
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.h:3118
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3264
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition: Decl.cpp:4573
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Represents a function declaration or definition.
Definition: Decl.h:1935
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2565
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3653
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2796
bool isMSExternInline() const
The combination of the extern and inline keywords under MSVC forces the function to be required.
Definition: Decl.cpp:3782
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4292
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition: Decl.h:2338
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4039
bool isInlineDefinitionExternallyVisible() const
For an inline function definition in C, or for a gnu_inline function in C++, determine whether the de...
Definition: Decl.cpp:3952
static FunctionEffectSet getIntersection(FunctionEffectsRef LHS, FunctionEffectsRef RHS)
Definition: Type.cpp:5333
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition: Type.cpp:5371
Represents an abstract function effect, using just an enumeration describing its kind.
Definition: Type.h:4722
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition: Type.h:4909
size_t size() const
Definition: Type.h:4940
ArrayRef< EffectConditionExpr > conditions() const
Definition: Type.h:4943
bool empty() const
Definition: Type.h:4939
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition: Type.h:4687
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4703
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5108
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:5574
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:5388
unsigned getNumParams() const
Definition: Type.h:5361
QualType getParamType(unsigned i) const
Definition: Type.h:5363
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.cpp:3865
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:5394
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5485
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5372
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5368
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition: Type.h:5550
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition: Type.h:5546
Declaration of a template function.
Definition: DeclTemplate.h:958
A class which abstracts out some details necessary for making a call.
Definition: Type.h:4433
CallingConv getCC() const
Definition: Type.h:4495
bool getNoCfCheck() const
Definition: Type.h:4485
unsigned getRegParm() const
Definition: Type.h:4488
bool getNoCallerSavedRegs() const
Definition: Type.h:4484
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4507
bool getHasRegParm() const
Definition: Type.h:4486
bool getNoReturn() const
Definition: Type.h:4481
bool getProducesResult() const
Definition: Type.h:4482
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition: Type.h:4348
ExtParameterInfo withIsNoEscape(bool NoEscape) const
Definition: Type.h:4388
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4322
ExtInfo getExtInfo() const
Definition: Type.h:4661
QualType getReturnType() const
Definition: Type.h:4649
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:56
unsigned getMultiVersionIndex() const
Definition: GlobalDecl.h:122
CXXDtorType getDtorType() const
Definition: GlobalDecl.h:110
const Decl * getDecl() const
Definition: GlobalDecl.h:103
QualType getWrappedType() const
Definition: Type.h:6299
const Attributes & getAttrs() const
Definition: Type.h:6302
QualType getContainedType() const
Definition: Type.h:6300
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6307
One of these records is kept for each identifier that is lexed.
unsigned getLength() const
Efficiently return the length of this identifier info.
StringRef getName() const
Return the actual identifier string.
Implements an efficient mapping from strings to IdentifierInfo nodes.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition: Decl.h:4885
Represents a C array with an unspecified size.
Definition: Type.h:3765
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3782
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:6799
static ItaniumMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
@ Relative
Components in the vtable are relative offsets between the vtable and the other structs/functions.
@ Pointer
Components in the vtable are pointers to other structs/functions.
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3484
@ Swift
Interoperability with the latest known version of the Swift runtime.
@ Swift4_2
Interoperability with the Swift 4.2 runtime.
@ Swift4_1
Interoperability with the Swift 4.1 runtime.
@ Integer
Permit vector bitcasts between integer vectors with different numbers of elements but the same total ...
@ All
Permit vector bitcasts between all vectors with the same total bit-width.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:500
std::optional< TargetCXXABI::Kind > CXXABI
C++ ABI to compile with, if specified by the frontend through -fc++-abi=.
Definition: LangOptions.h:588
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:535
CoreFoundationABI CFRuntime
Definition: LangOptions.h:537
CommentOptions CommentOpts
Options for parsing comments.
Definition: LangOptions.h:564
std::string CUID
The user provided compilation unit ID, if non-empty.
Definition: LangOptions.h:584
A global _GUID constant.
Definition: DeclCXX.h:4312
static void Profile(llvm::FoldingSetNodeID &ID, Parts P)
Definition: DeclCXX.h:4349
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition: Type.h:5771
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
Definition: Mangle.h:45
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition: Type.h:4211
static bool isValidElementType(QualType T)
Valid elements types are the following:
Definition: Type.h:4218
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3520
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3556
QualType getPointeeType() const
Definition: Type.h:3536
const Type * getClass() const
Definition: Type.h:3550
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:619
static MicrosoftMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
Describes a module or submodule.
Definition: Module.h:115
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition: Module.h:195
This represents a decl that may have a name.
Definition: Decl.h:253
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:274
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition: Decl.cpp:1089
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:319
std::string getNameAsString() const
Get a human-readable name for the declaration, even if it is one of the special kinds of names (C++ c...
Definition: Decl.h:296
bool isExternallyVisible() const
Definition: Decl.h:412
NamespaceDecl * getNamespace()
Retrieve the namespace declaration aliased by this directive.
Definition: DeclCXX.h:3215
Represent a C++ namespace.
Definition: Decl.h:551
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl, bool Nested)
Definition: DeclCXX.cpp:3130
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, const IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
NamespaceAliasDecl * getAsNamespaceAlias() const
Retrieve the namespace alias stored in this nested name specifier.
IdentifierInfo * getAsIdentifier() const
Retrieve the identifier stored in this nested name specifier.
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
@ NamespaceAlias
A namespace alias, stored as a NamespaceAliasDecl*.
@ TypeSpec
A type, stored as a Type*.
@ TypeSpecWithTemplate
A type that was preceded by the 'template' keyword, stored as a Type*.
@ Super
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Identifier
An identifier, stored as an IdentifierInfo*.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace, stored as a NamespaceDecl*.
NamespaceDecl * getAsNamespace() const
Retrieve the namespace stored in this nested name specifier.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, unsigned D, unsigned P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
Helper data structure representing the traits in a match clause of an declare variant or metadirectiv...
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:2328
ObjCCategoryImplDecl - An object of this class encapsulates a category @implementation declaration.
Definition: DeclObjC.h:2544
ObjCContainerDecl - Represents a container for method declarations.
Definition: DeclObjC.h:947
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2596
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
ObjCTypeParamList * getTypeParamList() const
Retrieve the type parameters of this class.
Definition: DeclObjC.cpp:320
static ObjCInterfaceDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation atLoc, const IdentifierInfo *Id, ObjCTypeParamList *typeParamList, ObjCInterfaceDecl *PrevDecl, SourceLocation ClassLoc=SourceLocation(), bool isInternal=false)
Definition: DeclObjC.cpp:1540
bool hasDefinition() const
Determine whether this class has been defined.
Definition: DeclObjC.h:1527
ivar_range ivars() const
Definition: DeclObjC.h:1450
bool ClassImplementsProtocol(ObjCProtocolDecl *lProto, bool lookupCategory, bool RHSIsQualifiedID=false)
ClassImplementsProtocol - Checks that 'lProto' protocol has been implemented in IDecl class,...
Definition: DeclObjC.cpp:1786
StringRef getObjCRuntimeNameAsString() const
Produce a name to be used for class's metadata.
Definition: DeclObjC.cpp:1611
ObjCImplementationDecl * getImplementation() const
Definition: DeclObjC.cpp:1627
ObjCInterfaceDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this Objective-C class.
Definition: DeclObjC.h:1914
ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.cpp:350
bool isSuperClassOf(const ObjCInterfaceDecl *I) const
isSuperClassOf - Return true if this class is the specified class or is a super class of the specifie...
Definition: DeclObjC.h:1809
known_extensions_range known_extensions() const
Definition: DeclObjC.h:1761
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:7530
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition: Type.cpp:936
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1951
ObjCIvarDecl * getNextIvar()
Definition: DeclObjC.h:1986
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: DeclObjC.h:246
unsigned param_size() const
Definition: DeclObjC.h:347
param_const_iterator param_end() const
Definition: DeclObjC.h:358
param_const_iterator param_begin() const
Definition: DeclObjC.h:354
bool isVariadic() const
Definition: DeclObjC.h:431
const ParmVarDecl *const * param_const_iterator
Definition: DeclObjC.h:349
Selector getSelector() const
Definition: DeclObjC.h:327
bool isInstanceMethod() const
Definition: DeclObjC.h:426
QualType getReturnType() const
Definition: DeclObjC.h:329
Represents a pointer to an Objective C object.
Definition: Type.h:7586
bool isObjCQualifiedClassType() const
True if this is equivalent to 'Class.
Definition: Type.h:7667
const ObjCObjectPointerType * stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const
Strip off the Objective-C "kindof" type and (with it) any protocol qualifiers.
Definition: Type.cpp:943
bool isObjCQualifiedIdType() const
True if this is equivalent to 'id.
Definition: Type.h:7661
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7743
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:7623
bool qual_empty() const
Definition: Type.h:7715
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition: Type.h:7644
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:7598
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition: Type.h:7638
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1833
qual_range quals() const
Definition: Type.h:7705
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition: Type.h:7650
A class providing a concrete implementation of ObjCObjectType, so as to not increase the footprint of...
Definition: Type.h:7483
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:4448
Represents a class type in Objective C.
Definition: Type.h:7332
bool isKindOfTypeAsWritten() const
Whether this is a "__kindof" type as written.
Definition: Type.h:7447
bool isSpecialized() const
Determine whether this object type is "specialized", meaning that it has type arguments.
Definition: Type.cpp:865
ArrayRef< QualType > getTypeArgsAsWritten() const
Retrieve the type arguments of this object type as they were written.
Definition: Type.h:7442
bool isObjCQualifiedClass() const
Definition: Type.h:7414
QualType getBaseType() const
Gets the base type of this object type.
Definition: Type.h:7394
bool isObjCClass() const
Definition: Type.h:7400
bool isKindOfType() const
Whether this ia a "__kindof" type (semantically).
Definition: Type.cpp:901
bool isObjCQualifiedId() const
Definition: Type.h:7413
ArrayRef< QualType > getTypeArgs() const
Retrieve the type arguments of this object type (semantically).
Definition: Type.cpp:883
bool isObjCUnqualifiedId() const
Definition: Type.h:7404
ObjCInterfaceDecl * getInterface() const
Gets the interface declaration for this object type, if the base type really is an interface.
Definition: Type.h:7565
QualType getSuperClassType() const
Retrieve the type of the superclass of this object type.
Definition: Type.h:7458
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:730
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
Definition: DeclObjC.h:837
static ObjCPropertyDecl * findPropertyDecl(const DeclContext *DC, const IdentifierInfo *propertyID, ObjCPropertyQueryKind queryKind)
Lookup a property by name in the specified DeclContext.
Definition: DeclObjC.cpp:177
bool isOptional() const
Definition: DeclObjC.h:915
SetterKind getSetterKind() const
getSetterKind - Return the method used for doing assignment in the property setter.
Definition: DeclObjC.h:872
Selector getSetterName() const
Definition: DeclObjC.h:892
QualType getType() const
Definition: DeclObjC.h:803
Selector getGetterName() const
Definition: DeclObjC.h:884
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition: DeclObjC.h:814
ObjCPropertyImplDecl - Represents implementation declaration of a property in a class or category imp...
Definition: DeclObjC.h:2804
ObjCIvarDecl * getPropertyIvarDecl() const
Definition: DeclObjC.h:2878
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2083
protocol_range protocols() const
Definition: DeclObjC.h:2160
unsigned getNumProtocols() const
Return the number of qualifying protocols in this type, or 0 if there are none.
Definition: Type.h:7238
qual_iterator qual_end() const
Definition: Type.h:7232
qual_iterator qual_begin() const
Definition: Type.h:7231
qual_range quals() const
Definition: Type.h:7230
bool isGNUFamily() const
Is this runtime basically of the GNU family of runtimes?
Definition: ObjCRuntime.h:127
Represents the declaration of an Objective-C type parameter.
Definition: DeclObjC.h:578
ObjCTypeParamVariance getVariance() const
Determine the variance of this type parameter.
Definition: DeclObjC.h:623
Stores a list of Objective-C type parameters for a parameterized class or a category/extension thereo...
Definition: DeclObjC.h:659
Represents a type parameter type in Objective C.
Definition: Type.h:7258
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:4465
A structure for storing the information associated with an overloaded template name.
Definition: TemplateName.h:116
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition: ExprCXX.h:4180
Represents a pack expansion of types.
Definition: Type.h:7147
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7181
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5974
Sugar for parentheses used when specifying types.
Definition: Type.h:3173
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3187
void clear()
Clear parent maps.
Represents a parameter to a function.
Definition: Decl.h:1725
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: Decl.h:1789
QualType getOriginalType() const
Definition: Decl.cpp:2931
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:129
PipeType - OpenCL20.
Definition: Type.h:7786
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7803
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3199
QualType getPointeeType() const
Definition: Type.h:3209
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3214
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:138
A (possibly-)qualified type.
Definition: Type.h:929
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:8021
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2794
Qualifiers::GC getObjCGCAttr() const
Returns gc attribute of this type.
Definition: Type.h:8068
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:8026
QualType withConst() const
Definition: Type.h:1154
bool hasLocalQualifiers() const
Determine whether this particular QualType instance has any qualifiers, without looking through any t...
Definition: Type.h:1056
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:996
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7937
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:8063
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7977
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1433
QualType getCanonicalType() const
Definition: Type.h:7989
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:8031
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition: Type.h:7958
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:8010
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1531
bool isCanonical() const
Definition: Type.h:7994
const Type * getTypePtrOrNull() const
Definition: Type.h:7941
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1327
PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const
Check if this is a non-trivial type that would cause a C struct transitively containing this type to ...
Definition: Type.cpp:2931
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:7969
Represents a template name as written in source code.
Definition: TemplateName.h:491
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TemplateName.h:528
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:7877
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:7884
The collection of all-type qualifiers we support.
Definition: Type.h:324
unsigned getCVRQualifiers() const
Definition: Type.h:481
void removeCVRQualifiers(unsigned mask)
Definition: Type.h:488
GC getObjCGCAttr() const
Definition: Type.h:512
void addAddressSpace(LangAS space)
Definition: Type.h:590
static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R)
Returns the common set of qualifiers while removing them from the given sets.
Definition: Type.h:377
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:354
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:347
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:343
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:357
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:360
void removeObjCLifetime()
Definition: Type.h:544
bool hasNonFastQualifiers() const
Return true if the set contains any qualifiers which require an ExtQuals node to be allocated.
Definition: Type.h:631
void addConsistentQualifiers(Qualifiers qs)
Add the qualifiers from the given set to this set, given that they don't conflict.
Definition: Type.h:682
void removeFastQualifiers(unsigned mask)
Definition: Type.h:617
bool hasUnaligned() const
Definition: Type.h:504
bool hasAddressSpace() const
Definition: Type.h:563
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B, const ASTContext &Ctx)
Returns true if address space A is equal to or a superset of B.
Definition: Type.h:701
unsigned getFastQualifiers() const
Definition: Type.h:612
void removeAddressSpace()
Definition: Type.h:589
void setAddressSpace(LangAS space)
Definition: Type.h:584
bool hasObjCGCAttr() const
Definition: Type.h:511
uint64_t getAsOpaqueValue() const
Definition: Type.h:448
bool hasObjCLifetime() const
Definition: Type.h:537
ObjCLifetime getObjCLifetime() const
Definition: Type.h:538
bool empty() const
Definition: Type.h:640
void addObjCGCAttr(GC type)
Definition: Type.h:517
LangAS getAddressSpace() const
Definition: Type.h:564
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3502
unsigned getCommentBeginLine(RawComment *C, FileID File, unsigned Offset) const
const std::map< unsigned, RawComment * > * getCommentsInFile(FileID File) const
unsigned getCommentEndOffset(RawComment *C) const
void addComment(const RawComment &RC, const CommentOptions &CommentOpts, llvm::BumpPtrAllocator &Allocator)
bool isTrailingComment() const LLVM_READONLY
Returns true if it is a comment that should be put after a member:
SourceRange getSourceRange() const LLVM_READONLY
bool isDocumentation() const LLVM_READONLY
Returns true if this comment any kind of a documentation comment.
comments::FullComment * parse(const ASTContext &Context, const Preprocessor *PP, const Decl *D) const
Parse the comment, assuming it is attached to decl D.
Represents a struct/union/class.
Definition: Decl.h:4162
bool hasFlexibleArrayMember() const
Definition: Decl.h:4195
field_range fields() const
Definition: Decl.h:4376
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition: Decl.cpp:5059
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition: Decl.cpp:5125
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4361
bool field_empty() const
Definition: Decl.h:4384
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6078
RecordDecl * getDecl() const
Definition: Type.h:6088
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:215
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:203
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:225
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:295
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3440
QualType getPointeeType() const
Definition: Type.h:3458
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3466
This table allows us to fully hide how we implement multi-keyword caching.
std::string getAsString() const
Derive the full selector name (e.g.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
DiagnosticsEngine & getDiagnostics() const
StringRef getBufferData(FileID FID, bool *Invalid=nullptr) const
Return a StringRef to the source buffer data for the specified FileID.
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
unsigned getLineNumber(FileID FID, unsigned FilePos, bool *Invalid=nullptr) const
Given a SourceLocation, return the spelling line number for the position indicated.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
std::pair< FileID, unsigned > getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
The streaming interface shared between DiagnosticBuilder and PartialDiagnostic.
Definition: Diagnostic.h:1102
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1778
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, const SourceLocation *Loc, unsigned NumConcatenated)
This is the "fully general" constructor that allows representation of strings formed from multiple co...
Definition: Expr.cpp:1194
A structure for storing an already-substituted template template parameter pack.
Definition: TemplateName.h:149
Decl * getAssociatedDecl() const
A template-like entity which owns the whole pattern being substituted.
void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context)
TemplateTemplateParmDecl * getParameterPack() const
Retrieve the template template parameter pack being substituted.
TemplateArgument getArgumentPack() const
Retrieve the template template argument pack with which this parameter was substituted.
unsigned getIndex() const
Returns the index of the replaced parameter in the associated declaration.
Definition: TemplateName.h:164
A structure for storing the information associated with a substituted template template parameter.
Definition: TemplateName.h:408
void Profile(llvm::FoldingSetNodeID &ID)
TemplateTemplateParmDecl * getParameter() const
Represents the result of substituting a set of types for a template type parameter pack.
Definition: Type.h:6470
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:4309
Represents the result of substituting a type for a template type parameter.
Definition: Type.h:6389
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6434
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3578
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition: Decl.h:3806
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4780
bool isUnion() const
Definition: Decl.h:3784
TagDecl * getDecl() const
Definition: Type.cpp:4120
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
Kind
The basic C++ ABI kind.
Definition: TargetCXXABI.h:31
static Kind getKind(StringRef Name)
Definition: TargetCXXABI.h:59
Exposes information about the current target.
Definition: TargetInfo.h:220
TargetOptions & getTargetOpts() const
Retrieve the target options.
Definition: TargetInfo.h:311
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1262
IntType getInt64Type() const
Definition: TargetInfo.h:411
unsigned getMaxAtomicInlineWidth() const
Return the maximum width lock-free atomic operation which can be inlined given the supported features...
Definition: TargetInfo.h:844
virtual LangAS getCUDABuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
Definition: TargetInfo.h:1646
virtual LangAS getOpenCLBuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
Definition: TargetInfo.h:1640
unsigned getDefaultAlignForAttributeAligned() const
Return the default alignment for attribute((aligned)) on this target, to be used if no alignment valu...
Definition: TargetInfo.h:737
unsigned getBFloat16Width() const
getBFloat16Width/Align/Format - Return the size/align/format of '__bf16'.
Definition: TargetInfo.h:782
BuiltinVaListKind
The different kinds of __builtin_va_list types defined by the target implementation.
Definition: TargetInfo.h:318
@ AArch64ABIBuiltinVaList
__builtin_va_list as defined by the AArch64 ABI http://infocenter.arm.com/help/topic/com....
Definition: TargetInfo.h:327
@ PNaClABIBuiltinVaList
__builtin_va_list as defined by the PNaCl ABI: http://www.chromium.org/nativeclient/pnacl/bitcode-abi...
Definition: TargetInfo.h:331
@ PowerABIBuiltinVaList
__builtin_va_list as defined by the Power ABI: https://www.power.org /resources/downloads/Power-Arch-...
Definition: TargetInfo.h:336
@ AAPCSABIBuiltinVaList
__builtin_va_list as defined by ARM AAPCS ABI http://infocenter.arm.com
Definition: TargetInfo.h:345
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition: TargetInfo.h:320
@ VoidPtrBuiltinVaList
typedef void* __builtin_va_list;
Definition: TargetInfo.h:323
@ X86_64ABIBuiltinVaList
__builtin_va_list as defined by the x86-64 ABI: http://refspecs.linuxbase.org/elf/x86_64-abi-0....
Definition: TargetInfo.h:340
virtual uint64_t getNullPointerValue(LangAS AddrSpace) const
Get integer value for null pointer.
Definition: TargetInfo.h:494
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:478
static bool isTypeSigned(IntType T)
Returns true if the type is signed; false otherwise.
Definition: TargetInfo.cpp:386
unsigned getHalfAlign() const
Definition: TargetInfo.h:773
unsigned getBFloat16Align() const
Definition: TargetInfo.h:783
FloatModeKind getRealTypeByWidth(unsigned BitWidth, FloatModeKind ExplicitType) const
Return floating point type with specified width.
Definition: TargetInfo.cpp:332
virtual IntType getIntTypeByWidth(unsigned BitWidth, bool IsSigned) const
Return integer type with specified width.
Definition: TargetInfo.cpp:302
unsigned getHalfWidth() const
getHalfWidth/Align/Format - Return the size/align/format of 'half'.
Definition: TargetInfo.h:772
unsigned getMaxAlignedAttribute() const
Get the maximum alignment in bits for a static variable with aligned attribute.
Definition: TargetInfo.h:957
virtual unsigned getMinGlobalAlign(uint64_t Size, bool HasNonWeakDef) const
getMinGlobalAlign - Return the minimum alignment of a global variable, unless its alignment is explic...
Definition: TargetInfo.h:745
unsigned getTargetAddressSpace(LangAS AS) const
Definition: TargetInfo.h:1627
unsigned getFloat128Width() const
getFloat128Width/Align/Format - Return the size/align/format of '__float128'.
Definition: TargetInfo.h:801
const llvm::fltSemantics & getLongDoubleFormat() const
Definition: TargetInfo.h:795
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1333
bool hasAArch64SVETypes() const
Returns whether or not the AArch64 SVE built-in types are available on this target.
Definition: TargetInfo.h:1046
bool useAddressSpaceMapMangling() const
Specify if mangling based on address space map should be used or not for language specific address sp...
Definition: TargetInfo.h:1008
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
Definition: TargetInfo.h:524
unsigned getFloat128Align() const
Definition: TargetInfo.h:802
virtual bool hasBFloat16Type() const
Determine whether the _BFloat16 type is supported on this target.
Definition: TargetInfo.h:709
const llvm::fltSemantics & getFloat128Format() const
Definition: TargetInfo.h:803
unsigned getLongDoubleWidth() const
getLongDoubleWidth/Align/Format - Return the size/align/format of 'long double'.
Definition: TargetInfo.h:793
unsigned getLongDoubleAlign() const
Definition: TargetInfo.h:794
virtual std::optional< std::pair< unsigned, unsigned > > getVScaleRange(const LangOptions &LangOpts) const
Returns target-specific min and max values VScale_Range.
Definition: TargetInfo.h:1026
llvm::StringMap< bool > FeatureMap
The map of which features have been enabled disabled based on the command line.
Definition: TargetOptions.h:62
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
SourceLocation getRAngleLoc() const
Definition: TemplateBase.h:648
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:659
SourceLocation getLAngleLoc() const
Definition: TemplateBase.h:647
A template argument list.
Definition: DeclTemplate.h:250
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:280
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
Represents a template argument.
Definition: TemplateBase.h:61
QualType getStructuralValueType() const
Get the type of a StructuralValue.
Definition: TemplateBase.h:399
QualType getParamTypeForDecl() const
Definition: TemplateBase.h:331
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:408
std::optional< unsigned > getNumTemplateExpansions() const
Retrieve the number of expansions that a template template argument expansion will produce,...
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:319
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
Definition: TemplateBase.h:337
static TemplateArgument CreatePackCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument pack by copying the given set of template arguments.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:343
bool structurallyEquals(const TemplateArgument &Other) const
Determines whether two template arguments are superficially the same.
QualType getIntegralType() const
Retrieve the type of the integral value.
Definition: TemplateBase.h:377
bool getIsDefaulted() const
If returns 'true', this TemplateArgument corresponds to a default template parameter.
Definition: TemplateBase.h:393
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:326
ArrayRef< TemplateArgument > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
Definition: TemplateBase.h:432
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
Definition: TemplateBase.h:89
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
Definition: TemplateBase.h:97
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:78
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:67
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:82
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:103
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
Definition: TemplateBase.h:350
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
Definition: TemplateBase.h:396
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:398
bool isTypeAlias() const
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:417
Represents a C++ template name within the type system.
Definition: TemplateName.h:220
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
NameKind getKind() const
void * getAsVoidPointer() const
Retrieve the template name as a void pointer.
Definition: TemplateName.h:388
@ UsingTemplate
A template name that refers to a template declaration found through a specific using shadow declarati...
Definition: TemplateName.h:265
@ OverloadedTemplate
A set of overloaded template declarations.
Definition: TemplateName.h:240
@ Template
A single template declaration.
Definition: TemplateName.h:237
@ DependentTemplate
A dependent template name that has not been resolved to a template (or set of templates).
Definition: TemplateName.h:252
@ SubstTemplateTemplateParm
A template template parameter that has been substituted for some other template name.
Definition: TemplateName.h:256
@ SubstTemplateTemplateParmPack
A template template parameter pack that has been substituted for a template template argument pack,...
Definition: TemplateName.h:261
@ DeducedTemplate
A template name that refers to another TemplateName with deduced default arguments.
Definition: TemplateName.h:269
@ QualifiedTemplate
A qualified template name, where the qualification is kept to describe the source code as written.
Definition: TemplateName.h:248
@ AssumedTemplate
An unqualified-id that has been assumed to name a function template that will be found by ADL.
Definition: TemplateName.h:244
A template parameter object.
static void Profile(llvm::FoldingSetNodeID &ID, QualType T, const APValue &V)
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:147
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
NamedDecl *const * const_iterator
Iterates through the template parameters in this list.
Definition: DeclTemplate.h:132
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
Definition: DeclTemplate.h:183
ArrayRef< NamedDecl * > asArray()
Definition: DeclTemplate.h:142
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:1719
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1695
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1736
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1703
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1711
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6667
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.cpp:4400
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
bool isParameterPack() const
Whether this template template parameter is a template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
bool isExpandedParameterPack() const
Whether this parameter is a template template parameter pack that has a known list of different templ...
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, bool Typename, TemplateParameterList *Params)
Declaration of a template type parameter.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, std::optional< unsigned > NumExpanded=std::nullopt)
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6361
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition: ASTConcept.h:227
ConceptDecl * getNamedConcept() const
Definition: ASTConcept.h:250
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition: ASTConcept.h:242
ConceptReference * getConceptReference() const
Definition: ASTConcept.h:246
Represents a declaration of a type.
Definition: Decl.h:3384
void setTypeForDecl(const Type *TD)
Definition: Decl.h:3410
const Type * getTypeForDecl() const
Definition: Decl.h:3409
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition: TypeLoc.h:78
static unsigned getFullDataSizeForType(QualType Ty)
Returns the size of type source info data block for the given type.
Definition: TypeLoc.cpp:94
void initialize(ASTContext &Context, SourceLocation Loc) const
Initializes this to state that every location in this type is the given location.
Definition: TypeLoc.h:200
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition: Type.h:5803
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition: Type.h:5853
A container of type source information.
Definition: Type.h:7908
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
The base class of the type hierarchy.
Definition: Type.h:1828
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1916
bool isBlockPointerType() const
Definition: Type.h:8206
bool isVoidType() const
Definition: Type.h:8516
bool isBooleanType() const
Definition: Type.h:8648
bool isFunctionReferenceType() const
Definition: Type.h:8239
bool isObjCBuiltinType() const
Definition: Type.h:8385
QualType getRVVEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an RVV builtin type.
Definition: Type.cpp:2622
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:773
bool isIncompleteArrayType() const
Definition: Type.h:8272
bool isPlaceholderType() const
Test for a type which does not represent an actual type-system type but is instead used as a placehol...
Definition: Type.h:8492
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2180
bool isConstantArrayType() const
Definition: Type.h:8268
bool hasIntegerRepresentation() const
Determine whether this type has an integer representation of some sort, e.g., it is an integer type o...
Definition: Type.cpp:2055
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition: Type.cpp:2386
bool isArrayType() const
Definition: Type.h:8264
bool isCharType() const
Definition: Type.cpp:2123
QualType getLocallyUnqualifiedSingleStepDesugaredType() const
Pull a single level of sugar off of this locally-unqualified type.
Definition: Type.cpp:509
bool isFunctionPointerType() const
Definition: Type.h:8232
bool isPointerType() const
Definition: Type.h:8192
bool isArrayParameterType() const
Definition: Type.h:8280
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8560
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8810
bool isSpecificPlaceholderType(unsigned K) const
Test for a specific placeholder type.
Definition: Type.h:8505
bool isSignedFixedPointType() const
Return true if this is a fixed point type that is signed according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8601
bool isEnumeralType() const
Definition: Type.h:8296
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2552
bool isObjCQualifiedIdType() const
Definition: Type.h:8355
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:738
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8635
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition: Type.cpp:2270
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition: Type.cpp:2591
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2812
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2715
bool isBitIntType() const
Definition: Type.h:8430
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:8485
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:8288
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2707
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8573
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8589
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2361
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition: Type.cpp:2220
QualType getCanonicalTypeInternal() const
Definition: Type.h:2990
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8691
bool isMemberPointerType() const
Definition: Type.h:8246
bool isObjCIdType() const
Definition: Type.h:8367
bool isUnsaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8597
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:8796
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2396
bool isFunctionType() const
Definition: Type.h:8188
bool isObjCObjectPointerType() const
Definition: Type.h:8334
bool isUnsignedFixedPointType() const
Return true if this is a fixed point type that is unsigned according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8615
bool isVectorType() const
Definition: Type.h:8304
bool isObjCClassType() const
Definition: Type.h:8373
bool isRVVVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'riscv_rvv_vector_bits' type attribute,...
Definition: Type.cpp:2604
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2539
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition: Type.cpp:2230
bool isAnyPointerType() const
Definition: Type.h:8200
TypeClass getTypeClass() const
Definition: Type.h:2341
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition: Type.h:2367
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8741
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition: Type.cpp:638
bool isNullPtrType() const
Definition: Type.h:8553
bool isRecordType() const
Definition: Type.h:8292
bool isObjCRetainableType() const
Definition: Type.cpp:5026
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4761
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition: Decl.h:3528
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5576
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3427
QualType getUnderlyingType() const
Definition: Decl.h:3482
void setTypeSourceInfo(TypeSourceInfo *newType)
Definition: Decl.h:3488
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5756
A unary type transform, which is a type constructed from another.
Definition: Type.h:5995
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition: DeclCXX.h:4369
static void Profile(llvm::FoldingSetNodeID &ID, QualType Ty, const APValue &APVal)
Definition: DeclCXX.h:4397
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition: Type.h:5673
Represents a dependent using declaration which was marked with typename.
Definition: DeclCXX.h:3982
Represents a C++ using-enum-declaration.
Definition: DeclCXX.h:3736
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3343
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5724
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:671
void setType(QualType newType)
Definition: Decl.h:683
QualType getType() const
Definition: Decl.h:682
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition: Decl.cpp:5410
void clear()
Definition: Value.cpp:218
Represents a variable declaration or definition.
Definition: Decl.h:882
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2786
bool hasInit() const
Definition: Decl.cpp:2387
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a static data member.
Definition: Decl.cpp:2433
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1234
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1159
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition: Decl.cpp:2748
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1495
@ DeclarationOnly
This declaration is only a declaration.
Definition: Decl.h:1246
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition: Decl.cpp:2364
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2755
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3809
Expr * getSizeExpr() const
Definition: Type.h:3828
Represents a GCC generic vector type.
Definition: Type.h:4035
unsigned getNumElements() const
Definition: Type.h:4050
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4059
VectorKind getVectorKind() const
Definition: Type.h:4055
QualType getElementType() const
Definition: Type.h:4049
A full comment attached to a declaration, contains block content.
Definition: Comment.h:1083
ArrayRef< BlockContentComment * > getBlocks() const
Definition: Comment.h:1121
const DeclInfo * getDeclInfo() const LLVM_READONLY
Definition: Comment.h:1115
const Decl * getDecl() const LLVM_READONLY
Definition: Comment.h:1111
Holds all information required to evaluate constexpr code in a module.
Definition: Context.h:40
Defines the Linkage enumeration and various utility functions.
Defines the clang::TargetInfo interface.
const internal::VariadicAllOfMatcher< Attr > attr
Matches attributes.
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ArrayType > arrayType
Matches all kinds of arrays.
const AstTypeMatcher< TagType > tagType
Matches tag types (record and enum types).
The JSON file list parser is used to communicate input to InstallAPI.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ OpenCL
Definition: LangStandard.h:65
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
GVALinkage
A more specific kind of linkage than enum Linkage.
Definition: Linkage.h:72
@ GVA_StrongODR
Definition: Linkage.h:77
@ GVA_StrongExternal
Definition: Linkage.h:76
@ GVA_AvailableExternally
Definition: Linkage.h:74
@ GVA_DiscardableODR
Definition: Linkage.h:75
@ GVA_Internal
Definition: Linkage.h:73
AutoTypeKeyword
Which keyword(s) were used to create an AutoType.
Definition: Type.h:1778
OpenCLTypeKind
OpenCL type kinds.
Definition: TargetInfo.h:206
@ OCLTK_ReserveID
Definition: TargetInfo.h:213
@ OCLTK_Sampler
Definition: TargetInfo.h:214
@ OCLTK_Pipe
Definition: TargetInfo.h:211
@ OCLTK_ClkEvent
Definition: TargetInfo.h:208
@ OCLTK_Event
Definition: TargetInfo.h:209
@ OCLTK_Default
Definition: TargetInfo.h:207
@ OCLTK_Queue
Definition: TargetInfo.h:212
FunctionType::ExtInfo getFunctionExtInfo(const Type &t)
Definition: Type.h:8090
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
NullabilityKind
Describes the nullability of a particular type.
Definition: Specifiers.h:336
@ Nullable
Values of this type can be null.
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
@ NonNull
Values of this type can never be null.
@ ICIS_NoInit
No in-class initializer.
Definition: Specifiers.h:272
CXXABI * CreateMicrosoftCXXABI(ASTContext &Ctx)
@ Vector
'vector' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
TypeOfKind
The kind of 'typeof' expression we're after.
Definition: Type.h:910
@ SC_Register
Definition: Specifiers.h:257
@ SC_Static
Definition: Specifiers.h:252
CXXABI * CreateItaniumCXXABI(ASTContext &Ctx)
Creates an instance of a C++ ABI class.
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ASTContext::SectionInfo &Section)
Insertion operator for diagnostics.
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition: Linkage.h:24
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
@ Result
The result type of a method or function.
ArraySizeModifier
Capture whether this is a normal array (e.g.
Definition: Type.h:3575
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
SubstTemplateTypeParmTypeFlag
Definition: Type.h:1789
TagTypeKind
The kind of a tag type.
Definition: Type.h:6877
@ Interface
The "__interface" keyword.
@ Struct
The "struct" keyword.
@ Class
The "class" keyword.
bool isDiscardableGVALinkage(GVALinkage L)
Definition: Linkage.h:80
BuiltinTemplateKind
Kinds of BuiltinTemplateDecl.
Definition: Builtins.h:308
@ BTK__type_pack_element
This names the __type_pack_element BuiltinTemplateDecl.
Definition: Builtins.h:313
@ BTK__builtin_common_type
This names the __builtin_common_type BuiltinTemplateDecl.
Definition: Builtins.h:316
@ BTK__make_integer_seq
This names the __make_integer_seq BuiltinTemplateDecl.
Definition: Builtins.h:310
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
TranslationUnitKind
Describes the kind of translation unit being processed.
Definition: LangOptions.h:1097
@ TypeAlignment
Definition: Type.h:76
FloatModeKind
Definition: TargetInfo.h:73
bool isPtrSizeAddressSpace(LangAS AS)
Definition: AddressSpaces.h:92
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:139
const FunctionProtoType * T
void printTemplateArgumentList(raw_ostream &OS, ArrayRef< TemplateArgument > Args, const PrintingPolicy &Policy, const TemplateParameterList *TPL=nullptr)
Print a template argument list, including the '<' and '>' enclosing the template arguments.
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1278
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:191
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:278
@ CC_C
Definition: Specifiers.h:279
@ CC_M68kRTD
Definition: Specifiers.h:300
@ CC_X86RegCall
Definition: Specifiers.h:287
@ CC_X86VectorCall
Definition: Specifiers.h:283
@ CC_X86StdCall
Definition: Specifiers.h:280
@ CC_X86FastCall
Definition: Specifiers.h:281
@ Invariant
The parameter is invariant: must match exactly.
@ Contravariant
The parameter is contravariant, e.g., X<T> is a subtype of X when the type parameter is covariant and...
@ Covariant
The parameter is covariant, e.g., X<T> is a subtype of X when the type parameter is covariant and T i...
VectorKind
Definition: Type.h:3994
@ AltiVecBool
is AltiVec 'vector bool ...'
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
@ AltiVecPixel
is AltiVec 'vector Pixel'
@ Generic
not a target-specific vector type
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
LangAS getLangASFromTargetAS(unsigned TargetAS)
Definition: AddressSpaces.h:87
AlignRequirementKind
Definition: ASTContext.h:144
@ None
The alignment was not explicit in code.
@ RequiredByEnum
The alignment comes from an alignment attribute on a enum type.
@ RequiredByTypedef
The alignment comes from an alignment attribute on a typedef.
@ RequiredByRecord
The alignment comes from an alignment attribute on a record type.
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:6852
@ None
No keyword precedes the qualified type name.
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_DependentNoexcept
noexcept(expression), value-dependent
@ EST_DynamicNone
throw()
@ EST_Uninstantiated
not instantiated yet
@ EST_Unparsed
not parsed yet
@ EST_NoThrow
Microsoft __declspec(nothrow) extension.
@ EST_None
no exception specification
@ EST_MSAny
Microsoft throw(...) extension.
@ EST_BasicNoexcept
noexcept
@ EST_NoexceptFalse
noexcept(expression), evals to 'false'
@ EST_Unevaluated
not evaluated yet, for special member function
@ EST_NoexceptTrue
noexcept(expression), evals to 'true'
@ EST_Dynamic
throw(T1, T2)
@ AS_public
Definition: Specifiers.h:124
unsigned long uint64_t
Diagnostic wrappers for TextAPI types for error reporting.
Definition: Dominators.h:30
unsigned NumTemplateArgs
The number of template arguments in TemplateArgs.
Definition: TemplateBase.h:694
Copy initialization expr of a __block variable and a boolean flag that indicates whether the expressi...
Definition: Expr.h:6460
Expr * getCopyExpr() const
Definition: Expr.h:6467
bool ParseAllComments
Treat ordinary comments as documentation comments.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
ArrayRef< TemplateArgument > Args
Definition: TemplateName.h:187
Holds information about the various types of exception specification.
Definition: Type.h:5165
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:5167
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition: Type.h:5170
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition: Type.h:5173
Extra information about a function prototype.
Definition: Type.h:5193
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:5200
bool requiresFunctionProtoTypeArmAttributes() const
Definition: Type.h:5225
FunctionEffectsRef FunctionEffects
Definition: Type.h:5203
const ExtParameterInfo * ExtParameterInfos
Definition: Type.h:5201
bool requiresFunctionProtoTypeExtraBitfields() const
Definition: Type.h:5219
FunctionType::ExtInfo ExtInfo
Definition: Type.h:5194
A simple holder for a QualType representing a type in an exception specification.
Definition: Type.h:4560
A holder for Arm type attributes as described in the Arm C/C++ Language extensions which are not part...
Definition: Type.h:4626
A simple holder for various uncommon bits which do not fit in FunctionTypeBitfields.
Definition: Type.h:4565
A lazy value (of type T) that is within an AST node of type Owner, where the value might change in la...
Parts of a decomposed MSGuidDecl.
Definition: DeclCXX.h:4287
Contains information gathered from parsing the contents of TargetAttr.
Definition: TargetInfo.h:58
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition: Type.h:862
const Type * Ty
The locally-unqualified type.
Definition: Type.h:864
Qualifiers Quals
The local qualifiers.
Definition: Type.h:867
A this pointer adjustment.
Definition: Thunk.h:92
IntType
===-— Target Data Type Query Methods ----------------------------—===//
Definition: TargetInfo.h:144
AlignRequirementKind AlignRequirement
Definition: ASTContext.h:175
bool isAlignRequired()
Definition: ASTContext.h:167
AlignRequirementKind AlignRequirement
Definition: ASTContext.h:161
uint64_t Width
Definition: ASTContext.h:159
unsigned Align
Definition: ASTContext.h:160
Information about the declaration, useful to clients of FullComment.
Definition: Comment.h:962
const TemplateParameterList * TemplateParameters
Template parameters that can be referenced by \tparam if CommentDecl is a template (IsTemplateDecl or...
Definition: Comment.h:988
const Decl * CommentDecl
Declaration the comment is actually attached to (in the source).
Definition: Comment.h:965
static bool isEqual(const FoldingSetNodeID &LHS, const FoldingSetNodeID &RHS)
Definition: ASTContext.cpp:130
static FoldingSetNodeID getTombstoneKey()
Definition: ASTContext.cpp:118
static unsigned getHashValue(const FoldingSetNodeID &Val)
Definition: ASTContext.cpp:126