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 AARCH64_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
2273 ElBits, NF) \
2274 case BuiltinType::Id: \
2275 Width = NumEls * ElBits * NF; \
2276 Align = NumEls * ElBits; \
2277 break;
2278#include "clang/Basic/AArch64SVEACLETypes.def"
2279#define PPC_VECTOR_TYPE(Name, Id, Size) \
2280 case BuiltinType::Id: \
2281 Width = Size; \
2282 Align = Size; \
2283 break;
2284#include "clang/Basic/PPCTypes.def"
2285#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
2286 IsFP, IsBF) \
2287 case BuiltinType::Id: \
2288 Width = 0; \
2289 Align = ElBits; \
2290 break;
2291#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2292 case BuiltinType::Id: \
2293 Width = 0; \
2294 Align = 8; \
2295 break;
2296#include "clang/Basic/RISCVVTypes.def"
2297#define WASM_TYPE(Name, Id, SingletonId) \
2298 case BuiltinType::Id: \
2299 Width = 0; \
2300 Align = 8; \
2301 break;
2302#include "clang/Basic/WebAssemblyReferenceTypes.def"
2303#define AMDGPU_TYPE(NAME, ID, SINGLETONID, WIDTH, ALIGN) \
2304 case BuiltinType::ID: \
2305 Width = WIDTH; \
2306 Align = ALIGN; \
2307 break;
2308#include "clang/Basic/AMDGPUTypes.def"
2309#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2310#include "clang/Basic/HLSLIntangibleTypes.def"
2311 Width = Target->getPointerWidth(LangAS::Default);
2312 Align = Target->getPointerAlign(LangAS::Default);
2313 break;
2314 }
2315 break;
2316 case Type::ObjCObjectPointer:
2317 Width = Target->getPointerWidth(LangAS::Default);
2318 Align = Target->getPointerAlign(LangAS::Default);
2319 break;
2320 case Type::BlockPointer:
2321 AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
2322 Width = Target->getPointerWidth(AS);
2323 Align = Target->getPointerAlign(AS);
2324 break;
2325 case Type::LValueReference:
2326 case Type::RValueReference:
2327 // alignof and sizeof should never enter this code path here, so we go
2328 // the pointer route.
2329 AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
2330 Width = Target->getPointerWidth(AS);
2331 Align = Target->getPointerAlign(AS);
2332 break;
2333 case Type::Pointer:
2334 AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
2335 Width = Target->getPointerWidth(AS);
2336 Align = Target->getPointerAlign(AS);
2337 break;
2338 case Type::MemberPointer: {
2339 const auto *MPT = cast<MemberPointerType>(T);
2340 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2341 Width = MPI.Width;
2342 Align = MPI.Align;
2343 break;
2344 }
2345 case Type::Complex: {
2346 // Complex types have the same alignment as their elements, but twice the
2347 // size.
2348 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2349 Width = EltInfo.Width * 2;
2350 Align = EltInfo.Align;
2351 break;
2352 }
2353 case Type::ObjCObject:
2354 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2355 case Type::Adjusted:
2356 case Type::Decayed:
2357 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2358 case Type::ObjCInterface: {
2359 const auto *ObjCI = cast<ObjCInterfaceType>(T);
2360 if (ObjCI->getDecl()->isInvalidDecl()) {
2361 Width = 8;
2362 Align = 8;
2363 break;
2364 }
2365 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2366 Width = toBits(Layout.getSize());
2367 Align = toBits(Layout.getAlignment());
2368 break;
2369 }
2370 case Type::BitInt: {
2371 const auto *EIT = cast<BitIntType>(T);
2372 Align = Target->getBitIntAlign(EIT->getNumBits());
2373 Width = Target->getBitIntWidth(EIT->getNumBits());
2374 break;
2375 }
2376 case Type::Record:
2377 case Type::Enum: {
2378 const auto *TT = cast<TagType>(T);
2379
2380 if (TT->getDecl()->isInvalidDecl()) {
2381 Width = 8;
2382 Align = 8;
2383 break;
2384 }
2385
2386 if (const auto *ET = dyn_cast<EnumType>(TT)) {
2387 const EnumDecl *ED = ET->getDecl();
2388 TypeInfo Info =
2390 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2391 Info.Align = AttrAlign;
2393 }
2394 return Info;
2395 }
2396
2397 const auto *RT = cast<RecordType>(TT);
2398 const RecordDecl *RD = RT->getDecl();
2399 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2400 Width = toBits(Layout.getSize());
2401 Align = toBits(Layout.getAlignment());
2402 AlignRequirement = RD->hasAttr<AlignedAttr>()
2405 break;
2406 }
2407
2408 case Type::SubstTemplateTypeParm:
2409 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2410 getReplacementType().getTypePtr());
2411
2412 case Type::Auto:
2413 case Type::DeducedTemplateSpecialization: {
2414 const auto *A = cast<DeducedType>(T);
2415 assert(!A->getDeducedType().isNull() &&
2416 "cannot request the size of an undeduced or dependent auto type");
2417 return getTypeInfo(A->getDeducedType().getTypePtr());
2418 }
2419
2420 case Type::Paren:
2421 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2422
2423 case Type::MacroQualified:
2424 return getTypeInfo(
2425 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2426
2427 case Type::ObjCTypeParam:
2428 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2429
2430 case Type::Using:
2431 return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr());
2432
2433 case Type::Typedef: {
2434 const auto *TT = cast<TypedefType>(T);
2435 TypeInfo Info = getTypeInfo(TT->desugar().getTypePtr());
2436 // If the typedef has an aligned attribute on it, it overrides any computed
2437 // alignment we have. This violates the GCC documentation (which says that
2438 // attribute(aligned) can only round up) but matches its implementation.
2439 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2440 Align = AttrAlign;
2441 AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2442 } else {
2443 Align = Info.Align;
2444 AlignRequirement = Info.AlignRequirement;
2445 }
2446 Width = Info.Width;
2447 break;
2448 }
2449
2450 case Type::Elaborated:
2451 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
2452
2453 case Type::Attributed:
2454 return getTypeInfo(
2455 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2456
2457 case Type::CountAttributed:
2458 return getTypeInfo(cast<CountAttributedType>(T)->desugar().getTypePtr());
2459
2460 case Type::BTFTagAttributed:
2461 return getTypeInfo(
2462 cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr());
2463
2464 case Type::HLSLAttributedResource:
2465 return getTypeInfo(
2466 cast<HLSLAttributedResourceType>(T)->getWrappedType().getTypePtr());
2467
2468 case Type::Atomic: {
2469 // Start with the base type information.
2470 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2471 Width = Info.Width;
2472 Align = Info.Align;
2473
2474 if (!Width) {
2475 // An otherwise zero-sized type should still generate an
2476 // atomic operation.
2477 Width = Target->getCharWidth();
2478 assert(Align);
2479 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2480 // If the size of the type doesn't exceed the platform's max
2481 // atomic promotion width, make the size and alignment more
2482 // favorable to atomic operations:
2483
2484 // Round the size up to a power of 2.
2485 Width = llvm::bit_ceil(Width);
2486
2487 // Set the alignment equal to the size.
2488 Align = static_cast<unsigned>(Width);
2489 }
2490 }
2491 break;
2492
2493 case Type::Pipe:
2494 Width = Target->getPointerWidth(LangAS::opencl_global);
2495 Align = Target->getPointerAlign(LangAS::opencl_global);
2496 break;
2497 }
2498
2499 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2500 return TypeInfo(Width, Align, AlignRequirement);
2501}
2502
2504 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2505 if (I != MemoizedUnadjustedAlign.end())
2506 return I->second;
2507
2508 unsigned UnadjustedAlign;
2509 if (const auto *RT = T->getAs<RecordType>()) {
2510 const RecordDecl *RD = RT->getDecl();
2511 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2512 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2513 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2514 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2515 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2516 } else {
2517 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2518 }
2519
2520 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2521 return UnadjustedAlign;
2522}
2523
2525 unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign(
2526 getTargetInfo().getTriple(), Target->getTargetOpts().FeatureMap);
2527 return SimdAlign;
2528}
2529
2530/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2532 return CharUnits::fromQuantity(BitSize / getCharWidth());
2533}
2534
2535/// toBits - Convert a size in characters to a size in characters.
2536int64_t ASTContext::toBits(CharUnits CharSize) const {
2537 return CharSize.getQuantity() * getCharWidth();
2538}
2539
2540/// getTypeSizeInChars - Return the size of the specified type, in characters.
2541/// This method does not work on incomplete types.
2543 return getTypeInfoInChars(T).Width;
2544}
2546 return getTypeInfoInChars(T).Width;
2547}
2548
2549/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2550/// characters. This method does not work on incomplete types.
2553}
2556}
2557
2558/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2559/// type, in characters, before alignment adjustments. This method does
2560/// not work on incomplete types.
2563}
2566}
2567
2568/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2569/// type for the current target in bits. This can be different than the ABI
2570/// alignment in cases where it is beneficial for performance or backwards
2571/// compatibility preserving to overalign a data type. (Note: despite the name,
2572/// the preferred alignment is ABI-impacting, and not an optimization.)
2574 TypeInfo TI = getTypeInfo(T);
2575 unsigned ABIAlign = TI.Align;
2576
2578
2579 // The preferred alignment of member pointers is that of a pointer.
2580 if (T->isMemberPointerType())
2581 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2582
2583 if (!Target->allowsLargerPreferedTypeAlignment())
2584 return ABIAlign;
2585
2586 if (const auto *RT = T->getAs<RecordType>()) {
2587 const RecordDecl *RD = RT->getDecl();
2588
2589 // When used as part of a typedef, or together with a 'packed' attribute,
2590 // the 'aligned' attribute can be used to decrease alignment. Note that the
2591 // 'packed' case is already taken into consideration when computing the
2592 // alignment, we only need to handle the typedef case here.
2594 RD->isInvalidDecl())
2595 return ABIAlign;
2596
2597 unsigned PreferredAlign = static_cast<unsigned>(
2598 toBits(getASTRecordLayout(RD).PreferredAlignment));
2599 assert(PreferredAlign >= ABIAlign &&
2600 "PreferredAlign should be at least as large as ABIAlign.");
2601 return PreferredAlign;
2602 }
2603
2604 // Double (and, for targets supporting AIX `power` alignment, long double) and
2605 // long long should be naturally aligned (despite requiring less alignment) if
2606 // possible.
2607 if (const auto *CT = T->getAs<ComplexType>())
2608 T = CT->getElementType().getTypePtr();
2609 if (const auto *ET = T->getAs<EnumType>())
2610 T = ET->getDecl()->getIntegerType().getTypePtr();
2611 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2612 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2613 T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2614 (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2615 Target->defaultsToAIXPowerAlignment()))
2616 // Don't increase the alignment if an alignment attribute was specified on a
2617 // typedef declaration.
2618 if (!TI.isAlignRequired())
2619 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2620
2621 return ABIAlign;
2622}
2623
2624/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2625/// for __attribute__((aligned)) on this target, to be used if no alignment
2626/// value is specified.
2629}
2630
2631/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2632/// to a global variable of the specified type.
2634 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2635 return std::max(getPreferredTypeAlign(T),
2636 getMinGlobalAlignOfVar(TypeSize, VD));
2637}
2638
2639/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2640/// should be given to a global variable of the specified type.
2642 const VarDecl *VD) const {
2644}
2645
2647 const VarDecl *VD) const {
2648 // Make the default handling as that of a non-weak definition in the
2649 // current translation unit.
2650 bool HasNonWeakDef = !VD || (VD->hasDefinition() && !VD->isWeak());
2651 return getTargetInfo().getMinGlobalAlign(Size, HasNonWeakDef);
2652}
2653
2655 CharUnits Offset = CharUnits::Zero();
2656 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2657 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2658 Offset += Layout->getBaseClassOffset(Base);
2659 Layout = &getASTRecordLayout(Base);
2660 }
2661 return Offset;
2662}
2663
2665 const ValueDecl *MPD = MP.getMemberPointerDecl();
2668 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2669 const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext());
2670 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2671 const CXXRecordDecl *Base = RD;
2672 const CXXRecordDecl *Derived = Path[I];
2673 if (DerivedMember)
2674 std::swap(Base, Derived);
2676 RD = Path[I];
2677 }
2678 if (DerivedMember)
2680 return ThisAdjustment;
2681}
2682
2683/// DeepCollectObjCIvars -
2684/// This routine first collects all declared, but not synthesized, ivars in
2685/// super class and then collects all ivars, including those synthesized for
2686/// current class. This routine is used for implementation of current class
2687/// when all ivars, declared and synthesized are known.
2689 bool leafClass,
2691 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2692 DeepCollectObjCIvars(SuperClass, false, Ivars);
2693 if (!leafClass) {
2694 llvm::append_range(Ivars, OI->ivars());
2695 } else {
2696 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2697 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2698 Iv= Iv->getNextIvar())
2699 Ivars.push_back(Iv);
2700 }
2701}
2702
2703/// CollectInheritedProtocols - Collect all protocols in current class and
2704/// those inherited by it.
2707 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2708 // We can use protocol_iterator here instead of
2709 // all_referenced_protocol_iterator since we are walking all categories.
2710 for (auto *Proto : OI->all_referenced_protocols()) {
2711 CollectInheritedProtocols(Proto, Protocols);
2712 }
2713
2714 // Categories of this Interface.
2715 for (const auto *Cat : OI->visible_categories())
2716 CollectInheritedProtocols(Cat, Protocols);
2717
2718 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2719 while (SD) {
2720 CollectInheritedProtocols(SD, Protocols);
2721 SD = SD->getSuperClass();
2722 }
2723 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2724 for (auto *Proto : OC->protocols()) {
2725 CollectInheritedProtocols(Proto, Protocols);
2726 }
2727 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2728 // Insert the protocol.
2729 if (!Protocols.insert(
2730 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2731 return;
2732
2733 for (auto *Proto : OP->protocols())
2734 CollectInheritedProtocols(Proto, Protocols);
2735 }
2736}
2737
2739 const RecordDecl *RD,
2740 bool CheckIfTriviallyCopyable) {
2741 assert(RD->isUnion() && "Must be union type");
2742 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2743
2744 for (const auto *Field : RD->fields()) {
2745 if (!Context.hasUniqueObjectRepresentations(Field->getType(),
2746 CheckIfTriviallyCopyable))
2747 return false;
2748 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2749 if (FieldSize != UnionSize)
2750 return false;
2751 }
2752 return !RD->field_empty();
2753}
2754
2755static int64_t getSubobjectOffset(const FieldDecl *Field,
2756 const ASTContext &Context,
2757 const clang::ASTRecordLayout & /*Layout*/) {
2758 return Context.getFieldOffset(Field);
2759}
2760
2761static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2762 const ASTContext &Context,
2763 const clang::ASTRecordLayout &Layout) {
2764 return Context.toBits(Layout.getBaseClassOffset(RD));
2765}
2766
2767static std::optional<int64_t>
2769 const RecordDecl *RD,
2770 bool CheckIfTriviallyCopyable);
2771
2772static std::optional<int64_t>
2773getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context,
2774 bool CheckIfTriviallyCopyable) {
2775 if (Field->getType()->isRecordType()) {
2776 const RecordDecl *RD = Field->getType()->getAsRecordDecl();
2777 if (!RD->isUnion())
2778 return structHasUniqueObjectRepresentations(Context, RD,
2779 CheckIfTriviallyCopyable);
2780 }
2781
2782 // A _BitInt type may not be unique if it has padding bits
2783 // but if it is a bitfield the padding bits are not used.
2784 bool IsBitIntType = Field->getType()->isBitIntType();
2785 if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2786 !Context.hasUniqueObjectRepresentations(Field->getType(),
2787 CheckIfTriviallyCopyable))
2788 return std::nullopt;
2789
2790 int64_t FieldSizeInBits =
2791 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2792 if (Field->isBitField()) {
2793 // If we have explicit padding bits, they don't contribute bits
2794 // to the actual object representation, so return 0.
2795 if (Field->isUnnamedBitField())
2796 return 0;
2797
2798 int64_t BitfieldSize = Field->getBitWidthValue();
2799 if (IsBitIntType) {
2800 if ((unsigned)BitfieldSize >
2801 cast<BitIntType>(Field->getType())->getNumBits())
2802 return std::nullopt;
2803 } else if (BitfieldSize > FieldSizeInBits) {
2804 return std::nullopt;
2805 }
2806 FieldSizeInBits = BitfieldSize;
2807 } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations(
2808 Field->getType(), CheckIfTriviallyCopyable)) {
2809 return std::nullopt;
2810 }
2811 return FieldSizeInBits;
2812}
2813
2814static std::optional<int64_t>
2816 bool CheckIfTriviallyCopyable) {
2817 return structHasUniqueObjectRepresentations(Context, RD,
2818 CheckIfTriviallyCopyable);
2819}
2820
2821template <typename RangeT>
2823 const RangeT &Subobjects, int64_t CurOffsetInBits,
2824 const ASTContext &Context, const clang::ASTRecordLayout &Layout,
2825 bool CheckIfTriviallyCopyable) {
2826 for (const auto *Subobject : Subobjects) {
2827 std::optional<int64_t> SizeInBits =
2828 getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable);
2829 if (!SizeInBits)
2830 return std::nullopt;
2831 if (*SizeInBits != 0) {
2832 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2833 if (Offset != CurOffsetInBits)
2834 return std::nullopt;
2835 CurOffsetInBits += *SizeInBits;
2836 }
2837 }
2838 return CurOffsetInBits;
2839}
2840
2841static std::optional<int64_t>
2843 const RecordDecl *RD,
2844 bool CheckIfTriviallyCopyable) {
2845 assert(!RD->isUnion() && "Must be struct/class type");
2846 const auto &Layout = Context.getASTRecordLayout(RD);
2847
2848 int64_t CurOffsetInBits = 0;
2849 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2850 if (ClassDecl->isDynamicClass())
2851 return std::nullopt;
2852
2854 for (const auto &Base : ClassDecl->bases()) {
2855 // Empty types can be inherited from, and non-empty types can potentially
2856 // have tail padding, so just make sure there isn't an error.
2857 Bases.emplace_back(Base.getType()->getAsCXXRecordDecl());
2858 }
2859
2860 llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
2861 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
2862 });
2863
2864 std::optional<int64_t> OffsetAfterBases =
2866 Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable);
2867 if (!OffsetAfterBases)
2868 return std::nullopt;
2869 CurOffsetInBits = *OffsetAfterBases;
2870 }
2871
2872 std::optional<int64_t> OffsetAfterFields =
2874 RD->fields(), CurOffsetInBits, Context, Layout,
2875 CheckIfTriviallyCopyable);
2876 if (!OffsetAfterFields)
2877 return std::nullopt;
2878 CurOffsetInBits = *OffsetAfterFields;
2879
2880 return CurOffsetInBits;
2881}
2882
2884 QualType Ty, bool CheckIfTriviallyCopyable) const {
2885 // C++17 [meta.unary.prop]:
2886 // The predicate condition for a template specialization
2887 // has_unique_object_representations<T> shall be satisfied if and only if:
2888 // (9.1) - T is trivially copyable, and
2889 // (9.2) - any two objects of type T with the same value have the same
2890 // object representation, where:
2891 // - two objects of array or non-union class type are considered to have
2892 // the same value if their respective sequences of direct subobjects
2893 // have the same values, and
2894 // - two objects of union type are considered to have the same value if
2895 // they have the same active member and the corresponding members have
2896 // the same value.
2897 // The set of scalar types for which this condition holds is
2898 // implementation-defined. [ Note: If a type has padding bits, the condition
2899 // does not hold; otherwise, the condition holds true for unsigned integral
2900 // types. -- end note ]
2901 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2902
2903 // Arrays are unique only if their element type is unique.
2904 if (Ty->isArrayType())
2906 CheckIfTriviallyCopyable);
2907
2908 assert((Ty->isVoidType() || !Ty->isIncompleteType()) &&
2909 "hasUniqueObjectRepresentations should not be called with an "
2910 "incomplete type");
2911
2912 // (9.1) - T is trivially copyable...
2913 if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(*this))
2914 return false;
2915
2916 // All integrals and enums are unique.
2917 if (Ty->isIntegralOrEnumerationType()) {
2918 // Except _BitInt types that have padding bits.
2919 if (const auto *BIT = Ty->getAs<BitIntType>())
2920 return getTypeSize(BIT) == BIT->getNumBits();
2921
2922 return true;
2923 }
2924
2925 // All other pointers are unique.
2926 if (Ty->isPointerType())
2927 return true;
2928
2929 if (const auto *MPT = Ty->getAs<MemberPointerType>())
2930 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2931
2932 if (Ty->isRecordType()) {
2933 const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl();
2934
2935 if (Record->isInvalidDecl())
2936 return false;
2937
2938 if (Record->isUnion())
2940 CheckIfTriviallyCopyable);
2941
2942 std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(
2943 *this, Record, CheckIfTriviallyCopyable);
2944
2945 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(Ty));
2946 }
2947
2948 // FIXME: More cases to handle here (list by rsmith):
2949 // vectors (careful about, eg, vector of 3 foo)
2950 // _Complex int and friends
2951 // _Atomic T
2952 // Obj-C block pointers
2953 // Obj-C object pointers
2954 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2955 // clk_event_t, queue_t, reserve_id_t)
2956 // There're also Obj-C class types and the Obj-C selector type, but I think it
2957 // makes sense for those to return false here.
2958
2959 return false;
2960}
2961
2963 unsigned count = 0;
2964 // Count ivars declared in class extension.
2965 for (const auto *Ext : OI->known_extensions())
2966 count += Ext->ivar_size();
2967
2968 // Count ivar defined in this class's implementation. This
2969 // includes synthesized ivars.
2970 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2971 count += ImplDecl->ivar_size();
2972
2973 return count;
2974}
2975
2977 if (!E)
2978 return false;
2979
2980 // nullptr_t is always treated as null.
2981 if (E->getType()->isNullPtrType()) return true;
2982
2983 if (E->getType()->isAnyPointerType() &&
2986 return true;
2987
2988 // Unfortunately, __null has type 'int'.
2989 if (isa<GNUNullExpr>(E)) return true;
2990
2991 return false;
2992}
2993
2994/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
2995/// exists.
2997 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2998 I = ObjCImpls.find(D);
2999 if (I != ObjCImpls.end())
3000 return cast<ObjCImplementationDecl>(I->second);
3001 return nullptr;
3002}
3003
3004/// Get the implementation of ObjCCategoryDecl, or nullptr if none
3005/// exists.
3007 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3008 I = ObjCImpls.find(D);
3009 if (I != ObjCImpls.end())
3010 return cast<ObjCCategoryImplDecl>(I->second);
3011 return nullptr;
3012}
3013
3014/// Set the implementation of ObjCInterfaceDecl.
3016 ObjCImplementationDecl *ImplD) {
3017 assert(IFaceD && ImplD && "Passed null params");
3018 ObjCImpls[IFaceD] = ImplD;
3019}
3020
3021/// Set the implementation of ObjCCategoryDecl.
3023 ObjCCategoryImplDecl *ImplD) {
3024 assert(CatD && ImplD && "Passed null params");
3025 ObjCImpls[CatD] = ImplD;
3026}
3027
3028const ObjCMethodDecl *
3030 return ObjCMethodRedecls.lookup(MD);
3031}
3032
3034 const ObjCMethodDecl *Redecl) {
3035 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
3036 ObjCMethodRedecls[MD] = Redecl;
3037}
3038
3040 const NamedDecl *ND) const {
3041 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
3042 return ID;
3043 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
3044 return CD->getClassInterface();
3045 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
3046 return IMD->getClassInterface();
3047
3048 return nullptr;
3049}
3050
3051/// Get the copy initialization expression of VarDecl, or nullptr if
3052/// none exists.
3054 assert(VD && "Passed null params");
3055 assert(VD->hasAttr<BlocksAttr>() &&
3056 "getBlockVarCopyInits - not __block var");
3057 auto I = BlockVarCopyInits.find(VD);
3058 if (I != BlockVarCopyInits.end())
3059 return I->second;
3060 return {nullptr, false};
3061}
3062
3063/// Set the copy initialization expression of a block var decl.
3065 bool CanThrow) {
3066 assert(VD && CopyExpr && "Passed null params");
3067 assert(VD->hasAttr<BlocksAttr>() &&
3068 "setBlockVarCopyInits - not __block var");
3069 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
3070}
3071
3073 unsigned DataSize) const {
3074 if (!DataSize)
3076 else
3077 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
3078 "incorrect data size provided to CreateTypeSourceInfo!");
3079
3080 auto *TInfo =
3081 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
3082 new (TInfo) TypeSourceInfo(T, DataSize);
3083 return TInfo;
3084}
3085
3087 SourceLocation L) const {
3089 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
3090 return DI;
3091}
3092
3093const ASTRecordLayout &
3095 return getObjCLayout(D, nullptr);
3096}
3097
3098const ASTRecordLayout &
3100 const ObjCImplementationDecl *D) const {
3101 return getObjCLayout(D->getClassInterface(), D);
3102}
3103
3106 bool &AnyNonCanonArgs) {
3107 SmallVector<TemplateArgument, 16> CanonArgs(Args);
3108 for (auto &Arg : CanonArgs) {
3109 TemplateArgument OrigArg = Arg;
3110 Arg = C.getCanonicalTemplateArgument(Arg);
3111 AnyNonCanonArgs |= !Arg.structurallyEquals(OrigArg);
3112 }
3113 return CanonArgs;
3114}
3115
3116//===----------------------------------------------------------------------===//
3117// Type creation/memoization methods
3118//===----------------------------------------------------------------------===//
3119
3121ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3122 unsigned fastQuals = quals.getFastQualifiers();
3123 quals.removeFastQualifiers();
3124
3125 // Check if we've already instantiated this type.
3126 llvm::FoldingSetNodeID ID;
3127 ExtQuals::Profile(ID, baseType, quals);
3128 void *insertPos = nullptr;
3129 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
3130 assert(eq->getQualifiers() == quals);
3131 return QualType(eq, fastQuals);
3132 }
3133
3134 // If the base type is not canonical, make the appropriate canonical type.
3135 QualType canon;
3136 if (!baseType->isCanonicalUnqualified()) {
3137 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3138 canonSplit.Quals.addConsistentQualifiers(quals);
3139 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
3140
3141 // Re-find the insert position.
3142 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
3143 }
3144
3145 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3146 ExtQualNodes.InsertNode(eq, insertPos);
3147 return QualType(eq, fastQuals);
3148}
3149
3151 LangAS AddressSpace) const {
3152 QualType CanT = getCanonicalType(T);
3153 if (CanT.getAddressSpace() == AddressSpace)
3154 return T;
3155
3156 // If we are composing extended qualifiers together, merge together
3157 // into one ExtQuals node.
3158 QualifierCollector Quals;
3159 const Type *TypeNode = Quals.strip(T);
3160
3161 // If this type already has an address space specified, it cannot get
3162 // another one.
3163 assert(!Quals.hasAddressSpace() &&
3164 "Type cannot be in multiple addr spaces!");
3165 Quals.addAddressSpace(AddressSpace);
3166
3167 return getExtQualType(TypeNode, Quals);
3168}
3169
3171 // If the type is not qualified with an address space, just return it
3172 // immediately.
3173 if (!T.hasAddressSpace())
3174 return T;
3175
3176 QualifierCollector Quals;
3177 const Type *TypeNode;
3178 // For arrays, strip the qualifier off the element type, then reconstruct the
3179 // array type
3180 if (T.getTypePtr()->isArrayType()) {
3181 T = getUnqualifiedArrayType(T, Quals);
3182 TypeNode = T.getTypePtr();
3183 } else {
3184 // If we are composing extended qualifiers together, merge together
3185 // into one ExtQuals node.
3186 while (T.hasAddressSpace()) {
3187 TypeNode = Quals.strip(T);
3188
3189 // If the type no longer has an address space after stripping qualifiers,
3190 // jump out.
3191 if (!QualType(TypeNode, 0).hasAddressSpace())
3192 break;
3193
3194 // There might be sugar in the way. Strip it and try again.
3195 T = T.getSingleStepDesugaredType(*this);
3196 }
3197 }
3198
3199 Quals.removeAddressSpace();
3200
3201 // Removal of the address space can mean there are no longer any
3202 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3203 // or required.
3204 if (Quals.hasNonFastQualifiers())
3205 return getExtQualType(TypeNode, Quals);
3206 else
3207 return QualType(TypeNode, Quals.getFastQualifiers());
3208}
3209
3210uint16_t
3212 assert(RD->isPolymorphic() &&
3213 "Attempted to get vtable pointer discriminator on a monomorphic type");
3214 std::unique_ptr<MangleContext> MC(createMangleContext());
3215 SmallString<256> Str;
3216 llvm::raw_svector_ostream Out(Str);
3217 MC->mangleCXXVTable(RD, Out);
3218 return llvm::getPointerAuthStableSipHash(Str);
3219}
3220
3221/// Encode a function type for use in the discriminator of a function pointer
3222/// type. We can't use the itanium scheme for this since C has quite permissive
3223/// rules for type compatibility that we need to be compatible with.
3224///
3225/// Formally, this function associates every function pointer type T with an
3226/// encoded string E(T). Let the equivalence relation T1 ~ T2 be defined as
3227/// E(T1) == E(T2). E(T) is part of the ABI of values of type T. C type
3228/// compatibility requires equivalent treatment under the ABI, so
3229/// CCompatible(T1, T2) must imply E(T1) == E(T2), that is, CCompatible must be
3230/// a subset of ~. Crucially, however, it must be a proper subset because
3231/// CCompatible is not an equivalence relation: for example, int[] is compatible
3232/// with both int[1] and int[2], but the latter are not compatible with each
3233/// other. Therefore this encoding function must be careful to only distinguish
3234/// types if there is no third type with which they are both required to be
3235/// compatible.
3237 raw_ostream &OS, QualType QT) {
3238 // FIXME: Consider address space qualifiers.
3239 const Type *T = QT.getCanonicalType().getTypePtr();
3240
3241 // FIXME: Consider using the C++ type mangling when we encounter a construct
3242 // that is incompatible with C.
3243
3244 switch (T->getTypeClass()) {
3245 case Type::Atomic:
3247 Ctx, OS, cast<AtomicType>(T)->getValueType());
3248
3249 case Type::LValueReference:
3250 OS << "R";
3252 cast<ReferenceType>(T)->getPointeeType());
3253 return;
3254 case Type::RValueReference:
3255 OS << "O";
3257 cast<ReferenceType>(T)->getPointeeType());
3258 return;
3259
3260 case Type::Pointer:
3261 // C11 6.7.6.1p2:
3262 // For two pointer types to be compatible, both shall be identically
3263 // qualified and both shall be pointers to compatible types.
3264 // FIXME: we should also consider pointee types.
3265 OS << "P";
3266 return;
3267
3268 case Type::ObjCObjectPointer:
3269 case Type::BlockPointer:
3270 OS << "P";
3271 return;
3272
3273 case Type::Complex:
3274 OS << "C";
3276 Ctx, OS, cast<ComplexType>(T)->getElementType());
3277
3278 case Type::VariableArray:
3279 case Type::ConstantArray:
3280 case Type::IncompleteArray:
3281 case Type::ArrayParameter:
3282 // C11 6.7.6.2p6:
3283 // For two array types to be compatible, both shall have compatible
3284 // element types, and if both size specifiers are present, and are integer
3285 // constant expressions, then both size specifiers shall have the same
3286 // constant value [...]
3287 //
3288 // So since ElemType[N] has to be compatible ElemType[], we can't encode the
3289 // width of the array.
3290 OS << "A";
3292 Ctx, OS, cast<ArrayType>(T)->getElementType());
3293
3294 case Type::ObjCInterface:
3295 case Type::ObjCObject:
3296 OS << "<objc_object>";
3297 return;
3298
3299 case Type::Enum: {
3300 // C11 6.7.2.2p4:
3301 // Each enumerated type shall be compatible with char, a signed integer
3302 // type, or an unsigned integer type.
3303 //
3304 // So we have to treat enum types as integers.
3305 QualType UnderlyingType = cast<EnumType>(T)->getDecl()->getIntegerType();
3307 Ctx, OS, UnderlyingType.isNull() ? Ctx.IntTy : UnderlyingType);
3308 }
3309
3310 case Type::FunctionNoProto:
3311 case Type::FunctionProto: {
3312 // C11 6.7.6.3p15:
3313 // For two function types to be compatible, both shall specify compatible
3314 // return types. Moreover, the parameter type lists, if both are present,
3315 // shall agree in the number of parameters and in the use of the ellipsis
3316 // terminator; corresponding parameters shall have compatible types.
3317 //
3318 // That paragraph goes on to describe how unprototyped functions are to be
3319 // handled, which we ignore here. Unprototyped function pointers are hashed
3320 // as though they were prototyped nullary functions since thats probably
3321 // what the user meant. This behavior is non-conforming.
3322 // FIXME: If we add a "custom discriminator" function type attribute we
3323 // should encode functions as their discriminators.
3324 OS << "F";
3325 const auto *FuncType = cast<FunctionType>(T);
3326 encodeTypeForFunctionPointerAuth(Ctx, OS, FuncType->getReturnType());
3327 if (const auto *FPT = dyn_cast<FunctionProtoType>(FuncType)) {
3328 for (QualType Param : FPT->param_types()) {
3329 Param = Ctx.getSignatureParameterType(Param);
3330 encodeTypeForFunctionPointerAuth(Ctx, OS, Param);
3331 }
3332 if (FPT->isVariadic())
3333 OS << "z";
3334 }
3335 OS << "E";
3336 return;
3337 }
3338
3339 case Type::MemberPointer: {
3340 OS << "M";
3341 const auto *MPT = T->castAs<MemberPointerType>();
3342 encodeTypeForFunctionPointerAuth(Ctx, OS, QualType(MPT->getClass(), 0));
3343 encodeTypeForFunctionPointerAuth(Ctx, OS, MPT->getPointeeType());
3344 return;
3345 }
3346 case Type::ExtVector:
3347 case Type::Vector:
3348 OS << "Dv" << Ctx.getTypeSizeInChars(T).getQuantity();
3349 break;
3350
3351 // Don't bother discriminating based on these types.
3352 case Type::Pipe:
3353 case Type::BitInt:
3354 case Type::ConstantMatrix:
3355 OS << "?";
3356 return;
3357
3358 case Type::Builtin: {
3359 const auto *BTy = T->castAs<BuiltinType>();
3360 switch (BTy->getKind()) {
3361#define SIGNED_TYPE(Id, SingletonId) \
3362 case BuiltinType::Id: \
3363 OS << "i"; \
3364 return;
3365#define UNSIGNED_TYPE(Id, SingletonId) \
3366 case BuiltinType::Id: \
3367 OS << "i"; \
3368 return;
3369#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
3370#define BUILTIN_TYPE(Id, SingletonId)
3371#include "clang/AST/BuiltinTypes.def"
3372 llvm_unreachable("placeholder types should not appear here.");
3373
3374 case BuiltinType::Half:
3375 OS << "Dh";
3376 return;
3377 case BuiltinType::Float:
3378 OS << "f";
3379 return;
3380 case BuiltinType::Double:
3381 OS << "d";
3382 return;
3383 case BuiltinType::LongDouble:
3384 OS << "e";
3385 return;
3386 case BuiltinType::Float16:
3387 OS << "DF16_";
3388 return;
3389 case BuiltinType::Float128:
3390 OS << "g";
3391 return;
3392
3393 case BuiltinType::Void:
3394 OS << "v";
3395 return;
3396
3397 case BuiltinType::ObjCId:
3398 case BuiltinType::ObjCClass:
3399 case BuiltinType::ObjCSel:
3400 case BuiltinType::NullPtr:
3401 OS << "P";
3402 return;
3403
3404 // Don't bother discriminating based on OpenCL types.
3405 case BuiltinType::OCLSampler:
3406 case BuiltinType::OCLEvent:
3407 case BuiltinType::OCLClkEvent:
3408 case BuiltinType::OCLQueue:
3409 case BuiltinType::OCLReserveID:
3410 case BuiltinType::BFloat16:
3411 case BuiltinType::VectorQuad:
3412 case BuiltinType::VectorPair:
3413 OS << "?";
3414 return;
3415
3416 // Don't bother discriminating based on these seldom-used types.
3417 case BuiltinType::Ibm128:
3418 return;
3419#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3420 case BuiltinType::Id: \
3421 return;
3422#include "clang/Basic/OpenCLImageTypes.def"
3423#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3424 case BuiltinType::Id: \
3425 return;
3426#include "clang/Basic/OpenCLExtensionTypes.def"
3427#define SVE_TYPE(Name, Id, SingletonId) \
3428 case BuiltinType::Id: \
3429 return;
3430#include "clang/Basic/AArch64SVEACLETypes.def"
3431#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3432 case BuiltinType::Id: \
3433 return;
3434#include "clang/Basic/HLSLIntangibleTypes.def"
3435 case BuiltinType::Dependent:
3436 llvm_unreachable("should never get here");
3437#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
3438#include "clang/Basic/AMDGPUTypes.def"
3439 case BuiltinType::WasmExternRef:
3440#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3441#include "clang/Basic/RISCVVTypes.def"
3442 llvm_unreachable("not yet implemented");
3443 }
3444 llvm_unreachable("should never get here");
3445 }
3446 case Type::Record: {
3447 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
3448 const IdentifierInfo *II = RD->getIdentifier();
3449
3450 // In C++, an immediate typedef of an anonymous struct or union
3451 // is considered to name it for ODR purposes, but C's specification
3452 // of type compatibility does not have a similar rule. Using the typedef
3453 // name in function type discriminators anyway, as we do here,
3454 // therefore technically violates the C standard: two function pointer
3455 // types defined in terms of two typedef'd anonymous structs with
3456 // different names are formally still compatible, but we are assigning
3457 // them different discriminators and therefore incompatible ABIs.
3458 //
3459 // This is a relatively minor violation that significantly improves
3460 // discrimination in some cases and has not caused problems in
3461 // practice. Regardless, it is now part of the ABI in places where
3462 // function type discrimination is used, and it can no longer be
3463 // changed except on new platforms.
3464
3465 if (!II)
3466 if (const TypedefNameDecl *Typedef = RD->getTypedefNameForAnonDecl())
3467 II = Typedef->getDeclName().getAsIdentifierInfo();
3468
3469 if (!II) {
3470 OS << "<anonymous_record>";
3471 return;
3472 }
3473 OS << II->getLength() << II->getName();
3474 return;
3475 }
3476 case Type::HLSLAttributedResource:
3477 llvm_unreachable("should never get here");
3478 break;
3479 case Type::DeducedTemplateSpecialization:
3480 case Type::Auto:
3481#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3482#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3483#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3484#define ABSTRACT_TYPE(Class, Base)
3485#define TYPE(Class, Base)
3486#include "clang/AST/TypeNodes.inc"
3487 llvm_unreachable("unexpected non-canonical or dependent type!");
3488 return;
3489 }
3490}
3491
3493 assert(!T->isDependentType() &&
3494 "cannot compute type discriminator of a dependent type");
3495
3496 SmallString<256> Str;
3497 llvm::raw_svector_ostream Out(Str);
3498
3500 T = T->getPointeeType();
3501
3502 if (T->isFunctionType()) {
3504 } else {
3505 T = T.getUnqualifiedType();
3506 // Calls to member function pointers don't need to worry about
3507 // language interop or the laxness of the C type compatibility rules.
3508 // We just mangle the member pointer type directly, which is
3509 // implicitly much stricter about type matching. However, we do
3510 // strip any top-level exception specification before this mangling.
3511 // C++23 requires calls to work when the function type is convertible
3512 // to the pointer type by a function pointer conversion, which can
3513 // change the exception specification. This does not technically
3514 // require the exception specification to not affect representation,
3515 // because the function pointer conversion is still always a direct
3516 // value conversion and therefore an opportunity to resign the
3517 // pointer. (This is in contrast to e.g. qualification conversions,
3518 // which can be applied in nested pointer positions, effectively
3519 // requiring qualified and unqualified representations to match.)
3520 // However, it is pragmatic to ignore exception specifications
3521 // because it allows a certain amount of `noexcept` mismatching
3522 // to not become a visible ODR problem. This also leaves some
3523 // room for the committee to add laxness to function pointer
3524 // conversions in future standards.
3525 if (auto *MPT = T->getAs<MemberPointerType>())
3526 if (MPT->isMemberFunctionPointer()) {
3527 QualType PointeeType = MPT->getPointeeType();
3528 if (PointeeType->castAs<FunctionProtoType>()->getExceptionSpecType() !=
3529 EST_None) {
3531 T = getMemberPointerType(FT, MPT->getClass());
3532 }
3533 }
3534 std::unique_ptr<MangleContext> MC(createMangleContext());
3535 MC->mangleCanonicalTypeName(T, Out);
3536 }
3537
3538 return llvm::getPointerAuthStableSipHash(Str);
3539}
3540
3542 Qualifiers::GC GCAttr) const {
3543 QualType CanT = getCanonicalType(T);
3544 if (CanT.getObjCGCAttr() == GCAttr)
3545 return T;
3546
3547 if (const auto *ptr = T->getAs<PointerType>()) {
3548 QualType Pointee = ptr->getPointeeType();
3549 if (Pointee->isAnyPointerType()) {
3550 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
3551 return getPointerType(ResultType);
3552 }
3553 }
3554
3555 // If we are composing extended qualifiers together, merge together
3556 // into one ExtQuals node.
3557 QualifierCollector Quals;
3558 const Type *TypeNode = Quals.strip(T);
3559
3560 // If this type already has an ObjCGC specified, it cannot get
3561 // another one.
3562 assert(!Quals.hasObjCGCAttr() &&
3563 "Type cannot have multiple ObjCGCs!");
3564 Quals.addObjCGCAttr(GCAttr);
3565
3566 return getExtQualType(TypeNode, Quals);
3567}
3568
3570 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3571 QualType Pointee = Ptr->getPointeeType();
3572 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3573 return getPointerType(removeAddrSpaceQualType(Pointee));
3574 }
3575 }
3576 return T;
3577}
3578
3580 QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull,
3581 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3582 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3583
3584 llvm::FoldingSetNodeID ID;
3585 CountAttributedType::Profile(ID, WrappedTy, CountExpr, CountInBytes, OrNull);
3586
3587 void *InsertPos = nullptr;
3588 CountAttributedType *CATy =
3589 CountAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
3590 if (CATy)
3591 return QualType(CATy, 0);
3592
3593 QualType CanonTy = getCanonicalType(WrappedTy);
3594 size_t Size = CountAttributedType::totalSizeToAlloc<TypeCoupledDeclRefInfo>(
3595 DependentDecls.size());
3597 new (CATy) CountAttributedType(WrappedTy, CanonTy, CountExpr, CountInBytes,
3598 OrNull, DependentDecls);
3599 Types.push_back(CATy);
3600 CountAttributedTypes.InsertNode(CATy, InsertPos);
3601
3602 return QualType(CATy, 0);
3603}
3604
3607 llvm::function_ref<QualType(QualType)> Adjust) const {
3608 switch (Orig->getTypeClass()) {
3609 case Type::Attributed: {
3610 const auto *AT = cast<AttributedType>(Orig);
3611 return getAttributedType(AT->getAttrKind(),
3612 adjustType(AT->getModifiedType(), Adjust),
3613 adjustType(AT->getEquivalentType(), Adjust),
3614 AT->getAttr());
3615 }
3616
3617 case Type::BTFTagAttributed: {
3618 const auto *BTFT = dyn_cast<BTFTagAttributedType>(Orig);
3619 return getBTFTagAttributedType(BTFT->getAttr(),
3620 adjustType(BTFT->getWrappedType(), Adjust));
3621 }
3622
3623 case Type::Elaborated: {
3624 const auto *ET = cast<ElaboratedType>(Orig);
3625 return getElaboratedType(ET->getKeyword(), ET->getQualifier(),
3626 adjustType(ET->getNamedType(), Adjust));
3627 }
3628
3629 case Type::Paren:
3630 return getParenType(
3631 adjustType(cast<ParenType>(Orig)->getInnerType(), Adjust));
3632
3633 case Type::Adjusted: {
3634 const auto *AT = cast<AdjustedType>(Orig);
3635 return getAdjustedType(AT->getOriginalType(),
3636 adjustType(AT->getAdjustedType(), Adjust));
3637 }
3638
3639 case Type::MacroQualified: {
3640 const auto *MQT = cast<MacroQualifiedType>(Orig);
3641 return getMacroQualifiedType(adjustType(MQT->getUnderlyingType(), Adjust),
3642 MQT->getMacroIdentifier());
3643 }
3644
3645 default:
3646 return Adjust(Orig);
3647 }
3648}
3649
3651 FunctionType::ExtInfo Info) {
3652 if (T->getExtInfo() == Info)
3653 return T;
3654
3656 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3657 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3658 } else {
3659 const auto *FPT = cast<FunctionProtoType>(T);
3660 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3661 EPI.ExtInfo = Info;
3662 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3663 }
3664
3665 return cast<FunctionType>(Result.getTypePtr());
3666}
3667
3669 QualType ResultType) {
3670 return adjustType(FunctionType, [&](QualType Orig) {
3671 if (const auto *FNPT = Orig->getAs<FunctionNoProtoType>())
3672 return getFunctionNoProtoType(ResultType, FNPT->getExtInfo());
3673
3674 const auto *FPT = Orig->castAs<FunctionProtoType>();
3675 return getFunctionType(ResultType, FPT->getParamTypes(),
3676 FPT->getExtProtoInfo());
3677 });
3678}
3679
3681 QualType ResultType) {
3682 FD = FD->getMostRecentDecl();
3683 while (true) {
3684 FD->setType(adjustFunctionResultType(FD->getType(), ResultType));
3685 if (FunctionDecl *Next = FD->getPreviousDecl())
3686 FD = Next;
3687 else
3688 break;
3689 }
3691 L->DeducedReturnType(FD, ResultType);
3692}
3693
3694/// Get a function type and produce the equivalent function type with the
3695/// specified exception specification. Type sugar that can be present on a
3696/// declaration of a function with an exception specification is permitted
3697/// and preserved. Other type sugar (for instance, typedefs) is not.
3699 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3700 return adjustType(Orig, [&](QualType Ty) {
3701 const auto *Proto = Ty->castAs<FunctionProtoType>();
3702 return getFunctionType(Proto->getReturnType(), Proto->getParamTypes(),
3703 Proto->getExtProtoInfo().withExceptionSpec(ESI));
3704 });
3705}
3706
3708 QualType U) const {
3709 return hasSameType(T, U) ||
3710 (getLangOpts().CPlusPlus17 &&
3713}
3714
3716 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3717 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3718 SmallVector<QualType, 16> Args(Proto->param_types().size());
3719 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3720 Args[i] = removePtrSizeAddrSpace(Proto->param_types()[i]);
3721 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3722 }
3723
3724 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3725 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3726 return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3727 }
3728
3729 return T;
3730}
3731
3733 return hasSameType(T, U) ||
3736}
3737
3739 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3740 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3741 EPI.ExtParameterInfos = nullptr;
3742 return getFunctionType(Proto->getReturnType(), Proto->param_types(), EPI);
3743 }
3744 return T;
3745}
3746
3748 QualType U) const {
3751}
3752
3755 bool AsWritten) {
3756 // Update the type.
3757 QualType Updated =
3759 FD->setType(Updated);
3760
3761 if (!AsWritten)
3762 return;
3763
3764 // Update the type in the type source information too.
3765 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3766 // If the type and the type-as-written differ, we may need to update
3767 // the type-as-written too.
3768 if (TSInfo->getType() != FD->getType())
3769 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3770
3771 // FIXME: When we get proper type location information for exceptions,
3772 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3773 // up the TypeSourceInfo;
3774 assert(TypeLoc::getFullDataSizeForType(Updated) ==
3775 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3776 "TypeLoc size mismatch from updating exception specification");
3777 TSInfo->overrideType(Updated);
3778 }
3779}
3780
3781/// getComplexType - Return the uniqued reference to the type for a complex
3782/// number with the specified element type.
3784 // Unique pointers, to guarantee there is only one pointer of a particular
3785 // structure.
3786 llvm::FoldingSetNodeID ID;
3788
3789 void *InsertPos = nullptr;
3790 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3791 return QualType(CT, 0);
3792
3793 // If the pointee type isn't canonical, this won't be a canonical type either,
3794 // so fill in the canonical type field.
3795 QualType Canonical;
3796 if (!T.isCanonical()) {
3797 Canonical = getComplexType(getCanonicalType(T));
3798
3799 // Get the new insert position for the node we care about.
3800 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3801 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3802 }
3803 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
3804 Types.push_back(New);
3805 ComplexTypes.InsertNode(New, InsertPos);
3806 return QualType(New, 0);
3807}
3808
3809/// getPointerType - Return the uniqued reference to the type for a pointer to
3810/// the specified type.
3812 // Unique pointers, to guarantee there is only one pointer of a particular
3813 // structure.
3814 llvm::FoldingSetNodeID ID;
3816
3817 void *InsertPos = nullptr;
3818 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3819 return QualType(PT, 0);
3820
3821 // If the pointee type isn't canonical, this won't be a canonical type either,
3822 // so fill in the canonical type field.
3823 QualType Canonical;
3824 if (!T.isCanonical()) {
3825 Canonical = getPointerType(getCanonicalType(T));
3826
3827 // Get the new insert position for the node we care about.
3828 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3829 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3830 }
3831 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
3832 Types.push_back(New);
3833 PointerTypes.InsertNode(New, InsertPos);
3834 return QualType(New, 0);
3835}
3836
3838 llvm::FoldingSetNodeID ID;
3839 AdjustedType::Profile(ID, Orig, New);
3840 void *InsertPos = nullptr;
3841 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3842 if (AT)
3843 return QualType(AT, 0);
3844
3845 QualType Canonical = getCanonicalType(New);
3846
3847 // Get the new insert position for the node we care about.
3848 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3849 assert(!AT && "Shouldn't be in the map!");
3850
3851 AT = new (*this, alignof(AdjustedType))
3852 AdjustedType(Type::Adjusted, Orig, New, Canonical);
3853 Types.push_back(AT);
3854 AdjustedTypes.InsertNode(AT, InsertPos);
3855 return QualType(AT, 0);
3856}
3857
3859 llvm::FoldingSetNodeID ID;
3860 AdjustedType::Profile(ID, Orig, Decayed);
3861 void *InsertPos = nullptr;
3862 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3863 if (AT)
3864 return QualType(AT, 0);
3865
3866 QualType Canonical = getCanonicalType(Decayed);
3867
3868 // Get the new insert position for the node we care about.
3869 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3870 assert(!AT && "Shouldn't be in the map!");
3871
3872 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
3873 Types.push_back(AT);
3874 AdjustedTypes.InsertNode(AT, InsertPos);
3875 return QualType(AT, 0);
3876}
3877
3879 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
3880
3881 QualType Decayed;
3882
3883 // C99 6.7.5.3p7:
3884 // A declaration of a parameter as "array of type" shall be
3885 // adjusted to "qualified pointer to type", where the type
3886 // qualifiers (if any) are those specified within the [ and ] of
3887 // the array type derivation.
3888 if (T->isArrayType())
3889 Decayed = getArrayDecayedType(T);
3890
3891 // C99 6.7.5.3p8:
3892 // A declaration of a parameter as "function returning type"
3893 // shall be adjusted to "pointer to function returning type", as
3894 // in 6.3.2.1.
3895 if (T->isFunctionType())
3896 Decayed = getPointerType(T);
3897
3898 return getDecayedType(T, Decayed);
3899}
3900
3902 if (Ty->isArrayParameterType())
3903 return Ty;
3904 assert(Ty->isConstantArrayType() && "Ty must be an array type.");
3905 const auto *ATy = cast<ConstantArrayType>(Ty);
3906 llvm::FoldingSetNodeID ID;
3907 ATy->Profile(ID, *this, ATy->getElementType(), ATy->getZExtSize(),
3908 ATy->getSizeExpr(), ATy->getSizeModifier(),
3909 ATy->getIndexTypeQualifiers().getAsOpaqueValue());
3910 void *InsertPos = nullptr;
3911 ArrayParameterType *AT =
3912 ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
3913 if (AT)
3914 return QualType(AT, 0);
3915
3916 QualType Canonical;
3917 if (!Ty.isCanonical()) {
3918 Canonical = getArrayParameterType(getCanonicalType(Ty));
3919
3920 // Get the new insert position for the node we care about.
3921 AT = ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
3922 assert(!AT && "Shouldn't be in the map!");
3923 }
3924
3925 AT = new (*this, alignof(ArrayParameterType))
3926 ArrayParameterType(ATy, Canonical);
3927 Types.push_back(AT);
3928 ArrayParameterTypes.InsertNode(AT, InsertPos);
3929 return QualType(AT, 0);
3930}
3931
3932/// getBlockPointerType - Return the uniqued reference to the type for
3933/// a pointer to the specified block.
3935 assert(T->isFunctionType() && "block of function types only");
3936 // Unique pointers, to guarantee there is only one block of a particular
3937 // structure.
3938 llvm::FoldingSetNodeID ID;
3940
3941 void *InsertPos = nullptr;
3942 if (BlockPointerType *PT =
3943 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3944 return QualType(PT, 0);
3945
3946 // If the block pointee type isn't canonical, this won't be a canonical
3947 // type either so fill in the canonical type field.
3948 QualType Canonical;
3949 if (!T.isCanonical()) {
3951
3952 // Get the new insert position for the node we care about.
3953 BlockPointerType *NewIP =
3954 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3955 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3956 }
3957 auto *New =
3958 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
3959 Types.push_back(New);
3960 BlockPointerTypes.InsertNode(New, InsertPos);
3961 return QualType(New, 0);
3962}
3963
3964/// getLValueReferenceType - Return the uniqued reference to the type for an
3965/// lvalue reference to the specified type.
3967ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
3968 assert((!T->isPlaceholderType() ||
3969 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
3970 "Unresolved placeholder type");
3971
3972 // Unique pointers, to guarantee there is only one pointer of a particular
3973 // structure.
3974 llvm::FoldingSetNodeID ID;
3975 ReferenceType::Profile(ID, T, SpelledAsLValue);
3976
3977 void *InsertPos = nullptr;
3978 if (LValueReferenceType *RT =
3979 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3980 return QualType(RT, 0);
3981
3982 const auto *InnerRef = T->getAs<ReferenceType>();
3983
3984 // If the referencee type isn't canonical, this won't be a canonical type
3985 // either, so fill in the canonical type field.
3986 QualType Canonical;
3987 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
3988 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3989 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
3990
3991 // Get the new insert position for the node we care about.
3992 LValueReferenceType *NewIP =
3993 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3994 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3995 }
3996
3997 auto *New = new (*this, alignof(LValueReferenceType))
3998 LValueReferenceType(T, Canonical, SpelledAsLValue);
3999 Types.push_back(New);
4000 LValueReferenceTypes.InsertNode(New, InsertPos);
4001
4002 return QualType(New, 0);
4003}
4004
4005/// getRValueReferenceType - Return the uniqued reference to the type for an
4006/// rvalue reference to the specified type.
4008 assert((!T->isPlaceholderType() ||
4009 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4010 "Unresolved placeholder type");
4011
4012 // Unique pointers, to guarantee there is only one pointer of a particular
4013 // structure.
4014 llvm::FoldingSetNodeID ID;
4015 ReferenceType::Profile(ID, T, false);
4016
4017 void *InsertPos = nullptr;
4018 if (RValueReferenceType *RT =
4019 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4020 return QualType(RT, 0);
4021
4022 const auto *InnerRef = T->getAs<ReferenceType>();
4023
4024 // If the referencee type isn't canonical, this won't be a canonical type
4025 // either, so fill in the canonical type field.
4026 QualType Canonical;
4027 if (InnerRef || !T.isCanonical()) {
4028 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4029 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
4030
4031 // Get the new insert position for the node we care about.
4032 RValueReferenceType *NewIP =
4033 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4034 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4035 }
4036
4037 auto *New = new (*this, alignof(RValueReferenceType))
4038 RValueReferenceType(T, Canonical);
4039 Types.push_back(New);
4040 RValueReferenceTypes.InsertNode(New, InsertPos);
4041 return QualType(New, 0);
4042}
4043
4044/// getMemberPointerType - Return the uniqued reference to the type for a
4045/// member pointer to the specified type, in the specified class.
4047 // Unique pointers, to guarantee there is only one pointer of a particular
4048 // structure.
4049 llvm::FoldingSetNodeID ID;
4050 MemberPointerType::Profile(ID, T, Cls);
4051
4052 void *InsertPos = nullptr;
4053 if (MemberPointerType *PT =
4054 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4055 return QualType(PT, 0);
4056
4057 // If the pointee or class type isn't canonical, this won't be a canonical
4058 // type either, so fill in the canonical type field.
4059 QualType Canonical;
4060 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
4062
4063 // Get the new insert position for the node we care about.
4064 MemberPointerType *NewIP =
4065 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4066 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4067 }
4068 auto *New = new (*this, alignof(MemberPointerType))
4069 MemberPointerType(T, Cls, Canonical);
4070 Types.push_back(New);
4071 MemberPointerTypes.InsertNode(New, InsertPos);
4072 return QualType(New, 0);
4073}
4074
4075/// getConstantArrayType - Return the unique reference to the type for an
4076/// array of the specified element type.
4078 const llvm::APInt &ArySizeIn,
4079 const Expr *SizeExpr,
4081 unsigned IndexTypeQuals) const {
4082 assert((EltTy->isDependentType() ||
4083 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
4084 "Constant array of VLAs is illegal!");
4085
4086 // We only need the size as part of the type if it's instantiation-dependent.
4087 if (SizeExpr && !SizeExpr->isInstantiationDependent())
4088 SizeExpr = nullptr;
4089
4090 // Convert the array size into a canonical width matching the pointer size for
4091 // the target.
4092 llvm::APInt ArySize(ArySizeIn);
4093 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
4094
4095 llvm::FoldingSetNodeID ID;
4096 ConstantArrayType::Profile(ID, *this, EltTy, ArySize.getZExtValue(), SizeExpr,
4097 ASM, IndexTypeQuals);
4098
4099 void *InsertPos = nullptr;
4100 if (ConstantArrayType *ATP =
4101 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
4102 return QualType(ATP, 0);
4103
4104 // If the element type isn't canonical or has qualifiers, or the array bound
4105 // is instantiation-dependent, this won't be a canonical type either, so fill
4106 // in the canonical type field.
4107 QualType Canon;
4108 // FIXME: Check below should look for qualifiers behind sugar.
4109 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
4110 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4111 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
4112 ASM, IndexTypeQuals);
4113 Canon = getQualifiedType(Canon, canonSplit.Quals);
4114
4115 // Get the new insert position for the node we care about.
4116 ConstantArrayType *NewIP =
4117 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
4118 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4119 }
4120
4121 auto *New = ConstantArrayType::Create(*this, EltTy, Canon, ArySize, SizeExpr,
4122 ASM, IndexTypeQuals);
4123 ConstantArrayTypes.InsertNode(New, InsertPos);
4124 Types.push_back(New);
4125 return QualType(New, 0);
4126}
4127
4128/// getVariableArrayDecayedType - Turns the given type, which may be
4129/// variably-modified, into the corresponding type with all the known
4130/// sizes replaced with [*].
4132 // Vastly most common case.
4133 if (!type->isVariablyModifiedType()) return type;
4134
4135 QualType result;
4136
4137 SplitQualType split = type.getSplitDesugaredType();
4138 const Type *ty = split.Ty;
4139 switch (ty->getTypeClass()) {
4140#define TYPE(Class, Base)
4141#define ABSTRACT_TYPE(Class, Base)
4142#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4143#include "clang/AST/TypeNodes.inc"
4144 llvm_unreachable("didn't desugar past all non-canonical types?");
4145
4146 // These types should never be variably-modified.
4147 case Type::Builtin:
4148 case Type::Complex:
4149 case Type::Vector:
4150 case Type::DependentVector:
4151 case Type::ExtVector:
4152 case Type::DependentSizedExtVector:
4153 case Type::ConstantMatrix:
4154 case Type::DependentSizedMatrix:
4155 case Type::DependentAddressSpace:
4156 case Type::ObjCObject:
4157 case Type::ObjCInterface:
4158 case Type::ObjCObjectPointer:
4159 case Type::Record:
4160 case Type::Enum:
4161 case Type::UnresolvedUsing:
4162 case Type::TypeOfExpr:
4163 case Type::TypeOf:
4164 case Type::Decltype:
4165 case Type::UnaryTransform:
4166 case Type::DependentName:
4167 case Type::InjectedClassName:
4168 case Type::TemplateSpecialization:
4169 case Type::DependentTemplateSpecialization:
4170 case Type::TemplateTypeParm:
4171 case Type::SubstTemplateTypeParmPack:
4172 case Type::Auto:
4173 case Type::DeducedTemplateSpecialization:
4174 case Type::PackExpansion:
4175 case Type::PackIndexing:
4176 case Type::BitInt:
4177 case Type::DependentBitInt:
4178 case Type::ArrayParameter:
4179 case Type::HLSLAttributedResource:
4180 llvm_unreachable("type should never be variably-modified");
4181
4182 // These types can be variably-modified but should never need to
4183 // further decay.
4184 case Type::FunctionNoProto:
4185 case Type::FunctionProto:
4186 case Type::BlockPointer:
4187 case Type::MemberPointer:
4188 case Type::Pipe:
4189 return type;
4190
4191 // These types can be variably-modified. All these modifications
4192 // preserve structure except as noted by comments.
4193 // TODO: if we ever care about optimizing VLAs, there are no-op
4194 // optimizations available here.
4195 case Type::Pointer:
4197 cast<PointerType>(ty)->getPointeeType()));
4198 break;
4199
4200 case Type::LValueReference: {
4201 const auto *lv = cast<LValueReferenceType>(ty);
4202 result = getLValueReferenceType(
4203 getVariableArrayDecayedType(lv->getPointeeType()),
4204 lv->isSpelledAsLValue());
4205 break;
4206 }
4207
4208 case Type::RValueReference: {
4209 const auto *lv = cast<RValueReferenceType>(ty);
4210 result = getRValueReferenceType(
4211 getVariableArrayDecayedType(lv->getPointeeType()));
4212 break;
4213 }
4214
4215 case Type::Atomic: {
4216 const auto *at = cast<AtomicType>(ty);
4217 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
4218 break;
4219 }
4220
4221 case Type::ConstantArray: {
4222 const auto *cat = cast<ConstantArrayType>(ty);
4223 result = getConstantArrayType(
4224 getVariableArrayDecayedType(cat->getElementType()),
4225 cat->getSize(),
4226 cat->getSizeExpr(),
4227 cat->getSizeModifier(),
4228 cat->getIndexTypeCVRQualifiers());
4229 break;
4230 }
4231
4232 case Type::DependentSizedArray: {
4233 const auto *dat = cast<DependentSizedArrayType>(ty);
4235 getVariableArrayDecayedType(dat->getElementType()),
4236 dat->getSizeExpr(),
4237 dat->getSizeModifier(),
4238 dat->getIndexTypeCVRQualifiers(),
4239 dat->getBracketsRange());
4240 break;
4241 }
4242
4243 // Turn incomplete types into [*] types.
4244 case Type::IncompleteArray: {
4245 const auto *iat = cast<IncompleteArrayType>(ty);
4246 result =
4248 /*size*/ nullptr, ArraySizeModifier::Normal,
4249 iat->getIndexTypeCVRQualifiers(), SourceRange());
4250 break;
4251 }
4252
4253 // Turn VLA types into [*] types.
4254 case Type::VariableArray: {
4255 const auto *vat = cast<VariableArrayType>(ty);
4256 result = getVariableArrayType(
4257 getVariableArrayDecayedType(vat->getElementType()),
4258 /*size*/ nullptr, ArraySizeModifier::Star,
4259 vat->getIndexTypeCVRQualifiers(), vat->getBracketsRange());
4260 break;
4261 }
4262 }
4263
4264 // Apply the top-level qualifiers from the original.
4265 return getQualifiedType(result, split.Quals);
4266}
4267
4268/// getVariableArrayType - Returns a non-unique reference to the type for a
4269/// variable array of the specified element type.
4272 unsigned IndexTypeQuals,
4273 SourceRange Brackets) const {
4274 // Since we don't unique expressions, it isn't possible to unique VLA's
4275 // that have an expression provided for their size.
4276 QualType Canon;
4277
4278 // Be sure to pull qualifiers off the element type.
4279 // FIXME: Check below should look for qualifiers behind sugar.
4280 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
4281 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4282 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
4283 IndexTypeQuals, Brackets);
4284 Canon = getQualifiedType(Canon, canonSplit.Quals);
4285 }
4286
4287 auto *New = new (*this, alignof(VariableArrayType))
4288 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
4289
4290 VariableArrayTypes.push_back(New);
4291 Types.push_back(New);
4292 return QualType(New, 0);
4293}
4294
4295/// getDependentSizedArrayType - Returns a non-unique reference to
4296/// the type for a dependently-sized array of the specified element
4297/// type.
4299 Expr *numElements,
4301 unsigned elementTypeQuals,
4302 SourceRange brackets) const {
4303 assert((!numElements || numElements->isTypeDependent() ||
4304 numElements->isValueDependent()) &&
4305 "Size must be type- or value-dependent!");
4306
4307 SplitQualType canonElementType = getCanonicalType(elementType).split();
4308
4309 void *insertPos = nullptr;
4310 llvm::FoldingSetNodeID ID;
4312 ID, *this, numElements ? QualType(canonElementType.Ty, 0) : elementType,
4313 ASM, elementTypeQuals, numElements);
4314
4315 // Look for an existing type with these properties.
4316 DependentSizedArrayType *canonTy =
4317 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4318
4319 // Dependently-sized array types that do not have a specified number
4320 // of elements will have their sizes deduced from a dependent
4321 // initializer.
4322 if (!numElements) {
4323 if (canonTy)
4324 return QualType(canonTy, 0);
4325
4326 auto *newType = new (*this, alignof(DependentSizedArrayType))
4327 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
4328 elementTypeQuals, brackets);
4329 DependentSizedArrayTypes.InsertNode(newType, insertPos);
4330 Types.push_back(newType);
4331 return QualType(newType, 0);
4332 }
4333
4334 // If we don't have one, build one.
4335 if (!canonTy) {
4336 canonTy = new (*this, alignof(DependentSizedArrayType))
4337 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
4338 numElements, ASM, elementTypeQuals, brackets);
4339 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
4340 Types.push_back(canonTy);
4341 }
4342
4343 // Apply qualifiers from the element type to the array.
4344 QualType canon = getQualifiedType(QualType(canonTy,0),
4345 canonElementType.Quals);
4346
4347 // If we didn't need extra canonicalization for the element type or the size
4348 // expression, then just use that as our result.
4349 if (QualType(canonElementType.Ty, 0) == elementType &&
4350 canonTy->getSizeExpr() == numElements)
4351 return canon;
4352
4353 // Otherwise, we need to build a type which follows the spelling
4354 // of the element type.
4355 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
4356 DependentSizedArrayType(elementType, canon, numElements, ASM,
4357 elementTypeQuals, brackets);
4358 Types.push_back(sugaredType);
4359 return QualType(sugaredType, 0);
4360}
4361
4364 unsigned elementTypeQuals) const {
4365 llvm::FoldingSetNodeID ID;
4366 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
4367
4368 void *insertPos = nullptr;
4369 if (IncompleteArrayType *iat =
4370 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
4371 return QualType(iat, 0);
4372
4373 // If the element type isn't canonical, this won't be a canonical type
4374 // either, so fill in the canonical type field. We also have to pull
4375 // qualifiers off the element type.
4376 QualType canon;
4377
4378 // FIXME: Check below should look for qualifiers behind sugar.
4379 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
4380 SplitQualType canonSplit = getCanonicalType(elementType).split();
4381 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
4382 ASM, elementTypeQuals);
4383 canon = getQualifiedType(canon, canonSplit.Quals);
4384
4385 // Get the new insert position for the node we care about.
4386 IncompleteArrayType *existing =
4387 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4388 assert(!existing && "Shouldn't be in the map!"); (void) existing;
4389 }
4390
4391 auto *newType = new (*this, alignof(IncompleteArrayType))
4392 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
4393
4394 IncompleteArrayTypes.InsertNode(newType, insertPos);
4395 Types.push_back(newType);
4396 return QualType(newType, 0);
4397}
4398
4401#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
4402 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
4403 NUMVECTORS};
4404
4405#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
4406 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
4407
4408 switch (Ty->getKind()) {
4409 default:
4410 llvm_unreachable("Unsupported builtin vector type");
4411
4412#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4413 ElBits, NF, IsSigned) \
4414 case BuiltinType::Id: \
4415 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4416 llvm::ElementCount::getScalable(NumEls), NF};
4417#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4418 ElBits, NF) \
4419 case BuiltinType::Id: \
4420 return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy), \
4421 llvm::ElementCount::getScalable(NumEls), NF};
4422#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4423 ElBits, NF) \
4424 case BuiltinType::Id: \
4425 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4426#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4427 case BuiltinType::Id: \
4428 return {BoolTy, llvm::ElementCount::getScalable(NumEls), NF};
4429#define AARCH64_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4430 ElBits, NF) \
4431 case BuiltinType::Id: \
4432 return {getIntTypeForBitwidth(ElBits, false), \
4433 llvm::ElementCount::getFixed(NumEls), NF};
4434#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId)
4435#include "clang/Basic/AArch64SVEACLETypes.def"
4436
4437#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4438 IsSigned) \
4439 case BuiltinType::Id: \
4440 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4441 llvm::ElementCount::getScalable(NumEls), NF};
4442#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4443 case BuiltinType::Id: \
4444 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4445 llvm::ElementCount::getScalable(NumEls), NF};
4446#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4447 case BuiltinType::Id: \
4448 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4449#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4450 case BuiltinType::Id: \
4451 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4452#include "clang/Basic/RISCVVTypes.def"
4453 }
4454}
4455
4456/// getExternrefType - Return a WebAssembly externref type, which represents an
4457/// opaque reference to a host value.
4459 if (Target->getTriple().isWasm() && Target->hasFeature("reference-types")) {
4460#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4461 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4462 return SingletonId;
4463#include "clang/Basic/WebAssemblyReferenceTypes.def"
4464 }
4465 llvm_unreachable(
4466 "shouldn't try to generate type externref outside WebAssembly target");
4467}
4468
4469/// getScalableVectorType - Return the unique reference to a scalable vector
4470/// type of the specified element type and size. VectorType must be a built-in
4471/// type.
4473 unsigned NumFields) const {
4474 if (Target->hasAArch64SVETypes()) {
4475 uint64_t EltTySize = getTypeSize(EltTy);
4476
4477#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4478 ElBits, NF, IsSigned) \
4479 if (EltTy->hasIntegerRepresentation() && !EltTy->isBooleanType() && \
4480 EltTy->hasSignedIntegerRepresentation() == IsSigned && \
4481 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4482 return SingletonId; \
4483 }
4484#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4485 ElBits, NF) \
4486 if (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4487 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4488 return SingletonId; \
4489 }
4490#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4491 ElBits, NF) \
4492 if (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4493 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4494 return SingletonId; \
4495 }
4496#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4497 if (EltTy->isBooleanType() && NumElts == (NumEls * NF) && NumFields == 1) \
4498 return SingletonId;
4499#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId)
4500#define AARCH64_VECTOR_TYPE(Name, MangledName, Id, SingletonId)
4501#include "clang/Basic/AArch64SVEACLETypes.def"
4502 } else if (Target->hasRISCVVTypes()) {
4503 uint64_t EltTySize = getTypeSize(EltTy);
4504#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4505 IsFP, IsBF) \
4506 if (!EltTy->isBooleanType() && \
4507 ((EltTy->hasIntegerRepresentation() && \
4508 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4509 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4510 IsFP && !IsBF) || \
4511 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4512 IsBF && !IsFP)) && \
4513 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4514 return SingletonId;
4515#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4516 if (EltTy->isBooleanType() && NumElts == NumEls) \
4517 return SingletonId;
4518#include "clang/Basic/RISCVVTypes.def"
4519 }
4520 return QualType();
4521}
4522
4523/// getVectorType - Return the unique reference to a vector type of
4524/// the specified element type and size. VectorType must be a built-in type.
4526 VectorKind VecKind) const {
4527 assert(vecType->isBuiltinType() ||
4528 (vecType->isBitIntType() &&
4529 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4530 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits()) &&
4531 vecType->castAs<BitIntType>()->getNumBits() >= 8));
4532
4533 // Check if we've already instantiated a vector of this type.
4534 llvm::FoldingSetNodeID ID;
4535 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
4536
4537 void *InsertPos = nullptr;
4538 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4539 return QualType(VTP, 0);
4540
4541 // If the element type isn't canonical, this won't be a canonical type either,
4542 // so fill in the canonical type field.
4543 QualType Canonical;
4544 if (!vecType.isCanonical()) {
4545 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4546
4547 // Get the new insert position for the node we care about.
4548 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4549 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4550 }
4551 auto *New = new (*this, alignof(VectorType))
4552 VectorType(vecType, NumElts, Canonical, VecKind);
4553 VectorTypes.InsertNode(New, InsertPos);
4554 Types.push_back(New);
4555 return QualType(New, 0);
4556}
4557
4559 SourceLocation AttrLoc,
4560 VectorKind VecKind) const {
4561 llvm::FoldingSetNodeID ID;
4562 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4563 VecKind);
4564 void *InsertPos = nullptr;
4565 DependentVectorType *Canon =
4566 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4568
4569 if (Canon) {
4570 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4571 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4572 } else {
4573 QualType CanonVecTy = getCanonicalType(VecType);
4574 if (CanonVecTy == VecType) {
4575 New = new (*this, alignof(DependentVectorType))
4576 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4577
4578 DependentVectorType *CanonCheck =
4579 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4580 assert(!CanonCheck &&
4581 "Dependent-sized vector_size canonical type broken");
4582 (void)CanonCheck;
4583 DependentVectorTypes.InsertNode(New, InsertPos);
4584 } else {
4585 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4586 SourceLocation(), VecKind);
4587 New = new (*this, alignof(DependentVectorType))
4588 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4589 }
4590 }
4591
4592 Types.push_back(New);
4593 return QualType(New, 0);
4594}
4595
4596/// getExtVectorType - Return the unique reference to an extended vector type of
4597/// the specified element type and size. VectorType must be a built-in type.
4599 unsigned NumElts) const {
4600 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4601 (vecType->isBitIntType() &&
4602 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4603 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits()) &&
4604 vecType->castAs<BitIntType>()->getNumBits() >= 8));
4605
4606 // Check if we've already instantiated a vector of this type.
4607 llvm::FoldingSetNodeID ID;
4608 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4610 void *InsertPos = nullptr;
4611 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4612 return QualType(VTP, 0);
4613
4614 // If the element type isn't canonical, this won't be a canonical type either,
4615 // so fill in the canonical type field.
4616 QualType Canonical;
4617 if (!vecType.isCanonical()) {
4618 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4619
4620 // Get the new insert position for the node we care about.
4621 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4622 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4623 }
4624 auto *New = new (*this, alignof(ExtVectorType))
4625 ExtVectorType(vecType, NumElts, Canonical);
4626 VectorTypes.InsertNode(New, InsertPos);
4627 Types.push_back(New);
4628 return QualType(New, 0);
4629}
4630
4633 Expr *SizeExpr,
4634 SourceLocation AttrLoc) const {
4635 llvm::FoldingSetNodeID ID;
4637 SizeExpr);
4638
4639 void *InsertPos = nullptr;
4641 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4643 if (Canon) {
4644 // We already have a canonical version of this array type; use it as
4645 // the canonical type for a newly-built type.
4646 New = new (*this, alignof(DependentSizedExtVectorType))
4647 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4648 AttrLoc);
4649 } else {
4650 QualType CanonVecTy = getCanonicalType(vecType);
4651 if (CanonVecTy == vecType) {
4652 New = new (*this, alignof(DependentSizedExtVectorType))
4653 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4654
4655 DependentSizedExtVectorType *CanonCheck
4656 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4657 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4658 (void)CanonCheck;
4659 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4660 } else {
4661 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4662 SourceLocation());
4663 New = new (*this, alignof(DependentSizedExtVectorType))
4664 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4665 }
4666 }
4667
4668 Types.push_back(New);
4669 return QualType(New, 0);
4670}
4671
4673 unsigned NumColumns) const {
4674 llvm::FoldingSetNodeID ID;
4675 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4676 Type::ConstantMatrix);
4677
4678 assert(MatrixType::isValidElementType(ElementTy) &&
4679 "need a valid element type");
4680 assert(ConstantMatrixType::isDimensionValid(NumRows) &&
4682 "need valid matrix dimensions");
4683 void *InsertPos = nullptr;
4684 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4685 return QualType(MTP, 0);
4686
4687 QualType Canonical;
4688 if (!ElementTy.isCanonical()) {
4689 Canonical =
4690 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4691
4692 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4693 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4694 (void)NewIP;
4695 }
4696
4697 auto *New = new (*this, alignof(ConstantMatrixType))
4698 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4699 MatrixTypes.InsertNode(New, InsertPos);
4700 Types.push_back(New);
4701 return QualType(New, 0);
4702}
4703
4705 Expr *RowExpr,
4706 Expr *ColumnExpr,
4707 SourceLocation AttrLoc) const {
4708 QualType CanonElementTy = getCanonicalType(ElementTy);
4709 llvm::FoldingSetNodeID ID;
4710 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4711 ColumnExpr);
4712
4713 void *InsertPos = nullptr;
4715 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4716
4717 if (!Canon) {
4718 Canon = new (*this, alignof(DependentSizedMatrixType))
4719 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4720 ColumnExpr, AttrLoc);
4721#ifndef NDEBUG
4722 DependentSizedMatrixType *CanonCheck =
4723 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4724 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4725#endif
4726 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4727 Types.push_back(Canon);
4728 }
4729
4730 // Already have a canonical version of the matrix type
4731 //
4732 // If it exactly matches the requested type, use it directly.
4733 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4734 Canon->getRowExpr() == ColumnExpr)
4735 return QualType(Canon, 0);
4736
4737 // Use Canon as the canonical type for newly-built type.
4738 DependentSizedMatrixType *New = new (*this, alignof(DependentSizedMatrixType))
4739 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4740 ColumnExpr, AttrLoc);
4741 Types.push_back(New);
4742 return QualType(New, 0);
4743}
4744
4746 Expr *AddrSpaceExpr,
4747 SourceLocation AttrLoc) const {
4748 assert(AddrSpaceExpr->isInstantiationDependent());
4749
4750 QualType canonPointeeType = getCanonicalType(PointeeType);
4751
4752 void *insertPos = nullptr;
4753 llvm::FoldingSetNodeID ID;
4754 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4755 AddrSpaceExpr);
4756
4757 DependentAddressSpaceType *canonTy =
4758 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4759
4760 if (!canonTy) {
4761 canonTy = new (*this, alignof(DependentAddressSpaceType))
4762 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
4763 AttrLoc);
4764 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4765 Types.push_back(canonTy);
4766 }
4767
4768 if (canonPointeeType == PointeeType &&
4769 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4770 return QualType(canonTy, 0);
4771
4772 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
4773 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
4774 AddrSpaceExpr, AttrLoc);
4775 Types.push_back(sugaredType);
4776 return QualType(sugaredType, 0);
4777}
4778
4779/// Determine whether \p T is canonical as the result type of a function.
4781 return T.isCanonical() &&
4782 (T.getObjCLifetime() == Qualifiers::OCL_None ||
4783 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4784}
4785
4786/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4789 const FunctionType::ExtInfo &Info) const {
4790 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
4791 // functionality creates a function without a prototype regardless of
4792 // language mode (so it makes them even in C++). Once the rewriter has been
4793 // fixed, this assertion can be enabled again.
4794 //assert(!LangOpts.requiresStrictPrototypes() &&
4795 // "strict prototypes are disabled");
4796
4797 // Unique functions, to guarantee there is only one function of a particular
4798 // structure.
4799 llvm::FoldingSetNodeID ID;
4800 FunctionNoProtoType::Profile(ID, ResultTy, Info);
4801
4802 void *InsertPos = nullptr;
4803 if (FunctionNoProtoType *FT =
4804 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4805 return QualType(FT, 0);
4806
4807 QualType Canonical;
4808 if (!isCanonicalResultType(ResultTy)) {
4809 Canonical =
4811
4812 // Get the new insert position for the node we care about.
4813 FunctionNoProtoType *NewIP =
4814 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4815 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4816 }
4817
4818 auto *New = new (*this, alignof(FunctionNoProtoType))
4819 FunctionNoProtoType(ResultTy, Canonical, Info);
4820 Types.push_back(New);
4821 FunctionNoProtoTypes.InsertNode(New, InsertPos);
4822 return QualType(New, 0);
4823}
4824
4827 CanQualType CanResultType = getCanonicalType(ResultType);
4828
4829 // Canonical result types do not have ARC lifetime qualifiers.
4830 if (CanResultType.getQualifiers().hasObjCLifetime()) {
4831 Qualifiers Qs = CanResultType.getQualifiers();
4832 Qs.removeObjCLifetime();
4834 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
4835 }
4836
4837 return CanResultType;
4838}
4839
4841 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
4842 if (ESI.Type == EST_None)
4843 return true;
4844 if (!NoexceptInType)
4845 return false;
4846
4847 // C++17 onwards: exception specification is part of the type, as a simple
4848 // boolean "can this function type throw".
4849 if (ESI.Type == EST_BasicNoexcept)
4850 return true;
4851
4852 // A noexcept(expr) specification is (possibly) canonical if expr is
4853 // value-dependent.
4854 if (ESI.Type == EST_DependentNoexcept)
4855 return true;
4856
4857 // A dynamic exception specification is canonical if it only contains pack
4858 // expansions (so we can't tell whether it's non-throwing) and all its
4859 // contained types are canonical.
4860 if (ESI.Type == EST_Dynamic) {
4861 bool AnyPackExpansions = false;
4862 for (QualType ET : ESI.Exceptions) {
4863 if (!ET.isCanonical())
4864 return false;
4865 if (ET->getAs<PackExpansionType>())
4866 AnyPackExpansions = true;
4867 }
4868 return AnyPackExpansions;
4869 }
4870
4871 return false;
4872}
4873
4874QualType ASTContext::getFunctionTypeInternal(
4875 QualType ResultTy, ArrayRef<QualType> ArgArray,
4876 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
4877 size_t NumArgs = ArgArray.size();
4878
4879 // Unique functions, to guarantee there is only one function of a particular
4880 // structure.
4881 llvm::FoldingSetNodeID ID;
4882 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
4883 *this, true);
4884
4885 QualType Canonical;
4886 bool Unique = false;
4887
4888 void *InsertPos = nullptr;
4889 if (FunctionProtoType *FPT =
4890 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4891 QualType Existing = QualType(FPT, 0);
4892
4893 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
4894 // it so long as our exception specification doesn't contain a dependent
4895 // noexcept expression, or we're just looking for a canonical type.
4896 // Otherwise, we're going to need to create a type
4897 // sugar node to hold the concrete expression.
4898 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
4899 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
4900 return Existing;
4901
4902 // We need a new type sugar node for this one, to hold the new noexcept
4903 // expression. We do no canonicalization here, but that's OK since we don't
4904 // expect to see the same noexcept expression much more than once.
4905 Canonical = getCanonicalType(Existing);
4906 Unique = true;
4907 }
4908
4909 bool NoexceptInType = getLangOpts().CPlusPlus17;
4910 bool IsCanonicalExceptionSpec =
4912
4913 // Determine whether the type being created is already canonical or not.
4914 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
4915 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
4916 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
4917 if (!ArgArray[i].isCanonicalAsParam())
4918 isCanonical = false;
4919
4920 if (OnlyWantCanonical)
4921 assert(isCanonical &&
4922 "given non-canonical parameters constructing canonical type");
4923
4924 // If this type isn't canonical, get the canonical version of it if we don't
4925 // already have it. The exception spec is only partially part of the
4926 // canonical type, and only in C++17 onwards.
4927 if (!isCanonical && Canonical.isNull()) {
4928 SmallVector<QualType, 16> CanonicalArgs;
4929 CanonicalArgs.reserve(NumArgs);
4930 for (unsigned i = 0; i != NumArgs; ++i)
4931 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
4932
4933 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
4934 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
4935 CanonicalEPI.HasTrailingReturn = false;
4936
4937 if (IsCanonicalExceptionSpec) {
4938 // Exception spec is already OK.
4939 } else if (NoexceptInType) {
4940 switch (EPI.ExceptionSpec.Type) {
4942 // We don't know yet. It shouldn't matter what we pick here; no-one
4943 // should ever look at this.
4944 [[fallthrough]];
4945 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
4946 CanonicalEPI.ExceptionSpec.Type = EST_None;
4947 break;
4948
4949 // A dynamic exception specification is almost always "not noexcept",
4950 // with the exception that a pack expansion might expand to no types.
4951 case EST_Dynamic: {
4952 bool AnyPacks = false;
4953 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
4954 if (ET->getAs<PackExpansionType>())
4955 AnyPacks = true;
4956 ExceptionTypeStorage.push_back(getCanonicalType(ET));
4957 }
4958 if (!AnyPacks)
4959 CanonicalEPI.ExceptionSpec.Type = EST_None;
4960 else {
4961 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
4962 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
4963 }
4964 break;
4965 }
4966
4967 case EST_DynamicNone:
4968 case EST_BasicNoexcept:
4969 case EST_NoexceptTrue:
4970 case EST_NoThrow:
4971 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
4972 break;
4973
4975 llvm_unreachable("dependent noexcept is already canonical");
4976 }
4977 } else {
4979 }
4980
4981 // Adjust the canonical function result type.
4982 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
4983 Canonical =
4984 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
4985
4986 // Get the new insert position for the node we care about.
4987 FunctionProtoType *NewIP =
4988 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4989 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4990 }
4991
4992 // Compute the needed size to hold this FunctionProtoType and the
4993 // various trailing objects.
4994 auto ESH = FunctionProtoType::getExceptionSpecSize(
4995 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
4996 size_t Size = FunctionProtoType::totalSizeToAlloc<
5002 EPI.requiresFunctionProtoTypeArmAttributes(), ESH.NumExceptionType,
5003 ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
5004 EPI.ExtParameterInfos ? NumArgs : 0,
5006 EPI.FunctionEffects.conditions().size());
5007
5008 auto *FTP = (FunctionProtoType *)Allocate(Size, alignof(FunctionProtoType));
5010 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
5011 Types.push_back(FTP);
5012 if (!Unique)
5013 FunctionProtoTypes.InsertNode(FTP, InsertPos);
5014 if (!EPI.FunctionEffects.empty())
5015 AnyFunctionEffects = true;
5016 return QualType(FTP, 0);
5017}
5018
5019QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
5020 llvm::FoldingSetNodeID ID;
5021 PipeType::Profile(ID, T, ReadOnly);
5022
5023 void *InsertPos = nullptr;
5024 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
5025 return QualType(PT, 0);
5026
5027 // If the pipe element type isn't canonical, this won't be a canonical type
5028 // either, so fill in the canonical type field.
5029 QualType Canonical;
5030 if (!T.isCanonical()) {
5031 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
5032
5033 // Get the new insert position for the node we care about.
5034 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
5035 assert(!NewIP && "Shouldn't be in the map!");
5036 (void)NewIP;
5037 }
5038 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
5039 Types.push_back(New);
5040 PipeTypes.InsertNode(New, InsertPos);
5041 return QualType(New, 0);
5042}
5043
5045 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
5046 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
5047 : Ty;
5048}
5049
5051 return getPipeType(T, true);
5052}
5053
5055 return getPipeType(T, false);
5056}
5057
5058QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
5059 llvm::FoldingSetNodeID ID;
5060 BitIntType::Profile(ID, IsUnsigned, NumBits);
5061
5062 void *InsertPos = nullptr;
5063 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5064 return QualType(EIT, 0);
5065
5066 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
5067 BitIntTypes.InsertNode(New, InsertPos);
5068 Types.push_back(New);
5069 return QualType(New, 0);
5070}
5071
5073 Expr *NumBitsExpr) const {
5074 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
5075 llvm::FoldingSetNodeID ID;
5076 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
5077
5078 void *InsertPos = nullptr;
5079 if (DependentBitIntType *Existing =
5080 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5081 return QualType(Existing, 0);
5082
5083 auto *New = new (*this, alignof(DependentBitIntType))
5084 DependentBitIntType(IsUnsigned, NumBitsExpr);
5085 DependentBitIntTypes.InsertNode(New, InsertPos);
5086
5087 Types.push_back(New);
5088 return QualType(New, 0);
5089}
5090
5091#ifndef NDEBUG
5093 if (!isa<CXXRecordDecl>(D)) return false;
5094 const auto *RD = cast<CXXRecordDecl>(D);
5095 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
5096 return true;
5097 if (RD->getDescribedClassTemplate() &&
5098 !isa<ClassTemplateSpecializationDecl>(RD))
5099 return true;
5100 return false;
5101}
5102#endif
5103
5104/// getInjectedClassNameType - Return the unique reference to the
5105/// injected class name type for the specified templated declaration.
5107 QualType TST) const {
5109 if (Decl->TypeForDecl) {
5110 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
5111 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
5112 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
5113 Decl->TypeForDecl = PrevDecl->TypeForDecl;
5114 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
5115 } else {
5116 Type *newType = new (*this, alignof(InjectedClassNameType))
5118 Decl->TypeForDecl = newType;
5119 Types.push_back(newType);
5120 }
5121 return QualType(Decl->TypeForDecl, 0);
5122}
5123
5124/// getTypeDeclType - Return the unique reference to the type for the
5125/// specified type declaration.
5126QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
5127 assert(Decl && "Passed null for Decl param");
5128 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
5129
5130 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
5131 return getTypedefType(Typedef);
5132
5133 assert(!isa<TemplateTypeParmDecl>(Decl) &&
5134 "Template type parameter types are always available.");
5135
5136 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
5137 assert(Record->isFirstDecl() && "struct/union has previous declaration");
5139 return getRecordType(Record);
5140 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
5141 assert(Enum->isFirstDecl() && "enum has previous declaration");
5142 return getEnumType(Enum);
5143 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
5144 return getUnresolvedUsingType(Using);
5145 } else
5146 llvm_unreachable("TypeDecl without a type?");
5147
5148 return QualType(Decl->TypeForDecl, 0);
5149}
5150
5151/// getTypedefType - Return the unique reference to the type for the
5152/// specified typedef name decl.
5154 QualType Underlying) const {
5155 if (!Decl->TypeForDecl) {
5156 if (Underlying.isNull())
5157 Underlying = Decl->getUnderlyingType();
5158 auto *NewType = new (*this, alignof(TypedefType)) TypedefType(
5159 Type::Typedef, Decl, QualType(), getCanonicalType(Underlying));
5160 Decl->TypeForDecl = NewType;
5161 Types.push_back(NewType);
5162 return QualType(NewType, 0);
5163 }
5164 if (Underlying.isNull() || Decl->getUnderlyingType() == Underlying)
5165 return QualType(Decl->TypeForDecl, 0);
5166 assert(hasSameType(Decl->getUnderlyingType(), Underlying));
5167
5168 llvm::FoldingSetNodeID ID;
5169 TypedefType::Profile(ID, Decl, Underlying);
5170
5171 void *InsertPos = nullptr;
5172 if (TypedefType *T = TypedefTypes.FindNodeOrInsertPos(ID, InsertPos)) {
5173 assert(!T->typeMatchesDecl() &&
5174 "non-divergent case should be handled with TypeDecl");
5175 return QualType(T, 0);
5176 }
5177
5178 void *Mem = Allocate(TypedefType::totalSizeToAlloc<QualType>(true),
5179 alignof(TypedefType));
5180 auto *NewType = new (Mem) TypedefType(Type::Typedef, Decl, Underlying,
5181 getCanonicalType(Underlying));
5182 TypedefTypes.InsertNode(NewType, InsertPos);
5183 Types.push_back(NewType);
5184 return QualType(NewType, 0);
5185}
5186
5188 QualType Underlying) const {
5189 llvm::FoldingSetNodeID ID;
5190 UsingType::Profile(ID, Found, Underlying);
5191
5192 void *InsertPos = nullptr;
5193 if (UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5194 return QualType(T, 0);
5195
5196 const Type *TypeForDecl =
5197 cast<TypeDecl>(Found->getTargetDecl())->getTypeForDecl();
5198
5199 assert(!Underlying.hasLocalQualifiers());
5200 QualType Canon = Underlying->getCanonicalTypeInternal();
5201 assert(TypeForDecl->getCanonicalTypeInternal() == Canon);
5202
5203 if (Underlying.getTypePtr() == TypeForDecl)
5204 Underlying = QualType();
5205 void *Mem =
5206 Allocate(UsingType::totalSizeToAlloc<QualType>(!Underlying.isNull()),
5207 alignof(UsingType));
5208 UsingType *NewType = new (Mem) UsingType(Found, Underlying, Canon);
5209 Types.push_back(NewType);
5210 UsingTypes.InsertNode(NewType, InsertPos);
5211 return QualType(NewType, 0);
5212}
5213
5215 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
5216
5217 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
5218 if (PrevDecl->TypeForDecl)
5219 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
5220
5221 auto *newType = new (*this, alignof(RecordType)) RecordType(Decl);
5222 Decl->TypeForDecl = newType;
5223 Types.push_back(newType);
5224 return QualType(newType, 0);
5225}
5226
5228 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
5229
5230 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
5231 if (PrevDecl->TypeForDecl)
5232 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
5233
5234 auto *newType = new (*this, alignof(EnumType)) EnumType(Decl);
5235 Decl->TypeForDecl = newType;
5236 Types.push_back(newType);
5237 return QualType(newType, 0);
5238}
5239
5240bool ASTContext::computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits,
5241 unsigned NumPositiveBits,
5242 QualType &BestType,
5243 QualType &BestPromotionType) {
5244 unsigned IntWidth = Target->getIntWidth();
5245 unsigned CharWidth = Target->getCharWidth();
5246 unsigned ShortWidth = Target->getShortWidth();
5247 bool EnumTooLarge = false;
5248 unsigned BestWidth;
5249 if (NumNegativeBits) {
5250 // If there is a negative value, figure out the smallest integer type (of
5251 // int/long/longlong) that fits.
5252 // If it's packed, check also if it fits a char or a short.
5253 if (IsPacked && NumNegativeBits <= CharWidth &&
5254 NumPositiveBits < CharWidth) {
5255 BestType = SignedCharTy;
5256 BestWidth = CharWidth;
5257 } else if (IsPacked && NumNegativeBits <= ShortWidth &&
5258 NumPositiveBits < ShortWidth) {
5259 BestType = ShortTy;
5260 BestWidth = ShortWidth;
5261 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5262 BestType = IntTy;
5263 BestWidth = IntWidth;
5264 } else {
5265 BestWidth = Target->getLongWidth();
5266
5267 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
5268 BestType = LongTy;
5269 } else {
5270 BestWidth = Target->getLongLongWidth();
5271
5272 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5273 EnumTooLarge = true;
5274 BestType = LongLongTy;
5275 }
5276 }
5277 BestPromotionType = (BestWidth <= IntWidth ? IntTy : BestType);
5278 } else {
5279 // If there is no negative value, figure out the smallest type that fits
5280 // all of the enumerator values.
5281 // If it's packed, check also if it fits a char or a short.
5282 if (IsPacked && NumPositiveBits <= CharWidth) {
5283 BestType = UnsignedCharTy;
5284 BestPromotionType = IntTy;
5285 BestWidth = CharWidth;
5286 } else if (IsPacked && NumPositiveBits <= ShortWidth) {
5287 BestType = UnsignedShortTy;
5288 BestPromotionType = IntTy;
5289 BestWidth = ShortWidth;
5290 } else if (NumPositiveBits <= IntWidth) {
5291 BestType = UnsignedIntTy;
5292 BestWidth = IntWidth;
5293 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5295 : IntTy;
5296 } else if (NumPositiveBits <= (BestWidth = Target->getLongWidth())) {
5297 BestType = UnsignedLongTy;
5298 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5300 : LongTy;
5301 } else {
5302 BestWidth = Target->getLongLongWidth();
5303 if (NumPositiveBits > BestWidth) {
5304 // This can happen with bit-precise integer types, but those are not
5305 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
5306 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
5307 // a 128-bit integer, we should consider doing the same.
5308 EnumTooLarge = true;
5309 }
5310 BestType = UnsignedLongLongTy;
5311 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5313 : LongLongTy;
5314 }
5315 }
5316 return EnumTooLarge;
5317}
5318
5320 const UnresolvedUsingTypenameDecl *Decl) const {
5321 if (Decl->TypeForDecl)
5322 return QualType(Decl->TypeForDecl, 0);
5323
5324 if (const UnresolvedUsingTypenameDecl *CanonicalDecl =
5326 if (CanonicalDecl->TypeForDecl)
5327 return QualType(Decl->TypeForDecl = CanonicalDecl->TypeForDecl, 0);
5328
5329 Type *newType =
5330 new (*this, alignof(UnresolvedUsingType)) UnresolvedUsingType(Decl);
5331 Decl->TypeForDecl = newType;
5332 Types.push_back(newType);
5333 return QualType(newType, 0);
5334}
5335
5337 QualType modifiedType,
5338 QualType equivalentType,
5339 const Attr *attr) const {
5340 llvm::FoldingSetNodeID id;
5341 AttributedType::Profile(id, attrKind, modifiedType, equivalentType, attr);
5342
5343 void *insertPos = nullptr;
5344 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
5345 if (type) return QualType(type, 0);
5346
5347 assert(!attr || attr->getKind() == attrKind);
5348
5349 QualType canon = getCanonicalType(equivalentType);
5350 type = new (*this, alignof(AttributedType))
5351 AttributedType(canon, attrKind, attr, modifiedType, equivalentType);
5352
5353 Types.push_back(type);
5354 AttributedTypes.InsertNode(type, insertPos);
5355
5356 return QualType(type, 0);
5357}
5358
5360 QualType equivalentType) const {
5361 return getAttributedType(attr->getKind(), modifiedType, equivalentType, attr);
5362}
5363
5365 QualType modifiedType,
5366 QualType equivalentType) {
5367 switch (nullability) {
5369 return getAttributedType(attr::TypeNonNull, modifiedType, equivalentType);
5370
5372 return getAttributedType(attr::TypeNullable, modifiedType, equivalentType);
5373
5375 return getAttributedType(attr::TypeNullableResult, modifiedType,
5376 equivalentType);
5377
5379 return getAttributedType(attr::TypeNullUnspecified, modifiedType,
5380 equivalentType);
5381 }
5382
5383 llvm_unreachable("Unknown nullability kind");
5384}
5385
5386QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
5387 QualType Wrapped) const {
5388 llvm::FoldingSetNodeID ID;
5389 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
5390
5391 void *InsertPos = nullptr;
5393 BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
5394 if (Ty)
5395 return QualType(Ty, 0);
5396
5397 QualType Canon = getCanonicalType(Wrapped);
5398 Ty = new (*this, alignof(BTFTagAttributedType))
5399 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
5400
5401 Types.push_back(Ty);
5402 BTFTagAttributedTypes.InsertNode(Ty, InsertPos);
5403
5404 return QualType(Ty, 0);
5405}
5406
5408 QualType Wrapped, QualType Contained,
5410
5411 llvm::FoldingSetNodeID ID;
5412 HLSLAttributedResourceType::Profile(ID, Wrapped, Contained, Attrs);
5413
5414 void *InsertPos = nullptr;
5416 HLSLAttributedResourceTypes.FindNodeOrInsertPos(ID, InsertPos);
5417 if (Ty)
5418 return QualType(Ty, 0);
5419
5420 Ty = new (*this, alignof(HLSLAttributedResourceType))
5421 HLSLAttributedResourceType(Wrapped, Contained, Attrs);
5422
5423 Types.push_back(Ty);
5424 HLSLAttributedResourceTypes.InsertNode(Ty, InsertPos);
5425
5426 return QualType(Ty, 0);
5427}
5428/// Retrieve a substitution-result type.
5430 QualType Replacement, Decl *AssociatedDecl, unsigned Index,
5431 std::optional<unsigned> PackIndex,
5432 SubstTemplateTypeParmTypeFlag Flag) const {
5433 llvm::FoldingSetNodeID ID;
5434 SubstTemplateTypeParmType::Profile(ID, Replacement, AssociatedDecl, Index,
5435 PackIndex, Flag);
5436 void *InsertPos = nullptr;
5437 SubstTemplateTypeParmType *SubstParm =
5438 SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5439
5440 if (!SubstParm) {
5441 void *Mem = Allocate(SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
5442 !Replacement.isCanonical()),
5443 alignof(SubstTemplateTypeParmType));
5444 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
5445 Index, PackIndex, Flag);
5446 Types.push_back(SubstParm);
5447 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
5448 }
5449
5450 return QualType(SubstParm, 0);
5451}
5452
5453/// Retrieve a
5456 unsigned Index, bool Final,
5457 const TemplateArgument &ArgPack) {
5458#ifndef NDEBUG
5459 for (const auto &P : ArgPack.pack_elements())
5460 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
5461#endif
5462
5463 llvm::FoldingSetNodeID ID;
5464 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
5465 ArgPack);
5466 void *InsertPos = nullptr;
5467 if (SubstTemplateTypeParmPackType *SubstParm =
5468 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
5469 return QualType(SubstParm, 0);
5470
5471 QualType Canon;
5472 {
5473 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5474 if (!AssociatedDecl->isCanonicalDecl() ||
5475 !CanonArgPack.structurallyEquals(ArgPack)) {
5477 AssociatedDecl->getCanonicalDecl(), Index, Final, CanonArgPack);
5478 [[maybe_unused]] const auto *Nothing =
5479 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
5480 assert(!Nothing);
5481 }
5482 }
5483
5484 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
5485 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
5486 ArgPack);
5487 Types.push_back(SubstParm);
5488 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
5489 return QualType(SubstParm, 0);
5490}
5491
5492/// Retrieve the template type parameter type for a template
5493/// parameter or parameter pack with the given depth, index, and (optionally)
5494/// name.
5495QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
5496 bool ParameterPack,
5497 TemplateTypeParmDecl *TTPDecl) const {
5498 llvm::FoldingSetNodeID ID;
5499 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
5500 void *InsertPos = nullptr;
5501 TemplateTypeParmType *TypeParm
5502 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5503
5504 if (TypeParm)
5505 return QualType(TypeParm, 0);
5506
5507 if (TTPDecl) {
5508 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
5509 TypeParm = new (*this, alignof(TemplateTypeParmType))
5510 TemplateTypeParmType(Depth, Index, ParameterPack, TTPDecl, Canon);
5511
5512 TemplateTypeParmType *TypeCheck
5513 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5514 assert(!TypeCheck && "Template type parameter canonical type broken");
5515 (void)TypeCheck;
5516 } else
5517 TypeParm = new (*this, alignof(TemplateTypeParmType)) TemplateTypeParmType(
5518 Depth, Index, ParameterPack, /*TTPDecl=*/nullptr, /*Canon=*/QualType());
5519
5520 Types.push_back(TypeParm);
5521 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
5522
5523 return QualType(TypeParm, 0);
5524}
5525
5528 SourceLocation NameLoc,
5529 const TemplateArgumentListInfo &Args,
5530 QualType Underlying) const {
5531 assert(!Name.getAsDependentTemplateName() &&
5532 "No dependent template names here!");
5533 QualType TST =
5534 getTemplateSpecializationType(Name, Args.arguments(), Underlying);
5535
5540 TL.setTemplateNameLoc(NameLoc);
5541 TL.setLAngleLoc(Args.getLAngleLoc());
5542 TL.setRAngleLoc(Args.getRAngleLoc());
5543 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5544 TL.setArgLocInfo(i, Args[i].getLocInfo());
5545 return DI;
5546}
5547
5551 QualType Underlying) const {
5552 assert(!Template.getAsDependentTemplateName() &&
5553 "No dependent template names here!");
5554
5556 ArgVec.reserve(Args.size());
5557 for (const TemplateArgumentLoc &Arg : Args)
5558 ArgVec.push_back(Arg.getArgument());
5559
5560 return getTemplateSpecializationType(Template, ArgVec, Underlying);
5561}
5562
5563#ifndef NDEBUG
5565 for (const TemplateArgument &Arg : Args)
5566 if (Arg.isPackExpansion())
5567 return true;
5568
5569 return true;
5570}
5571#endif
5572
5576 QualType Underlying) const {
5577 assert(!Template.getAsDependentTemplateName() &&
5578 "No dependent template names here!");
5579
5580 const auto *TD = Template.getAsTemplateDecl(/*IgnoreDeduced=*/true);
5581 bool IsTypeAlias = TD && TD->isTypeAlias();
5582 QualType CanonType;
5583 if (!Underlying.isNull())
5584 CanonType = getCanonicalType(Underlying);
5585 else {
5586 // We can get here with an alias template when the specialization contains
5587 // a pack expansion that does not match up with a parameter pack.
5588 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
5589 "Caller must compute aliased type");
5590 IsTypeAlias = false;
5591 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
5592 }
5593
5594 // Allocate the (non-canonical) template specialization type, but don't
5595 // try to unique it: these types typically have location information that
5596 // we don't unique and don't want to lose.
5597 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
5598 sizeof(TemplateArgument) * Args.size() +
5599 (IsTypeAlias ? sizeof(QualType) : 0),
5601 auto *Spec
5602 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
5603 IsTypeAlias ? Underlying : QualType());
5604
5605 Types.push_back(Spec);
5606 return QualType(Spec, 0);
5607}
5608
5610 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
5611 assert(!Template.getAsDependentTemplateName() &&
5612 "No dependent template names here!");
5613
5614 // Build the canonical template specialization type.
5615 // Any DeducedTemplateNames are ignored, because the effective name of a TST
5616 // accounts for the TST arguments laid over any default arguments contained in
5617 // its name.
5618 TemplateName CanonTemplate =
5619 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true);
5620
5621 bool AnyNonCanonArgs = false;
5622 auto CanonArgs =
5623 ::getCanonicalTemplateArguments(*this, Args, AnyNonCanonArgs);
5624
5625 // Determine whether this canonical template specialization type already
5626 // exists.
5627 llvm::FoldingSetNodeID ID;
5628 TemplateSpecializationType::Profile(ID, CanonTemplate,
5629 CanonArgs, *this);
5630
5631 void *InsertPos = nullptr;
5633 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5634
5635 if (!Spec) {
5636 // Allocate a new canonical template specialization type.
5637 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
5638 sizeof(TemplateArgument) * CanonArgs.size()),
5640 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
5641 CanonArgs,
5642 QualType(), QualType());
5643 Types.push_back(Spec);
5644 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
5645 }
5646
5647 assert(Spec->isDependentType() &&
5648 "Non-dependent template-id type must have a canonical type");
5649 return QualType(Spec, 0);
5650}
5651
5654 QualType NamedType,
5655 TagDecl *OwnedTagDecl) const {
5656 llvm::FoldingSetNodeID ID;
5657 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
5658
5659 void *InsertPos = nullptr;
5660 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
5661 if (T)
5662 return QualType(T, 0);
5663
5664 QualType Canon = NamedType;
5665 if (!Canon.isCanonical()) {
5666 Canon = getCanonicalType(NamedType);
5667 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
5668 assert(!CheckT && "Elaborated canonical type broken");
5669 (void)CheckT;
5670 }
5671
5672 void *Mem =
5673 Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
5674 alignof(ElaboratedType));
5675 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
5676
5677 Types.push_back(T);
5678 ElaboratedTypes.InsertNode(T, InsertPos);
5679 return QualType(T, 0);
5680}
5681
5684 llvm::FoldingSetNodeID ID;
5685 ParenType::Profile(ID, InnerType);
5686
5687 void *InsertPos = nullptr;
5688 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
5689 if (T)
5690 return QualType(T, 0);
5691
5692 QualType Canon = InnerType;
5693 if (!Canon.isCanonical()) {
5694 Canon = getCanonicalType(InnerType);
5695 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
5696 assert(!CheckT && "Paren canonical type broken");
5697 (void)CheckT;
5698 }
5699
5700 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
5701 Types.push_back(T);
5702 ParenTypes.InsertNode(T, InsertPos);
5703 return QualType(T, 0);
5704}
5705
5708 const IdentifierInfo *MacroII) const {
5709 QualType Canon = UnderlyingTy;
5710 if (!Canon.isCanonical())
5711 Canon = getCanonicalType(UnderlyingTy);
5712
5713 auto *newType = new (*this, alignof(MacroQualifiedType))
5714 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
5715 Types.push_back(newType);
5716 return QualType(newType, 0);
5717}
5718
5721 const IdentifierInfo *Name,
5722 QualType Canon) const {
5723 if (Canon.isNull()) {
5725 if (CanonNNS != NNS)
5726 Canon = getDependentNameType(Keyword, CanonNNS, Name);
5727 }
5728
5729 llvm::FoldingSetNodeID ID;
5730 DependentNameType::Profile(ID, Keyword, NNS, Name);
5731
5732 void *InsertPos = nullptr;
5734 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
5735 if (T)
5736 return QualType(T, 0);
5737
5738 T = new (*this, alignof(DependentNameType))
5739 DependentNameType(Keyword, NNS, Name, Canon);
5740 Types.push_back(T);
5741 DependentNameTypes.InsertNode(T, InsertPos);
5742 return QualType(T, 0);
5743}
5744
5747 const IdentifierInfo *Name, ArrayRef<TemplateArgumentLoc> Args) const {
5748 // TODO: avoid this copy
5750 for (unsigned I = 0, E = Args.size(); I != E; ++I)
5751 ArgCopy.push_back(Args[I].getArgument());
5752 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
5753}
5754
5757 ElaboratedTypeKeyword Keyword,
5759 const IdentifierInfo *Name,
5760 ArrayRef<TemplateArgument> Args) const {
5761 assert((!NNS || NNS->isDependent()) &&
5762 "nested-name-specifier must be dependent");
5763
5764 llvm::FoldingSetNodeID ID;
5765 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
5766 Name, Args);
5767
5768 void *InsertPos = nullptr;
5770 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5771 if (T)
5772 return QualType(T, 0);
5773
5775
5776 ElaboratedTypeKeyword CanonKeyword = Keyword;
5777 if (Keyword == ElaboratedTypeKeyword::None)
5778 CanonKeyword = ElaboratedTypeKeyword::Typename;
5779
5780 bool AnyNonCanonArgs = false;
5781 auto CanonArgs =
5782 ::getCanonicalTemplateArguments(*this, Args, AnyNonCanonArgs);
5783
5784 QualType Canon;
5785 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
5786 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
5787 Name,
5788 CanonArgs);
5789
5790 // Find the insert position again.
5791 [[maybe_unused]] auto *Nothing =
5792 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5793 assert(!Nothing && "canonical type broken");
5794 }
5795
5796 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
5797 sizeof(TemplateArgument) * Args.size()),
5799 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
5800 Name, Args, Canon);
5801 Types.push_back(T);
5802 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
5803 return QualType(T, 0);
5804}
5805
5807 TemplateArgument Arg;
5808 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
5809 QualType ArgType = getTypeDeclType(TTP);
5810 if (TTP->isParameterPack())
5811 ArgType = getPackExpansionType(ArgType, std::nullopt);
5812
5813 Arg = TemplateArgument(ArgType);
5814 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5815 QualType T =
5816 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
5817 // For class NTTPs, ensure we include the 'const' so the type matches that
5818 // of a real template argument.
5819 // FIXME: It would be more faithful to model this as something like an
5820 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
5821 ExprValueKind VK;
5822 if (T->isRecordType()) {
5823 // C++ [temp.param]p8: An id-expression naming a non-type
5824 // template-parameter of class type T denotes a static storage duration
5825 // object of type const T.
5826 T.addConst();
5827 VK = VK_LValue;
5828 } else {
5829 VK = Expr::getValueKindForType(NTTP->getType());
5830 }
5831 Expr *E = new (*this)
5832 DeclRefExpr(*this, NTTP, /*RefersToEnclosingVariableOrCapture=*/false,
5833 T, VK, NTTP->getLocation());
5834
5835 if (NTTP->isParameterPack())
5836 E = new (*this)
5837 PackExpansionExpr(DependentTy, E, NTTP->getLocation(), std::nullopt);
5838 Arg = TemplateArgument(E);
5839 } else {
5840 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
5842 nullptr, /*TemplateKeyword=*/false, TemplateName(TTP));
5843 if (TTP->isParameterPack())
5844 Arg = TemplateArgument(Name, std::optional<unsigned>());
5845 else
5846 Arg = TemplateArgument(Name);
5847 }
5848
5849 if (Param->isTemplateParameterPack())
5850 Arg =
5851 TemplateArgument::CreatePackCopy(const_cast<ASTContext &>(*this), Arg);
5852
5853 return Arg;
5854}
5855
5857 std::optional<unsigned> NumExpansions,
5858 bool ExpectPackInType) const {
5859 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
5860 "Pack expansions must expand one or more parameter packs");
5861
5862 llvm::FoldingSetNodeID ID;
5863 PackExpansionType::Profile(ID, Pattern, NumExpansions);
5864
5865 void *InsertPos = nullptr;
5866 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
5867 if (T)
5868 return QualType(T, 0);
5869
5870 QualType Canon;
5871 if (!Pattern.isCanonical()) {
5872 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
5873 /*ExpectPackInType=*/false);
5874
5875 // Find the insert position again, in case we inserted an element into
5876 // PackExpansionTypes and invalidated our insert position.
5877 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
5878 }
5879
5880 T = new (*this, alignof(PackExpansionType))
5881 PackExpansionType(Pattern, Canon, NumExpansions);
5882 Types.push_back(T);
5883 PackExpansionTypes.InsertNode(T, InsertPos);
5884 return QualType(T, 0);
5885}
5886
5887/// CmpProtocolNames - Comparison predicate for sorting protocols
5888/// alphabetically.
5889static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
5890 ObjCProtocolDecl *const *RHS) {
5891 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
5892}
5893
5895 if (Protocols.empty()) return true;
5896
5897 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
5898 return false;
5899
5900 for (unsigned i = 1; i != Protocols.size(); ++i)
5901 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
5902 Protocols[i]->getCanonicalDecl() != Protocols[i])
5903 return false;
5904 return true;
5905}
5906
5907static void
5909 // Sort protocols, keyed by name.
5910 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
5911
5912 // Canonicalize.
5913 for (ObjCProtocolDecl *&P : Protocols)
5914 P = P->getCanonicalDecl();
5915
5916 // Remove duplicates.
5917 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
5918 Protocols.erase(ProtocolsEnd, Protocols.end());
5919}
5920
5922 ObjCProtocolDecl * const *Protocols,
5923 unsigned NumProtocols) const {
5924 return getObjCObjectType(BaseType, {},
5925 llvm::ArrayRef(Protocols, NumProtocols),
5926 /*isKindOf=*/false);
5927}
5928
5930 QualType baseType,
5931 ArrayRef<QualType> typeArgs,
5933 bool isKindOf) const {
5934 // If the base type is an interface and there aren't any protocols or
5935 // type arguments to add, then the interface type will do just fine.
5936 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
5937 isa<ObjCInterfaceType>(baseType))
5938 return baseType;
5939
5940 // Look in the folding set for an existing type.
5941 llvm::FoldingSetNodeID ID;
5942 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
5943 void *InsertPos = nullptr;
5944 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
5945 return QualType(QT, 0);
5946
5947 // Determine the type arguments to be used for canonicalization,
5948 // which may be explicitly specified here or written on the base
5949 // type.
5950 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
5951 if (effectiveTypeArgs.empty()) {
5952 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
5953 effectiveTypeArgs = baseObject->getTypeArgs();
5954 }
5955
5956 // Build the canonical type, which has the canonical base type and a
5957 // sorted-and-uniqued list of protocols and the type arguments
5958 // canonicalized.
5959 QualType canonical;
5960 bool typeArgsAreCanonical = llvm::all_of(
5961 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
5962 bool protocolsSorted = areSortedAndUniqued(protocols);
5963 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
5964 // Determine the canonical type arguments.
5965 ArrayRef<QualType> canonTypeArgs;
5966 SmallVector<QualType, 4> canonTypeArgsVec;
5967 if (!typeArgsAreCanonical) {
5968 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
5969 for (auto typeArg : effectiveTypeArgs)
5970 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
5971 canonTypeArgs = canonTypeArgsVec;
5972 } else {
5973 canonTypeArgs = effectiveTypeArgs;
5974 }
5975
5976 ArrayRef<ObjCProtocolDecl *> canonProtocols;
5977 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
5978 if (!protocolsSorted) {
5979 canonProtocolsVec.append(protocols.begin(), protocols.end());
5980 SortAndUniqueProtocols(canonProtocolsVec);
5981 canonProtocols = canonProtocolsVec;
5982 } else {
5983 canonProtocols = protocols;
5984 }
5985
5986 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
5987 canonProtocols, isKindOf);
5988
5989 // Regenerate InsertPos.
5990 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
5991 }
5992
5993 unsigned size = sizeof(ObjCObjectTypeImpl);
5994 size += typeArgs.size() * sizeof(QualType);
5995 size += protocols.size() * sizeof(ObjCProtocolDecl *);
5996 void *mem = Allocate(size, alignof(ObjCObjectTypeImpl));
5997 auto *T =
5998 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
5999 isKindOf);
6000
6001 Types.push_back(T);
6002 ObjCObjectTypes.InsertNode(T, InsertPos);
6003 return QualType(T, 0);
6004}
6005
6006/// Apply Objective-C protocol qualifiers to the given type.
6007/// If this is for the canonical type of a type parameter, we can apply
6008/// protocol qualifiers on the ObjCObjectPointerType.
6011 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
6012 bool allowOnPointerType) const {
6013 hasError = false;
6014
6015 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
6016 return getObjCTypeParamType(objT->getDecl(), protocols);
6017 }
6018
6019 // Apply protocol qualifiers to ObjCObjectPointerType.
6020 if (allowOnPointerType) {
6021 if (const auto *objPtr =
6022 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
6023 const ObjCObjectType *objT = objPtr->getObjectType();
6024 // Merge protocol lists and construct ObjCObjectType.
6026 protocolsVec.append(objT->qual_begin(),
6027 objT->qual_end());
6028 protocolsVec.append(protocols.begin(), protocols.end());
6029 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
6031 objT->getBaseType(),
6032 objT->getTypeArgsAsWritten(),
6033 protocols,
6034 objT->isKindOfTypeAsWritten());
6036 }
6037 }
6038
6039 // Apply protocol qualifiers to ObjCObjectType.
6040 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
6041 // FIXME: Check for protocols to which the class type is already
6042 // known to conform.
6043
6044 return getObjCObjectType(objT->getBaseType(),
6045 objT->getTypeArgsAsWritten(),
6046 protocols,
6047 objT->isKindOfTypeAsWritten());
6048 }
6049
6050 // If the canonical type is ObjCObjectType, ...
6051 if (type->isObjCObjectType()) {
6052 // Silently overwrite any existing protocol qualifiers.
6053 // TODO: determine whether that's the right thing to do.
6054
6055 // FIXME: Check for protocols to which the class type is already
6056 // known to conform.
6057 return getObjCObjectType(type, {}, protocols, false);
6058 }
6059
6060 // id<protocol-list>
6061 if (type->isObjCIdType()) {
6062 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6063 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
6064 objPtr->isKindOfType());
6066 }
6067
6068 // Class<protocol-list>
6069 if (type->isObjCClassType()) {
6070 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6071 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
6072 objPtr->isKindOfType());
6074 }
6075
6076 hasError = true;
6077 return type;
6078}
6079
6082 ArrayRef<ObjCProtocolDecl *> protocols) const {
6083 // Look in the folding set for an existing type.
6084 llvm::FoldingSetNodeID ID;
6085 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
6086 void *InsertPos = nullptr;
6087 if (ObjCTypeParamType *TypeParam =
6088 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
6089 return QualType(TypeParam, 0);
6090
6091 // We canonicalize to the underlying type.
6092 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
6093 if (!protocols.empty()) {
6094 // Apply the protocol qualifers.
6095 bool hasError;
6097 Canonical, protocols, hasError, true /*allowOnPointerType*/));
6098 assert(!hasError && "Error when apply protocol qualifier to bound type");
6099 }
6100
6101 unsigned size = sizeof(ObjCTypeParamType);
6102 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6103 void *mem = Allocate(size, alignof(ObjCTypeParamType));
6104 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
6105
6106 Types.push_back(newType);
6107 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
6108 return QualType(newType, 0);
6109}
6110
6112 ObjCTypeParamDecl *New) const {
6114 // Update TypeForDecl after updating TypeSourceInfo.
6115 auto NewTypeParamTy = cast<ObjCTypeParamType>(New->getTypeForDecl());
6117 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
6118 QualType UpdatedTy = getObjCTypeParamType(New, protocols);
6119 New->setTypeForDecl(UpdatedTy.getTypePtr());
6120}
6121
6122/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
6123/// protocol list adopt all protocols in QT's qualified-id protocol
6124/// list.
6126 ObjCInterfaceDecl *IC) {
6127 if (!QT->isObjCQualifiedIdType())
6128 return false;
6129
6130 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
6131 // If both the right and left sides have qualifiers.
6132 for (auto *Proto : OPT->quals()) {
6133 if (!IC->ClassImplementsProtocol(Proto, false))
6134 return false;
6135 }
6136 return true;
6137 }
6138 return false;
6139}
6140
6141/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
6142/// QT's qualified-id protocol list adopt all protocols in IDecl's list
6143/// of protocols.
6145 ObjCInterfaceDecl *IDecl) {
6146 if (!QT->isObjCQualifiedIdType())
6147 return false;
6148 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
6149 if (!OPT)
6150 return false;
6151 if (!IDecl->hasDefinition())
6152 return false;
6154 CollectInheritedProtocols(IDecl, InheritedProtocols);
6155 if (InheritedProtocols.empty())
6156 return false;
6157 // Check that if every protocol in list of id<plist> conforms to a protocol
6158 // of IDecl's, then bridge casting is ok.
6159 bool Conforms = false;
6160 for (auto *Proto : OPT->quals()) {
6161 Conforms = false;
6162 for (auto *PI : InheritedProtocols) {
6163 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
6164 Conforms = true;
6165 break;
6166 }
6167 }
6168 if (!Conforms)
6169 break;
6170 }
6171 if (Conforms)
6172 return true;
6173
6174 for (auto *PI : InheritedProtocols) {
6175 // If both the right and left sides have qualifiers.
6176 bool Adopts = false;
6177 for (auto *Proto : OPT->quals()) {
6178 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
6179 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
6180 break;
6181 }
6182 if (!Adopts)
6183 return false;
6184 }
6185 return true;
6186}
6187
6188/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
6189/// the given object type.
6191 llvm::FoldingSetNodeID ID;
6192 ObjCObjectPointerType::Profile(ID, ObjectT);
6193
6194 void *InsertPos = nullptr;
6195 if (ObjCObjectPointerType *QT =
6196 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
6197 return QualType(QT, 0);
6198
6199 // Find the canonical object type.
6200 QualType Canonical;
6201 if (!ObjectT.isCanonical()) {
6202 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
6203
6204 // Regenerate InsertPos.
6205 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
6206 }
6207
6208 // No match.
6209 void *Mem =
6211 auto *QType =
6212 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
6213
6214 Types.push_back(QType);
6215 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
6216 return QualType(QType, 0);
6217}
6218
6219/// getObjCInterfaceType - Return the unique reference to the type for the
6220/// specified ObjC interface decl. The list of protocols is optional.
6222 ObjCInterfaceDecl *PrevDecl) const {
6223 if (Decl->TypeForDecl)
6224 return QualType(Decl->TypeForDecl, 0);
6225
6226 if (PrevDecl) {
6227 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
6228 Decl->TypeForDecl = PrevDecl->TypeForDecl;
6229 return QualType(PrevDecl->TypeForDecl, 0);
6230 }
6231
6232 // Prefer the definition, if there is one.
6233 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
6234 Decl = Def;
6235
6236 void *Mem = Allocate(sizeof(ObjCInterfaceType), alignof(ObjCInterfaceType));
6237 auto *T = new (Mem) ObjCInterfaceType(Decl);
6238 Decl->TypeForDecl = T;
6239 Types.push_back(T);
6240 return QualType(T, 0);
6241}
6242
6243/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
6244/// TypeOfExprType AST's (since expression's are never shared). For example,
6245/// multiple declarations that refer to "typeof(x)" all contain different
6246/// DeclRefExpr's. This doesn't effect the type checker, since it operates
6247/// on canonical type's (which are always unique).
6249 TypeOfExprType *toe;
6250 if (tofExpr->isTypeDependent()) {
6251 llvm::FoldingSetNodeID ID;
6252 DependentTypeOfExprType::Profile(ID, *this, tofExpr,
6253 Kind == TypeOfKind::Unqualified);
6254
6255 void *InsertPos = nullptr;
6257 DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
6258 if (Canon) {
6259 // We already have a "canonical" version of an identical, dependent
6260 // typeof(expr) type. Use that as our canonical type.
6261 toe = new (*this, alignof(TypeOfExprType)) TypeOfExprType(
6262 *this, tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
6263 } else {
6264 // Build a new, canonical typeof(expr) type.
6265 Canon = new (*this, alignof(DependentTypeOfExprType))
6266 DependentTypeOfExprType(*this, tofExpr, Kind);
6267 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
6268 toe = Canon;
6269 }
6270 } else {
6271 QualType Canonical = getCanonicalType(tofExpr->getType());
6272 toe = new (*this, alignof(TypeOfExprType))
6273 TypeOfExprType(*this, tofExpr, Kind, Canonical);
6274 }
6275 Types.push_back(toe);
6276 return QualType(toe, 0);
6277}
6278
6279/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
6280/// TypeOfType nodes. The only motivation to unique these nodes would be
6281/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
6282/// an issue. This doesn't affect the type checker, since it operates
6283/// on canonical types (which are always unique).
6285 QualType Canonical = getCanonicalType(tofType);
6286 auto *tot = new (*this, alignof(TypeOfType))
6287 TypeOfType(*this, tofType, Canonical, Kind);
6288 Types.push_back(tot);
6289 return QualType(tot, 0);
6290}
6291
6292/// getReferenceQualifiedType - Given an expr, will return the type for
6293/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
6294/// and class member access into account.
6296 // C++11 [dcl.type.simple]p4:
6297 // [...]
6298 QualType T = E->getType();
6299 switch (E->getValueKind()) {
6300 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6301 // type of e;
6302 case VK_XValue:
6303 return getRValueReferenceType(T);
6304 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6305 // type of e;
6306 case VK_LValue:
6307 return getLValueReferenceType(T);
6308 // - otherwise, decltype(e) is the type of e.
6309 case VK_PRValue:
6310 return T;
6311 }
6312 llvm_unreachable("Unknown value kind");
6313}
6314
6315/// Unlike many "get<Type>" functions, we don't unique DecltypeType
6316/// nodes. This would never be helpful, since each such type has its own
6317/// expression, and would not give a significant memory saving, since there
6318/// is an Expr tree under each such type.
6320 DecltypeType *dt;
6321
6322 // C++11 [temp.type]p2:
6323 // If an expression e involves a template parameter, decltype(e) denotes a
6324 // unique dependent type. Two such decltype-specifiers refer to the same
6325 // type only if their expressions are equivalent (14.5.6.1).
6326 if (e->isInstantiationDependent()) {
6327 llvm::FoldingSetNodeID ID;
6328 DependentDecltypeType::Profile(ID, *this, e);
6329
6330 void *InsertPos = nullptr;
6332 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
6333 if (!Canon) {
6334 // Build a new, canonical decltype(expr) type.
6335 Canon = new (*this, alignof(DependentDecltypeType))
6337 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
6338 }
6339 dt = new (*this, alignof(DecltypeType))
6340 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
6341 } else {
6342 dt = new (*this, alignof(DecltypeType))
6343 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
6344 }
6345 Types.push_back(dt);
6346 return QualType(dt, 0);
6347}
6348
6350 bool FullySubstituted,
6351 ArrayRef<QualType> Expansions,
6352 int Index) const {
6353 QualType Canonical;
6354 if (FullySubstituted && Index != -1) {
6355 Canonical = getCanonicalType(Expansions[Index]);
6356 } else {
6357 llvm::FoldingSetNodeID ID;
6358 PackIndexingType::Profile(ID, *this, Pattern.getCanonicalType(), IndexExpr,
6359 FullySubstituted);
6360 void *InsertPos = nullptr;
6361 PackIndexingType *Canon =
6362 DependentPackIndexingTypes.FindNodeOrInsertPos(ID, InsertPos);
6363 if (!Canon) {
6364 void *Mem = Allocate(
6365 PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6367 Canon = new (Mem)
6368 PackIndexingType(*this, QualType(), Pattern.getCanonicalType(),
6369 IndexExpr, FullySubstituted, Expansions);
6370 DependentPackIndexingTypes.InsertNode(Canon, InsertPos);
6371 }
6372 Canonical = QualType(Canon, 0);
6373 }
6374
6375 void *Mem =
6376 Allocate(PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6378 auto *T = new (Mem) PackIndexingType(*this, Canonical, Pattern, IndexExpr,
6379 FullySubstituted, Expansions);
6380 Types.push_back(T);
6381 return QualType(T, 0);
6382}
6383
6384/// getUnaryTransformationType - We don't unique these, since the memory
6385/// savings are minimal and these are rare.
6387 QualType UnderlyingType,
6389 const {
6390 UnaryTransformType *ut = nullptr;
6391
6392 if (BaseType->isDependentType()) {
6393 // Look in the folding set for an existing type.
6394 llvm::FoldingSetNodeID ID;
6396
6397 void *InsertPos = nullptr;
6399 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
6400
6401 if (!Canon) {
6402 // Build a new, canonical __underlying_type(type) type.
6403 Canon = new (*this, alignof(DependentUnaryTransformType))
6404 DependentUnaryTransformType(*this, getCanonicalType(BaseType), Kind);
6405 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
6406 }
6407 ut = new (*this, alignof(UnaryTransformType))
6408 UnaryTransformType(BaseType, QualType(), Kind, QualType(Canon, 0));
6409 } else {
6410 QualType CanonType = getCanonicalType(UnderlyingType);
6411 ut = new (*this, alignof(UnaryTransformType))
6412 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
6413 }
6414 Types.push_back(ut);
6415 return QualType(ut, 0);
6416}
6417
6418QualType ASTContext::getAutoTypeInternal(
6419 QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent,
6420 bool IsPack, ConceptDecl *TypeConstraintConcept,
6421 ArrayRef<TemplateArgument> TypeConstraintArgs, bool IsCanon) const {
6422 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
6423 !TypeConstraintConcept && !IsDependent)
6424 return getAutoDeductType();
6425
6426 // Look in the folding set for an existing type.
6427 llvm::FoldingSetNodeID ID;
6428 bool IsDeducedDependent =
6429 !DeducedType.isNull() && DeducedType->isDependentType();
6430 AutoType::Profile(ID, *this, DeducedType, Keyword,
6431 IsDependent || IsDeducedDependent, TypeConstraintConcept,
6432 TypeConstraintArgs);
6433 if (auto const AT_iter = AutoTypes.find(ID); AT_iter != AutoTypes.end())
6434 return QualType(AT_iter->getSecond(), 0);
6435
6436 QualType Canon;
6437 if (!IsCanon) {
6438 if (!DeducedType.isNull()) {
6439 Canon = DeducedType.getCanonicalType();
6440 } else if (TypeConstraintConcept) {
6441 bool AnyNonCanonArgs = false;
6442 ConceptDecl *CanonicalConcept = TypeConstraintConcept->getCanonicalDecl();
6443 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
6444 *this, TypeConstraintArgs, AnyNonCanonArgs);
6445 if (CanonicalConcept != TypeConstraintConcept || AnyNonCanonArgs) {
6446 Canon =
6447 getAutoTypeInternal(QualType(), Keyword, IsDependent, IsPack,
6448 CanonicalConcept, CanonicalConceptArgs, true);
6449 }
6450 }
6451 }
6452
6453 void *Mem = Allocate(sizeof(AutoType) +
6454 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
6455 alignof(AutoType));
6456 auto *AT = new (Mem) AutoType(
6457 DeducedType, Keyword,
6458 (IsDependent ? TypeDependence::DependentInstantiation
6459 : TypeDependence::None) |
6460 (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None),
6461 Canon, TypeConstraintConcept, TypeConstraintArgs);
6462#ifndef NDEBUG
6463 llvm::FoldingSetNodeID InsertedID;
6464 AT->Profile(InsertedID, *this);
6465 assert(InsertedID == ID && "ID does not match");
6466#endif
6467 Types.push_back(AT);
6468 AutoTypes.try_emplace(ID, AT);
6469 return QualType(AT, 0);
6470}
6471
6472/// getAutoType - Return the uniqued reference to the 'auto' type which has been
6473/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
6474/// canonical deduced-but-dependent 'auto' type.
6477 bool IsDependent, bool IsPack,
6478 ConceptDecl *TypeConstraintConcept,
6479 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
6480 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
6481 assert((!IsDependent || DeducedType.isNull()) &&
6482 "A dependent auto should be undeduced");
6483 return getAutoTypeInternal(DeducedType, Keyword, IsDependent, IsPack,
6484 TypeConstraintConcept, TypeConstraintArgs);
6485}
6486
6488 QualType CanonT = T.getNonPackExpansionType().getCanonicalType();
6489
6490 // Remove a type-constraint from a top-level auto or decltype(auto).
6491 if (auto *AT = CanonT->getAs<AutoType>()) {
6492 if (!AT->isConstrained())
6493 return T;
6494 return getQualifiedType(getAutoType(QualType(), AT->getKeyword(),
6495 AT->isDependentType(),
6496 AT->containsUnexpandedParameterPack()),
6497 T.getQualifiers());
6498 }
6499
6500 // FIXME: We only support constrained auto at the top level in the type of a
6501 // non-type template parameter at the moment. Once we lift that restriction,
6502 // we'll need to recursively build types containing auto here.
6503 assert(!CanonT->getContainedAutoType() ||
6504 !CanonT->getContainedAutoType()->isConstrained());
6505 return T;
6506}
6507
6508QualType ASTContext::getDeducedTemplateSpecializationTypeInternal(
6509 TemplateName Template, QualType DeducedType, bool IsDependent,
6510 QualType Canon) const {
6511 // Look in the folding set for an existing type.
6512 void *InsertPos = nullptr;
6513 llvm::FoldingSetNodeID ID;
6515 IsDependent);
6517 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6518 return QualType(DTST, 0);
6519
6520 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
6521 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent,
6522 Canon);
6523 llvm::FoldingSetNodeID TempID;
6524 DTST->Profile(TempID);
6525 assert(ID == TempID && "ID does not match");
6526 Types.push_back(DTST);
6527 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
6528 return QualType(DTST, 0);
6529}
6530
6531/// Return the uniqued reference to the deduced template specialization type
6532/// which has been deduced to the given type, or to the canonical undeduced
6533/// such type, or the canonical deduced-but-dependent such type.
6535 TemplateName Template, QualType DeducedType, bool IsDependent) const {
6536 QualType Canon = DeducedType.isNull()
6537 ? getDeducedTemplateSpecializationTypeInternal(
6539 IsDependent, QualType())
6540 : DeducedType.getCanonicalType();
6541 return getDeducedTemplateSpecializationTypeInternal(Template, DeducedType,
6542 IsDependent, Canon);
6543}
6544
6545/// getAtomicType - Return the uniqued reference to the atomic type for
6546/// the given value type.
6548 // Unique pointers, to guarantee there is only one pointer of a particular
6549 // structure.
6550 llvm::FoldingSetNodeID ID;
6552
6553 void *InsertPos = nullptr;
6554 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
6555 return QualType(AT, 0);
6556
6557 // If the atomic value type isn't canonical, this won't be a canonical type
6558 // either, so fill in the canonical type field.
6559 QualType Canonical;
6560 if (!T.isCanonical()) {
6561 Canonical = getAtomicType(getCanonicalType(T));
6562
6563 // Get the new insert position for the node we care about.
6564 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
6565 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
6566 }
6567 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
6568 Types.push_back(New);
6569 AtomicTypes.InsertNode(New, InsertPos);
6570 return QualType(New, 0);
6571}
6572
6573/// getAutoDeductType - Get type pattern for deducing against 'auto'.
6575 if (AutoDeductTy.isNull())
6576 AutoDeductTy = QualType(new (*this, alignof(AutoType))
6578 TypeDependence::None, QualType(),
6579 /*concept*/ nullptr, /*args*/ {}),
6580 0);
6581 return AutoDeductTy;
6582}
6583
6584/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
6588 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
6589 return AutoRRefDeductTy;
6590}
6591
6592/// getTagDeclType - Return the unique reference to the type for the
6593/// specified TagDecl (struct/union/class/enum) decl.
6595 assert(Decl);
6596 // FIXME: What is the design on getTagDeclType when it requires casting
6597 // away const? mutable?
6598 return getTypeDeclType(const_cast<TagDecl*>(Decl));
6599}
6600
6601/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
6602/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
6603/// needs to agree with the definition in <stddef.h>.
6605 return getFromTargetType(Target->getSizeType());
6606}
6607
6608/// Return the unique signed counterpart of the integer type
6609/// corresponding to size_t.
6611 return getFromTargetType(Target->getSignedSizeType());
6612}
6613
6614/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
6616 return getFromTargetType(Target->getIntMaxType());
6617}
6618
6619/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
6621 return getFromTargetType(Target->getUIntMaxType());
6622}
6623
6624/// getSignedWCharType - Return the type of "signed wchar_t".
6625/// Used when in C++, as a GCC extension.
6627 // FIXME: derive from "Target" ?
6628 return WCharTy;
6629}
6630
6631/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
6632/// Used when in C++, as a GCC extension.
6634 // FIXME: derive from "Target" ?
6635 return UnsignedIntTy;
6636}
6637
6639 return getFromTargetType(Target->getIntPtrType());
6640}
6641
6644}
6645
6646/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
6647/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
6649 return getFromTargetType(Target->getPtrDiffType(LangAS::Default));
6650}
6651
6652/// Return the unique unsigned counterpart of "ptrdiff_t"
6653/// integer type. The standard (C11 7.21.6.1p7) refers to this type
6654/// in the definition of %tu format specifier.
6656 return getFromTargetType(Target->getUnsignedPtrDiffType(LangAS::Default));
6657}
6658
6659/// Return the unique type for "pid_t" defined in
6660/// <sys/types.h>. We need this to compute the correct type for vfork().
6662 return getFromTargetType(Target->getProcessIDType());
6663}
6664
6665//===----------------------------------------------------------------------===//
6666// Type Operators
6667//===----------------------------------------------------------------------===//
6668
6670 // Push qualifiers into arrays, and then discard any remaining
6671 // qualifiers.
6672 T = getCanonicalType(T);
6674 const Type *Ty = T.getTypePtr();
6676 if (getLangOpts().HLSL && isa<ConstantArrayType>(Ty)) {
6678 } else if (isa<ArrayType>(Ty)) {
6680 } else if (isa<FunctionType>(Ty)) {
6681 Result = getPointerType(QualType(Ty, 0));
6682 } else {
6683 Result = QualType(Ty, 0);
6684 }
6685
6687}
6688
6690 Qualifiers &quals) const {
6691 SplitQualType splitType = type.getSplitUnqualifiedType();
6692
6693 // FIXME: getSplitUnqualifiedType() actually walks all the way to
6694 // the unqualified desugared type and then drops it on the floor.
6695 // We then have to strip that sugar back off with
6696 // getUnqualifiedDesugaredType(), which is silly.
6697 const auto *AT =
6698 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
6699
6700 // If we don't have an array, just use the results in splitType.
6701 if (!AT) {
6702 quals = splitType.Quals;
6703 return QualType(splitType.Ty, 0);
6704 }
6705
6706 // Otherwise, recurse on the array's element type.
6707 QualType elementType = AT->getElementType();
6708 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
6709
6710 // If that didn't change the element type, AT has no qualifiers, so we
6711 // can just use the results in splitType.
6712 if (elementType == unqualElementType) {
6713 assert(quals.empty()); // from the recursive call
6714 quals = splitType.Quals;
6715 return QualType(splitType.Ty, 0);
6716 }
6717
6718 // Otherwise, add in the qualifiers from the outermost type, then
6719 // build the type back up.
6720 quals.addConsistentQualifiers(splitType.Quals);
6721
6722 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
6723 return getConstantArrayType(unqualElementType, CAT->getSize(),
6724 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
6725 }
6726
6727 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
6728 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
6729 }
6730
6731 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
6732 return getVariableArrayType(unqualElementType,
6733 VAT->getSizeExpr(),
6734 VAT->getSizeModifier(),
6735 VAT->getIndexTypeCVRQualifiers(),
6736 VAT->getBracketsRange());
6737 }
6738
6739 const auto *DSAT = cast<DependentSizedArrayType>(AT);
6740 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
6741 DSAT->getSizeModifier(), 0,
6742 SourceRange());
6743}
6744
6745/// Attempt to unwrap two types that may both be array types with the same bound
6746/// (or both be array types of unknown bound) for the purpose of comparing the
6747/// cv-decomposition of two types per C++ [conv.qual].
6748///
6749/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
6750/// C++20 [conv.qual], if permitted by the current language mode.
6752 bool AllowPiMismatch) const {
6753 while (true) {
6754 auto *AT1 = getAsArrayType(T1);
6755 if (!AT1)
6756 return;
6757
6758 auto *AT2 = getAsArrayType(T2);
6759 if (!AT2)
6760 return;
6761
6762 // If we don't have two array types with the same constant bound nor two
6763 // incomplete array types, we've unwrapped everything we can.
6764 // C++20 also permits one type to be a constant array type and the other
6765 // to be an incomplete array type.
6766 // FIXME: Consider also unwrapping array of unknown bound and VLA.
6767 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
6768 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
6769 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
6770 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
6771 isa<IncompleteArrayType>(AT2))))
6772 return;
6773 } else if (isa<IncompleteArrayType>(AT1)) {
6774 if (!(isa<IncompleteArrayType>(AT2) ||
6775 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
6776 isa<ConstantArrayType>(AT2))))
6777 return;
6778 } else {
6779 return;
6780 }
6781
6782 T1 = AT1->getElementType();
6783 T2 = AT2->getElementType();
6784 }
6785}
6786
6787/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
6788///
6789/// If T1 and T2 are both pointer types of the same kind, or both array types
6790/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
6791/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
6792///
6793/// This function will typically be called in a loop that successively
6794/// "unwraps" pointer and pointer-to-member types to compare them at each
6795/// level.
6796///
6797/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
6798/// C++20 [conv.qual], if permitted by the current language mode.
6799///
6800/// \return \c true if a pointer type was unwrapped, \c false if we reached a
6801/// pair of types that can't be unwrapped further.
6803 bool AllowPiMismatch) const {
6804 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
6805
6806 const auto *T1PtrType = T1->getAs<PointerType>();
6807 const auto *T2PtrType = T2->getAs<PointerType>();
6808 if (T1PtrType && T2PtrType) {
6809 T1 = T1PtrType->getPointeeType();
6810 T2 = T2PtrType->getPointeeType();
6811 return true;
6812 }
6813
6814 const auto *T1MPType = T1->getAs<MemberPointerType>();
6815 const auto *T2MPType = T2->getAs<MemberPointerType>();
6816 if (T1MPType && T2MPType &&
6817 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
6818 QualType(T2MPType->getClass(), 0))) {
6819 T1 = T1MPType->getPointeeType();
6820 T2 = T2MPType->getPointeeType();
6821 return true;
6822 }
6823
6824 if (getLangOpts().ObjC) {
6825 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
6826 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
6827 if (T1OPType && T2OPType) {
6828 T1 = T1OPType->getPointeeType();
6829 T2 = T2OPType->getPointeeType();
6830 return true;
6831 }
6832 }
6833
6834 // FIXME: Block pointers, too?
6835
6836 return false;
6837}
6838
6840 while (true) {
6841 Qualifiers Quals;
6842 T1 = getUnqualifiedArrayType(T1, Quals);
6843 T2 = getUnqualifiedArrayType(T2, Quals);
6844 if (hasSameType(T1, T2))
6845 return true;
6846 if (!UnwrapSimilarTypes(T1, T2))
6847 return false;
6848 }
6849}
6850
6852 while (true) {
6853 Qualifiers Quals1, Quals2;
6854 T1 = getUnqualifiedArrayType(T1, Quals1);
6855 T2 = getUnqualifiedArrayType(T2, Quals2);
6856
6857 Quals1.removeCVRQualifiers();
6858 Quals2.removeCVRQualifiers();
6859 if (Quals1 != Quals2)
6860 return false;
6861
6862 if (hasSameType(T1, T2))
6863 return true;
6864
6865 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
6866 return false;
6867 }
6868}
6869
6872 SourceLocation NameLoc) const {
6873 switch (Name.getKind()) {
6876 // DNInfo work in progress: CHECKME: what about DNLoc?
6877 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
6878 NameLoc);
6879
6881 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
6882 // DNInfo work in progress: CHECKME: what about DNLoc?
6883 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
6884 }
6885
6887 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
6888 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
6889 }
6890
6892 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
6893 DeclarationName DName;
6894 if (DTN->isIdentifier()) {
6896 return DeclarationNameInfo(DName, NameLoc);
6897 } else {
6899 // DNInfo work in progress: FIXME: source locations?
6900 DeclarationNameLoc DNLoc =
6902 return DeclarationNameInfo(DName, NameLoc, DNLoc);
6903 }
6904 }
6905
6908 = Name.getAsSubstTemplateTemplateParm();
6909 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
6910 NameLoc);
6911 }
6912
6915 = Name.getAsSubstTemplateTemplateParmPack();
6917 NameLoc);
6918 }
6920 return DeclarationNameInfo(Name.getAsUsingShadowDecl()->getDeclName(),
6921 NameLoc);
6923 DeducedTemplateStorage *DTS = Name.getAsDeducedTemplateName();
6924 return getNameForTemplate(DTS->getUnderlying(), NameLoc);
6925 }
6926 }
6927
6928 llvm_unreachable("bad template name kind!");
6929}
6930
6931static const TemplateArgument *
6933 auto handleParam = [](auto *TP) -> const TemplateArgument * {
6934 if (!TP->hasDefaultArgument())
6935 return nullptr;
6936 return &TP->getDefaultArgument().getArgument();
6937 };
6938 switch (P->getKind()) {
6939 case NamedDecl::TemplateTypeParm:
6940 return handleParam(cast<TemplateTypeParmDecl>(P));
6941 case NamedDecl::NonTypeTemplateParm:
6942 return handleParam(cast<NonTypeTemplateParmDecl>(P));
6943 case NamedDecl::TemplateTemplateParm:
6944 return handleParam(cast<TemplateTemplateParmDecl>(P));
6945 default:
6946 llvm_unreachable("Unexpected template parameter kind");
6947 }
6948}
6949
6951 bool IgnoreDeduced) const {
6952 while (std::optional<TemplateName> UnderlyingOrNone =
6953 Name.desugar(IgnoreDeduced))
6954 Name = *UnderlyingOrNone;
6955
6956 switch (Name.getKind()) {
6958 TemplateDecl *Template = Name.getAsTemplateDecl();
6959 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
6960 Template = getCanonicalTemplateTemplateParmDecl(TTP);
6961
6962 // The canonical template name is the canonical template declaration.
6963 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
6964 }
6965
6968 llvm_unreachable("cannot canonicalize unresolved template");
6969
6971 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
6972 assert(DTN && "Non-dependent template names must refer to template decls.");
6973 return DTN->CanonicalTemplateName;
6974 }
6975
6978 Name.getAsSubstTemplateTemplateParmPack();
6979 TemplateArgument canonArgPack =
6982 canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
6983 subst->getFinal(), subst->getIndex());
6984 }
6986 assert(IgnoreDeduced == false);
6987 DeducedTemplateStorage *DTS = Name.getAsDeducedTemplateName();
6988 DefaultArguments DefArgs = DTS->getDefaultArguments();
6989 TemplateName Underlying = DTS->getUnderlying();
6990
6991 TemplateName CanonUnderlying =
6992 getCanonicalTemplateName(Underlying, /*IgnoreDeduced=*/true);
6993 bool NonCanonical = CanonUnderlying != Underlying;
6994 auto CanonArgs =
6995 getCanonicalTemplateArguments(*this, DefArgs.Args, NonCanonical);
6996
6997 ArrayRef<NamedDecl *> Params =
6998 CanonUnderlying.getAsTemplateDecl()->getTemplateParameters()->asArray();
6999 assert(CanonArgs.size() <= Params.size());
7000 // A deduced template name which deduces the same default arguments already
7001 // declared in the underlying template is the same template as the
7002 // underlying template. We need need to note any arguments which differ from
7003 // the corresponding declaration. If any argument differs, we must build a
7004 // deduced template name.
7005 for (int I = CanonArgs.size() - 1; I >= 0; --I) {
7007 if (!A)
7008 break;
7009 auto CanonParamDefArg = getCanonicalTemplateArgument(*A);
7010 TemplateArgument &CanonDefArg = CanonArgs[I];
7011 if (CanonDefArg.structurallyEquals(CanonParamDefArg))
7012 continue;
7013 // Keep popping from the back any deault arguments which are the same.
7014 if (I == int(CanonArgs.size() - 1))
7015 CanonArgs.pop_back();
7016 NonCanonical = true;
7017 }
7018 return NonCanonical ? getDeducedTemplateName(
7019 CanonUnderlying,
7020 /*DefaultArgs=*/{DefArgs.StartPos, CanonArgs})
7021 : Name;
7022 }
7026 llvm_unreachable("always sugar node");
7027 }
7028
7029 llvm_unreachable("bad template name!");
7030}
7031
7033 const TemplateName &Y,
7034 bool IgnoreDeduced) const {
7035 return getCanonicalTemplateName(X, IgnoreDeduced) ==
7036 getCanonicalTemplateName(Y, IgnoreDeduced);
7037}
7038
7039bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
7040 if (!XCE != !YCE)
7041 return false;
7042
7043 if (!XCE)
7044 return true;
7045
7046 llvm::FoldingSetNodeID XCEID, YCEID;
7047 XCE->Profile(XCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7048 YCE->Profile(YCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7049 return XCEID == YCEID;
7050}
7051
7053 const TypeConstraint *YTC) const {
7054 if (!XTC != !YTC)
7055 return false;
7056
7057 if (!XTC)
7058 return true;
7059
7060 auto *NCX = XTC->getNamedConcept();
7061 auto *NCY = YTC->getNamedConcept();
7062 if (!NCX || !NCY || !isSameEntity(NCX, NCY))
7063 return false;
7066 return false;
7068 if (XTC->getConceptReference()
7070 ->NumTemplateArgs !=
7072 return false;
7073
7074 // Compare slowly by profiling.
7075 //
7076 // We couldn't compare the profiling result for the template
7077 // args here. Consider the following example in different modules:
7078 //
7079 // template <__integer_like _Tp, C<_Tp> Sentinel>
7080 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
7081 // return __t;
7082 // }
7083 //
7084 // When we compare the profiling result for `C<_Tp>` in different
7085 // modules, it will compare the type of `_Tp` in different modules.
7086 // However, the type of `_Tp` in different modules refer to different
7087 // types here naturally. So we couldn't compare the profiling result
7088 // for the template args directly.
7091}
7092
7094 const NamedDecl *Y) const {
7095 if (X->getKind() != Y->getKind())
7096 return false;
7097
7098 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
7099 auto *TY = cast<TemplateTypeParmDecl>(Y);
7100 if (TX->isParameterPack() != TY->isParameterPack())
7101 return false;
7102 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
7103 return false;
7104 return isSameTypeConstraint(TX->getTypeConstraint(),
7105 TY->getTypeConstraint());
7106 }
7107
7108 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7109 auto *TY = cast<NonTypeTemplateParmDecl>(Y);
7110 return TX->isParameterPack() == TY->isParameterPack() &&
7111 TX->getASTContext().hasSameType(TX->getType(), TY->getType()) &&
7112 isSameConstraintExpr(TX->getPlaceholderTypeConstraint(),
7113 TY->getPlaceholderTypeConstraint());
7114 }
7115
7116 auto *TX = cast<TemplateTemplateParmDecl>(X);
7117 auto *TY = cast<TemplateTemplateParmDecl>(Y);
7118 return TX->isParameterPack() == TY->isParameterPack() &&
7119 isSameTemplateParameterList(TX->getTemplateParameters(),
7120 TY->getTemplateParameters());
7121}
7122
7124 const TemplateParameterList *X, const TemplateParameterList *Y) const {
7125 if (X->size() != Y->size())
7126 return false;
7127
7128 for (unsigned I = 0, N = X->size(); I != N; ++I)
7129 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
7130 return false;
7131
7132 return isSameConstraintExpr(X->getRequiresClause(), Y->getRequiresClause());
7133}
7134
7136 const NamedDecl *Y) const {
7137 // If the type parameter isn't the same already, we don't need to check the
7138 // default argument further.
7139 if (!isSameTemplateParameter(X, Y))
7140 return false;
7141
7142 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(X)) {
7143 auto *TTPY = cast<TemplateTypeParmDecl>(Y);
7144 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7145 return false;
7146
7147 return hasSameType(TTPX->getDefaultArgument().getArgument().getAsType(),
7148 TTPY->getDefaultArgument().getArgument().getAsType());
7149 }
7150
7151 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7152 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Y);
7153 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
7154 return false;
7155
7156 Expr *DefaultArgumentX =
7157 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7158 Expr *DefaultArgumentY =
7159 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7160 llvm::FoldingSetNodeID XID, YID;
7161 DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true);
7162 DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true);
7163 return XID == YID;
7164 }
7165
7166 auto *TTPX = cast<TemplateTemplateParmDecl>(X);
7167 auto *TTPY = cast<TemplateTemplateParmDecl>(Y);
7168
7169 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7170 return false;
7171
7172 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
7173 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
7174 return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate());
7175}
7176
7178 if (auto *NS = X->getAsNamespace())
7179 return NS;
7180 if (auto *NAS = X->getAsNamespaceAlias())
7181 return NAS->getNamespace();
7182 return nullptr;
7183}
7184
7186 const NestedNameSpecifier *Y) {
7187 if (auto *NSX = getNamespace(X)) {
7188 auto *NSY = getNamespace(Y);
7189 if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl())
7190 return false;
7191 } else if (X->getKind() != Y->getKind())
7192 return false;
7193
7194 // FIXME: For namespaces and types, we're permitted to check that the entity
7195 // is named via the same tokens. We should probably do so.
7196 switch (X->getKind()) {
7198 if (X->getAsIdentifier() != Y->getAsIdentifier())
7199 return false;
7200 break;
7203 // We've already checked that we named the same namespace.
7204 break;
7207 if (X->getAsType()->getCanonicalTypeInternal() !=
7209 return false;
7210 break;
7213 return true;
7214 }
7215
7216 // Recurse into earlier portion of NNS, if any.
7217 auto *PX = X->getPrefix();
7218 auto *PY = Y->getPrefix();
7219 if (PX && PY)
7220 return isSameQualifier(PX, PY);
7221 return !PX && !PY;
7222}
7223
7224/// Determine whether the attributes we can overload on are identical for A and
7225/// B. Will ignore any overloadable attrs represented in the type of A and B.
7227 const FunctionDecl *B) {
7228 // Note that pass_object_size attributes are represented in the function's
7229 // ExtParameterInfo, so we don't need to check them here.
7230
7231 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
7232 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
7233 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
7234
7235 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
7236 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
7237 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
7238
7239 // Return false if the number of enable_if attributes is different.
7240 if (!Cand1A || !Cand2A)
7241 return false;
7242
7243 Cand1ID.clear();
7244 Cand2ID.clear();
7245
7246 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
7247 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
7248
7249 // Return false if any of the enable_if expressions of A and B are
7250 // different.
7251 if (Cand1ID != Cand2ID)
7252 return false;
7253 }
7254 return true;
7255}
7256
7257bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
7258 // Caution: this function is called by the AST reader during deserialization,
7259 // so it cannot rely on AST invariants being met. Non-trivial accessors
7260 // should be avoided, along with any traversal of redeclaration chains.
7261
7262 if (X == Y)
7263 return true;
7264
7265 if (X->getDeclName() != Y->getDeclName())
7266 return false;
7267
7268 // Must be in the same context.
7269 //
7270 // Note that we can't use DeclContext::Equals here, because the DeclContexts
7271 // could be two different declarations of the same function. (We will fix the
7272 // semantic DC to refer to the primary definition after merging.)
7273 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
7274 cast<Decl>(Y->getDeclContext()->getRedeclContext())))
7275 return false;
7276
7277 // Two typedefs refer to the same entity if they have the same underlying
7278 // type.
7279 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
7280 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
7281 return hasSameType(TypedefX->getUnderlyingType(),
7282 TypedefY->getUnderlyingType());
7283
7284 // Must have the same kind.
7285 if (X->getKind() != Y->getKind())
7286 return false;
7287
7288 // Objective-C classes and protocols with the same name always match.
7289 if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
7290 return true;
7291
7292 if (isa<ClassTemplateSpecializationDecl>(X)) {
7293 // No need to handle these here: we merge them when adding them to the
7294 // template.
7295 return false;
7296 }
7297
7298 // Compatible tags match.
7299 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
7300 const auto *TagY = cast<TagDecl>(Y);
7301 return (TagX->getTagKind() == TagY->getTagKind()) ||
7302 ((TagX->getTagKind() == TagTypeKind::Struct ||
7303 TagX->getTagKind() == TagTypeKind::Class ||
7304 TagX->getTagKind() == TagTypeKind::Interface) &&
7305 (TagY->getTagKind() == TagTypeKind::Struct ||
7306 TagY->getTagKind() == TagTypeKind::Class ||
7307 TagY->getTagKind() == TagTypeKind::Interface));
7308 }
7309
7310 // Functions with the same type and linkage match.
7311 // FIXME: This needs to cope with merging of prototyped/non-prototyped
7312 // functions, etc.
7313 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
7314 const auto *FuncY = cast<FunctionDecl>(Y);
7315 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
7316 const auto *CtorY = cast<CXXConstructorDecl>(Y);
7317 if (CtorX->getInheritedConstructor() &&
7318 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
7319 CtorY->getInheritedConstructor().getConstructor()))
7320 return false;
7321 }
7322
7323 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
7324 return false;
7325
7326 // Multiversioned functions with different feature strings are represented
7327 // as separate declarations.
7328 if (FuncX->isMultiVersion()) {
7329 const auto *TAX = FuncX->getAttr<TargetAttr>();
7330 const auto *TAY = FuncY->getAttr<TargetAttr>();
7331 assert(TAX && TAY && "Multiversion Function without target attribute");
7332
7333 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
7334 return false;
7335 }
7336
7337 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
7338 // not the same entity if they are constrained.
7339 if ((FuncX->isMemberLikeConstrainedFriend() ||
7340 FuncY->isMemberLikeConstrainedFriend()) &&
7341 !FuncX->getLexicalDeclContext()->Equals(
7342 FuncY->getLexicalDeclContext())) {
7343 return false;
7344 }
7345
7346 if (!isSameConstraintExpr(FuncX->getTrailingRequiresClause(),
7347 FuncY->getTrailingRequiresClause()))
7348 return false;
7349
7350 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
7351 // Map to the first declaration that we've already merged into this one.
7352 // The TSI of redeclarations might not match (due to calling conventions
7353 // being inherited onto the type but not the TSI), but the TSI type of
7354 // the first declaration of the function should match across modules.
7355 FD = FD->getCanonicalDecl();
7356 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
7357 : FD->getType();
7358 };
7359 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
7360 if (!hasSameType(XT, YT)) {
7361 // We can get functions with different types on the redecl chain in C++17
7362 // if they have differing exception specifications and at least one of
7363 // the excpetion specs is unresolved.
7364 auto *XFPT = XT->getAs<FunctionProtoType>();
7365 auto *YFPT = YT->getAs<FunctionProtoType>();
7366 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
7367 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
7370 return true;
7371 return false;
7372 }
7373
7374 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
7375 hasSameOverloadableAttrs(FuncX, FuncY);
7376 }
7377
7378 // Variables with the same type and linkage match.
7379 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
7380 const auto *VarY = cast<VarDecl>(Y);
7381 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
7382 // During deserialization, we might compare variables before we load
7383 // their types. Assume the types will end up being the same.
7384 if (VarX->getType().isNull() || VarY->getType().isNull())
7385 return true;
7386
7387 if (hasSameType(VarX->getType(), VarY->getType()))
7388 return true;
7389
7390 // We can get decls with different types on the redecl chain. Eg.
7391 // template <typename T> struct S { static T Var[]; }; // #1
7392 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
7393 // Only? happens when completing an incomplete array type. In this case
7394 // when comparing #1 and #2 we should go through their element type.
7395 const ArrayType *VarXTy = getAsArrayType(VarX->getType());
7396 const ArrayType *VarYTy = getAsArrayType(VarY->getType());
7397 if (!VarXTy || !VarYTy)
7398 return false;
7399 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
7400 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
7401 }
7402 return false;
7403 }
7404
7405 // Namespaces with the same name and inlinedness match.
7406 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
7407 const auto *NamespaceY = cast<NamespaceDecl>(Y);
7408 return NamespaceX->isInline() == NamespaceY->isInline();
7409 }
7410
7411 // Identical template names and kinds match if their template parameter lists
7412 // and patterns match.
7413 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
7414 const auto *TemplateY = cast<TemplateDecl>(Y);
7415
7416 // ConceptDecl wouldn't be the same if their constraint expression differs.
7417 if (const auto *ConceptX = dyn_cast<ConceptDecl>(X)) {
7418 const auto *ConceptY = cast<ConceptDecl>(Y);
7419 if (!isSameConstraintExpr(ConceptX->getConstraintExpr(),
7420 ConceptY->getConstraintExpr()))
7421 return false;
7422 }
7423
7424 return isSameEntity(TemplateX->getTemplatedDecl(),
7425 TemplateY->getTemplatedDecl()) &&
7426 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
7427 TemplateY->getTemplateParameters());
7428 }
7429
7430 // Fields with the same name and the same type match.
7431 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
7432 const auto *FDY = cast<FieldDecl>(Y);
7433 // FIXME: Also check the bitwidth is odr-equivalent, if any.
7434 return hasSameType(FDX->getType(), FDY->getType());
7435 }
7436
7437 // Indirect fields with the same target field match.
7438 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
7439 const auto *IFDY = cast<IndirectFieldDecl>(Y);
7440 return IFDX->getAnonField()->getCanonicalDecl() ==
7441 IFDY->getAnonField()->getCanonicalDecl();
7442 }
7443
7444 // Enumerators with the same name match.
7445 if (isa<EnumConstantDecl>(X))
7446 // FIXME: Also check the value is odr-equivalent.
7447 return true;
7448
7449 // Using shadow declarations with the same target match.
7450 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
7451 const auto *USY = cast<UsingShadowDecl>(Y);
7452 return declaresSameEntity(USX->getTargetDecl(), USY->getTargetDecl());
7453 }
7454
7455 // Using declarations with the same qualifier match. (We already know that
7456 // the name matches.)
7457 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
7458 const auto *UY = cast<UsingDecl>(Y);
7459 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7460 UX->hasTypename() == UY->hasTypename() &&
7461 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7462 }
7463 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
7464 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
7465 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7466 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7467 }
7468 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
7469 return isSameQualifier(
7470 UX->getQualifier(),
7471 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
7472 }
7473
7474 // Using-pack declarations are only created by instantiation, and match if
7475 // they're instantiated from matching UnresolvedUsing...Decls.
7476 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
7477 return declaresSameEntity(
7478 UX->getInstantiatedFromUsingDecl(),
7479 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
7480 }
7481
7482 // Namespace alias definitions with the same target match.
7483 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
7484 const auto *NAY = cast<NamespaceAliasDecl>(Y);
7485 return NAX->getNamespace()->Equals(NAY->getNamespace());
7486 }
7487
7488 return false;
7489}
7490
7493 switch (Arg.getKind()) {
7495 return Arg;
7496
7498 return Arg;
7499
7501 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
7503 Arg.getIsDefaulted());
7504 }
7505
7508 /*isNullPtr*/ true, Arg.getIsDefaulted());
7509
7512 Arg.getIsDefaulted());
7513
7515 return TemplateArgument(
7518
7521
7523 return TemplateArgument(*this,
7526
7529 /*isNullPtr*/ false, Arg.getIsDefaulted());
7530
7532 bool AnyNonCanonArgs = false;
7533 auto CanonArgs = ::getCanonicalTemplateArguments(
7534 *this, Arg.pack_elements(), AnyNonCanonArgs);
7535 if (!AnyNonCanonArgs)
7536 return Arg;
7538 const_cast<ASTContext &>(*this), CanonArgs);
7539 NewArg.setIsDefaulted(Arg.getIsDefaulted());
7540 return NewArg;
7541 }
7542 }
7543
7544 // Silence GCC warning
7545 llvm_unreachable("Unhandled template argument kind");
7546}
7547
7550 if (!NNS)
7551 return nullptr;
7552
7553 switch (NNS->getKind()) {
7555 // Canonicalize the prefix but keep the identifier the same.
7556 return NestedNameSpecifier::Create(*this,
7558 NNS->getAsIdentifier());
7559
7561 // A namespace is canonical; build a nested-name-specifier with
7562 // this namespace and no prefix.
7563 return NestedNameSpecifier::Create(*this, nullptr,
7564 NNS->getAsNamespace()->getFirstDecl());
7565
7567 // A namespace is canonical; build a nested-name-specifier with
7568 // this namespace and no prefix.
7570 *this, nullptr,
7572
7573 // The difference between TypeSpec and TypeSpecWithTemplate is that the
7574 // latter will have the 'template' keyword when printed.
7577 const Type *T = getCanonicalType(NNS->getAsType());
7578
7579 // If we have some kind of dependent-named type (e.g., "typename T::type"),
7580 // break it apart into its prefix and identifier, then reconsititute those
7581 // as the canonical nested-name-specifier. This is required to canonicalize
7582 // a dependent nested-name-specifier involving typedefs of dependent-name
7583 // types, e.g.,
7584 // typedef typename T::type T1;
7585 // typedef typename T1::type T2;
7586 if (const auto *DNT = T->getAs<DependentNameType>())
7587 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
7588 DNT->getIdentifier());
7589 if (const auto *DTST = T->getAs<DependentTemplateSpecializationType>())
7590 return NestedNameSpecifier::Create(*this, DTST->getQualifier(), true, T);
7591
7592 // TODO: Set 'Template' parameter to true for other template types.
7593 return NestedNameSpecifier::Create(*this, nullptr, false, T);
7594 }
7595
7598 // The global specifier and __super specifer are canonical and unique.
7599 return NNS;
7600 }
7601
7602 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
7603}
7604
7606 // Handle the non-qualified case efficiently.
7607 if (!T.hasLocalQualifiers()) {
7608 // Handle the common positive case fast.
7609 if (const auto *AT = dyn_cast<ArrayType>(T))
7610 return AT;
7611 }
7612
7613 // Handle the common negative case fast.
7614 if (!isa<ArrayType>(T.getCanonicalType()))
7615 return nullptr;
7616
7617 // Apply any qualifiers from the array type to the element type. This
7618 // implements C99 6.7.3p8: "If the specification of an array type includes
7619 // any type qualifiers, the element type is so qualified, not the array type."
7620
7621 // If we get here, we either have type qualifiers on the type, or we have
7622 // sugar such as a typedef in the way. If we have type qualifiers on the type
7623 // we must propagate them down into the element type.
7624
7625 SplitQualType split = T.getSplitDesugaredType();
7626 Qualifiers qs = split.Quals;
7627
7628 // If we have a simple case, just return now.
7629 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
7630 if (!ATy || qs.empty())
7631 return ATy;
7632
7633 // Otherwise, we have an array and we have qualifiers on it. Push the
7634 // qualifiers into the array element type and return a new array type.
7635 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
7636
7637 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
7638 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
7639 CAT->getSizeExpr(),
7640 CAT->getSizeModifier(),
7641 CAT->getIndexTypeCVRQualifiers()));
7642 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
7643 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
7644 IAT->getSizeModifier(),
7645 IAT->getIndexTypeCVRQualifiers()));
7646
7647 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
7648 return cast<ArrayType>(
7650 DSAT->getSizeExpr(),
7651 DSAT->getSizeModifier(),
7652 DSAT->getIndexTypeCVRQualifiers(),
7653 DSAT->getBracketsRange()));
7654
7655 const auto *VAT = cast<VariableArrayType>(ATy);
7656 return cast<ArrayType>(getVariableArrayType(NewEltTy,
7657 VAT->getSizeExpr(),
7658 VAT->getSizeModifier(),
7659 VAT->getIndexTypeCVRQualifiers(),
7660 VAT->getBracketsRange()));
7661}
7662
7665 return getArrayParameterType(T);
7666 if (T->isArrayType() || T->isFunctionType())
7667 return getDecayedType(T);
7668 return T;
7669}
7670
7674 return T.getUnqualifiedType();
7675}
7676
7678 // C++ [except.throw]p3:
7679 // A throw-expression initializes a temporary object, called the exception
7680 // object, the type of which is determined by removing any top-level
7681 // cv-qualifiers from the static type of the operand of throw and adjusting
7682 // the type from "array of T" or "function returning T" to "pointer to T"
7683 // or "pointer to function returning T", [...]
7685 if (T->isArrayType() || T->isFunctionType())
7686 T = getDecayedType(T);
7687 return T.getUnqualifiedType();
7688}
7689
7690/// getArrayDecayedType - Return the properly qualified result of decaying the
7691/// specified array type to a pointer. This operation is non-trivial when
7692/// handling typedefs etc. The canonical type of "T" must be an array type,
7693/// this returns a pointer to a properly qualified element of the array.
7694///
7695/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
7697 // Get the element type with 'getAsArrayType' so that we don't lose any
7698 // typedefs in the element type of the array. This also handles propagation
7699 // of type qualifiers from the array type into the element type if present
7700 // (C99 6.7.3p8).
7701 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
7702 assert(PrettyArrayType && "Not an array type!");
7703
7704 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
7705
7706 // int x[restrict 4] -> int *restrict
7708 PrettyArrayType->getIndexTypeQualifiers());
7709
7710 // int x[_Nullable] -> int * _Nullable
7711 if (auto Nullability = Ty->getNullability()) {
7712 Result = const_cast<ASTContext *>(this)->getAttributedType(*Nullability,
7713 Result, Result);
7714 }
7715 return Result;
7716}
7717
7719 return getBaseElementType(array->getElementType());
7720}
7721
7723 Qualifiers qs;
7724 while (true) {
7725 SplitQualType split = type.getSplitDesugaredType();
7726 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
7727 if (!array) break;
7728
7729 type = array->getElementType();
7731 }
7732
7733 return getQualifiedType(type, qs);
7734}
7735
7736/// getConstantArrayElementCount - Returns number of constant array elements.
7737uint64_t
7739 uint64_t ElementCount = 1;
7740 do {
7741 ElementCount *= CA->getZExtSize();
7742 CA = dyn_cast_or_null<ConstantArrayType>(
7744 } while (CA);
7745 return ElementCount;
7746}
7747
7749 const ArrayInitLoopExpr *AILE) const {
7750 if (!AILE)
7751 return 0;
7752
7753 uint64_t ElementCount = 1;
7754
7755 do {
7756 ElementCount *= AILE->getArraySize().getZExtValue();
7757 AILE = dyn_cast<ArrayInitLoopExpr>(AILE->getSubExpr());
7758 } while (AILE);
7759
7760 return ElementCount;
7761}
7762
7763/// getFloatingRank - Return a relative rank for floating point types.
7764/// This routine will assert if passed a built-in type that isn't a float.
7766 if (const auto *CT = T->getAs<ComplexType>())
7767 return getFloatingRank(CT->getElementType());
7768
7769 switch (T->castAs<BuiltinType>()->getKind()) {
7770 default: llvm_unreachable("getFloatingRank(): not a floating type");
7771 case BuiltinType::Float16: return Float16Rank;
7772 case BuiltinType::Half: return HalfRank;
7773 case BuiltinType::Float: return FloatRank;
7774 case BuiltinType::Double: return DoubleRank;
7775 case BuiltinType::LongDouble: return LongDoubleRank;
7776 case BuiltinType::Float128: return Float128Rank;
7777 case BuiltinType::BFloat16: return BFloat16Rank;
7778 case BuiltinType::Ibm128: return Ibm128Rank;
7779 }
7780}
7781
7782/// getFloatingTypeOrder - Compare the rank of the two specified floating
7783/// point types, ignoring the domain of the type (i.e. 'double' ==
7784/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
7785/// LHS < RHS, return -1.
7787 FloatingRank LHSR = getFloatingRank(LHS);
7788 FloatingRank RHSR = getFloatingRank(RHS);
7789
7790 if (LHSR == RHSR)
7791 return 0;
7792 if (LHSR > RHSR)
7793 return 1;
7794 return -1;
7795}
7796
7799 return 0;
7800 return getFloatingTypeOrder(LHS, RHS);
7801}
7802
7803/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
7804/// routine will assert if passed a built-in type that isn't an integer or enum,
7805/// or if it is not canonicalized.
7806unsigned ASTContext::getIntegerRank(const Type *T) const {
7807 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
7808
7809 // Results in this 'losing' to any type of the same size, but winning if
7810 // larger.
7811 if (const auto *EIT = dyn_cast<BitIntType>(T))
7812 return 0 + (EIT->getNumBits() << 3);
7813
7814 switch (cast<BuiltinType>(T)->getKind()) {
7815 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
7816 case BuiltinType::Bool:
7817 return 1 + (getIntWidth(BoolTy) << 3);
7818 case BuiltinType::Char_S:
7819 case BuiltinType::Char_U:
7820 case BuiltinType::SChar:
7821 case BuiltinType::UChar:
7822 return 2 + (getIntWidth(CharTy) << 3);
7823 case BuiltinType::Short:
7824 case BuiltinType::UShort:
7825 return 3 + (getIntWidth(ShortTy) << 3);
7826 case BuiltinType::Int:
7827 case BuiltinType::UInt:
7828 return 4 + (getIntWidth(IntTy) << 3);
7829 case BuiltinType::Long:
7830 case BuiltinType::ULong:
7831 return 5 + (getIntWidth(LongTy) << 3);
7832 case BuiltinType::LongLong:
7833 case BuiltinType::ULongLong:
7834 return 6 + (getIntWidth(LongLongTy) << 3);
7835 case BuiltinType::Int128:
7836 case BuiltinType::UInt128:
7837 return 7 + (getIntWidth(Int128Ty) << 3);
7838
7839 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
7840 // their underlying types" [c++20 conv.rank]
7841 case BuiltinType::Char8:
7842 return getIntegerRank(UnsignedCharTy.getTypePtr());
7843 case BuiltinType::Char16:
7844 return getIntegerRank(
7845 getFromTargetType(Target->getChar16Type()).getTypePtr());
7846 case BuiltinType::Char32:
7847 return getIntegerRank(
7848 getFromTargetType(Target->getChar32Type()).getTypePtr());
7849 case BuiltinType::WChar_S:
7850 case BuiltinType::WChar_U:
7851 return getIntegerRank(
7852 getFromTargetType(Target->getWCharType()).getTypePtr());
7853 }
7854}
7855
7856/// Whether this is a promotable bitfield reference according
7857/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
7858///
7859/// \returns the type this bit-field will promote to, or NULL if no
7860/// promotion occurs.
7862 if (E->isTypeDependent() || E->isValueDependent())
7863 return {};
7864
7865 // C++ [conv.prom]p5:
7866 // If the bit-field has an enumerated type, it is treated as any other
7867 // value of that type for promotion purposes.
7869 return {};
7870
7871 // FIXME: We should not do this unless E->refersToBitField() is true. This
7872 // matters in C where getSourceBitField() will find bit-fields for various
7873 // cases where the source expression is not a bit-field designator.
7874
7875 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
7876 if (!Field)
7877 return {};
7878
7879 QualType FT = Field->getType();
7880
7881 uint64_t BitWidth = Field->getBitWidthValue();
7882 uint64_t IntSize = getTypeSize(IntTy);
7883 // C++ [conv.prom]p5:
7884 // A prvalue for an integral bit-field can be converted to a prvalue of type
7885 // int if int can represent all the values of the bit-field; otherwise, it
7886 // can be converted to unsigned int if unsigned int can represent all the
7887 // values of the bit-field. If the bit-field is larger yet, no integral
7888 // promotion applies to it.
7889 // C11 6.3.1.1/2:
7890 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
7891 // If an int can represent all values of the original type (as restricted by
7892 // the width, for a bit-field), the value is converted to an int; otherwise,
7893 // it is converted to an unsigned int.
7894 //
7895 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
7896 // We perform that promotion here to match GCC and C++.
7897 // FIXME: C does not permit promotion of an enum bit-field whose rank is
7898 // greater than that of 'int'. We perform that promotion to match GCC.
7899 //
7900 // C23 6.3.1.1p2:
7901 // The value from a bit-field of a bit-precise integer type is converted to
7902 // the corresponding bit-precise integer type. (The rest is the same as in
7903 // C11.)
7904 if (QualType QT = Field->getType(); QT->isBitIntType())
7905 return QT;
7906
7907 if (BitWidth < IntSize)
7908 return IntTy;
7909
7910 if (BitWidth == IntSize)
7911 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
7912
7913 // Bit-fields wider than int are not subject to promotions, and therefore act
7914 // like the base type. GCC has some weird bugs in this area that we
7915 // deliberately do not follow (GCC follows a pre-standard resolution to
7916 // C's DR315 which treats bit-width as being part of the type, and this leaks
7917 // into their semantics in some cases).
7918 return {};
7919}
7920
7921/// getPromotedIntegerType - Returns the type that Promotable will
7922/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
7923/// integer type.
7925 assert(!Promotable.isNull());
7926 assert(isPromotableIntegerType(Promotable));
7927 if (const auto *ET = Promotable->getAs<EnumType>())
7928 return ET->getDecl()->getPromotionType();
7929
7930 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
7931 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
7932 // (3.9.1) can be converted to a prvalue of the first of the following
7933 // types that can represent all the values of its underlying type:
7934 // int, unsigned int, long int, unsigned long int, long long int, or
7935 // unsigned long long int [...]
7936 // FIXME: Is there some better way to compute this?
7937 if (BT->getKind() == BuiltinType::WChar_S ||
7938 BT->getKind() == BuiltinType::WChar_U ||
7939 BT->getKind() == BuiltinType::Char8 ||
7940 BT->getKind() == BuiltinType::Char16 ||
7941 BT->getKind() == BuiltinType::Char32) {
7942 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
7943 uint64_t FromSize = getTypeSize(BT);
7944 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
7946 for (const auto &PT : PromoteTypes) {
7947 uint64_t ToSize = getTypeSize(PT);
7948 if (FromSize < ToSize ||
7949 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
7950 return PT;
7951 }
7952 llvm_unreachable("char type should fit into long long");
7953 }
7954 }
7955
7956 // At this point, we should have a signed or unsigned integer type.
7957 if (Promotable->isSignedIntegerType())
7958 return IntTy;
7959 uint64_t PromotableSize = getIntWidth(Promotable);
7960 uint64_t IntSize = getIntWidth(IntTy);
7961 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
7962 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
7963}
7964
7965/// Recurses in pointer/array types until it finds an objc retainable
7966/// type and returns its ownership.
7968 while (!T.isNull()) {
7969 if (T.getObjCLifetime() != Qualifiers::OCL_None)
7970 return T.getObjCLifetime();
7971 if (T->isArrayType())
7973 else if (const auto *PT = T->getAs<PointerType>())
7974 T = PT->getPointeeType();
7975 else if (const auto *RT = T->getAs<ReferenceType>())
7976 T = RT->getPointeeType();
7977 else
7978 break;
7979 }
7980
7981 return Qualifiers::OCL_None;
7982}
7983
7984static const Type *getIntegerTypeForEnum(const EnumType *ET) {
7985 // Incomplete enum types are not treated as integer types.
7986 // FIXME: In C++, enum types are never integer types.
7987 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
7988 return ET->getDecl()->getIntegerType().getTypePtr();
7989 return nullptr;
7990}
7991
7992/// getIntegerTypeOrder - Returns the highest ranked integer type:
7993/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
7994/// LHS < RHS, return -1.
7996 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
7997 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
7998
7999 // Unwrap enums to their underlying type.
8000 if (const auto *ET = dyn_cast<EnumType>(LHSC))
8001 LHSC = getIntegerTypeForEnum(ET);
8002 if (const auto *ET = dyn_cast<EnumType>(RHSC))
8003 RHSC = getIntegerTypeForEnum(ET);
8004
8005 if (LHSC == RHSC) return 0;
8006
8007 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
8008 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
8009
8010 unsigned LHSRank = getIntegerRank(LHSC);
8011 unsigned RHSRank = getIntegerRank(RHSC);
8012
8013 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
8014 if (LHSRank == RHSRank) return 0;
8015 return LHSRank > RHSRank ? 1 : -1;
8016 }
8017
8018 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
8019 if (LHSUnsigned) {
8020 // If the unsigned [LHS] type is larger, return it.
8021 if (LHSRank >= RHSRank)
8022 return 1;
8023
8024 // If the signed type can represent all values of the unsigned type, it
8025 // wins. Because we are dealing with 2's complement and types that are
8026 // powers of two larger than each other, this is always safe.
8027 return -1;
8028 }
8029
8030 // If the unsigned [RHS] type is larger, return it.
8031 if (RHSRank >= LHSRank)
8032 return -1;
8033
8034 // If the signed type can represent all values of the unsigned type, it
8035 // wins. Because we are dealing with 2's complement and types that are
8036 // powers of two larger than each other, this is always safe.
8037 return 1;
8038}
8039
8041 if (CFConstantStringTypeDecl)
8042 return CFConstantStringTypeDecl;
8043
8044 assert(!CFConstantStringTagDecl &&
8045 "tag and typedef should be initialized together");
8046 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
8047 CFConstantStringTagDecl->startDefinition();
8048
8049 struct {
8050 QualType Type;
8051 const char *Name;
8052 } Fields[5];
8053 unsigned Count = 0;
8054
8055 /// Objective-C ABI
8056 ///
8057 /// typedef struct __NSConstantString_tag {
8058 /// const int *isa;
8059 /// int flags;
8060 /// const char *str;
8061 /// long length;
8062 /// } __NSConstantString;
8063 ///
8064 /// Swift ABI (4.1, 4.2)
8065 ///
8066 /// typedef struct __NSConstantString_tag {
8067 /// uintptr_t _cfisa;
8068 /// uintptr_t _swift_rc;
8069 /// _Atomic(uint64_t) _cfinfoa;
8070 /// const char *_ptr;
8071 /// uint32_t _length;
8072 /// } __NSConstantString;
8073 ///
8074 /// Swift ABI (5.0)
8075 ///
8076 /// typedef struct __NSConstantString_tag {
8077 /// uintptr_t _cfisa;
8078 /// uintptr_t _swift_rc;
8079 /// _Atomic(uint64_t) _cfinfoa;
8080 /// const char *_ptr;
8081 /// uintptr_t _length;
8082 /// } __NSConstantString;
8083
8084 const auto CFRuntime = getLangOpts().CFRuntime;
8085 if (static_cast<unsigned>(CFRuntime) <
8086 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
8087 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
8088 Fields[Count++] = { IntTy, "flags" };
8089 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
8090 Fields[Count++] = { LongTy, "length" };
8091 } else {
8092 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
8093 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
8094 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
8095 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
8098 Fields[Count++] = { IntTy, "_ptr" };
8099 else
8100 Fields[Count++] = { getUIntPtrType(), "_ptr" };
8101 }
8102
8103 // Create fields
8104 for (unsigned i = 0; i < Count; ++i) {
8105 FieldDecl *Field =
8106 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
8107 SourceLocation(), &Idents.get(Fields[i].Name),
8108 Fields[i].Type, /*TInfo=*/nullptr,
8109 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8110 Field->setAccess(AS_public);
8111 CFConstantStringTagDecl->addDecl(Field);
8112 }
8113
8114 CFConstantStringTagDecl->completeDefinition();
8115 // This type is designed to be compatible with NSConstantString, but cannot
8116 // use the same name, since NSConstantString is an interface.
8117 auto tagType = getTagDeclType(CFConstantStringTagDecl);
8118 CFConstantStringTypeDecl =
8119 buildImplicitTypedef(tagType, "__NSConstantString");
8120
8121 return CFConstantStringTypeDecl;
8122}
8123
8125 if (!CFConstantStringTagDecl)
8126 getCFConstantStringDecl(); // Build the tag and the typedef.
8127 return CFConstantStringTagDecl;
8128}
8129
8130// getCFConstantStringType - Return the type used for constant CFStrings.
8133}
8134
8136 if (ObjCSuperType.isNull()) {
8137 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
8138 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
8139 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
8140 }
8141 return ObjCSuperType;
8142}
8143
8145 const auto *TD = T->castAs<TypedefType>();
8146 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
8147 const auto *TagType =
8148 CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>();
8149 CFConstantStringTagDecl = TagType->getDecl();
8150}
8151
8153 if (BlockDescriptorType)
8154 return getTagDeclType(BlockDescriptorType);
8155
8156 RecordDecl *RD;
8157 // FIXME: Needs the FlagAppleBlock bit.
8158 RD = buildImplicitRecord("__block_descriptor");
8159 RD->startDefinition();
8160
8161 QualType FieldTypes[] = {
8164 };
8165
8166 static const char *const FieldNames[] = {
8167 "reserved",
8168 "Size"
8169 };
8170
8171 for (size_t i = 0; i < 2; ++i) {
8173 *this, RD, SourceLocation(), SourceLocation(),
8174 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8175 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8176 Field->setAccess(AS_public);
8177 RD->addDecl(Field);
8178 }
8179
8180 RD->completeDefinition();
8181
8182 BlockDescriptorType = RD;
8183
8184 return getTagDeclType(BlockDescriptorType);
8185}
8186
8188 if (BlockDescriptorExtendedType)
8189 return getTagDeclType(BlockDescriptorExtendedType);
8190
8191 RecordDecl *RD;
8192 // FIXME: Needs the FlagAppleBlock bit.
8193 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
8194 RD->startDefinition();
8195
8196 QualType FieldTypes[] = {
8201 };
8202
8203 static const char *const FieldNames[] = {
8204 "reserved",
8205 "Size",
8206 "CopyFuncPtr",
8207 "DestroyFuncPtr"
8208 };
8209
8210 for (size_t i = 0; i < 4; ++i) {
8212 *this, RD, SourceLocation(), SourceLocation(),
8213 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8214 /*BitWidth=*/nullptr,
8215 /*Mutable=*/false, ICIS_NoInit);
8216 Field->setAccess(AS_public);
8217 RD->addDecl(Field);
8218 }
8219
8220 RD->completeDefinition();
8221
8222 BlockDescriptorExtendedType = RD;
8223 return getTagDeclType(BlockDescriptorExtendedType);
8224}
8225
8227 const auto *BT = dyn_cast<BuiltinType>(T);
8228
8229 if (!BT) {
8230 if (isa<PipeType>(T))
8231 return OCLTK_Pipe;
8232
8233 return OCLTK_Default;
8234 }
8235
8236 switch (BT->getKind()) {
8237#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8238 case BuiltinType::Id: \
8239 return OCLTK_Image;
8240#include "clang/Basic/OpenCLImageTypes.def"
8241
8242 case BuiltinType::OCLClkEvent:
8243 return OCLTK_ClkEvent;
8244
8245 case BuiltinType::OCLEvent:
8246 return OCLTK_Event;
8247
8248 case BuiltinType::OCLQueue:
8249 return OCLTK_Queue;
8250
8251 case BuiltinType::OCLReserveID:
8252 return OCLTK_ReserveID;
8253
8254 case BuiltinType::OCLSampler:
8255 return OCLTK_Sampler;
8256
8257 default:
8258 return OCLTK_Default;
8259 }
8260}
8261
8263 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
8264}
8265
8266/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
8267/// requires copy/dispose. Note that this must match the logic
8268/// in buildByrefHelpers.
8270 const VarDecl *D) {
8271 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
8272 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
8273 if (!copyExpr && record->hasTrivialDestructor()) return false;
8274
8275 return true;
8276 }
8277
8278 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
8279 // move or destroy.
8281 return true;
8282
8283 if (!Ty->isObjCRetainableType()) return false;
8284
8285 Qualifiers qs = Ty.getQualifiers();
8286
8287 // If we have lifetime, that dominates.
8288 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
8289 switch (lifetime) {
8290 case Qualifiers::OCL_None: llvm_unreachable("impossible");
8291
8292 // These are just bits as far as the runtime is concerned.
8295 return false;
8296
8297 // These cases should have been taken care of when checking the type's
8298 // non-triviality.
8301 llvm_unreachable("impossible");
8302 }
8303 llvm_unreachable("fell out of lifetime switch!");
8304 }
8305 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
8307}
8308
8310 Qualifiers::ObjCLifetime &LifeTime,
8311 bool &HasByrefExtendedLayout) const {
8312 if (!getLangOpts().ObjC ||
8313 getLangOpts().getGC() != LangOptions::NonGC)
8314 return false;
8315
8316 HasByrefExtendedLayout = false;
8317 if (Ty->isRecordType()) {
8318 HasByrefExtendedLayout = true;
8319 LifeTime = Qualifiers::OCL_None;
8320 } else if ((LifeTime = Ty.getObjCLifetime())) {
8321 // Honor the ARC qualifiers.
8322 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
8323 // The MRR rule.
8325 } else {
8326 LifeTime = Qualifiers::OCL_None;
8327 }
8328 return true;
8329}
8330
8332 assert(Target && "Expected target to be initialized");
8333 const llvm::Triple &T = Target->getTriple();
8334 // Windows is LLP64 rather than LP64
8335 if (T.isOSWindows() && T.isArch64Bit())
8336 return UnsignedLongLongTy;
8337 return UnsignedLongTy;
8338}
8339
8341 assert(Target && "Expected target to be initialized");
8342 const llvm::Triple &T = Target->getTriple();
8343 // Windows is LLP64 rather than LP64
8344 if (T.isOSWindows() && T.isArch64Bit())
8345 return LongLongTy;
8346 return LongTy;
8347}
8348
8350 if (!ObjCInstanceTypeDecl)
8351 ObjCInstanceTypeDecl =
8352 buildImplicitTypedef(getObjCIdType(), "instancetype");
8353 return ObjCInstanceTypeDecl;
8354}
8355
8356// This returns true if a type has been typedefed to BOOL:
8357// typedef <type> BOOL;
8359 if (const auto *TT = dyn_cast<TypedefType>(T))
8360 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
8361 return II->isStr("BOOL");
8362
8363 return false;
8364}
8365
8366/// getObjCEncodingTypeSize returns size of type for objective-c encoding
8367/// purpose.
8369 if (!type->isIncompleteArrayType() && type->isIncompleteType())
8370 return CharUnits::Zero();
8371
8373
8374 // Make all integer and enum types at least as large as an int
8375 if (sz.isPositive() && type->isIntegralOrEnumerationType())
8376 sz = std::max(sz, getTypeSizeInChars(IntTy));
8377 // Treat arrays as pointers, since that's how they're passed in.
8378 else if (type->isArrayType())
8380 return sz;
8381}
8382
8384 return getTargetInfo().getCXXABI().isMicrosoft() &&
8385 VD->isStaticDataMember() &&
8387 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
8388}
8389
8392 if (!VD->isInline())
8394
8395 // In almost all cases, it's a weak definition.
8396 auto *First = VD->getFirstDecl();
8397 if (First->isInlineSpecified() || !First->isStaticDataMember())
8399
8400 // If there's a file-context declaration in this translation unit, it's a
8401 // non-discardable definition.
8402 for (auto *D : VD->redecls())
8404 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
8406
8407 // If we've not seen one yet, we don't know.
8409}
8410
8411static std::string charUnitsToString(const CharUnits &CU) {
8412 return llvm::itostr(CU.getQuantity());
8413}
8414
8415/// getObjCEncodingForBlock - Return the encoded type for this block
8416/// declaration.
8418 std::string S;
8419
8420 const BlockDecl *Decl = Expr->getBlockDecl();
8421 QualType BlockTy =
8423 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
8424 // Encode result type.
8425 if (getLangOpts().EncodeExtendedBlockSig)
8427 true /*Extended*/);
8428 else
8429 getObjCEncodingForType(BlockReturnTy, S);
8430 // Compute size of all parameters.
8431 // Start with computing size of a pointer in number of bytes.
8432 // FIXME: There might(should) be a better way of doing this computation!
8434 CharUnits ParmOffset = PtrSize;
8435 for (auto *PI : Decl->parameters()) {
8436 QualType PType = PI->getType();
8438 if (sz.isZero())
8439 continue;
8440 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
8441 ParmOffset += sz;
8442 }
8443 // Size of the argument frame
8444 S += charUnitsToString(ParmOffset);
8445 // Block pointer and offset.
8446 S += "@?0";
8447
8448 // Argument types.
8449 ParmOffset = PtrSize;
8450 for (auto *PVDecl : Decl->parameters()) {
8451 QualType PType = PVDecl->getOriginalType();
8452 if (const auto *AT =
8453 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8454 // Use array's original type only if it has known number of
8455 // elements.
8456 if (!isa<ConstantArrayType>(AT))
8457 PType = PVDecl->getType();
8458 } else if (PType->isFunctionType())
8459 PType = PVDecl->getType();
8460 if (getLangOpts().EncodeExtendedBlockSig)
8462 S, true /*Extended*/);
8463 else
8464 getObjCEncodingForType(PType, S);
8465 S += charUnitsToString(ParmOffset);
8466 ParmOffset += getObjCEncodingTypeSize(PType);
8467 }
8468
8469 return S;
8470}
8471
8472std::string
8474 std::string S;
8475 // Encode result type.
8476 getObjCEncodingForType(Decl->getReturnType(), S);
8477 CharUnits ParmOffset;
8478 // Compute size of all parameters.
8479 for (auto *PI : Decl->parameters()) {
8480 QualType PType = PI->getType();
8482 if (sz.isZero())
8483 continue;
8484
8485 assert(sz.isPositive() &&
8486 "getObjCEncodingForFunctionDecl - Incomplete param type");
8487 ParmOffset += sz;
8488 }
8489 S += charUnitsToString(ParmOffset);
8490 ParmOffset = CharUnits::Zero();
8491
8492 // Argument types.
8493 for (auto *PVDecl : Decl->parameters()) {
8494 QualType PType = PVDecl->getOriginalType();
8495 if (const auto *AT =
8496 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8497 // Use array's original type only if it has known number of
8498 // elements.
8499 if (!isa<ConstantArrayType>(AT))
8500 PType = PVDecl->getType();
8501 } else if (PType->isFunctionType())
8502 PType = PVDecl->getType();
8503 getObjCEncodingForType(PType, S);
8504 S += charUnitsToString(ParmOffset);
8505 ParmOffset += getObjCEncodingTypeSize(PType);
8506 }
8507
8508 return S;
8509}
8510
8511/// getObjCEncodingForMethodParameter - Return the encoded type for a single
8512/// method parameter or return type. If Extended, include class names and
8513/// block object types.
8515 QualType T, std::string& S,
8516 bool Extended) const {
8517 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
8519 // Encode parameter type.
8520 ObjCEncOptions Options = ObjCEncOptions()
8521 .setExpandPointedToStructures()
8522 .setExpandStructures()
8523 .setIsOutermostType();
8524 if (Extended)
8525 Options.setEncodeBlockParameters().setEncodeClassNames();
8526 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
8527}
8528
8529/// getObjCEncodingForMethodDecl - Return the encoded type for this method
8530/// declaration.
8532 bool Extended) const {
8533 // FIXME: This is not very efficient.
8534 // Encode return type.
8535 std::string S;
8536 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
8537 Decl->getReturnType(), S, Extended);
8538 // Compute size of all parameters.
8539 // Start with computing size of a pointer in number of bytes.
8540 // FIXME: There might(should) be a better way of doing this computation!
8542 // The first two arguments (self and _cmd) are pointers; account for
8543 // their size.
8544 CharUnits ParmOffset = 2 * PtrSize;
8545 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8546 E = Decl->sel_param_end(); PI != E; ++PI) {
8547 QualType PType = (*PI)->getType();
8549 if (sz.isZero())
8550 continue;
8551
8552 assert(sz.isPositive() &&
8553 "getObjCEncodingForMethodDecl - Incomplete param type");
8554 ParmOffset += sz;
8555 }
8556 S += charUnitsToString(ParmOffset);
8557 S += "@0:";
8558 S += charUnitsToString(PtrSize);
8559
8560 // Argument types.
8561 ParmOffset = 2 * PtrSize;
8562 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8563 E = Decl->sel_param_end(); PI != E; ++PI) {
8564 const ParmVarDecl *PVDecl = *PI;
8565 QualType PType = PVDecl->getOriginalType();
8566 if (const auto *AT =
8567 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8568 // Use array's original type only if it has known number of
8569 // elements.
8570 if (!isa<ConstantArrayType>(AT))
8571 PType = PVDecl->getType();
8572 } else if (PType->isFunctionType())
8573 PType = PVDecl->getType();
8575 PType, S, Extended);
8576 S += charUnitsToString(ParmOffset);
8577 ParmOffset += getObjCEncodingTypeSize(PType);
8578 }
8579
8580 return S;
8581}
8582
8585 const ObjCPropertyDecl *PD,
8586 const Decl *Container) const {
8587 if (!Container)
8588 return nullptr;
8589 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
8590 for (auto *PID : CID->property_impls())
8591 if (PID->getPropertyDecl() == PD)
8592 return PID;
8593 } else {
8594 const auto *OID = cast<ObjCImplementationDecl>(Container);
8595 for (auto *PID : OID->property_impls())
8596 if (PID->getPropertyDecl() == PD)
8597 return PID;
8598 }
8599 return nullptr;
8600}
8601
8602/// getObjCEncodingForPropertyDecl - Return the encoded type for this
8603/// property declaration. If non-NULL, Container must be either an
8604/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
8605/// NULL when getting encodings for protocol properties.
8606/// Property attributes are stored as a comma-delimited C string. The simple
8607/// attributes readonly and bycopy are encoded as single characters. The
8608/// parametrized attributes, getter=name, setter=name, and ivar=name, are
8609/// encoded as single characters, followed by an identifier. Property types
8610/// are also encoded as a parametrized attribute. The characters used to encode
8611/// these attributes are defined by the following enumeration:
8612/// @code
8613/// enum PropertyAttributes {
8614/// kPropertyReadOnly = 'R', // property is read-only.
8615/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
8616/// kPropertyByref = '&', // property is a reference to the value last assigned
8617/// kPropertyDynamic = 'D', // property is dynamic
8618/// kPropertyGetter = 'G', // followed by getter selector name
8619/// kPropertySetter = 'S', // followed by setter selector name
8620/// kPropertyInstanceVariable = 'V' // followed by instance variable name
8621/// kPropertyType = 'T' // followed by old-style type encoding.
8622/// kPropertyWeak = 'W' // 'weak' property
8623/// kPropertyStrong = 'P' // property GC'able
8624/// kPropertyNonAtomic = 'N' // property non-atomic
8625/// kPropertyOptional = '?' // property optional
8626/// };
8627/// @endcode
8628std::string
8630 const Decl *Container) const {
8631 // Collect information from the property implementation decl(s).
8632 bool Dynamic = false;
8633 ObjCPropertyImplDecl *SynthesizePID = nullptr;
8634
8635 if (ObjCPropertyImplDecl *PropertyImpDecl =
8637 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
8638 Dynamic = true;
8639 else
8640 SynthesizePID = PropertyImpDecl;
8641 }
8642
8643 // FIXME: This is not very efficient.
8644 std::string S = "T";
8645
8646 // Encode result type.
8647 // GCC has some special rules regarding encoding of properties which
8648 // closely resembles encoding of ivars.
8650
8651 if (PD->isOptional())
8652 S += ",?";
8653
8654 if (PD->isReadOnly()) {
8655 S += ",R";
8657 S += ",C";
8659 S += ",&";
8661 S += ",W";
8662 } else {
8663 switch (PD->getSetterKind()) {
8664 case ObjCPropertyDecl::Assign: break;
8665 case ObjCPropertyDecl::Copy: S += ",C"; break;
8666 case ObjCPropertyDecl::Retain: S += ",&"; break;
8667 case ObjCPropertyDecl::Weak: S += ",W"; break;
8668 }
8669 }
8670
8671 // It really isn't clear at all what this means, since properties
8672 // are "dynamic by default".
8673 if (Dynamic)
8674 S += ",D";
8675
8677 S += ",N";
8678
8680 S += ",G";
8681 S += PD->getGetterName().getAsString();
8682 }
8683
8685 S += ",S";
8686 S += PD->getSetterName().getAsString();
8687 }
8688
8689 if (SynthesizePID) {
8690 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
8691 S += ",V";
8692 S += OID->getNameAsString();
8693 }
8694
8695 // FIXME: OBJCGC: weak & strong
8696 return S;
8697}
8698
8699/// getLegacyIntegralTypeEncoding -
8700/// Another legacy compatibility encoding: 32-bit longs are encoded as
8701/// 'l' or 'L' , but not always. For typedefs, we need to use
8702/// 'i' or 'I' instead if encoding a struct field, or a pointer!
8704 if (PointeeTy->getAs<TypedefType>()) {
8705 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
8706 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
8707 PointeeTy = UnsignedIntTy;
8708 else
8709 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
8710 PointeeTy = IntTy;
8711 }
8712 }
8713}
8714
8716 const FieldDecl *Field,
8717 QualType *NotEncodedT) const {
8718 // We follow the behavior of gcc, expanding structures which are
8719 // directly pointed to, and expanding embedded structures. Note that
8720 // these rules are sufficient to prevent recursive encoding of the
8721 // same type.
8722 getObjCEncodingForTypeImpl(T, S,
8723 ObjCEncOptions()
8724 .setExpandPointedToStructures()
8725 .setExpandStructures()
8726 .setIsOutermostType(),
8727 Field, NotEncodedT);
8728}
8729
8731 std::string& S) const {
8732 // Encode result type.
8733 // GCC has some special rules regarding encoding of properties which
8734 // closely resembles encoding of ivars.
8735 getObjCEncodingForTypeImpl(T, S,
8736 ObjCEncOptions()
8737 .setExpandPointedToStructures()
8738 .setExpandStructures()
8739 .setIsOutermostType()
8740 .setEncodingProperty(),
8741 /*Field=*/nullptr);
8742}
8743
8745 const BuiltinType *BT) {
8746 BuiltinType::Kind kind = BT->getKind();
8747 switch (kind) {
8748 case BuiltinType::Void: return 'v';
8749 case BuiltinType::Bool: return 'B';
8750 case BuiltinType::Char8:
8751 case BuiltinType::Char_U:
8752 case BuiltinType::UChar: return 'C';
8753 case BuiltinType::Char16:
8754 case BuiltinType::UShort: return 'S';
8755 case BuiltinType::Char32:
8756 case BuiltinType::UInt: return 'I';
8757 case BuiltinType::ULong:
8758 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
8759 case BuiltinType::UInt128: return 'T';
8760 case BuiltinType::ULongLong: return 'Q';
8761 case BuiltinType::Char_S:
8762 case BuiltinType::SChar: return 'c';
8763 case BuiltinType::Short: return 's';
8764 case BuiltinType::WChar_S:
8765 case BuiltinType::WChar_U:
8766 case BuiltinType::Int: return 'i';
8767 case BuiltinType::Long:
8768 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
8769 case BuiltinType::LongLong: return 'q';
8770 case BuiltinType::Int128: return 't';
8771 case BuiltinType::Float: return 'f';
8772 case BuiltinType::Double: return 'd';
8773 case BuiltinType::LongDouble: return 'D';
8774 case BuiltinType::NullPtr: return '*'; // like char*
8775
8776 case BuiltinType::BFloat16:
8777 case BuiltinType::Float16:
8778 case BuiltinType::Float128:
8779 case BuiltinType::Ibm128:
8780 case BuiltinType::Half:
8781 case BuiltinType::ShortAccum:
8782 case BuiltinType::Accum:
8783 case BuiltinType::LongAccum:
8784 case BuiltinType::UShortAccum:
8785 case BuiltinType::UAccum:
8786 case BuiltinType::ULongAccum:
8787 case BuiltinType::ShortFract:
8788 case BuiltinType::Fract:
8789 case BuiltinType::LongFract:
8790 case BuiltinType::UShortFract:
8791 case BuiltinType::UFract:
8792 case BuiltinType::ULongFract:
8793 case BuiltinType::SatShortAccum:
8794 case BuiltinType::SatAccum:
8795 case BuiltinType::SatLongAccum:
8796 case BuiltinType::SatUShortAccum:
8797 case BuiltinType::SatUAccum:
8798 case BuiltinType::SatULongAccum:
8799 case BuiltinType::SatShortFract:
8800 case BuiltinType::SatFract:
8801 case BuiltinType::SatLongFract:
8802 case BuiltinType::SatUShortFract:
8803 case BuiltinType::SatUFract:
8804 case BuiltinType::SatULongFract:
8805 // FIXME: potentially need @encodes for these!
8806 return ' ';
8807
8808#define SVE_TYPE(Name, Id, SingletonId) \
8809 case BuiltinType::Id:
8810#include "clang/Basic/AArch64SVEACLETypes.def"
8811#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
8812#include "clang/Basic/RISCVVTypes.def"
8813#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
8814#include "clang/Basic/WebAssemblyReferenceTypes.def"
8815#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
8816#include "clang/Basic/AMDGPUTypes.def"
8817 {
8818 DiagnosticsEngine &Diags = C->getDiagnostics();
8819 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
8820 "cannot yet @encode type %0");
8821 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
8822 return ' ';
8823 }
8824
8825 case BuiltinType::ObjCId:
8826 case BuiltinType::ObjCClass:
8827 case BuiltinType::ObjCSel:
8828 llvm_unreachable("@encoding ObjC primitive type");
8829
8830 // OpenCL and placeholder types don't need @encodings.
8831#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8832 case BuiltinType::Id:
8833#include "clang/Basic/OpenCLImageTypes.def"
8834#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
8835 case BuiltinType::Id:
8836#include "clang/Basic/OpenCLExtensionTypes.def"
8837 case BuiltinType::OCLEvent:
8838 case BuiltinType::OCLClkEvent:
8839 case BuiltinType::OCLQueue:
8840 case BuiltinType::OCLReserveID:
8841 case BuiltinType::OCLSampler:
8842 case BuiltinType::Dependent:
8843#define PPC_VECTOR_TYPE(Name, Id, Size) \
8844 case BuiltinType::Id:
8845#include "clang/Basic/PPCTypes.def"
8846#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
8847#include "clang/Basic/HLSLIntangibleTypes.def"
8848#define BUILTIN_TYPE(KIND, ID)
8849#define PLACEHOLDER_TYPE(KIND, ID) \
8850 case BuiltinType::KIND:
8851#include "clang/AST/BuiltinTypes.def"
8852 llvm_unreachable("invalid builtin type for @encode");
8853 }
8854 llvm_unreachable("invalid BuiltinType::Kind value");
8855}
8856
8857static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
8858 EnumDecl *Enum = ET->getDecl();
8859
8860 // The encoding of an non-fixed enum type is always 'i', regardless of size.
8861 if (!Enum->isFixed())
8862 return 'i';
8863
8864 // The encoding of a fixed enum type matches its fixed underlying type.
8865 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
8867}
8868
8869static void EncodeBitField(const ASTContext *Ctx, std::string& S,
8870 QualType T, const FieldDecl *FD) {
8871 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
8872 S += 'b';
8873 // The NeXT runtime encodes bit fields as b followed by the number of bits.
8874 // The GNU runtime requires more information; bitfields are encoded as b,
8875 // then the offset (in bits) of the first element, then the type of the
8876 // bitfield, then the size in bits. For example, in this structure:
8877 //
8878 // struct
8879 // {
8880 // int integer;
8881 // int flags:2;
8882 // };
8883 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
8884 // runtime, but b32i2 for the GNU runtime. The reason for this extra
8885 // information is not especially sensible, but we're stuck with it for
8886 // compatibility with GCC, although providing it breaks anything that
8887 // actually uses runtime introspection and wants to work on both runtimes...
8888 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
8889 uint64_t Offset;
8890
8891 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
8892 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
8893 IVD);
8894 } else {
8895 const RecordDecl *RD = FD->getParent();
8896 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
8897 Offset = RL.getFieldOffset(FD->getFieldIndex());
8898 }
8899
8900 S += llvm::utostr(Offset);
8901
8902 if (const auto *ET = T->getAs<EnumType>())
8903 S += ObjCEncodingForEnumType(Ctx, ET);
8904 else {
8905 const auto *BT = T->castAs<BuiltinType>();
8906 S += getObjCEncodingForPrimitiveType(Ctx, BT);
8907 }
8908 }
8909 S += llvm::utostr(FD->getBitWidthValue());
8910}
8911
8912// Helper function for determining whether the encoded type string would include
8913// a template specialization type.
8915 bool VisitBasesAndFields) {
8917
8918 if (auto *PT = T->getAs<PointerType>())
8920 PT->getPointeeType().getTypePtr(), false);
8921
8922 auto *CXXRD = T->getAsCXXRecordDecl();
8923
8924 if (!CXXRD)
8925 return false;
8926
8927 if (isa<ClassTemplateSpecializationDecl>(CXXRD))
8928 return true;
8929
8930 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
8931 return false;
8932
8933 for (const auto &B : CXXRD->bases())
8934 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
8935 true))
8936 return true;
8937
8938 for (auto *FD : CXXRD->fields())
8939 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
8940 true))
8941 return true;
8942
8943 return false;
8944}
8945
8946// FIXME: Use SmallString for accumulating string.
8947void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
8948 const ObjCEncOptions Options,
8949 const FieldDecl *FD,
8950 QualType *NotEncodedT) const {
8952 switch (CT->getTypeClass()) {
8953 case Type::Builtin:
8954 case Type::Enum:
8955 if (FD && FD->isBitField())
8956 return EncodeBitField(this, S, T, FD);
8957 if (const auto *BT = dyn_cast<BuiltinType>(CT))
8958 S += getObjCEncodingForPrimitiveType(this, BT);
8959 else
8960 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
8961 return;
8962
8963 case Type::Complex:
8964 S += 'j';
8965 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
8966 ObjCEncOptions(),
8967 /*Field=*/nullptr);
8968 return;
8969
8970 case Type::Atomic:
8971 S += 'A';
8972 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
8973 ObjCEncOptions(),
8974 /*Field=*/nullptr);
8975 return;
8976
8977 // encoding for pointer or reference types.
8978 case Type::Pointer:
8979 case Type::LValueReference:
8980 case Type::RValueReference: {
8981 QualType PointeeTy;
8982 if (isa<PointerType>(CT)) {
8983 const auto *PT = T->castAs<PointerType>();
8984 if (PT->isObjCSelType()) {
8985 S += ':';
8986 return;
8987 }
8988 PointeeTy = PT->getPointeeType();
8989 } else {
8990 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
8991 }
8992
8993 bool isReadOnly = false;
8994 // For historical/compatibility reasons, the read-only qualifier of the
8995 // pointee gets emitted _before_ the '^'. The read-only qualifier of
8996 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
8997 // Also, do not emit the 'r' for anything but the outermost type!
8998 if (T->getAs<TypedefType>()) {
8999 if (Options.IsOutermostType() && T.isConstQualified()) {
9000 isReadOnly = true;
9001 S += 'r';
9002 }
9003 } else if (Options.IsOutermostType()) {
9004 QualType P = PointeeTy;
9005 while (auto PT = P->getAs<PointerType>())
9006 P = PT->getPointeeType();
9007 if (P.isConstQualified()) {
9008 isReadOnly = true;
9009 S += 'r';
9010 }
9011 }
9012 if (isReadOnly) {
9013 // Another legacy compatibility encoding. Some ObjC qualifier and type
9014 // combinations need to be rearranged.
9015 // Rewrite "in const" from "nr" to "rn"
9016 if (StringRef(S).ends_with("nr"))
9017 S.replace(S.end()-2, S.end(), "rn");
9018 }
9019
9020 if (PointeeTy->isCharType()) {
9021 // char pointer types should be encoded as '*' unless it is a
9022 // type that has been typedef'd to 'BOOL'.
9023 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
9024 S += '*';
9025 return;
9026 }
9027 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
9028 // GCC binary compat: Need to convert "struct objc_class *" to "#".
9029 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
9030 S += '#';
9031 return;
9032 }
9033 // GCC binary compat: Need to convert "struct objc_object *" to "@".
9034 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
9035 S += '@';
9036 return;
9037 }
9038 // If the encoded string for the class includes template names, just emit
9039 // "^v" for pointers to the class.
9040 if (getLangOpts().CPlusPlus &&
9041 (!getLangOpts().EncodeCXXClassTemplateSpec &&
9043 RTy, Options.ExpandPointedToStructures()))) {
9044 S += "^v";
9045 return;
9046 }
9047 // fall through...
9048 }
9049 S += '^';
9051
9052 ObjCEncOptions NewOptions;
9053 if (Options.ExpandPointedToStructures())
9054 NewOptions.setExpandStructures();
9055 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
9056 /*Field=*/nullptr, NotEncodedT);
9057 return;
9058 }
9059
9060 case Type::ConstantArray:
9061 case Type::IncompleteArray:
9062 case Type::VariableArray: {
9063 const auto *AT = cast<ArrayType>(CT);
9064
9065 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
9066 // Incomplete arrays are encoded as a pointer to the array element.
9067 S += '^';
9068
9069 getObjCEncodingForTypeImpl(
9070 AT->getElementType(), S,
9071 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
9072 } else {
9073 S += '[';
9074
9075 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
9076 S += llvm::utostr(CAT->getZExtSize());
9077 else {
9078 //Variable length arrays are encoded as a regular array with 0 elements.
9079 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
9080 "Unknown array type!");
9081 S += '0';
9082 }
9083
9084 getObjCEncodingForTypeImpl(
9085 AT->getElementType(), S,
9086 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
9087 NotEncodedT);
9088 S += ']';
9089 }
9090 return;
9091 }
9092
9093 case Type::FunctionNoProto:
9094 case Type::FunctionProto:
9095 S += '?';
9096 return;
9097
9098 case Type::Record: {
9099 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
9100 S += RDecl->isUnion() ? '(' : '{';
9101 // Anonymous structures print as '?'
9102 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
9103 S += II->getName();
9104 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
9105 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
9106 llvm::raw_string_ostream OS(S);
9107 printTemplateArgumentList(OS, TemplateArgs.asArray(),
9109 }
9110 } else {
9111 S += '?';
9112 }
9113 if (Options.ExpandStructures()) {
9114 S += '=';
9115 if (!RDecl->isUnion()) {
9116 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
9117 } else {
9118 for (const auto *Field : RDecl->fields()) {
9119 if (FD) {
9120 S += '"';
9121 S += Field->getNameAsString();
9122 S += '"';
9123 }
9124
9125 // Special case bit-fields.
9126 if (Field->isBitField()) {
9127 getObjCEncodingForTypeImpl(Field->getType(), S,
9128 ObjCEncOptions().setExpandStructures(),
9129 Field);
9130 } else {
9131 QualType qt = Field->getType();
9133 getObjCEncodingForTypeImpl(
9134 qt, S,
9135 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
9136 NotEncodedT);
9137 }
9138 }
9139 }
9140 }
9141 S += RDecl->isUnion() ? ')' : '}';
9142 return;
9143 }
9144
9145 case Type::BlockPointer: {
9146 const auto *BT = T->castAs<BlockPointerType>();
9147 S += "@?"; // Unlike a pointer-to-function, which is "^?".
9148 if (Options.EncodeBlockParameters()) {
9149 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
9150
9151 S += '<';
9152 // Block return type
9153 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
9154 Options.forComponentType(), FD, NotEncodedT);
9155 // Block self
9156 S += "@?";
9157 // Block parameters
9158 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
9159 for (const auto &I : FPT->param_types())
9160 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
9161 NotEncodedT);
9162 }
9163 S += '>';
9164 }
9165 return;
9166 }
9167
9168 case Type::ObjCObject: {
9169 // hack to match legacy encoding of *id and *Class
9171 if (Ty->isObjCIdType()) {
9172 S += "{objc_object=}";
9173 return;
9174 }
9175 else if (Ty->isObjCClassType()) {
9176 S += "{objc_class=}";
9177 return;
9178 }
9179 // TODO: Double check to make sure this intentionally falls through.
9180 [[fallthrough]];
9181 }
9182
9183 case Type::ObjCInterface: {
9184 // Ignore protocol qualifiers when mangling at this level.
9185 // @encode(class_name)
9186 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
9187 S += '{';
9188 S += OI->getObjCRuntimeNameAsString();
9189 if (Options.ExpandStructures()) {
9190 S += '=';
9192 DeepCollectObjCIvars(OI, true, Ivars);
9193 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
9194 const FieldDecl *Field = Ivars[i];
9195 if (Field->isBitField())
9196 getObjCEncodingForTypeImpl(Field->getType(), S,
9197 ObjCEncOptions().setExpandStructures(),
9198 Field);
9199 else
9200 getObjCEncodingForTypeImpl(Field->getType(), S,
9201 ObjCEncOptions().setExpandStructures(), FD,
9202 NotEncodedT);
9203 }
9204 }
9205 S += '}';
9206 return;
9207 }
9208
9209 case Type::ObjCObjectPointer: {
9210 const auto *OPT = T->castAs<ObjCObjectPointerType>();
9211 if (OPT->isObjCIdType()) {
9212 S += '@';
9213 return;
9214 }
9215
9216 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
9217 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
9218 // Since this is a binary compatibility issue, need to consult with
9219 // runtime folks. Fortunately, this is a *very* obscure construct.
9220 S += '#';
9221 return;
9222 }
9223
9224 if (OPT->isObjCQualifiedIdType()) {
9225 getObjCEncodingForTypeImpl(
9226 getObjCIdType(), S,
9227 Options.keepingOnly(ObjCEncOptions()
9228 .setExpandPointedToStructures()
9229 .setExpandStructures()),
9230 FD);
9231 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
9232 // Note that we do extended encoding of protocol qualifier list
9233 // Only when doing ivar or property encoding.
9234 S += '"';
9235 for (const auto *I : OPT->quals()) {
9236 S += '<';
9237 S += I->getObjCRuntimeNameAsString();
9238 S += '>';
9239 }
9240 S += '"';
9241 }
9242 return;
9243 }
9244
9245 S += '@';
9246 if (OPT->getInterfaceDecl() &&
9247 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
9248 S += '"';
9249 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
9250 for (const auto *I : OPT->quals()) {
9251 S += '<';
9252 S += I->getObjCRuntimeNameAsString();
9253 S += '>';
9254 }
9255 S += '"';
9256 }
9257 return;
9258 }
9259
9260 // gcc just blithely ignores member pointers.
9261 // FIXME: we should do better than that. 'M' is available.
9262 case Type::MemberPointer:
9263 // This matches gcc's encoding, even though technically it is insufficient.
9264 //FIXME. We should do a better job than gcc.
9265 case Type::Vector:
9266 case Type::ExtVector:
9267 // Until we have a coherent encoding of these three types, issue warning.
9268 if (NotEncodedT)
9269 *NotEncodedT = T;
9270 return;
9271
9272 case Type::ConstantMatrix:
9273 if (NotEncodedT)
9274 *NotEncodedT = T;
9275 return;
9276
9277 case Type::BitInt:
9278 if (NotEncodedT)
9279 *NotEncodedT = T;
9280 return;
9281
9282 // We could see an undeduced auto type here during error recovery.
9283 // Just ignore it.
9284 case Type::Auto:
9285 case Type::DeducedTemplateSpecialization:
9286 return;
9287
9288 case Type::HLSLAttributedResource:
9289 llvm_unreachable("unexpected type");
9290
9291 case Type::ArrayParameter:
9292 case Type::Pipe:
9293#define ABSTRACT_TYPE(KIND, BASE)
9294#define TYPE(KIND, BASE)
9295#define DEPENDENT_TYPE(KIND, BASE) \
9296 case Type::KIND:
9297#define NON_CANONICAL_TYPE(KIND, BASE) \
9298 case Type::KIND:
9299#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
9300 case Type::KIND:
9301#include "clang/AST/TypeNodes.inc"
9302 llvm_unreachable("@encode for dependent type!");
9303 }
9304 llvm_unreachable("bad type kind!");
9305}
9306
9307void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
9308 std::string &S,
9309 const FieldDecl *FD,
9310 bool includeVBases,
9311 QualType *NotEncodedT) const {
9312 assert(RDecl && "Expected non-null RecordDecl");
9313 assert(!RDecl->isUnion() && "Should not be called for unions");
9314 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
9315 return;
9316
9317 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
9318 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
9319 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
9320
9321 if (CXXRec) {
9322 for (const auto &BI : CXXRec->bases()) {
9323 if (!BI.isVirtual()) {
9324 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9325 if (base->isEmpty())
9326 continue;
9327 uint64_t offs = toBits(layout.getBaseClassOffset(base));
9328 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9329 std::make_pair(offs, base));
9330 }
9331 }
9332 }
9333
9334 for (FieldDecl *Field : RDecl->fields()) {
9335 if (!Field->isZeroLengthBitField() && Field->isZeroSize(*this))
9336 continue;
9337 uint64_t offs = layout.getFieldOffset(Field->getFieldIndex());
9338 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9339 std::make_pair(offs, Field));
9340 }
9341
9342 if (CXXRec && includeVBases) {
9343 for (const auto &BI : CXXRec->vbases()) {
9344 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9345 if (base->isEmpty())
9346 continue;
9347 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
9348 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
9349 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
9350 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
9351 std::make_pair(offs, base));
9352 }
9353 }
9354
9355 CharUnits size;
9356 if (CXXRec) {
9357 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
9358 } else {
9359 size = layout.getSize();
9360 }
9361
9362#ifndef NDEBUG
9363 uint64_t CurOffs = 0;
9364#endif
9365 std::multimap<uint64_t, NamedDecl *>::iterator
9366 CurLayObj = FieldOrBaseOffsets.begin();
9367
9368 if (CXXRec && CXXRec->isDynamicClass() &&
9369 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
9370 if (FD) {
9371 S += "\"_vptr$";
9372 std::string recname = CXXRec->getNameAsString();
9373 if (recname.empty()) recname = "?";
9374 S += recname;
9375 S += '"';
9376 }
9377 S += "^^?";
9378#ifndef NDEBUG
9379 CurOffs += getTypeSize(VoidPtrTy);
9380#endif
9381 }
9382
9383 if (!RDecl->hasFlexibleArrayMember()) {
9384 // Mark the end of the structure.
9385 uint64_t offs = toBits(size);
9386 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9387 std::make_pair(offs, nullptr));
9388 }
9389
9390 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
9391#ifndef NDEBUG
9392 assert(CurOffs <= CurLayObj->first);
9393 if (CurOffs < CurLayObj->first) {
9394 uint64_t padding = CurLayObj->first - CurOffs;
9395 // FIXME: There doesn't seem to be a way to indicate in the encoding that
9396 // packing/alignment of members is different that normal, in which case
9397 // the encoding will be out-of-sync with the real layout.
9398 // If the runtime switches to just consider the size of types without
9399 // taking into account alignment, we could make padding explicit in the
9400 // encoding (e.g. using arrays of chars). The encoding strings would be
9401 // longer then though.
9402 CurOffs += padding;
9403 }
9404#endif
9405
9406 NamedDecl *dcl = CurLayObj->second;
9407 if (!dcl)
9408 break; // reached end of structure.
9409
9410 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
9411 // We expand the bases without their virtual bases since those are going
9412 // in the initial structure. Note that this differs from gcc which
9413 // expands virtual bases each time one is encountered in the hierarchy,
9414 // making the encoding type bigger than it really is.
9415 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
9416 NotEncodedT);
9417 assert(!base->isEmpty());
9418#ifndef NDEBUG
9419 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
9420#endif
9421 } else {
9422 const auto *field = cast<FieldDecl>(dcl);
9423 if (FD) {
9424 S += '"';
9425 S += field->getNameAsString();
9426 S += '"';
9427 }
9428
9429 if (field->isBitField()) {
9430 EncodeBitField(this, S, field->getType(), field);
9431#ifndef NDEBUG
9432 CurOffs += field->getBitWidthValue();
9433#endif
9434 } else {
9435 QualType qt = field->getType();
9437 getObjCEncodingForTypeImpl(
9438 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
9439 FD, NotEncodedT);
9440#ifndef NDEBUG
9441 CurOffs += getTypeSize(field->getType());
9442#endif
9443 }
9444 }
9445 }
9446}
9447
9449 std::string& S) const {
9450 if (QT & Decl::OBJC_TQ_In)
9451 S += 'n';
9452 if (QT & Decl::OBJC_TQ_Inout)
9453 S += 'N';
9454 if (QT & Decl::OBJC_TQ_Out)
9455 S += 'o';
9456 if (QT & Decl::OBJC_TQ_Bycopy)
9457 S += 'O';
9458 if (QT & Decl::OBJC_TQ_Byref)
9459 S += 'R';
9460 if (QT & Decl::OBJC_TQ_Oneway)
9461 S += 'V';
9462}
9463
9465 if (!ObjCIdDecl) {
9468 ObjCIdDecl = buildImplicitTypedef(T, "id");
9469 }
9470 return ObjCIdDecl;
9471}
9472
9474 if (!ObjCSelDecl) {
9476 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
9477 }
9478 return ObjCSelDecl;
9479}
9480
9482 if (!ObjCClassDecl) {
9485 ObjCClassDecl = buildImplicitTypedef(T, "Class");
9486 }
9487 return ObjCClassDecl;
9488}
9489
9491 if (!ObjCProtocolClassDecl) {
9492 ObjCProtocolClassDecl
9495 &Idents.get("Protocol"),
9496 /*typeParamList=*/nullptr,
9497 /*PrevDecl=*/nullptr,
9498 SourceLocation(), true);
9499 }
9500
9501 return ObjCProtocolClassDecl;
9502}
9503
9504//===----------------------------------------------------------------------===//
9505// __builtin_va_list Construction Functions
9506//===----------------------------------------------------------------------===//
9507
9509 StringRef Name) {
9510 // typedef char* __builtin[_ms]_va_list;
9511 QualType T = Context->getPointerType(Context->CharTy);
9512 return Context->buildImplicitTypedef(T, Name);
9513}
9514
9516 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
9517}
9518
9520 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
9521}
9522
9524 // typedef void* __builtin_va_list;
9525 QualType T = Context->getPointerType(Context->VoidTy);
9526 return Context->buildImplicitTypedef(T, "__builtin_va_list");
9527}
9528
9529static TypedefDecl *
9531 // struct __va_list
9532 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
9533 if (Context->getLangOpts().CPlusPlus) {
9534 // namespace std { struct __va_list {
9535 auto *NS = NamespaceDecl::Create(
9536 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
9537 /*Inline=*/false, SourceLocation(), SourceLocation(),
9538 &Context->Idents.get("std"),
9539 /*PrevDecl=*/nullptr, /*Nested=*/false);
9540 NS->setImplicit();
9541 VaListTagDecl->setDeclContext(NS);
9542 }
9543
9544 VaListTagDecl->startDefinition();
9545
9546 const size_t NumFields = 5;
9547 QualType FieldTypes[NumFields];
9548 const char *FieldNames[NumFields];
9549
9550 // void *__stack;
9551 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
9552 FieldNames[0] = "__stack";
9553
9554 // void *__gr_top;
9555 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
9556 FieldNames[1] = "__gr_top";
9557
9558 // void *__vr_top;
9559 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9560 FieldNames[2] = "__vr_top";
9561
9562 // int __gr_offs;
9563 FieldTypes[3] = Context->IntTy;
9564 FieldNames[3] = "__gr_offs";
9565
9566 // int __vr_offs;
9567 FieldTypes[4] = Context->IntTy;
9568 FieldNames[4] = "__vr_offs";
9569
9570 // Create fields
9571 for (unsigned i = 0; i < NumFields; ++i) {
9572 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9573 VaListTagDecl,
9576 &Context->Idents.get(FieldNames[i]),
9577 FieldTypes[i], /*TInfo=*/nullptr,
9578 /*BitWidth=*/nullptr,
9579 /*Mutable=*/false,
9580 ICIS_NoInit);
9581 Field->setAccess(AS_public);
9582 VaListTagDecl->addDecl(Field);
9583 }
9584 VaListTagDecl->completeDefinition();
9585 Context->VaListTagDecl = VaListTagDecl;
9586 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9587
9588 // } __builtin_va_list;
9589 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
9590}
9591
9593 // typedef struct __va_list_tag {
9594 RecordDecl *VaListTagDecl;
9595
9596 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9597 VaListTagDecl->startDefinition();
9598
9599 const size_t NumFields = 5;
9600 QualType FieldTypes[NumFields];
9601 const char *FieldNames[NumFields];
9602
9603 // unsigned char gpr;
9604 FieldTypes[0] = Context->UnsignedCharTy;
9605 FieldNames[0] = "gpr";
9606
9607 // unsigned char fpr;
9608 FieldTypes[1] = Context->UnsignedCharTy;
9609 FieldNames[1] = "fpr";
9610
9611 // unsigned short reserved;
9612 FieldTypes[2] = Context->UnsignedShortTy;
9613 FieldNames[2] = "reserved";
9614
9615 // void* overflow_arg_area;
9616 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
9617 FieldNames[3] = "overflow_arg_area";
9618
9619 // void* reg_save_area;
9620 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
9621 FieldNames[4] = "reg_save_area";
9622
9623 // Create fields
9624 for (unsigned i = 0; i < NumFields; ++i) {
9625 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
9628 &Context->Idents.get(FieldNames[i]),
9629 FieldTypes[i], /*TInfo=*/nullptr,
9630 /*BitWidth=*/nullptr,
9631 /*Mutable=*/false,
9632 ICIS_NoInit);
9633 Field->setAccess(AS_public);
9634 VaListTagDecl->addDecl(Field);
9635 }
9636 VaListTagDecl->completeDefinition();
9637 Context->VaListTagDecl = VaListTagDecl;
9638 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9639
9640 // } __va_list_tag;
9641 TypedefDecl *VaListTagTypedefDecl =
9642 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
9643
9644 QualType VaListTagTypedefType =
9645 Context->getTypedefType(VaListTagTypedefDecl);
9646
9647 // typedef __va_list_tag __builtin_va_list[1];
9648 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9649 QualType VaListTagArrayType = Context->getConstantArrayType(
9650 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
9651 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9652}
9653
9654static TypedefDecl *
9656 // struct __va_list_tag {
9657 RecordDecl *VaListTagDecl;
9658 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9659 VaListTagDecl->startDefinition();
9660
9661 const size_t NumFields = 4;
9662 QualType FieldTypes[NumFields];
9663 const char *FieldNames[NumFields];
9664
9665 // unsigned gp_offset;
9666 FieldTypes[0] = Context->UnsignedIntTy;
9667 FieldNames[0] = "gp_offset";
9668
9669 // unsigned fp_offset;
9670 FieldTypes[1] = Context->UnsignedIntTy;
9671 FieldNames[1] = "fp_offset";
9672
9673 // void* overflow_arg_area;
9674 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9675 FieldNames[2] = "overflow_arg_area";
9676
9677 // void* reg_save_area;
9678 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
9679 FieldNames[3] = "reg_save_area";
9680
9681 // Create fields
9682 for (unsigned i = 0; i < NumFields; ++i) {
9683 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9684 VaListTagDecl,
9687 &Context->Idents.get(FieldNames[i]),
9688 FieldTypes[i], /*TInfo=*/nullptr,
9689 /*BitWidth=*/nullptr,
9690 /*Mutable=*/false,
9691 ICIS_NoInit);
9692 Field->setAccess(AS_public);
9693 VaListTagDecl->addDecl(Field);
9694 }
9695 VaListTagDecl->completeDefinition();
9696 Context->VaListTagDecl = VaListTagDecl;
9697 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9698
9699 // };
9700
9701 // typedef struct __va_list_tag __builtin_va_list[1];
9702 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9703 QualType VaListTagArrayType = Context->getConstantArrayType(
9704 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
9705 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9706}
9707
9709 // typedef int __builtin_va_list[4];
9710 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
9711 QualType IntArrayType = Context->getConstantArrayType(
9712 Context->IntTy, Size, nullptr, ArraySizeModifier::Normal, 0);
9713 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
9714}
9715
9716static TypedefDecl *
9718 // struct __va_list
9719 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
9720 if (Context->getLangOpts().CPlusPlus) {
9721 // namespace std { struct __va_list {
9722 NamespaceDecl *NS;
9723 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
9724 Context->getTranslationUnitDecl(),
9725 /*Inline=*/false, SourceLocation(),
9726 SourceLocation(), &Context->Idents.get("std"),
9727 /*PrevDecl=*/nullptr, /*Nested=*/false);
9728 NS->setImplicit();
9729 VaListDecl->setDeclContext(NS);
9730 }
9731
9732 VaListDecl->startDefinition();
9733
9734 // void * __ap;
9735 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9736 VaListDecl,
9739 &Context->Idents.get("__ap"),
9740 Context->getPointerType(Context->VoidTy),
9741 /*TInfo=*/nullptr,
9742 /*BitWidth=*/nullptr,
9743 /*Mutable=*/false,
9744 ICIS_NoInit);
9745 Field->setAccess(AS_public);
9746 VaListDecl->addDecl(Field);
9747
9748 // };
9749 VaListDecl->completeDefinition();
9750 Context->VaListTagDecl = VaListDecl;
9751
9752 // typedef struct __va_list __builtin_va_list;
9753 QualType T = Context->getRecordType(VaListDecl);
9754 return Context->buildImplicitTypedef(T, "__builtin_va_list");
9755}
9756
9757static TypedefDecl *
9759 // struct __va_list_tag {
9760 RecordDecl *VaListTagDecl;
9761 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9762 VaListTagDecl->startDefinition();
9763
9764 const size_t NumFields = 4;
9765 QualType FieldTypes[NumFields];
9766 const char *FieldNames[NumFields];
9767
9768 // long __gpr;
9769 FieldTypes[0] = Context->LongTy;
9770 FieldNames[0] = "__gpr";
9771
9772 // long __fpr;
9773 FieldTypes[1] = Context->LongTy;
9774 FieldNames[1] = "__fpr";
9775
9776 // void *__overflow_arg_area;
9777 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9778 FieldNames[2] = "__overflow_arg_area";
9779
9780 // void *__reg_save_area;
9781 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
9782 FieldNames[3] = "__reg_save_area";
9783
9784 // Create fields
9785 for (unsigned i = 0; i < NumFields; ++i) {
9786 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9787 VaListTagDecl,
9790 &Context->Idents.get(FieldNames[i]),
9791 FieldTypes[i], /*TInfo=*/nullptr,
9792 /*BitWidth=*/nullptr,
9793 /*Mutable=*/false,
9794 ICIS_NoInit);
9795 Field->setAccess(AS_public);
9796 VaListTagDecl->addDecl(Field);
9797 }
9798 VaListTagDecl->completeDefinition();
9799 Context->VaListTagDecl = VaListTagDecl;
9800 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9801
9802 // };
9803
9804 // typedef __va_list_tag __builtin_va_list[1];
9805 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9806 QualType VaListTagArrayType = Context->getConstantArrayType(
9807 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
9808
9809 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9810}
9811
9813 // typedef struct __va_list_tag {
9814 RecordDecl *VaListTagDecl;
9815 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9816 VaListTagDecl->startDefinition();
9817
9818 const size_t NumFields = 3;
9819 QualType FieldTypes[NumFields];
9820 const char *FieldNames[NumFields];
9821
9822 // void *CurrentSavedRegisterArea;
9823 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
9824 FieldNames[0] = "__current_saved_reg_area_pointer";
9825
9826 // void *SavedRegAreaEnd;
9827 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
9828 FieldNames[1] = "__saved_reg_area_end_pointer";
9829
9830 // void *OverflowArea;
9831 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9832 FieldNames[2] = "__overflow_area_pointer";
9833
9834 // Create fields
9835 for (unsigned i = 0; i < NumFields; ++i) {
9837 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
9838 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
9839 /*TInfo=*/nullptr,
9840 /*BitWidth=*/nullptr,
9841 /*Mutable=*/false, ICIS_NoInit);
9842 Field->setAccess(AS_public);
9843 VaListTagDecl->addDecl(Field);
9844 }
9845 VaListTagDecl->completeDefinition();
9846 Context->VaListTagDecl = VaListTagDecl;
9847 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9848
9849 // } __va_list_tag;
9850 TypedefDecl *VaListTagTypedefDecl =
9851 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
9852
9853 QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl);
9854
9855 // typedef __va_list_tag __builtin_va_list[1];
9856 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9857 QualType VaListTagArrayType = Context->getConstantArrayType(
9858 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
9859
9860 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9861}
9862
9863static TypedefDecl *
9865 // typedef struct __va_list_tag {
9866 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9867
9868 VaListTagDecl->startDefinition();
9869
9870 // int* __va_stk;
9871 // int* __va_reg;
9872 // int __va_ndx;
9873 constexpr size_t NumFields = 3;
9874 QualType FieldTypes[NumFields] = {Context->getPointerType(Context->IntTy),
9875 Context->getPointerType(Context->IntTy),
9876 Context->IntTy};
9877 const char *FieldNames[NumFields] = {"__va_stk", "__va_reg", "__va_ndx"};
9878
9879 // Create fields
9880 for (unsigned i = 0; i < NumFields; ++i) {
9882 *Context, VaListTagDecl, SourceLocation(), SourceLocation(),
9883 &Context->Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
9884 /*BitWidth=*/nullptr,
9885 /*Mutable=*/false, ICIS_NoInit);
9886 Field->setAccess(AS_public);
9887 VaListTagDecl->addDecl(Field);
9888 }
9889 VaListTagDecl->completeDefinition();
9890 Context->VaListTagDecl = VaListTagDecl;
9891 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9892
9893 // } __va_list_tag;
9894 TypedefDecl *VaListTagTypedefDecl =
9895 Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
9896
9897 return VaListTagTypedefDecl;
9898}
9899
9902 switch (Kind) {
9904 return CreateCharPtrBuiltinVaListDecl(Context);
9906 return CreateVoidPtrBuiltinVaListDecl(Context);
9908 return CreateAArch64ABIBuiltinVaListDecl(Context);
9910 return CreatePowerABIBuiltinVaListDecl(Context);
9912 return CreateX86_64ABIBuiltinVaListDecl(Context);
9914 return CreatePNaClABIBuiltinVaListDecl(Context);
9916 return CreateAAPCSABIBuiltinVaListDecl(Context);
9918 return CreateSystemZBuiltinVaListDecl(Context);
9920 return CreateHexagonBuiltinVaListDecl(Context);
9922 return CreateXtensaABIBuiltinVaListDecl(Context);
9923 }
9924
9925 llvm_unreachable("Unhandled __builtin_va_list type kind");
9926}
9927
9929 if (!BuiltinVaListDecl) {
9930 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
9931 assert(BuiltinVaListDecl->isImplicit());
9932 }
9933
9934 return BuiltinVaListDecl;
9935}
9936
9938 // Force the creation of VaListTagDecl by building the __builtin_va_list
9939 // declaration.
9940 if (!VaListTagDecl)
9941 (void)getBuiltinVaListDecl();
9942
9943 return VaListTagDecl;
9944}
9945
9947 if (!BuiltinMSVaListDecl)
9948 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
9949
9950 return BuiltinMSVaListDecl;
9951}
9952
9954 // Allow redecl custom type checking builtin for HLSL.
9955 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
9957 return true;
9959}
9960
9962 assert(ObjCConstantStringType.isNull() &&
9963 "'NSConstantString' type already set!");
9964
9965 ObjCConstantStringType = getObjCInterfaceType(Decl);
9966}
9967
9968/// Retrieve the template name that corresponds to a non-empty
9969/// lookup.
9972 UnresolvedSetIterator End) const {
9973 unsigned size = End - Begin;
9974 assert(size > 1 && "set is not overloaded!");
9975
9976 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
9977 size * sizeof(FunctionTemplateDecl*));
9978 auto *OT = new (memory) OverloadedTemplateStorage(size);
9979
9980 NamedDecl **Storage = OT->getStorage();
9981 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
9982 NamedDecl *D = *I;
9983 assert(isa<FunctionTemplateDecl>(D) ||
9984 isa<UnresolvedUsingValueDecl>(D) ||
9985 (isa<UsingShadowDecl>(D) &&
9986 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
9987 *Storage++ = D;
9988 }
9989
9990 return TemplateName(OT);
9991}
9992
9993/// Retrieve a template name representing an unqualified-id that has been
9994/// assumed to name a template for ADL purposes.
9996 auto *OT = new (*this) AssumedTemplateStorage(Name);
9997 return TemplateName(OT);
9998}
9999
10000/// Retrieve the template name that represents a qualified
10001/// template name such as \c std::vector.
10003 bool TemplateKeyword,
10004 TemplateName Template) const {
10005 assert(Template.getKind() == TemplateName::Template ||
10006 Template.getKind() == TemplateName::UsingTemplate);
10007
10008 // FIXME: Canonicalization?
10009 llvm::FoldingSetNodeID ID;
10010 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
10011
10012 void *InsertPos = nullptr;
10014 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
10015 if (!QTN) {
10016 QTN = new (*this, alignof(QualifiedTemplateName))
10017 QualifiedTemplateName(NNS, TemplateKeyword, Template);
10018 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
10019 }
10020
10021 return TemplateName(QTN);
10022}
10023
10024/// Retrieve the template name that represents a dependent
10025/// template name such as \c MetaFun::template apply.
10028 const IdentifierInfo *Name) const {
10029 assert((!NNS || NNS->isDependent()) &&
10030 "Nested name specifier must be dependent");
10031
10032 llvm::FoldingSetNodeID ID;
10033 DependentTemplateName::Profile(ID, NNS, Name);
10034
10035 void *InsertPos = nullptr;
10037 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
10038
10039 if (QTN)
10040 return TemplateName(QTN);
10041
10043 if (CanonNNS == NNS) {
10044 QTN = new (*this, alignof(DependentTemplateName))
10045 DependentTemplateName(NNS, Name);
10046 } else {
10047 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
10048 QTN = new (*this, alignof(DependentTemplateName))
10049 DependentTemplateName(NNS, Name, Canon);
10050 DependentTemplateName *CheckQTN =
10051 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
10052 assert(!CheckQTN && "Dependent type name canonicalization broken");
10053 (void)CheckQTN;
10054 }
10055
10056 DependentTemplateNames.InsertNode(QTN, InsertPos);
10057 return TemplateName(QTN);
10058}
10059
10060/// Retrieve the template name that represents a dependent
10061/// template name such as \c MetaFun::template operator+.
10064 OverloadedOperatorKind Operator) const {
10065 assert((!NNS || NNS->isDependent()) &&
10066 "Nested name specifier must be dependent");
10067
10068 llvm::FoldingSetNodeID ID;
10069 DependentTemplateName::Profile(ID, NNS, Operator);
10070
10071 void *InsertPos = nullptr;
10073 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
10074
10075 if (QTN)
10076 return TemplateName(QTN);
10077
10079 if (CanonNNS == NNS) {
10080 QTN = new (*this, alignof(DependentTemplateName))
10081 DependentTemplateName(NNS, Operator);
10082 } else {
10083 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
10084 QTN = new (*this, alignof(DependentTemplateName))
10085 DependentTemplateName(NNS, Operator, Canon);
10086
10087 DependentTemplateName *CheckQTN
10088 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
10089 assert(!CheckQTN && "Dependent template name canonicalization broken");
10090 (void)CheckQTN;
10091 }
10092
10093 DependentTemplateNames.InsertNode(QTN, InsertPos);
10094 return TemplateName(QTN);
10095}
10096
10098 TemplateName Replacement, Decl *AssociatedDecl, unsigned Index,
10099 std::optional<unsigned> PackIndex) const {
10100 llvm::FoldingSetNodeID ID;
10101 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
10102 Index, PackIndex);
10103
10104 void *insertPos = nullptr;
10106 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
10107
10108 if (!subst) {
10109 subst = new (*this) SubstTemplateTemplateParmStorage(
10110 Replacement, AssociatedDecl, Index, PackIndex);
10111 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
10112 }
10113
10114 return TemplateName(subst);
10115}
10116
10119 Decl *AssociatedDecl,
10120 unsigned Index, bool Final) const {
10121 auto &Self = const_cast<ASTContext &>(*this);
10122 llvm::FoldingSetNodeID ID;
10124 AssociatedDecl, Index, Final);
10125
10126 void *InsertPos = nullptr;
10128 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
10129
10130 if (!Subst) {
10131 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
10132 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
10133 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
10134 }
10135
10136 return TemplateName(Subst);
10137}
10138
10139/// Retrieve the template name that represents a template name
10140/// deduced from a specialization.
10143 DefaultArguments DefaultArgs) const {
10144 if (!DefaultArgs)
10145 return Underlying;
10146
10147 llvm::FoldingSetNodeID ID;
10148 DeducedTemplateStorage::Profile(ID, *this, Underlying, DefaultArgs);
10149
10150 void *InsertPos = nullptr;
10152 DeducedTemplates.FindNodeOrInsertPos(ID, InsertPos);
10153 if (!DTS) {
10154 void *Mem = Allocate(sizeof(DeducedTemplateStorage) +
10155 sizeof(TemplateArgument) * DefaultArgs.Args.size(),
10156 alignof(DeducedTemplateStorage));
10157 DTS = new (Mem) DeducedTemplateStorage(Underlying, DefaultArgs);
10158 DeducedTemplates.InsertNode(DTS, InsertPos);
10159 }
10160 return TemplateName(DTS);
10161}
10162
10163/// getFromTargetType - Given one of the integer types provided by
10164/// TargetInfo, produce the corresponding type. The unsigned @p Type
10165/// is actually a value of type @c TargetInfo::IntType.
10166CanQualType ASTContext::getFromTargetType(unsigned Type) const {
10167 switch (Type) {
10168 case TargetInfo::NoInt: return {};
10171 case TargetInfo::SignedShort: return ShortTy;
10173 case TargetInfo::SignedInt: return IntTy;
10175 case TargetInfo::SignedLong: return LongTy;
10179 }
10180
10181 llvm_unreachable("Unhandled TargetInfo::IntType value");
10182}
10183
10184//===----------------------------------------------------------------------===//
10185// Type Predicates.
10186//===----------------------------------------------------------------------===//
10187
10188/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
10189/// garbage collection attribute.
10190///
10192 if (getLangOpts().getGC() == LangOptions::NonGC)
10193 return Qualifiers::GCNone;
10194
10195 assert(getLangOpts().ObjC);
10196 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
10197
10198 // Default behaviour under objective-C's gc is for ObjC pointers
10199 // (or pointers to them) be treated as though they were declared
10200 // as __strong.
10201 if (GCAttrs == Qualifiers::GCNone) {
10203 return Qualifiers::Strong;
10204 else if (Ty->isPointerType())
10206 } else {
10207 // It's not valid to set GC attributes on anything that isn't a
10208 // pointer.
10209#ifndef NDEBUG
10211 while (const auto *AT = dyn_cast<ArrayType>(CT))
10212 CT = AT->getElementType();
10213 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
10214#endif
10215 }
10216 return GCAttrs;
10217}
10218
10219//===----------------------------------------------------------------------===//
10220// Type Compatibility Testing
10221//===----------------------------------------------------------------------===//
10222
10223/// areCompatVectorTypes - Return true if the two specified vector types are
10224/// compatible.
10225static bool areCompatVectorTypes(const VectorType *LHS,
10226 const VectorType *RHS) {
10227 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10228 return LHS->getElementType() == RHS->getElementType() &&
10229 LHS->getNumElements() == RHS->getNumElements();
10230}
10231
10232/// areCompatMatrixTypes - Return true if the two specified matrix types are
10233/// compatible.
10235 const ConstantMatrixType *RHS) {
10236 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10237 return LHS->getElementType() == RHS->getElementType() &&
10238 LHS->getNumRows() == RHS->getNumRows() &&
10239 LHS->getNumColumns() == RHS->getNumColumns();
10240}
10241
10243 QualType SecondVec) {
10244 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
10245 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
10246
10247 if (hasSameUnqualifiedType(FirstVec, SecondVec))
10248 return true;
10249
10250 // Treat Neon vector types and most AltiVec vector types as if they are the
10251 // equivalent GCC vector types.
10252 const auto *First = FirstVec->castAs<VectorType>();
10253 const auto *Second = SecondVec->castAs<VectorType>();
10254 if (First->getNumElements() == Second->getNumElements() &&
10255 hasSameType(First->getElementType(), Second->getElementType()) &&
10256 First->getVectorKind() != VectorKind::AltiVecPixel &&
10257 First->getVectorKind() != VectorKind::AltiVecBool &&
10260 First->getVectorKind() != VectorKind::SveFixedLengthData &&
10261 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10264 First->getVectorKind() != VectorKind::RVVFixedLengthData &&
10266 First->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10268 First->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10270 First->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10272 First->getVectorKind() != VectorKind::RVVFixedLengthMask_4 &&
10274 return true;
10275
10276 return false;
10277}
10278
10279/// getSVETypeSize - Return SVE vector or predicate register size.
10280static uint64_t getSVETypeSize(ASTContext &Context, const BuiltinType *Ty) {
10281 assert(Ty->isSveVLSBuiltinType() && "Invalid SVE Type");
10282 if (Ty->getKind() == BuiltinType::SveBool ||
10283 Ty->getKind() == BuiltinType::SveCount)
10284 return (Context.getLangOpts().VScaleMin * 128) / Context.getCharWidth();
10285 return Context.getLangOpts().VScaleMin * 128;
10286}
10287
10289 QualType SecondType) {
10290 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10291 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10292 if (const auto *VT = SecondType->getAs<VectorType>()) {
10293 // Predicates have the same representation as uint8 so we also have to
10294 // check the kind to make these types incompatible.
10295 if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
10296 return BT->getKind() == BuiltinType::SveBool;
10297 else if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
10298 return VT->getElementType().getCanonicalType() ==
10299 FirstType->getSveEltType(*this);
10300 else if (VT->getVectorKind() == VectorKind::Generic)
10301 return getTypeSize(SecondType) == getSVETypeSize(*this, BT) &&
10302 hasSameType(VT->getElementType(),
10303 getBuiltinVectorTypeInfo(BT).ElementType);
10304 }
10305 }
10306 return false;
10307 };
10308
10309 return IsValidCast(FirstType, SecondType) ||
10310 IsValidCast(SecondType, FirstType);
10311}
10312
10314 QualType SecondType) {
10315 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10316 const auto *BT = FirstType->getAs<BuiltinType>();
10317 if (!BT)
10318 return false;
10319
10320 const auto *VecTy = SecondType->getAs<VectorType>();
10321 if (VecTy && (VecTy->getVectorKind() == VectorKind::SveFixedLengthData ||
10322 VecTy->getVectorKind() == VectorKind::Generic)) {
10324 getLangOpts().getLaxVectorConversions();
10325
10326 // Can not convert between sve predicates and sve vectors because of
10327 // different size.
10328 if (BT->getKind() == BuiltinType::SveBool &&
10329 VecTy->getVectorKind() == VectorKind::SveFixedLengthData)
10330 return false;
10331
10332 // If __ARM_FEATURE_SVE_BITS != N do not allow GNU vector lax conversion.
10333 // "Whenever __ARM_FEATURE_SVE_BITS==N, GNUT implicitly
10334 // converts to VLAT and VLAT implicitly converts to GNUT."
10335 // ACLE Spec Version 00bet6, 3.7.3.2. Behavior common to vectors and
10336 // predicates.
10337 if (VecTy->getVectorKind() == VectorKind::Generic &&
10338 getTypeSize(SecondType) != getSVETypeSize(*this, BT))
10339 return false;
10340
10341 // If -flax-vector-conversions=all is specified, the types are
10342 // certainly compatible.
10344 return true;
10345
10346 // If -flax-vector-conversions=integer is specified, the types are
10347 // compatible if the elements are integer types.
10349 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10350 FirstType->getSveEltType(*this)->isIntegerType();
10351 }
10352
10353 return false;
10354 };
10355
10356 return IsLaxCompatible(FirstType, SecondType) ||
10357 IsLaxCompatible(SecondType, FirstType);
10358}
10359
10360/// getRVVTypeSize - Return RVV vector register size.
10361static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
10362 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
10363 auto VScale = Context.getTargetInfo().getVScaleRange(Context.getLangOpts());
10364 if (!VScale)
10365 return 0;
10366
10368
10369 uint64_t EltSize = Context.getTypeSize(Info.ElementType);
10370 if (Info.ElementType == Context.BoolTy)
10371 EltSize = 1;
10372
10373 uint64_t MinElts = Info.EC.getKnownMinValue();
10374 return VScale->first * MinElts * EltSize;
10375}
10376
10378 QualType SecondType) {
10379 assert(
10380 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10381 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10382 "Expected RVV builtin type and vector type!");
10383
10384 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10385 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10386 if (const auto *VT = SecondType->getAs<VectorType>()) {
10387 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10389 return FirstType->isRVVVLSBuiltinType() &&
10390 Info.ElementType == BoolTy &&
10391 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)));
10392 }
10393 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1) {
10395 return FirstType->isRVVVLSBuiltinType() &&
10396 Info.ElementType == BoolTy &&
10397 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT) * 8));
10398 }
10399 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2) {
10401 return FirstType->isRVVVLSBuiltinType() &&
10402 Info.ElementType == BoolTy &&
10403 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 4);
10404 }
10405 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10407 return FirstType->isRVVVLSBuiltinType() &&
10408 Info.ElementType == BoolTy &&
10409 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 2);
10410 }
10411 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
10412 VT->getVectorKind() == VectorKind::Generic)
10413 return FirstType->isRVVVLSBuiltinType() &&
10414 getTypeSize(SecondType) == getRVVTypeSize(*this, BT) &&
10415 hasSameType(VT->getElementType(),
10416 getBuiltinVectorTypeInfo(BT).ElementType);
10417 }
10418 }
10419 return false;
10420 };
10421
10422 return IsValidCast(FirstType, SecondType) ||
10423 IsValidCast(SecondType, FirstType);
10424}
10425
10427 QualType SecondType) {
10428 assert(
10429 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10430 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10431 "Expected RVV builtin type and vector type!");
10432
10433 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10434 const auto *BT = FirstType->getAs<BuiltinType>();
10435 if (!BT)
10436 return false;
10437
10438 if (!BT->isRVVVLSBuiltinType())
10439 return false;
10440
10441 const auto *VecTy = SecondType->getAs<VectorType>();
10442 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
10444 getLangOpts().getLaxVectorConversions();
10445
10446 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
10447 if (getTypeSize(SecondType) != getRVVTypeSize(*this, BT))
10448 return false;
10449
10450 // If -flax-vector-conversions=all is specified, the types are
10451 // certainly compatible.
10453 return true;
10454
10455 // If -flax-vector-conversions=integer is specified, the types are
10456 // compatible if the elements are integer types.
10458 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10459 FirstType->getRVVEltType(*this)->isIntegerType();
10460 }
10461
10462 return false;
10463 };
10464
10465 return IsLaxCompatible(FirstType, SecondType) ||
10466 IsLaxCompatible(SecondType, FirstType);
10467}
10468
10470 while (true) {
10471 // __strong id
10472 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
10473 if (Attr->getAttrKind() == attr::ObjCOwnership)
10474 return true;
10475
10476 Ty = Attr->getModifiedType();
10477
10478 // X *__strong (...)
10479 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
10480 Ty = Paren->getInnerType();
10481
10482 // We do not want to look through typedefs, typeof(expr),
10483 // typeof(type), or any other way that the type is somehow
10484 // abstracted.
10485 } else {
10486 return false;
10487 }
10488 }
10489}
10490
10491//===----------------------------------------------------------------------===//
10492// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
10493//===----------------------------------------------------------------------===//
10494
10495/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
10496/// inheritance hierarchy of 'rProto'.
10497bool
10499 ObjCProtocolDecl *rProto) const {
10500 if (declaresSameEntity(lProto, rProto))
10501 return true;
10502 for (auto *PI : rProto->protocols())
10503 if (ProtocolCompatibleWithProtocol(lProto, PI))
10504 return true;
10505 return false;
10506}
10507
10508/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
10509/// Class<pr1, ...>.
10511 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
10512 for (auto *lhsProto : lhs->quals()) {
10513 bool match = false;
10514 for (auto *rhsProto : rhs->quals()) {
10515 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
10516 match = true;
10517 break;
10518 }
10519 }
10520 if (!match)
10521 return false;
10522 }
10523 return true;
10524}
10525
10526/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
10527/// ObjCQualifiedIDType.
10529 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
10530 bool compare) {
10531 // Allow id<P..> and an 'id' in all cases.
10532 if (lhs->isObjCIdType() || rhs->isObjCIdType())
10533 return true;
10534
10535 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
10536 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
10538 return false;
10539
10540 if (lhs->isObjCQualifiedIdType()) {
10541 if (rhs->qual_empty()) {
10542 // If the RHS is a unqualified interface pointer "NSString*",
10543 // make sure we check the class hierarchy.
10544 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10545 for (auto *I : lhs->quals()) {
10546 // when comparing an id<P> on lhs with a static type on rhs,
10547 // see if static class implements all of id's protocols, directly or
10548 // through its super class and categories.
10549 if (!rhsID->ClassImplementsProtocol(I, true))
10550 return false;
10551 }
10552 }
10553 // If there are no qualifiers and no interface, we have an 'id'.
10554 return true;
10555 }
10556 // Both the right and left sides have qualifiers.
10557 for (auto *lhsProto : lhs->quals()) {
10558 bool match = false;
10559
10560 // when comparing an id<P> on lhs with a static type on rhs,
10561 // see if static class implements all of id's protocols, directly or
10562 // through its super class and categories.
10563 for (auto *rhsProto : rhs->quals()) {
10564 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10565 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10566 match = true;
10567 break;
10568 }
10569 }
10570 // If the RHS is a qualified interface pointer "NSString<P>*",
10571 // make sure we check the class hierarchy.
10572 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10573 for (auto *I : lhs->quals()) {
10574 // when comparing an id<P> on lhs with a static type on rhs,
10575 // see if static class implements all of id's protocols, directly or
10576 // through its super class and categories.
10577 if (rhsID->ClassImplementsProtocol(I, true)) {
10578 match = true;
10579 break;
10580 }
10581 }
10582 }
10583 if (!match)
10584 return false;
10585 }
10586
10587 return true;
10588 }
10589
10590 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
10591
10592 if (lhs->getInterfaceType()) {
10593 // If both the right and left sides have qualifiers.
10594 for (auto *lhsProto : lhs->quals()) {
10595 bool match = false;
10596
10597 // when comparing an id<P> on rhs with a static type on lhs,
10598 // see if static class implements all of id's protocols, directly or
10599 // through its super class and categories.
10600 // First, lhs protocols in the qualifier list must be found, direct
10601 // or indirect in rhs's qualifier list or it is a mismatch.
10602 for (auto *rhsProto : rhs->quals()) {
10603 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10604 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10605 match = true;
10606 break;
10607 }
10608 }
10609 if (!match)
10610 return false;
10611 }
10612
10613 // Static class's protocols, or its super class or category protocols
10614 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
10615 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
10616 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
10617 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
10618 // This is rather dubious but matches gcc's behavior. If lhs has
10619 // no type qualifier and its class has no static protocol(s)
10620 // assume that it is mismatch.
10621 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
10622 return false;
10623 for (auto *lhsProto : LHSInheritedProtocols) {
10624 bool match = false;
10625 for (auto *rhsProto : rhs->quals()) {
10626 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10627 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10628 match = true;
10629 break;
10630 }
10631 }
10632 if (!match)
10633 return false;
10634 }
10635 }
10636 return true;
10637 }
10638 return false;
10639}
10640
10641/// canAssignObjCInterfaces - Return true if the two interface types are
10642/// compatible for assignment from RHS to LHS. This handles validation of any
10643/// protocol qualifiers on the LHS or RHS.
10645 const ObjCObjectPointerType *RHSOPT) {
10646 const ObjCObjectType* LHS = LHSOPT->getObjectType();
10647 const ObjCObjectType* RHS = RHSOPT->getObjectType();
10648
10649 // If either type represents the built-in 'id' type, return true.
10650 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
10651 return true;
10652
10653 // Function object that propagates a successful result or handles
10654 // __kindof types.
10655 auto finish = [&](bool succeeded) -> bool {
10656 if (succeeded)
10657 return true;
10658
10659 if (!RHS->isKindOfType())
10660 return false;
10661
10662 // Strip off __kindof and protocol qualifiers, then check whether
10663 // we can assign the other way.
10665 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
10666 };
10667
10668 // Casts from or to id<P> are allowed when the other side has compatible
10669 // protocols.
10670 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
10671 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
10672 }
10673
10674 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
10675 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
10676 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
10677 }
10678
10679 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
10680 if (LHS->isObjCClass() && RHS->isObjCClass()) {
10681 return true;
10682 }
10683
10684 // If we have 2 user-defined types, fall into that path.
10685 if (LHS->getInterface() && RHS->getInterface()) {
10686 return finish(canAssignObjCInterfaces(LHS, RHS));
10687 }
10688
10689 return false;
10690}
10691
10692/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
10693/// for providing type-safety for objective-c pointers used to pass/return
10694/// arguments in block literals. When passed as arguments, passing 'A*' where
10695/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
10696/// not OK. For the return type, the opposite is not OK.
10698 const ObjCObjectPointerType *LHSOPT,
10699 const ObjCObjectPointerType *RHSOPT,
10700 bool BlockReturnType) {
10701
10702 // Function object that propagates a successful result or handles
10703 // __kindof types.
10704 auto finish = [&](bool succeeded) -> bool {
10705 if (succeeded)
10706 return true;
10707
10708 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
10709 if (!Expected->isKindOfType())
10710 return false;
10711
10712 // Strip off __kindof and protocol qualifiers, then check whether
10713 // we can assign the other way.
10715 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
10716 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
10717 BlockReturnType);
10718 };
10719
10720 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
10721 return true;
10722
10723 if (LHSOPT->isObjCBuiltinType()) {
10724 return finish(RHSOPT->isObjCBuiltinType() ||
10725 RHSOPT->isObjCQualifiedIdType());
10726 }
10727
10728 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
10729 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
10730 // Use for block parameters previous type checking for compatibility.
10731 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
10732 // Or corrected type checking as in non-compat mode.
10733 (!BlockReturnType &&
10734 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
10735 else
10737 (BlockReturnType ? LHSOPT : RHSOPT),
10738 (BlockReturnType ? RHSOPT : LHSOPT), false));
10739 }
10740
10741 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
10742 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
10743 if (LHS && RHS) { // We have 2 user-defined types.
10744 if (LHS != RHS) {
10745 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
10746 return finish(BlockReturnType);
10747 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
10748 return finish(!BlockReturnType);
10749 }
10750 else
10751 return true;
10752 }
10753 return false;
10754}
10755
10756/// Comparison routine for Objective-C protocols to be used with
10757/// llvm::array_pod_sort.
10759 ObjCProtocolDecl * const *rhs) {
10760 return (*lhs)->getName().compare((*rhs)->getName());
10761}
10762
10763/// getIntersectionOfProtocols - This routine finds the intersection of set
10764/// of protocols inherited from two distinct objective-c pointer objects with
10765/// the given common base.
10766/// It is used to build composite qualifier list of the composite type of
10767/// the conditional expression involving two objective-c pointer objects.
10768static
10770 const ObjCInterfaceDecl *CommonBase,
10771 const ObjCObjectPointerType *LHSOPT,
10772 const ObjCObjectPointerType *RHSOPT,
10773 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
10774
10775 const ObjCObjectType* LHS = LHSOPT->getObjectType();
10776 const ObjCObjectType* RHS = RHSOPT->getObjectType();
10777 assert(LHS->getInterface() && "LHS must have an interface base");
10778 assert(RHS->getInterface() && "RHS must have an interface base");
10779
10780 // Add all of the protocols for the LHS.
10782
10783 // Start with the protocol qualifiers.
10784 for (auto *proto : LHS->quals()) {
10785 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
10786 }
10787
10788 // Also add the protocols associated with the LHS interface.
10789 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
10790
10791 // Add all of the protocols for the RHS.
10793
10794 // Start with the protocol qualifiers.
10795 for (auto *proto : RHS->quals()) {
10796 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
10797 }
10798
10799 // Also add the protocols associated with the RHS interface.
10800 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
10801
10802 // Compute the intersection of the collected protocol sets.
10803 for (auto *proto : LHSProtocolSet) {
10804 if (RHSProtocolSet.count(proto))
10805 IntersectionSet.push_back(proto);
10806 }
10807
10808 // Compute the set of protocols that is implied by either the common type or
10809 // the protocols within the intersection.
10811 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
10812
10813 // Remove any implied protocols from the list of inherited protocols.
10814 if (!ImpliedProtocols.empty()) {
10815 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
10816 return ImpliedProtocols.contains(proto);
10817 });
10818 }
10819
10820 // Sort the remaining protocols by name.
10821 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
10823}
10824
10825/// Determine whether the first type is a subtype of the second.
10827 QualType rhs) {
10828 // Common case: two object pointers.
10829 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
10830 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
10831 if (lhsOPT && rhsOPT)
10832 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
10833
10834 // Two block pointers.
10835 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
10836 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
10837 if (lhsBlock && rhsBlock)
10838 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
10839
10840 // If either is an unqualified 'id' and the other is a block, it's
10841 // acceptable.
10842 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
10843 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
10844 return true;
10845
10846 return false;
10847}
10848
10849// Check that the given Objective-C type argument lists are equivalent.
10851 const ObjCInterfaceDecl *iface,
10852 ArrayRef<QualType> lhsArgs,
10853 ArrayRef<QualType> rhsArgs,
10854 bool stripKindOf) {
10855 if (lhsArgs.size() != rhsArgs.size())
10856 return false;
10857
10858 ObjCTypeParamList *typeParams = iface->getTypeParamList();
10859 if (!typeParams)
10860 return false;
10861
10862 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
10863 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
10864 continue;
10865
10866 switch (typeParams->begin()[i]->getVariance()) {
10868 if (!stripKindOf ||
10869 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
10870 rhsArgs[i].stripObjCKindOfType(ctx))) {
10871 return false;
10872 }
10873 break;
10874
10876 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
10877 return false;
10878 break;
10879
10881 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
10882 return false;
10883 break;
10884 }
10885 }
10886
10887 return true;
10888}
10889
10891 const ObjCObjectPointerType *Lptr,
10892 const ObjCObjectPointerType *Rptr) {
10893 const ObjCObjectType *LHS = Lptr->getObjectType();
10894 const ObjCObjectType *RHS = Rptr->getObjectType();
10895 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
10896 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
10897
10898 if (!LDecl || !RDecl)
10899 return {};
10900
10901 // When either LHS or RHS is a kindof type, we should return a kindof type.
10902 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
10903 // kindof(A).
10904 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
10905
10906 // Follow the left-hand side up the class hierarchy until we either hit a
10907 // root or find the RHS. Record the ancestors in case we don't find it.
10908 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
10909 LHSAncestors;
10910 while (true) {
10911 // Record this ancestor. We'll need this if the common type isn't in the
10912 // path from the LHS to the root.
10913 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
10914
10915 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
10916 // Get the type arguments.
10917 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
10918 bool anyChanges = false;
10919 if (LHS->isSpecialized() && RHS->isSpecialized()) {
10920 // Both have type arguments, compare them.
10921 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
10922 LHS->getTypeArgs(), RHS->getTypeArgs(),
10923 /*stripKindOf=*/true))
10924 return {};
10925 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
10926 // If only one has type arguments, the result will not have type
10927 // arguments.
10928 LHSTypeArgs = {};
10929 anyChanges = true;
10930 }
10931
10932 // Compute the intersection of protocols.
10934 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
10935 Protocols);
10936 if (!Protocols.empty())
10937 anyChanges = true;
10938
10939 // If anything in the LHS will have changed, build a new result type.
10940 // If we need to return a kindof type but LHS is not a kindof type, we
10941 // build a new result type.
10942 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
10944 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
10945 anyKindOf || LHS->isKindOfType());
10947 }
10948
10949 return getObjCObjectPointerType(QualType(LHS, 0));
10950 }
10951
10952 // Find the superclass.
10953 QualType LHSSuperType = LHS->getSuperClassType();
10954 if (LHSSuperType.isNull())
10955 break;
10956
10957 LHS = LHSSuperType->castAs<ObjCObjectType>();
10958 }
10959
10960 // We didn't find anything by following the LHS to its root; now check
10961 // the RHS against the cached set of ancestors.
10962 while (true) {
10963 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
10964 if (KnownLHS != LHSAncestors.end()) {
10965 LHS = KnownLHS->second;
10966
10967 // Get the type arguments.
10968 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
10969 bool anyChanges = false;
10970 if (LHS->isSpecialized() && RHS->isSpecialized()) {
10971 // Both have type arguments, compare them.
10972 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
10973 LHS->getTypeArgs(), RHS->getTypeArgs(),
10974 /*stripKindOf=*/true))
10975 return {};
10976 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
10977 // If only one has type arguments, the result will not have type
10978 // arguments.
10979 RHSTypeArgs = {};
10980 anyChanges = true;
10981 }
10982
10983 // Compute the intersection of protocols.
10985 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
10986 Protocols);
10987 if (!Protocols.empty())
10988 anyChanges = true;
10989
10990 // If we need to return a kindof type but RHS is not a kindof type, we
10991 // build a new result type.
10992 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
10994 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
10995 anyKindOf || RHS->isKindOfType());
10997 }
10998
10999 return getObjCObjectPointerType(QualType(RHS, 0));
11000 }
11001
11002 // Find the superclass of the RHS.
11003 QualType RHSSuperType = RHS->getSuperClassType();
11004 if (RHSSuperType.isNull())
11005 break;
11006
11007 RHS = RHSSuperType->castAs<ObjCObjectType>();
11008 }
11009
11010 return {};
11011}
11012
11014 const ObjCObjectType *RHS) {
11015 assert(LHS->getInterface() && "LHS is not an interface type");
11016 assert(RHS->getInterface() && "RHS is not an interface type");
11017
11018 // Verify that the base decls are compatible: the RHS must be a subclass of
11019 // the LHS.
11020 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
11021 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
11022 if (!IsSuperClass)
11023 return false;
11024
11025 // If the LHS has protocol qualifiers, determine whether all of them are
11026 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
11027 // LHS).
11028 if (LHS->getNumProtocols() > 0) {
11029 // OK if conversion of LHS to SuperClass results in narrowing of types
11030 // ; i.e., SuperClass may implement at least one of the protocols
11031 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
11032 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
11033 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
11034 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
11035 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
11036 // qualifiers.
11037 for (auto *RHSPI : RHS->quals())
11038 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
11039 // If there is no protocols associated with RHS, it is not a match.
11040 if (SuperClassInheritedProtocols.empty())
11041 return false;
11042
11043 for (const auto *LHSProto : LHS->quals()) {
11044 bool SuperImplementsProtocol = false;
11045 for (auto *SuperClassProto : SuperClassInheritedProtocols)
11046 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
11047 SuperImplementsProtocol = true;
11048 break;
11049 }
11050 if (!SuperImplementsProtocol)
11051 return false;
11052 }
11053 }
11054
11055 // If the LHS is specialized, we may need to check type arguments.
11056 if (LHS->isSpecialized()) {
11057 // Follow the superclass chain until we've matched the LHS class in the
11058 // hierarchy. This substitutes type arguments through.
11059 const ObjCObjectType *RHSSuper = RHS;
11060 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
11061 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
11062
11063 // If the RHS is specializd, compare type arguments.
11064 if (RHSSuper->isSpecialized() &&
11065 !sameObjCTypeArgs(*this, LHS->getInterface(),
11066 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
11067 /*stripKindOf=*/true)) {
11068 return false;
11069 }
11070 }
11071
11072 return true;
11073}
11074
11076 // get the "pointed to" types
11077 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
11078 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
11079
11080 if (!LHSOPT || !RHSOPT)
11081 return false;
11082
11083 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
11084 canAssignObjCInterfaces(RHSOPT, LHSOPT);
11085}
11086
11089 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
11090 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
11091}
11092
11093/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
11094/// both shall have the identically qualified version of a compatible type.
11095/// C99 6.2.7p1: Two types have compatible types if their types are the
11096/// same. See 6.7.[2,3,5] for additional rules.
11098 bool CompareUnqualified) {
11099 if (getLangOpts().CPlusPlus)
11100 return hasSameType(LHS, RHS);
11101
11102 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
11103}
11104
11106 return typesAreCompatible(LHS, RHS);
11107}
11108
11110 return !mergeTypes(LHS, RHS, true).isNull();
11111}
11112
11113/// mergeTransparentUnionType - if T is a transparent union type and a member
11114/// of T is compatible with SubType, return the merged type, else return
11115/// QualType()
11117 bool OfBlockPointer,
11118 bool Unqualified) {
11119 if (const RecordType *UT = T->getAsUnionType()) {
11120 RecordDecl *UD = UT->getDecl();
11121 if (UD->hasAttr<TransparentUnionAttr>()) {
11122 for (const auto *I : UD->fields()) {
11123 QualType ET = I->getType().getUnqualifiedType();
11124 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
11125 if (!MT.isNull())
11126 return MT;
11127 }
11128 }
11129 }
11130
11131 return {};
11132}
11133
11134/// mergeFunctionParameterTypes - merge two types which appear as function
11135/// parameter types
11137 bool OfBlockPointer,
11138 bool Unqualified) {
11139 // GNU extension: two types are compatible if they appear as a function
11140 // argument, one of the types is a transparent union type and the other
11141 // type is compatible with a union member
11142 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
11143 Unqualified);
11144 if (!lmerge.isNull())
11145 return lmerge;
11146
11147 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
11148 Unqualified);
11149 if (!rmerge.isNull())
11150 return rmerge;
11151
11152 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
11153}
11154
11156 bool OfBlockPointer, bool Unqualified,
11157 bool AllowCXX,
11158 bool IsConditionalOperator) {
11159 const auto *lbase = lhs->castAs<FunctionType>();
11160 const auto *rbase = rhs->castAs<FunctionType>();
11161 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
11162 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
11163 bool allLTypes = true;
11164 bool allRTypes = true;
11165
11166 // Check return type
11167 QualType retType;
11168 if (OfBlockPointer) {
11169 QualType RHS = rbase->getReturnType();
11170 QualType LHS = lbase->getReturnType();
11171 bool UnqualifiedResult = Unqualified;
11172 if (!UnqualifiedResult)
11173 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
11174 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
11175 }
11176 else
11177 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
11178 Unqualified);
11179 if (retType.isNull())
11180 return {};
11181
11182 if (Unqualified)
11183 retType = retType.getUnqualifiedType();
11184
11185 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
11186 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
11187 if (Unqualified) {
11188 LRetType = LRetType.getUnqualifiedType();
11189 RRetType = RRetType.getUnqualifiedType();
11190 }
11191
11192 if (getCanonicalType(retType) != LRetType)
11193 allLTypes = false;
11194 if (getCanonicalType(retType) != RRetType)
11195 allRTypes = false;
11196
11197 // FIXME: double check this
11198 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
11199 // rbase->getRegParmAttr() != 0 &&
11200 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
11201 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
11202 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
11203
11204 // Compatible functions must have compatible calling conventions
11205 if (lbaseInfo.getCC() != rbaseInfo.getCC())
11206 return {};
11207
11208 // Regparm is part of the calling convention.
11209 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
11210 return {};
11211 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
11212 return {};
11213
11214 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
11215 return {};
11216 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
11217 return {};
11218 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
11219 return {};
11220
11221 // When merging declarations, it's common for supplemental information like
11222 // attributes to only be present in one of the declarations, and we generally
11223 // want type merging to preserve the union of information. So a merged
11224 // function type should be noreturn if it was noreturn in *either* operand
11225 // type.
11226 //
11227 // But for the conditional operator, this is backwards. The result of the
11228 // operator could be either operand, and its type should conservatively
11229 // reflect that. So a function type in a composite type is noreturn only
11230 // if it's noreturn in *both* operand types.
11231 //
11232 // Arguably, noreturn is a kind of subtype, and the conditional operator
11233 // ought to produce the most specific common supertype of its operand types.
11234 // That would differ from this rule in contravariant positions. However,
11235 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
11236 // as a practical matter, it would only affect C code that does abstraction of
11237 // higher-order functions (taking noreturn callbacks!), which is uncommon to
11238 // say the least. So we use the simpler rule.
11239 bool NoReturn = IsConditionalOperator
11240 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
11241 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
11242 if (lbaseInfo.getNoReturn() != NoReturn)
11243 allLTypes = false;
11244 if (rbaseInfo.getNoReturn() != NoReturn)
11245 allRTypes = false;
11246
11247 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
11248
11249 std::optional<FunctionEffectSet> MergedFX;
11250
11251 if (lproto && rproto) { // two C99 style function prototypes
11252 assert((AllowCXX ||
11253 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
11254 "C++ shouldn't be here");
11255 // Compatible functions must have the same number of parameters
11256 if (lproto->getNumParams() != rproto->getNumParams())
11257 return {};
11258
11259 // Variadic and non-variadic functions aren't compatible
11260 if (lproto->isVariadic() != rproto->isVariadic())
11261 return {};
11262
11263 if (lproto->getMethodQuals() != rproto->getMethodQuals())
11264 return {};
11265
11266 // Function effects are handled similarly to noreturn, see above.
11267 FunctionEffectsRef LHSFX = lproto->getFunctionEffects();
11268 FunctionEffectsRef RHSFX = rproto->getFunctionEffects();
11269 if (LHSFX != RHSFX) {
11270 if (IsConditionalOperator)
11271 MergedFX = FunctionEffectSet::getIntersection(LHSFX, RHSFX);
11272 else {
11274 MergedFX = FunctionEffectSet::getUnion(LHSFX, RHSFX, Errs);
11275 // Here we're discarding a possible error due to conflicts in the effect
11276 // sets. But we're not in a context where we can report it. The
11277 // operation does however guarantee maintenance of invariants.
11278 }
11279 if (*MergedFX != LHSFX)
11280 allLTypes = false;
11281 if (*MergedFX != RHSFX)
11282 allRTypes = false;
11283 }
11284
11286 bool canUseLeft, canUseRight;
11287 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
11288 newParamInfos))
11289 return {};
11290
11291 if (!canUseLeft)
11292 allLTypes = false;
11293 if (!canUseRight)
11294 allRTypes = false;
11295
11296 // Check parameter type compatibility
11298 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
11299 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
11300 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
11302 lParamType, rParamType, OfBlockPointer, Unqualified);
11303 if (paramType.isNull())
11304 return {};
11305
11306 if (Unqualified)
11307 paramType = paramType.getUnqualifiedType();
11308
11309 types.push_back(paramType);
11310 if (Unqualified) {
11311 lParamType = lParamType.getUnqualifiedType();
11312 rParamType = rParamType.getUnqualifiedType();
11313 }
11314
11315 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
11316 allLTypes = false;
11317 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
11318 allRTypes = false;
11319 }
11320
11321 if (allLTypes) return lhs;
11322 if (allRTypes) return rhs;
11323
11324 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
11325 EPI.ExtInfo = einfo;
11326 EPI.ExtParameterInfos =
11327 newParamInfos.empty() ? nullptr : newParamInfos.data();
11328 if (MergedFX)
11329 EPI.FunctionEffects = *MergedFX;
11330 return getFunctionType(retType, types, EPI);
11331 }
11332
11333 if (lproto) allRTypes = false;
11334 if (rproto) allLTypes = false;
11335
11336 const FunctionProtoType *proto = lproto ? lproto : rproto;
11337 if (proto) {
11338 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
11339 if (proto->isVariadic())
11340 return {};
11341 // Check that the types are compatible with the types that
11342 // would result from default argument promotions (C99 6.7.5.3p15).
11343 // The only types actually affected are promotable integer
11344 // types and floats, which would be passed as a different
11345 // type depending on whether the prototype is visible.
11346 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
11347 QualType paramTy = proto->getParamType(i);
11348
11349 // Look at the converted type of enum types, since that is the type used
11350 // to pass enum values.
11351 if (const auto *Enum = paramTy->getAs<EnumType>()) {
11352 paramTy = Enum->getDecl()->getIntegerType();
11353 if (paramTy.isNull())
11354 return {};
11355 }
11356
11357 if (isPromotableIntegerType(paramTy) ||
11358 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
11359 return {};
11360 }
11361
11362 if (allLTypes) return lhs;
11363 if (allRTypes) return rhs;
11364
11366 EPI.ExtInfo = einfo;
11367 if (MergedFX)
11368 EPI.FunctionEffects = *MergedFX;
11369 return getFunctionType(retType, proto->getParamTypes(), EPI);
11370 }
11371
11372 if (allLTypes) return lhs;
11373 if (allRTypes) return rhs;
11374 return getFunctionNoProtoType(retType, einfo);
11375}
11376
11377/// Given that we have an enum type and a non-enum type, try to merge them.
11379 QualType other, bool isBlockReturnType) {
11380 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
11381 // a signed integer type, or an unsigned integer type.
11382 // Compatibility is based on the underlying type, not the promotion
11383 // type.
11384 QualType underlyingType = ET->getDecl()->getIntegerType();
11385 if (underlyingType.isNull())
11386 return {};
11387 if (Context.hasSameType(underlyingType, other))
11388 return other;
11389
11390 // In block return types, we're more permissive and accept any
11391 // integral type of the same size.
11392 if (isBlockReturnType && other->isIntegerType() &&
11393 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
11394 return other;
11395
11396 return {};
11397}
11398
11399QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
11400 bool Unqualified, bool BlockReturnType,
11401 bool IsConditionalOperator) {
11402 // For C++ we will not reach this code with reference types (see below),
11403 // for OpenMP variant call overloading we might.
11404 //
11405 // C++ [expr]: If an expression initially has the type "reference to T", the
11406 // type is adjusted to "T" prior to any further analysis, the expression
11407 // designates the object or function denoted by the reference, and the
11408 // expression is an lvalue unless the reference is an rvalue reference and
11409 // the expression is a function call (possibly inside parentheses).
11410 auto *LHSRefTy = LHS->getAs<ReferenceType>();
11411 auto *RHSRefTy = RHS->getAs<ReferenceType>();
11412 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
11413 LHS->getTypeClass() == RHS->getTypeClass())
11414 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
11415 OfBlockPointer, Unqualified, BlockReturnType);
11416 if (LHSRefTy || RHSRefTy)
11417 return {};
11418
11419 if (Unqualified) {
11420 LHS = LHS.getUnqualifiedType();
11421 RHS = RHS.getUnqualifiedType();
11422 }
11423
11424 QualType LHSCan = getCanonicalType(LHS),
11425 RHSCan = getCanonicalType(RHS);
11426
11427 // If two types are identical, they are compatible.
11428 if (LHSCan == RHSCan)
11429 return LHS;
11430
11431 // If the qualifiers are different, the types aren't compatible... mostly.
11432 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11433 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11434 if (LQuals != RQuals) {
11435 // If any of these qualifiers are different, we have a type
11436 // mismatch.
11437 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11438 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
11439 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
11440 LQuals.hasUnaligned() != RQuals.hasUnaligned())
11441 return {};
11442
11443 // Exactly one GC qualifier difference is allowed: __strong is
11444 // okay if the other type has no GC qualifier but is an Objective
11445 // C object pointer (i.e. implicitly strong by default). We fix
11446 // this by pretending that the unqualified type was actually
11447 // qualified __strong.
11448 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11449 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11450 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11451
11452 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11453 return {};
11454
11455 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
11457 }
11458 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
11460 }
11461 return {};
11462 }
11463
11464 // Okay, qualifiers are equal.
11465
11466 Type::TypeClass LHSClass = LHSCan->getTypeClass();
11467 Type::TypeClass RHSClass = RHSCan->getTypeClass();
11468
11469 // We want to consider the two function types to be the same for these
11470 // comparisons, just force one to the other.
11471 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
11472 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
11473
11474 // Same as above for arrays
11475 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
11476 LHSClass = Type::ConstantArray;
11477 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
11478 RHSClass = Type::ConstantArray;
11479
11480 // ObjCInterfaces are just specialized ObjCObjects.
11481 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
11482 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
11483
11484 // Canonicalize ExtVector -> Vector.
11485 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
11486 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
11487
11488 // If the canonical type classes don't match.
11489 if (LHSClass != RHSClass) {
11490 // Note that we only have special rules for turning block enum
11491 // returns into block int returns, not vice-versa.
11492 if (const auto *ETy = LHS->getAs<EnumType>()) {
11493 return mergeEnumWithInteger(*this, ETy, RHS, false);
11494 }
11495 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
11496 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
11497 }
11498 // allow block pointer type to match an 'id' type.
11499 if (OfBlockPointer && !BlockReturnType) {
11500 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
11501 return LHS;
11502 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
11503 return RHS;
11504 }
11505 // Allow __auto_type to match anything; it merges to the type with more
11506 // information.
11507 if (const auto *AT = LHS->getAs<AutoType>()) {
11508 if (!AT->isDeduced() && AT->isGNUAutoType())
11509 return RHS;
11510 }
11511 if (const auto *AT = RHS->getAs<AutoType>()) {
11512 if (!AT->isDeduced() && AT->isGNUAutoType())
11513 return LHS;
11514 }
11515 return {};
11516 }
11517
11518 // The canonical type classes match.
11519 switch (LHSClass) {
11520#define TYPE(Class, Base)
11521#define ABSTRACT_TYPE(Class, Base)
11522#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
11523#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
11524#define DEPENDENT_TYPE(Class, Base) case Type::Class:
11525#include "clang/AST/TypeNodes.inc"
11526 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
11527
11528 case Type::Auto:
11529 case Type::DeducedTemplateSpecialization:
11530 case Type::LValueReference:
11531 case Type::RValueReference:
11532 case Type::MemberPointer:
11533 llvm_unreachable("C++ should never be in mergeTypes");
11534
11535 case Type::ObjCInterface:
11536 case Type::IncompleteArray:
11537 case Type::VariableArray:
11538 case Type::FunctionProto:
11539 case Type::ExtVector:
11540 llvm_unreachable("Types are eliminated above");
11541
11542 case Type::Pointer:
11543 {
11544 // Merge two pointer types, while trying to preserve typedef info
11545 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
11546 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
11547 if (Unqualified) {
11548 LHSPointee = LHSPointee.getUnqualifiedType();
11549 RHSPointee = RHSPointee.getUnqualifiedType();
11550 }
11551 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
11552 Unqualified);
11553 if (ResultType.isNull())
11554 return {};
11555 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11556 return LHS;
11557 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
11558 return RHS;
11559 return getPointerType(ResultType);
11560 }
11561 case Type::BlockPointer:
11562 {
11563 // Merge two block pointer types, while trying to preserve typedef info
11564 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
11565 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
11566 if (Unqualified) {
11567 LHSPointee = LHSPointee.getUnqualifiedType();
11568 RHSPointee = RHSPointee.getUnqualifiedType();
11569 }
11570 if (getLangOpts().OpenCL) {
11571 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
11572 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
11573 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
11574 // 6.12.5) thus the following check is asymmetric.
11575 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual, *this))
11576 return {};
11577 LHSPteeQual.removeAddressSpace();
11578 RHSPteeQual.removeAddressSpace();
11579 LHSPointee =
11580 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
11581 RHSPointee =
11582 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
11583 }
11584 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
11585 Unqualified);
11586 if (ResultType.isNull())
11587 return {};
11588 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11589 return LHS;
11590 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
11591 return RHS;
11592 return getBlockPointerType(ResultType);
11593 }
11594 case Type::Atomic:
11595 {
11596 // Merge two pointer types, while trying to preserve typedef info
11597 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
11598 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
11599 if (Unqualified) {
11600 LHSValue = LHSValue.getUnqualifiedType();
11601 RHSValue = RHSValue.getUnqualifiedType();
11602 }
11603 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
11604 Unqualified);
11605 if (ResultType.isNull())
11606 return {};
11607 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
11608 return LHS;
11609 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
11610 return RHS;
11611 return getAtomicType(ResultType);
11612 }
11613 case Type::ConstantArray:
11614 {
11615 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
11616 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
11617 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
11618 return {};
11619
11620 QualType LHSElem = getAsArrayType(LHS)->getElementType();
11621 QualType RHSElem = getAsArrayType(RHS)->getElementType();
11622 if (Unqualified) {
11623 LHSElem = LHSElem.getUnqualifiedType();
11624 RHSElem = RHSElem.getUnqualifiedType();
11625 }
11626
11627 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
11628 if (ResultType.isNull())
11629 return {};
11630
11631 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
11632 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
11633
11634 // If either side is a variable array, and both are complete, check whether
11635 // the current dimension is definite.
11636 if (LVAT || RVAT) {
11637 auto SizeFetch = [this](const VariableArrayType* VAT,
11638 const ConstantArrayType* CAT)
11639 -> std::pair<bool,llvm::APInt> {
11640 if (VAT) {
11641 std::optional<llvm::APSInt> TheInt;
11642 Expr *E = VAT->getSizeExpr();
11643 if (E && (TheInt = E->getIntegerConstantExpr(*this)))
11644 return std::make_pair(true, *TheInt);
11645 return std::make_pair(false, llvm::APSInt());
11646 }
11647 if (CAT)
11648 return std::make_pair(true, CAT->getSize());
11649 return std::make_pair(false, llvm::APInt());
11650 };
11651
11652 bool HaveLSize, HaveRSize;
11653 llvm::APInt LSize, RSize;
11654 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
11655 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
11656 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
11657 return {}; // Definite, but unequal, array dimension
11658 }
11659
11660 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
11661 return LHS;
11662 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
11663 return RHS;
11664 if (LCAT)
11665 return getConstantArrayType(ResultType, LCAT->getSize(),
11666 LCAT->getSizeExpr(), ArraySizeModifier(), 0);
11667 if (RCAT)
11668 return getConstantArrayType(ResultType, RCAT->getSize(),
11669 RCAT->getSizeExpr(), ArraySizeModifier(), 0);
11670 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
11671 return LHS;
11672 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
11673 return RHS;
11674 if (LVAT) {
11675 // FIXME: This isn't correct! But tricky to implement because
11676 // the array's size has to be the size of LHS, but the type
11677 // has to be different.
11678 return LHS;
11679 }
11680 if (RVAT) {
11681 // FIXME: This isn't correct! But tricky to implement because
11682 // the array's size has to be the size of RHS, but the type
11683 // has to be different.
11684 return RHS;
11685 }
11686 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
11687 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
11688 return getIncompleteArrayType(ResultType, ArraySizeModifier(), 0);
11689 }
11690 case Type::FunctionNoProto:
11691 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified,
11692 /*AllowCXX=*/false, IsConditionalOperator);
11693 case Type::Record:
11694 case Type::Enum:
11695 return {};
11696 case Type::Builtin:
11697 // Only exactly equal builtin types are compatible, which is tested above.
11698 return {};
11699 case Type::Complex:
11700 // Distinct complex types are incompatible.
11701 return {};
11702 case Type::Vector:
11703 // FIXME: The merged type should be an ExtVector!
11704 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
11705 RHSCan->castAs<VectorType>()))
11706 return LHS;
11707 return {};
11708 case Type::ConstantMatrix:
11710 RHSCan->castAs<ConstantMatrixType>()))
11711 return LHS;
11712 return {};
11713 case Type::ObjCObject: {
11714 // Check if the types are assignment compatible.
11715 // FIXME: This should be type compatibility, e.g. whether
11716 // "LHS x; RHS x;" at global scope is legal.
11718 RHS->castAs<ObjCObjectType>()))
11719 return LHS;
11720 return {};
11721 }
11722 case Type::ObjCObjectPointer:
11723 if (OfBlockPointer) {
11726 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
11727 return LHS;
11728 return {};
11729 }
11732 return LHS;
11733 return {};
11734 case Type::Pipe:
11735 assert(LHS != RHS &&
11736 "Equivalent pipe types should have already been handled!");
11737 return {};
11738 case Type::ArrayParameter:
11739 assert(LHS != RHS &&
11740 "Equivalent ArrayParameter types should have already been handled!");
11741 return {};
11742 case Type::BitInt: {
11743 // Merge two bit-precise int types, while trying to preserve typedef info.
11744 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
11745 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
11746 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
11747 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
11748
11749 // Like unsigned/int, shouldn't have a type if they don't match.
11750 if (LHSUnsigned != RHSUnsigned)
11751 return {};
11752
11753 if (LHSBits != RHSBits)
11754 return {};
11755 return LHS;
11756 }
11757 case Type::HLSLAttributedResource: {
11758 const HLSLAttributedResourceType *LHSTy =
11760 const HLSLAttributedResourceType *RHSTy =
11762 assert(LHSTy->getWrappedType() == RHSTy->getWrappedType() &&
11763 LHSTy->getWrappedType()->isHLSLResourceType() &&
11764 "HLSLAttributedResourceType should always wrap __hlsl_resource_t");
11765
11766 if (LHSTy->getAttrs() == RHSTy->getAttrs() &&
11767 LHSTy->getContainedType() == RHSTy->getContainedType())
11768 return LHS;
11769 return {};
11770 }
11771 }
11772
11773 llvm_unreachable("Invalid Type::Class!");
11774}
11775
11777 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
11778 bool &CanUseFirst, bool &CanUseSecond,
11780 assert(NewParamInfos.empty() && "param info list not empty");
11781 CanUseFirst = CanUseSecond = true;
11782 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
11783 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
11784
11785 // Fast path: if the first type doesn't have ext parameter infos,
11786 // we match if and only if the second type also doesn't have them.
11787 if (!FirstHasInfo && !SecondHasInfo)
11788 return true;
11789
11790 bool NeedParamInfo = false;
11791 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
11792 : SecondFnType->getExtParameterInfos().size();
11793
11794 for (size_t I = 0; I < E; ++I) {
11795 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
11796 if (FirstHasInfo)
11797 FirstParam = FirstFnType->getExtParameterInfo(I);
11798 if (SecondHasInfo)
11799 SecondParam = SecondFnType->getExtParameterInfo(I);
11800
11801 // Cannot merge unless everything except the noescape flag matches.
11802 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
11803 return false;
11804
11805 bool FirstNoEscape = FirstParam.isNoEscape();
11806 bool SecondNoEscape = SecondParam.isNoEscape();
11807 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
11808 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
11809 if (NewParamInfos.back().getOpaqueValue())
11810 NeedParamInfo = true;
11811 if (FirstNoEscape != IsNoEscape)
11812 CanUseFirst = false;
11813 if (SecondNoEscape != IsNoEscape)
11814 CanUseSecond = false;
11815 }
11816
11817 if (!NeedParamInfo)
11818 NewParamInfos.clear();
11819
11820 return true;
11821}
11822
11824 ObjCLayouts[CD] = nullptr;
11825}
11826
11827/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
11828/// 'RHS' attributes and returns the merged version; including for function
11829/// return types.
11831 QualType LHSCan = getCanonicalType(LHS),
11832 RHSCan = getCanonicalType(RHS);
11833 // If two types are identical, they are compatible.
11834 if (LHSCan == RHSCan)
11835 return LHS;
11836 if (RHSCan->isFunctionType()) {
11837 if (!LHSCan->isFunctionType())
11838 return {};
11839 QualType OldReturnType =
11840 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
11841 QualType NewReturnType =
11842 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
11843 QualType ResReturnType =
11844 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
11845 if (ResReturnType.isNull())
11846 return {};
11847 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
11848 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
11849 // In either case, use OldReturnType to build the new function type.
11850 const auto *F = LHS->castAs<FunctionType>();
11851 if (const auto *FPT = cast<FunctionProtoType>(F)) {
11852 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11853 EPI.ExtInfo = getFunctionExtInfo(LHS);
11854 QualType ResultType =
11855 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
11856 return ResultType;
11857 }
11858 }
11859 return {};
11860 }
11861
11862 // If the qualifiers are different, the types can still be merged.
11863 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11864 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11865 if (LQuals != RQuals) {
11866 // If any of these qualifiers are different, we have a type mismatch.
11867 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11868 LQuals.getAddressSpace() != RQuals.getAddressSpace())
11869 return {};
11870
11871 // Exactly one GC qualifier difference is allowed: __strong is
11872 // okay if the other type has no GC qualifier but is an Objective
11873 // C object pointer (i.e. implicitly strong by default). We fix
11874 // this by pretending that the unqualified type was actually
11875 // qualified __strong.
11876 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11877 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11878 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11879
11880 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11881 return {};
11882
11883 if (GC_L == Qualifiers::Strong)
11884 return LHS;
11885 if (GC_R == Qualifiers::Strong)
11886 return RHS;
11887 return {};
11888 }
11889
11890 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
11891 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
11892 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
11893 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
11894 if (ResQT == LHSBaseQT)
11895 return LHS;
11896 if (ResQT == RHSBaseQT)
11897 return RHS;
11898 }
11899 return {};
11900}
11901
11902//===----------------------------------------------------------------------===//
11903// Integer Predicates
11904//===----------------------------------------------------------------------===//
11905
11907 if (const auto *ET = T->getAs<EnumType>())
11908 T = ET->getDecl()->getIntegerType();
11909 if (T->isBooleanType())
11910 return 1;
11911 if (const auto *EIT = T->getAs<BitIntType>())
11912 return EIT->getNumBits();
11913 // For builtin types, just use the standard type sizing method
11914 return (unsigned)getTypeSize(T);
11915}
11916
11918 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
11919 T->isFixedPointType()) &&
11920 "Unexpected type");
11921
11922 // Turn <4 x signed int> -> <4 x unsigned int>
11923 if (const auto *VTy = T->getAs<VectorType>())
11924 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
11925 VTy->getNumElements(), VTy->getVectorKind());
11926
11927 // For _BitInt, return an unsigned _BitInt with same width.
11928 if (const auto *EITy = T->getAs<BitIntType>())
11929 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
11930
11931 // For enums, get the underlying integer type of the enum, and let the general
11932 // integer type signchanging code handle it.
11933 if (const auto *ETy = T->getAs<EnumType>())
11934 T = ETy->getDecl()->getIntegerType();
11935
11936 switch (T->castAs<BuiltinType>()->getKind()) {
11937 case BuiltinType::Char_U:
11938 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
11939 case BuiltinType::Char_S:
11940 case BuiltinType::SChar:
11941 case BuiltinType::Char8:
11942 return UnsignedCharTy;
11943 case BuiltinType::Short:
11944 return UnsignedShortTy;
11945 case BuiltinType::Int:
11946 return UnsignedIntTy;
11947 case BuiltinType::Long:
11948 return UnsignedLongTy;
11949 case BuiltinType::LongLong:
11950 return UnsignedLongLongTy;
11951 case BuiltinType::Int128:
11952 return UnsignedInt128Ty;
11953 // wchar_t is special. It is either signed or not, but when it's signed,
11954 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
11955 // version of its underlying type instead.
11956 case BuiltinType::WChar_S:
11957 return getUnsignedWCharType();
11958
11959 case BuiltinType::ShortAccum:
11960 return UnsignedShortAccumTy;
11961 case BuiltinType::Accum:
11962 return UnsignedAccumTy;
11963 case BuiltinType::LongAccum:
11964 return UnsignedLongAccumTy;
11965 case BuiltinType::SatShortAccum:
11967 case BuiltinType::SatAccum:
11968 return SatUnsignedAccumTy;
11969 case BuiltinType::SatLongAccum:
11971 case BuiltinType::ShortFract:
11972 return UnsignedShortFractTy;
11973 case BuiltinType::Fract:
11974 return UnsignedFractTy;
11975 case BuiltinType::LongFract:
11976 return UnsignedLongFractTy;
11977 case BuiltinType::SatShortFract:
11979 case BuiltinType::SatFract:
11980 return SatUnsignedFractTy;
11981 case BuiltinType::SatLongFract:
11983 default:
11986 "Unexpected signed integer or fixed point type");
11987 return T;
11988 }
11989}
11990
11992 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
11993 T->isFixedPointType()) &&
11994 "Unexpected type");
11995
11996 // Turn <4 x unsigned int> -> <4 x signed int>
11997 if (const auto *VTy = T->getAs<VectorType>())
11998 return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
11999 VTy->getNumElements(), VTy->getVectorKind());
12000
12001 // For _BitInt, return a signed _BitInt with same width.
12002 if (const auto *EITy = T->getAs<BitIntType>())
12003 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
12004
12005 // For enums, get the underlying integer type of the enum, and let the general
12006 // integer type signchanging code handle it.
12007 if (const auto *ETy = T->getAs<EnumType>())
12008 T = ETy->getDecl()->getIntegerType();
12009
12010 switch (T->castAs<BuiltinType>()->getKind()) {
12011 case BuiltinType::Char_S:
12012 // Plain `char` is mapped to `signed char` even if it's already signed
12013 case BuiltinType::Char_U:
12014 case BuiltinType::UChar:
12015 case BuiltinType::Char8:
12016 return SignedCharTy;
12017 case BuiltinType::UShort:
12018 return ShortTy;
12019 case BuiltinType::UInt:
12020 return IntTy;
12021 case BuiltinType::ULong:
12022 return LongTy;
12023 case BuiltinType::ULongLong:
12024 return LongLongTy;
12025 case BuiltinType::UInt128:
12026 return Int128Ty;
12027 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
12028 // there's no matching "signed wchar_t". Therefore we return the signed
12029 // version of its underlying type instead.
12030 case BuiltinType::WChar_U:
12031 return getSignedWCharType();
12032
12033 case BuiltinType::UShortAccum:
12034 return ShortAccumTy;
12035 case BuiltinType::UAccum:
12036 return AccumTy;
12037 case BuiltinType::ULongAccum:
12038 return LongAccumTy;
12039 case BuiltinType::SatUShortAccum:
12040 return SatShortAccumTy;
12041 case BuiltinType::SatUAccum:
12042 return SatAccumTy;
12043 case BuiltinType::SatULongAccum:
12044 return SatLongAccumTy;
12045 case BuiltinType::UShortFract:
12046 return ShortFractTy;
12047 case BuiltinType::UFract:
12048 return FractTy;
12049 case BuiltinType::ULongFract:
12050 return LongFractTy;
12051 case BuiltinType::SatUShortFract:
12052 return SatShortFractTy;
12053 case BuiltinType::SatUFract:
12054 return SatFractTy;
12055 case BuiltinType::SatULongFract:
12056 return SatLongFractTy;
12057 default:
12058 assert(
12060 "Unexpected signed integer or fixed point type");
12061 return T;
12062 }
12063}
12064
12066
12068 QualType ReturnType) {}
12069
12070//===----------------------------------------------------------------------===//
12071// Builtin Type Computation
12072//===----------------------------------------------------------------------===//
12073
12074/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
12075/// pointer over the consumed characters. This returns the resultant type. If
12076/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
12077/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
12078/// a vector of "i*".
12079///
12080/// RequiresICE is filled in on return to indicate whether the value is required
12081/// to be an Integer Constant Expression.
12082static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
12084 bool &RequiresICE,
12085 bool AllowTypeModifiers) {
12086 // Modifiers.
12087 int HowLong = 0;
12088 bool Signed = false, Unsigned = false;
12089 RequiresICE = false;
12090
12091 // Read the prefixed modifiers first.
12092 bool Done = false;
12093 #ifndef NDEBUG
12094 bool IsSpecial = false;
12095 #endif
12096 while (!Done) {
12097 switch (*Str++) {
12098 default: Done = true; --Str; break;
12099 case 'I':
12100 RequiresICE = true;
12101 break;
12102 case 'S':
12103 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
12104 assert(!Signed && "Can't use 'S' modifier multiple times!");
12105 Signed = true;
12106 break;
12107 case 'U':
12108 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
12109 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
12110 Unsigned = true;
12111 break;
12112 case 'L':
12113 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
12114 assert(HowLong <= 2 && "Can't have LLLL modifier");
12115 ++HowLong;
12116 break;
12117 case 'N':
12118 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
12119 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12120 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
12121 #ifndef NDEBUG
12122 IsSpecial = true;
12123 #endif
12124 if (Context.getTargetInfo().getLongWidth() == 32)
12125 ++HowLong;
12126 break;
12127 case 'W':
12128 // This modifier represents int64 type.
12129 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12130 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
12131 #ifndef NDEBUG
12132 IsSpecial = true;
12133 #endif
12134 switch (Context.getTargetInfo().getInt64Type()) {
12135 default:
12136 llvm_unreachable("Unexpected integer type");
12138 HowLong = 1;
12139 break;
12141 HowLong = 2;
12142 break;
12143 }
12144 break;
12145 case 'Z':
12146 // This modifier represents int32 type.
12147 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12148 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
12149 #ifndef NDEBUG
12150 IsSpecial = true;
12151 #endif
12152 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
12153 default:
12154 llvm_unreachable("Unexpected integer type");
12156 HowLong = 0;
12157 break;
12159 HowLong = 1;
12160 break;
12162 HowLong = 2;
12163 break;
12164 }
12165 break;
12166 case 'O':
12167 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12168 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
12169 #ifndef NDEBUG
12170 IsSpecial = true;
12171 #endif
12172 if (Context.getLangOpts().OpenCL)
12173 HowLong = 1;
12174 else
12175 HowLong = 2;
12176 break;
12177 }
12178 }
12179
12180 QualType Type;
12181
12182 // Read the base type.
12183 switch (*Str++) {
12184 default: llvm_unreachable("Unknown builtin type letter!");
12185 case 'x':
12186 assert(HowLong == 0 && !Signed && !Unsigned &&
12187 "Bad modifiers used with 'x'!");
12188 Type = Context.Float16Ty;
12189 break;
12190 case 'y':
12191 assert(HowLong == 0 && !Signed && !Unsigned &&
12192 "Bad modifiers used with 'y'!");
12193 Type = Context.BFloat16Ty;
12194 break;
12195 case 'v':
12196 assert(HowLong == 0 && !Signed && !Unsigned &&
12197 "Bad modifiers used with 'v'!");
12198 Type = Context.VoidTy;
12199 break;
12200 case 'h':
12201 assert(HowLong == 0 && !Signed && !Unsigned &&
12202 "Bad modifiers used with 'h'!");
12203 Type = Context.HalfTy;
12204 break;
12205 case 'f':
12206 assert(HowLong == 0 && !Signed && !Unsigned &&
12207 "Bad modifiers used with 'f'!");
12208 Type = Context.FloatTy;
12209 break;
12210 case 'd':
12211 assert(HowLong < 3 && !Signed && !Unsigned &&
12212 "Bad modifiers used with 'd'!");
12213 if (HowLong == 1)
12214 Type = Context.LongDoubleTy;
12215 else if (HowLong == 2)
12216 Type = Context.Float128Ty;
12217 else
12218 Type = Context.DoubleTy;
12219 break;
12220 case 's':
12221 assert(HowLong == 0 && "Bad modifiers used with 's'!");
12222 if (Unsigned)
12223 Type = Context.UnsignedShortTy;
12224 else
12225 Type = Context.ShortTy;
12226 break;
12227 case 'i':
12228 if (HowLong == 3)
12229 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
12230 else if (HowLong == 2)
12231 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
12232 else if (HowLong == 1)
12233 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
12234 else
12235 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
12236 break;
12237 case 'c':
12238 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
12239 if (Signed)
12240 Type = Context.SignedCharTy;
12241 else if (Unsigned)
12242 Type = Context.UnsignedCharTy;
12243 else
12244 Type = Context.CharTy;
12245 break;
12246 case 'b': // boolean
12247 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
12248 Type = Context.BoolTy;
12249 break;
12250 case 'z': // size_t.
12251 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
12252 Type = Context.getSizeType();
12253 break;
12254 case 'w': // wchar_t.
12255 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
12256 Type = Context.getWideCharType();
12257 break;
12258 case 'F':
12259 Type = Context.getCFConstantStringType();
12260 break;
12261 case 'G':
12262 Type = Context.getObjCIdType();
12263 break;
12264 case 'H':
12265 Type = Context.getObjCSelType();
12266 break;
12267 case 'M':
12268 Type = Context.getObjCSuperType();
12269 break;
12270 case 'a':
12271 Type = Context.getBuiltinVaListType();
12272 assert(!Type.isNull() && "builtin va list type not initialized!");
12273 break;
12274 case 'A':
12275 // This is a "reference" to a va_list; however, what exactly
12276 // this means depends on how va_list is defined. There are two
12277 // different kinds of va_list: ones passed by value, and ones
12278 // passed by reference. An example of a by-value va_list is
12279 // x86, where va_list is a char*. An example of by-ref va_list
12280 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
12281 // we want this argument to be a char*&; for x86-64, we want
12282 // it to be a __va_list_tag*.
12283 Type = Context.getBuiltinVaListType();
12284 assert(!Type.isNull() && "builtin va list type not initialized!");
12285 if (Type->isArrayType())
12286 Type = Context.getArrayDecayedType(Type);
12287 else
12288 Type = Context.getLValueReferenceType(Type);
12289 break;
12290 case 'q': {
12291 char *End;
12292 unsigned NumElements = strtoul(Str, &End, 10);
12293 assert(End != Str && "Missing vector size");
12294 Str = End;
12295
12296 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12297 RequiresICE, false);
12298 assert(!RequiresICE && "Can't require vector ICE");
12299
12300 Type = Context.getScalableVectorType(ElementType, NumElements);
12301 break;
12302 }
12303 case 'Q': {
12304 switch (*Str++) {
12305 case 'a': {
12306 Type = Context.SveCountTy;
12307 break;
12308 }
12309 case 'b': {
12310 Type = Context.AMDGPUBufferRsrcTy;
12311 break;
12312 }
12313 default:
12314 llvm_unreachable("Unexpected target builtin type");
12315 }
12316 break;
12317 }
12318 case 'V': {
12319 char *End;
12320 unsigned NumElements = strtoul(Str, &End, 10);
12321 assert(End != Str && "Missing vector size");
12322 Str = End;
12323
12324 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12325 RequiresICE, false);
12326 assert(!RequiresICE && "Can't require vector ICE");
12327
12328 // TODO: No way to make AltiVec vectors in builtins yet.
12329 Type = Context.getVectorType(ElementType, NumElements, VectorKind::Generic);
12330 break;
12331 }
12332 case 'E': {
12333 char *End;
12334
12335 unsigned NumElements = strtoul(Str, &End, 10);
12336 assert(End != Str && "Missing vector size");
12337
12338 Str = End;
12339
12340 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12341 false);
12342 Type = Context.getExtVectorType(ElementType, NumElements);
12343 break;
12344 }
12345 case 'X': {
12346 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12347 false);
12348 assert(!RequiresICE && "Can't require complex ICE");
12349 Type = Context.getComplexType(ElementType);
12350 break;
12351 }
12352 case 'Y':
12353 Type = Context.getPointerDiffType();
12354 break;
12355 case 'P':
12356 Type = Context.getFILEType();
12357 if (Type.isNull()) {
12359 return {};
12360 }
12361 break;
12362 case 'J':
12363 if (Signed)
12364 Type = Context.getsigjmp_bufType();
12365 else
12366 Type = Context.getjmp_bufType();
12367
12368 if (Type.isNull()) {
12370 return {};
12371 }
12372 break;
12373 case 'K':
12374 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
12375 Type = Context.getucontext_tType();
12376
12377 if (Type.isNull()) {
12379 return {};
12380 }
12381 break;
12382 case 'p':
12383 Type = Context.getProcessIDType();
12384 break;
12385 }
12386
12387 // If there are modifiers and if we're allowed to parse them, go for it.
12388 Done = !AllowTypeModifiers;
12389 while (!Done) {
12390 switch (char c = *Str++) {
12391 default: Done = true; --Str; break;
12392 case '*':
12393 case '&': {
12394 // Both pointers and references can have their pointee types
12395 // qualified with an address space.
12396 char *End;
12397 unsigned AddrSpace = strtoul(Str, &End, 10);
12398 if (End != Str) {
12399 // Note AddrSpace == 0 is not the same as an unspecified address space.
12400 Type = Context.getAddrSpaceQualType(
12401 Type,
12402 Context.getLangASForBuiltinAddressSpace(AddrSpace));
12403 Str = End;
12404 }
12405 if (c == '*')
12406 Type = Context.getPointerType(Type);
12407 else
12408 Type = Context.getLValueReferenceType(Type);
12409 break;
12410 }
12411 // FIXME: There's no way to have a built-in with an rvalue ref arg.
12412 case 'C':
12413 Type = Type.withConst();
12414 break;
12415 case 'D':
12416 Type = Context.getVolatileType(Type);
12417 break;
12418 case 'R':
12419 Type = Type.withRestrict();
12420 break;
12421 }
12422 }
12423
12424 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
12425 "Integer constant 'I' type must be an integer");
12426
12427 return Type;
12428}
12429
12430// On some targets such as PowerPC, some of the builtins are defined with custom
12431// type descriptors for target-dependent types. These descriptors are decoded in
12432// other functions, but it may be useful to be able to fall back to default
12433// descriptor decoding to define builtins mixing target-dependent and target-
12434// independent types. This function allows decoding one type descriptor with
12435// default decoding.
12436QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
12437 GetBuiltinTypeError &Error, bool &RequireICE,
12438 bool AllowTypeModifiers) const {
12439 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
12440}
12441
12442/// GetBuiltinType - Return the type for the specified builtin.
12444 GetBuiltinTypeError &Error,
12445 unsigned *IntegerConstantArgs) const {
12446 const char *TypeStr = BuiltinInfo.getTypeString(Id);
12447 if (TypeStr[0] == '\0') {
12448 Error = GE_Missing_type;
12449 return {};
12450 }
12451
12452 SmallVector<QualType, 8> ArgTypes;
12453
12454 bool RequiresICE = false;
12455 Error = GE_None;
12456 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
12457 RequiresICE, true);
12458 if (Error != GE_None)
12459 return {};
12460
12461 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
12462
12463 while (TypeStr[0] && TypeStr[0] != '.') {
12464 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
12465 if (Error != GE_None)
12466 return {};
12467
12468 // If this argument is required to be an IntegerConstantExpression and the
12469 // caller cares, fill in the bitmask we return.
12470 if (RequiresICE && IntegerConstantArgs)
12471 *IntegerConstantArgs |= 1 << ArgTypes.size();
12472
12473 // Do array -> pointer decay. The builtin should use the decayed type.
12474 if (Ty->isArrayType())
12475 Ty = getArrayDecayedType(Ty);
12476
12477 ArgTypes.push_back(Ty);
12478 }
12479
12480 if (Id == Builtin::BI__GetExceptionInfo)
12481 return {};
12482
12483 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
12484 "'.' should only occur at end of builtin type list!");
12485
12486 bool Variadic = (TypeStr[0] == '.');
12487
12489 Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
12490 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
12491
12492
12493 // We really shouldn't be making a no-proto type here.
12494 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
12495 return getFunctionNoProtoType(ResType, EI);
12496
12498 EPI.ExtInfo = EI;
12499 EPI.Variadic = Variadic;
12501 EPI.ExceptionSpec.Type =
12503
12504 return getFunctionType(ResType, ArgTypes, EPI);
12505}
12506
12508 const FunctionDecl *FD) {
12509 if (!FD->isExternallyVisible())
12510 return GVA_Internal;
12511
12512 // Non-user-provided functions get emitted as weak definitions with every
12513 // use, no matter whether they've been explicitly instantiated etc.
12514 if (!FD->isUserProvided())
12515 return GVA_DiscardableODR;
12516
12518 switch (FD->getTemplateSpecializationKind()) {
12519 case TSK_Undeclared:
12522 break;
12523
12525 return GVA_StrongODR;
12526
12527 // C++11 [temp.explicit]p10:
12528 // [ Note: The intent is that an inline function that is the subject of
12529 // an explicit instantiation declaration will still be implicitly
12530 // instantiated when used so that the body can be considered for
12531 // inlining, but that no out-of-line copy of the inline function would be
12532 // generated in the translation unit. -- end note ]
12535
12538 break;
12539 }
12540
12541 if (!FD->isInlined())
12542 return External;
12543
12544 if ((!Context.getLangOpts().CPlusPlus &&
12545 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12546 !FD->hasAttr<DLLExportAttr>()) ||
12547 FD->hasAttr<GNUInlineAttr>()) {
12548 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
12549
12550 // GNU or C99 inline semantics. Determine whether this symbol should be
12551 // externally visible.
12553 return External;
12554
12555 // C99 inline semantics, where the symbol is not externally visible.
12557 }
12558
12559 // Functions specified with extern and inline in -fms-compatibility mode
12560 // forcibly get emitted. While the body of the function cannot be later
12561 // replaced, the function definition cannot be discarded.
12562 if (FD->isMSExternInline())
12563 return GVA_StrongODR;
12564
12565 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12566 isa<CXXConstructorDecl>(FD) &&
12567 cast<CXXConstructorDecl>(FD)->isInheritingConstructor())
12568 // Our approach to inheriting constructors is fundamentally different from
12569 // that used by the MS ABI, so keep our inheriting constructor thunks
12570 // internal rather than trying to pick an unambiguous mangling for them.
12571 return GVA_Internal;
12572
12573 return GVA_DiscardableODR;
12574}
12575
12577 const Decl *D, GVALinkage L) {
12578 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
12579 // dllexport/dllimport on inline functions.
12580 if (D->hasAttr<DLLImportAttr>()) {
12581 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
12583 } else if (D->hasAttr<DLLExportAttr>()) {
12584 if (L == GVA_DiscardableODR)
12585 return GVA_StrongODR;
12586 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
12587 // Device-side functions with __global__ attribute must always be
12588 // visible externally so they can be launched from host.
12589 if (D->hasAttr<CUDAGlobalAttr>() &&
12590 (L == GVA_DiscardableODR || L == GVA_Internal))
12591 return GVA_StrongODR;
12592 // Single source offloading languages like CUDA/HIP need to be able to
12593 // access static device variables from host code of the same compilation
12594 // unit. This is done by externalizing the static variable with a shared
12595 // name between the host and device compilation which is the same for the
12596 // same compilation unit whereas different among different compilation
12597 // units.
12598 if (Context.shouldExternalize(D))
12599 return GVA_StrongExternal;
12600 }
12601 return L;
12602}
12603
12604/// Adjust the GVALinkage for a declaration based on what an external AST source
12605/// knows about whether there can be other definitions of this declaration.
12606static GVALinkage
12608 GVALinkage L) {
12609 ExternalASTSource *Source = Ctx.getExternalSource();
12610 if (!Source)
12611 return L;
12612
12613 switch (Source->hasExternalDefinitions(D)) {
12615 // Other translation units rely on us to provide the definition.
12616 if (L == GVA_DiscardableODR)
12617 return GVA_StrongODR;
12618 break;
12619
12622
12624 break;
12625 }
12626 return L;
12627}
12628
12632 basicGVALinkageForFunction(*this, FD)));
12633}
12634
12636 const VarDecl *VD) {
12637 // As an extension for interactive REPLs, make sure constant variables are
12638 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
12639 // marking them as internal.
12640 if (Context.getLangOpts().CPlusPlus &&
12641 Context.getLangOpts().IncrementalExtensions &&
12642 VD->getType().isConstQualified() &&
12643 !VD->getType().isVolatileQualified() && !VD->isInline() &&
12644 !isa<VarTemplateSpecializationDecl>(VD) && !VD->getDescribedVarTemplate())
12645 return GVA_DiscardableODR;
12646
12647 if (!VD->isExternallyVisible())
12648 return GVA_Internal;
12649
12650 if (VD->isStaticLocal()) {
12651 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
12652 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
12653 LexicalContext = LexicalContext->getLexicalParent();
12654
12655 // ObjC Blocks can create local variables that don't have a FunctionDecl
12656 // LexicalContext.
12657 if (!LexicalContext)
12658 return GVA_DiscardableODR;
12659
12660 // Otherwise, let the static local variable inherit its linkage from the
12661 // nearest enclosing function.
12662 auto StaticLocalLinkage =
12663 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
12664
12665 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
12666 // be emitted in any object with references to the symbol for the object it
12667 // contains, whether inline or out-of-line."
12668 // Similar behavior is observed with MSVC. An alternative ABI could use
12669 // StrongODR/AvailableExternally to match the function, but none are
12670 // known/supported currently.
12671 if (StaticLocalLinkage == GVA_StrongODR ||
12672 StaticLocalLinkage == GVA_AvailableExternally)
12673 return GVA_DiscardableODR;
12674 return StaticLocalLinkage;
12675 }
12676
12677 // MSVC treats in-class initialized static data members as definitions.
12678 // By giving them non-strong linkage, out-of-line definitions won't
12679 // cause link errors.
12681 return GVA_DiscardableODR;
12682
12683 // Most non-template variables have strong linkage; inline variables are
12684 // linkonce_odr or (occasionally, for compatibility) weak_odr.
12685 GVALinkage StrongLinkage;
12686 switch (Context.getInlineVariableDefinitionKind(VD)) {
12688 StrongLinkage = GVA_StrongExternal;
12689 break;
12692 StrongLinkage = GVA_DiscardableODR;
12693 break;
12695 StrongLinkage = GVA_StrongODR;
12696 break;
12697 }
12698
12699 switch (VD->getTemplateSpecializationKind()) {
12700 case TSK_Undeclared:
12701 return StrongLinkage;
12702
12704 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12705 VD->isStaticDataMember()
12707 : StrongLinkage;
12708
12710 return GVA_StrongODR;
12711
12714
12716 return GVA_DiscardableODR;
12717 }
12718
12719 llvm_unreachable("Invalid Linkage!");
12720}
12721
12725 basicGVALinkageForVariable(*this, VD)));
12726}
12727
12729 if (const auto *VD = dyn_cast<VarDecl>(D)) {
12730 if (!VD->isFileVarDecl())
12731 return false;
12732 // Global named register variables (GNU extension) are never emitted.
12733 if (VD->getStorageClass() == SC_Register)
12734 return false;
12735 if (VD->getDescribedVarTemplate() ||
12736 isa<VarTemplatePartialSpecializationDecl>(VD))
12737 return false;
12738 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
12739 // We never need to emit an uninstantiated function template.
12740 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12741 return false;
12742 } else if (isa<PragmaCommentDecl>(D))
12743 return true;
12744 else if (isa<PragmaDetectMismatchDecl>(D))
12745 return true;
12746 else if (isa<OMPRequiresDecl>(D))
12747 return true;
12748 else if (isa<OMPThreadPrivateDecl>(D))
12749 return !D->getDeclContext()->isDependentContext();
12750 else if (isa<OMPAllocateDecl>(D))
12751 return !D->getDeclContext()->isDependentContext();
12752 else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D))
12753 return !D->getDeclContext()->isDependentContext();
12754 else if (isa<ImportDecl>(D))
12755 return true;
12756 else
12757 return false;
12758
12759 // If this is a member of a class template, we do not need to emit it.
12761 return false;
12762
12763 // Weak references don't produce any output by themselves.
12764 if (D->hasAttr<WeakRefAttr>())
12765 return false;
12766
12767 // Aliases and used decls are required.
12768 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
12769 return true;
12770
12771 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
12772 // Forward declarations aren't required.
12773 if (!FD->doesThisDeclarationHaveABody())
12774 return FD->doesDeclarationForceExternallyVisibleDefinition();
12775
12776 // Constructors and destructors are required.
12777 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
12778 return true;
12779
12780 // The key function for a class is required. This rule only comes
12781 // into play when inline functions can be key functions, though.
12782 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
12783 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
12784 const CXXRecordDecl *RD = MD->getParent();
12785 if (MD->isOutOfLine() && RD->isDynamicClass()) {
12786 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
12787 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
12788 return true;
12789 }
12790 }
12791 }
12792
12794
12795 // static, static inline, always_inline, and extern inline functions can
12796 // always be deferred. Normal inline functions can be deferred in C99/C++.
12797 // Implicit template instantiations can also be deferred in C++.
12799 }
12800
12801 const auto *VD = cast<VarDecl>(D);
12802 assert(VD->isFileVarDecl() && "Expected file scoped var");
12803
12804 // If the decl is marked as `declare target to`, it should be emitted for the
12805 // host and for the device.
12806 if (LangOpts.OpenMP &&
12807 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
12808 return true;
12809
12810 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
12812 return false;
12813
12814 if (VD->shouldEmitInExternalSource())
12815 return false;
12816
12817 // Variables that can be needed in other TUs are required.
12820 return true;
12821
12822 // We never need to emit a variable that is available in another TU.
12824 return false;
12825
12826 // Variables that have destruction with side-effects are required.
12827 if (VD->needsDestruction(*this))
12828 return true;
12829
12830 // Variables that have initialization with side-effects are required.
12831 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
12832 // We can get a value-dependent initializer during error recovery.
12833 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
12834 return true;
12835
12836 // Likewise, variables with tuple-like bindings are required if their
12837 // bindings have side-effects.
12838 if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
12839 for (const auto *BD : DD->bindings())
12840 if (const auto *BindingVD = BD->getHoldingVar())
12841 if (DeclMustBeEmitted(BindingVD))
12842 return true;
12843
12844 return false;
12845}
12846
12848 const FunctionDecl *FD,
12849 llvm::function_ref<void(FunctionDecl *)> Pred) const {
12850 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
12851 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
12852 FD = FD->getMostRecentDecl();
12853 // FIXME: The order of traversal here matters and depends on the order of
12854 // lookup results, which happens to be (mostly) oldest-to-newest, but we
12855 // shouldn't rely on that.
12856 for (auto *CurDecl :
12858 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
12859 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
12860 SeenDecls.insert(CurFD).second) {
12861 Pred(CurFD);
12862 }
12863 }
12864}
12865
12867 bool IsCXXMethod,
12868 bool IsBuiltin) const {
12869 // Pass through to the C++ ABI object
12870 if (IsCXXMethod)
12871 return ABI->getDefaultMethodCallConv(IsVariadic);
12872
12873 // Builtins ignore user-specified default calling convention and remain the
12874 // Target's default calling convention.
12875 if (!IsBuiltin) {
12876 switch (LangOpts.getDefaultCallingConv()) {
12878 break;
12880 return CC_C;
12882 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
12883 return CC_X86FastCall;
12884 break;
12886 if (!IsVariadic)
12887 return CC_X86StdCall;
12888 break;
12890 // __vectorcall cannot be applied to variadic functions.
12891 if (!IsVariadic)
12892 return CC_X86VectorCall;
12893 break;
12895 // __regcall cannot be applied to variadic functions.
12896 if (!IsVariadic)
12897 return CC_X86RegCall;
12898 break;
12900 if (!IsVariadic)
12901 return CC_M68kRTD;
12902 break;
12903 }
12904 }
12905 return Target->getDefaultCallingConv();
12906}
12907
12909 // Pass through to the C++ ABI object
12910 return ABI->isNearlyEmpty(RD);
12911}
12912
12914 if (!VTContext.get()) {
12915 auto ABI = Target->getCXXABI();
12916 if (ABI.isMicrosoft())
12917 VTContext.reset(new MicrosoftVTableContext(*this));
12918 else {
12919 auto ComponentLayout = getLangOpts().RelativeCXXABIVTables
12922 VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout));
12923 }
12924 }
12925 return VTContext.get();
12926}
12927
12929 if (!T)
12930 T = Target;
12931 switch (T->getCXXABI().getKind()) {
12932 case TargetCXXABI::AppleARM64:
12933 case TargetCXXABI::Fuchsia:
12934 case TargetCXXABI::GenericAArch64:
12935 case TargetCXXABI::GenericItanium:
12936 case TargetCXXABI::GenericARM:
12937 case TargetCXXABI::GenericMIPS:
12938 case TargetCXXABI::iOS:
12939 case TargetCXXABI::WebAssembly:
12940 case TargetCXXABI::WatchOS:
12941 case TargetCXXABI::XL:
12943 case TargetCXXABI::Microsoft:
12945 }
12946 llvm_unreachable("Unsupported ABI");
12947}
12948
12950 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
12951 "Device mangle context does not support Microsoft mangling.");
12952 switch (T.getCXXABI().getKind()) {
12953 case TargetCXXABI::AppleARM64:
12954 case TargetCXXABI::Fuchsia:
12955 case TargetCXXABI::GenericAArch64:
12956 case TargetCXXABI::GenericItanium:
12957 case TargetCXXABI::GenericARM:
12958 case TargetCXXABI::GenericMIPS:
12959 case TargetCXXABI::iOS:
12960 case TargetCXXABI::WebAssembly:
12961 case TargetCXXABI::WatchOS:
12962 case TargetCXXABI::XL:
12964 *this, getDiagnostics(),
12965 [](ASTContext &, const NamedDecl *ND) -> std::optional<unsigned> {
12966 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
12967 return RD->getDeviceLambdaManglingNumber();
12968 return std::nullopt;
12969 },
12970 /*IsAux=*/true);
12971 case TargetCXXABI::Microsoft:
12973 /*IsAux=*/true);
12974 }
12975 llvm_unreachable("Unsupported ABI");
12976}
12977
12978CXXABI::~CXXABI() = default;
12979
12981 return ASTRecordLayouts.getMemorySize() +
12982 llvm::capacity_in_bytes(ObjCLayouts) +
12983 llvm::capacity_in_bytes(KeyFunctions) +
12984 llvm::capacity_in_bytes(ObjCImpls) +
12985 llvm::capacity_in_bytes(BlockVarCopyInits) +
12986 llvm::capacity_in_bytes(DeclAttrs) +
12987 llvm::capacity_in_bytes(TemplateOrInstantiation) +
12988 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
12989 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
12990 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
12991 llvm::capacity_in_bytes(OverriddenMethods) +
12992 llvm::capacity_in_bytes(Types) +
12993 llvm::capacity_in_bytes(VariableArrayTypes);
12994}
12995
12996/// getIntTypeForBitwidth -
12997/// sets integer QualTy according to specified details:
12998/// bitwidth, signed/unsigned.
12999/// Returns empty type if there is no appropriate target types.
13001 unsigned Signed) const {
13003 CanQualType QualTy = getFromTargetType(Ty);
13004 if (!QualTy && DestWidth == 128)
13005 return Signed ? Int128Ty : UnsignedInt128Ty;
13006 return QualTy;
13007}
13008
13009/// getRealTypeForBitwidth -
13010/// sets floating point QualTy according to specified bitwidth.
13011/// Returns empty type if there is no appropriate target types.
13013 FloatModeKind ExplicitType) const {
13014 FloatModeKind Ty =
13015 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
13016 switch (Ty) {
13018 return HalfTy;
13020 return FloatTy;
13022 return DoubleTy;
13024 return LongDoubleTy;
13026 return Float128Ty;
13028 return Ibm128Ty;
13030 return {};
13031 }
13032
13033 llvm_unreachable("Unhandled TargetInfo::RealType value");
13034}
13035
13036void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
13037 if (Number <= 1)
13038 return;
13039
13040 MangleNumbers[ND] = Number;
13041
13042 if (Listener)
13043 Listener->AddedManglingNumber(ND, Number);
13044}
13045
13047 bool ForAuxTarget) const {
13048 auto I = MangleNumbers.find(ND);
13049 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
13050 // CUDA/HIP host compilation encodes host and device mangling numbers
13051 // as lower and upper half of 32 bit integer.
13052 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
13053 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
13054 } else {
13055 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
13056 "number for aux target");
13057 }
13058 return Res > 1 ? Res : 1;
13059}
13060
13061void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
13062 if (Number <= 1)
13063 return;
13064
13065 StaticLocalNumbers[VD] = Number;
13066
13067 if (Listener)
13068 Listener->AddedStaticLocalNumbers(VD, Number);
13069}
13070
13072 auto I = StaticLocalNumbers.find(VD);
13073 return I != StaticLocalNumbers.end() ? I->second : 1;
13074}
13075
13078 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13079 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
13080 if (!MCtx)
13082 return *MCtx;
13083}
13084
13087 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13088 std::unique_ptr<MangleNumberingContext> &MCtx =
13089 ExtraMangleNumberingContexts[D];
13090 if (!MCtx)
13092 return *MCtx;
13093}
13094
13095std::unique_ptr<MangleNumberingContext>
13097 return ABI->createMangleNumberingContext();
13098}
13099
13100const CXXConstructorDecl *
13102 return ABI->getCopyConstructorForExceptionObject(
13103 cast<CXXRecordDecl>(RD->getFirstDecl()));
13104}
13105
13107 CXXConstructorDecl *CD) {
13108 return ABI->addCopyConstructorForExceptionObject(
13109 cast<CXXRecordDecl>(RD->getFirstDecl()),
13110 cast<CXXConstructorDecl>(CD->getFirstDecl()));
13111}
13112
13114 TypedefNameDecl *DD) {
13115 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
13116}
13117
13120 return ABI->getTypedefNameForUnnamedTagDecl(TD);
13121}
13122
13124 DeclaratorDecl *DD) {
13125 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
13126}
13127
13129 return ABI->getDeclaratorForUnnamedTagDecl(TD);
13130}
13131
13132void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
13133 ParamIndices[D] = index;
13134}
13135
13137 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
13138 assert(I != ParamIndices.end() &&
13139 "ParmIndices lacks entry set by ParmVarDecl");
13140 return I->second;
13141}
13142
13144 unsigned Length) const {
13145 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
13146 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
13147 EltTy = EltTy.withConst();
13148
13149 EltTy = adjustStringLiteralBaseType(EltTy);
13150
13151 // Get an array type for the string, according to C99 6.4.5. This includes
13152 // the null terminator character.
13153 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
13154 ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
13155}
13156
13159 StringLiteral *&Result = StringLiteralCache[Key];
13160 if (!Result)
13162 *this, Key, StringLiteralKind::Ordinary,
13163 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
13164 SourceLocation());
13165 return Result;
13166}
13167
13168MSGuidDecl *
13170 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
13171
13172 llvm::FoldingSetNodeID ID;
13173 MSGuidDecl::Profile(ID, Parts);
13174
13175 void *InsertPos;
13176 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
13177 return Existing;
13178
13179 QualType GUIDType = getMSGuidType().withConst();
13180 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
13181 MSGuidDecls.InsertNode(New, InsertPos);
13182 return New;
13183}
13184
13187 const APValue &APVal) const {
13188 llvm::FoldingSetNodeID ID;
13190
13191 void *InsertPos;
13192 if (UnnamedGlobalConstantDecl *Existing =
13193 UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos))
13194 return Existing;
13195
13197 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
13198 UnnamedGlobalConstantDecls.InsertNode(New, InsertPos);
13199 return New;
13200}
13201
13204 assert(T->isRecordType() && "template param object of unexpected type");
13205
13206 // C++ [temp.param]p8:
13207 // [...] a static storage duration object of type 'const T' [...]
13208 T.addConst();
13209
13210 llvm::FoldingSetNodeID ID;
13212
13213 void *InsertPos;
13214 if (TemplateParamObjectDecl *Existing =
13215 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
13216 return Existing;
13217
13218 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
13219 TemplateParamObjectDecls.InsertNode(New, InsertPos);
13220 return New;
13221}
13222
13224 const llvm::Triple &T = getTargetInfo().getTriple();
13225 if (!T.isOSDarwin())
13226 return false;
13227
13228 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
13229 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
13230 return false;
13231
13232 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
13233 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
13234 uint64_t Size = sizeChars.getQuantity();
13235 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
13236 unsigned Align = alignChars.getQuantity();
13237 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
13238 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
13239}
13240
13241bool
13243 const ObjCMethodDecl *MethodImpl) {
13244 // No point trying to match an unavailable/deprecated mothod.
13245 if (MethodDecl->hasAttr<UnavailableAttr>()
13246 || MethodDecl->hasAttr<DeprecatedAttr>())
13247 return false;
13248 if (MethodDecl->getObjCDeclQualifier() !=
13249 MethodImpl->getObjCDeclQualifier())
13250 return false;
13251 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
13252 return false;
13253
13254 if (MethodDecl->param_size() != MethodImpl->param_size())
13255 return false;
13256
13257 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
13258 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
13259 EF = MethodDecl->param_end();
13260 IM != EM && IF != EF; ++IM, ++IF) {
13261 const ParmVarDecl *DeclVar = (*IF);
13262 const ParmVarDecl *ImplVar = (*IM);
13263 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
13264 return false;
13265 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
13266 return false;
13267 }
13268
13269 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
13270}
13271
13273 LangAS AS;
13275 AS = LangAS::Default;
13276 else
13277 AS = QT->getPointeeType().getAddressSpace();
13278
13280}
13281
13284}
13285
13286bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
13287 if (X == Y)
13288 return true;
13289 if (!X || !Y)
13290 return false;
13291 llvm::FoldingSetNodeID IDX, IDY;
13292 X->Profile(IDX, *this, /*Canonical=*/true);
13293 Y->Profile(IDY, *this, /*Canonical=*/true);
13294 return IDX == IDY;
13295}
13296
13297// The getCommon* helpers return, for given 'same' X and Y entities given as
13298// inputs, another entity which is also the 'same' as the inputs, but which
13299// is closer to the canonical form of the inputs, each according to a given
13300// criteria.
13301// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
13302// the regular ones.
13303
13305 if (!declaresSameEntity(X, Y))
13306 return nullptr;
13307 for (const Decl *DX : X->redecls()) {
13308 // If we reach Y before reaching the first decl, that means X is older.
13309 if (DX == Y)
13310 return X;
13311 // If we reach the first decl, then Y is older.
13312 if (DX->isFirstDecl())
13313 return Y;
13314 }
13315 llvm_unreachable("Corrupt redecls chain");
13316}
13317
13318template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13319static T *getCommonDecl(T *X, T *Y) {
13320 return cast_or_null<T>(
13321 getCommonDecl(const_cast<Decl *>(cast_or_null<Decl>(X)),
13322 const_cast<Decl *>(cast_or_null<Decl>(Y))));
13323}
13324
13325template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13326static T *getCommonDeclChecked(T *X, T *Y) {
13327 return cast<T>(getCommonDecl(const_cast<Decl *>(cast<Decl>(X)),
13328 const_cast<Decl *>(cast<Decl>(Y))));
13329}
13330
13332 TemplateName Y,
13333 bool IgnoreDeduced = false) {
13334 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
13335 return X;
13336 // FIXME: There are cases here where we could find a common template name
13337 // with more sugar. For example one could be a SubstTemplateTemplate*
13338 // replacing the other.
13339 TemplateName CX = Ctx.getCanonicalTemplateName(X, IgnoreDeduced);
13340 if (CX.getAsVoidPointer() !=
13342 return TemplateName();
13343 return CX;
13344}
13345
13348 bool IgnoreDeduced) {
13349 TemplateName R = getCommonTemplateName(Ctx, X, Y, IgnoreDeduced);
13350 assert(R.getAsVoidPointer() != nullptr);
13351 return R;
13352}
13353
13355 ArrayRef<QualType> Ys, bool Unqualified = false) {
13356 assert(Xs.size() == Ys.size());
13357 SmallVector<QualType, 8> Rs(Xs.size());
13358 for (size_t I = 0; I < Rs.size(); ++I)
13359 Rs[I] = Ctx.getCommonSugaredType(Xs[I], Ys[I], Unqualified);
13360 return Rs;
13361}
13362
13363template <class T>
13364static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
13365 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
13366 : SourceLocation();
13367}
13368
13370 const TemplateArgument &X,
13371 const TemplateArgument &Y) {
13372 if (X.getKind() != Y.getKind())
13373 return TemplateArgument();
13374
13375 switch (X.getKind()) {
13377 if (!Ctx.hasSameType(X.getAsType(), Y.getAsType()))
13378 return TemplateArgument();
13379 return TemplateArgument(
13380 Ctx.getCommonSugaredType(X.getAsType(), Y.getAsType()));
13382 if (!Ctx.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
13383 return TemplateArgument();
13384 return TemplateArgument(
13385 Ctx.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
13386 /*Unqualified=*/true);
13388 if (!Ctx.hasSameType(X.getAsExpr()->getType(), Y.getAsExpr()->getType()))
13389 return TemplateArgument();
13390 // FIXME: Try to keep the common sugar.
13391 return X;
13393 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
13394 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13395 if (!CTN.getAsVoidPointer())
13396 return TemplateArgument();
13397 return TemplateArgument(CTN);
13398 }
13400 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
13402 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13403 if (!CTN.getAsVoidPointer())
13404 return TemplateName();
13405 auto NExpX = X.getNumTemplateExpansions();
13406 assert(NExpX == Y.getNumTemplateExpansions());
13407 return TemplateArgument(CTN, NExpX);
13408 }
13409 default:
13410 // FIXME: Handle the other argument kinds.
13411 return X;
13412 }
13413}
13414
13419 if (Xs.size() != Ys.size())
13420 return true;
13421 R.resize(Xs.size());
13422 for (size_t I = 0; I < R.size(); ++I) {
13423 R[I] = getCommonTemplateArgument(Ctx, Xs[I], Ys[I]);
13424 if (R[I].isNull())
13425 return true;
13426 }
13427 return false;
13428}
13429
13434 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
13435 assert(!Different);
13436 (void)Different;
13437 return R;
13438}
13439
13440template <class T>
13442 return X->getKeyword() == Y->getKeyword() ? X->getKeyword()
13444}
13445
13446template <class T>
13448 const T *Y) {
13449 // FIXME: Try to keep the common NNS sugar.
13450 return X->getQualifier() == Y->getQualifier()
13451 ? X->getQualifier()
13452 : Ctx.getCanonicalNestedNameSpecifier(X->getQualifier());
13453}
13454
13455template <class T>
13456static QualType getCommonElementType(ASTContext &Ctx, const T *X, const T *Y) {
13457 return Ctx.getCommonSugaredType(X->getElementType(), Y->getElementType());
13458}
13459
13460template <class T>
13462 Qualifiers &QX, const T *Y,
13463 Qualifiers &QY) {
13464 QualType EX = X->getElementType(), EY = Y->getElementType();
13465 QualType R = Ctx.getCommonSugaredType(EX, EY,
13466 /*Unqualified=*/true);
13467 Qualifiers RQ = R.getQualifiers();
13468 QX += EX.getQualifiers() - RQ;
13469 QY += EY.getQualifiers() - RQ;
13470 return R;
13471}
13472
13473template <class T>
13474static QualType getCommonPointeeType(ASTContext &Ctx, const T *X, const T *Y) {
13475 return Ctx.getCommonSugaredType(X->getPointeeType(), Y->getPointeeType());
13476}
13477
13478template <class T> static auto *getCommonSizeExpr(ASTContext &Ctx, T *X, T *Y) {
13479 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
13480 return X->getSizeExpr();
13481}
13482
13483static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
13484 assert(X->getSizeModifier() == Y->getSizeModifier());
13485 return X->getSizeModifier();
13486}
13487
13489 const ArrayType *Y) {
13490 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
13491 return X->getIndexTypeCVRQualifiers();
13492}
13493
13494// Merges two type lists such that the resulting vector will contain
13495// each type (in a canonical sense) only once, in the order they appear
13496// from X to Y. If they occur in both X and Y, the result will contain
13497// the common sugared type between them.
13500 llvm::DenseMap<QualType, unsigned> Found;
13501 for (auto Ts : {X, Y}) {
13502 for (QualType T : Ts) {
13503 auto Res = Found.try_emplace(Ctx.getCanonicalType(T), Out.size());
13504 if (!Res.second) {
13505 QualType &U = Out[Res.first->second];
13506 U = Ctx.getCommonSugaredType(U, T);
13507 } else {
13508 Out.emplace_back(T);
13509 }
13510 }
13511 }
13512}
13513
13517 SmallVectorImpl<QualType> &ExceptionTypeStorage,
13518 bool AcceptDependent) {
13519 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
13520
13521 // If either of them can throw anything, that is the result.
13522 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
13523 if (EST1 == I)
13524 return ESI1;
13525 if (EST2 == I)
13526 return ESI2;
13527 }
13528
13529 // If either of them is non-throwing, the result is the other.
13530 for (auto I :
13532 if (EST1 == I)
13533 return ESI2;
13534 if (EST2 == I)
13535 return ESI1;
13536 }
13537
13538 // If we're left with value-dependent computed noexcept expressions, we're
13539 // stuck. Before C++17, we can just drop the exception specification entirely,
13540 // since it's not actually part of the canonical type. And this should never
13541 // happen in C++17, because it would mean we were computing the composite
13542 // pointer type of dependent types, which should never happen.
13543 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
13544 assert(AcceptDependent &&
13545 "computing composite pointer type of dependent types");
13547 }
13548
13549 // Switch over the possibilities so that people adding new values know to
13550 // update this function.
13551 switch (EST1) {
13552 case EST_None:
13553 case EST_DynamicNone:
13554 case EST_MSAny:
13555 case EST_BasicNoexcept:
13557 case EST_NoexceptFalse:
13558 case EST_NoexceptTrue:
13559 case EST_NoThrow:
13560 llvm_unreachable("These ESTs should be handled above");
13561
13562 case EST_Dynamic: {
13563 // This is the fun case: both exception specifications are dynamic. Form
13564 // the union of the two lists.
13565 assert(EST2 == EST_Dynamic && "other cases should already be handled");
13566 mergeTypeLists(*this, ExceptionTypeStorage, ESI1.Exceptions,
13567 ESI2.Exceptions);
13569 Result.Exceptions = ExceptionTypeStorage;
13570 return Result;
13571 }
13572
13573 case EST_Unevaluated:
13574 case EST_Uninstantiated:
13575 case EST_Unparsed:
13576 llvm_unreachable("shouldn't see unresolved exception specifications here");
13577 }
13578
13579 llvm_unreachable("invalid ExceptionSpecificationType");
13580}
13581
13583 Qualifiers &QX, const Type *Y,
13584 Qualifiers &QY) {
13585 Type::TypeClass TC = X->getTypeClass();
13586 assert(TC == Y->getTypeClass());
13587 switch (TC) {
13588#define UNEXPECTED_TYPE(Class, Kind) \
13589 case Type::Class: \
13590 llvm_unreachable("Unexpected " Kind ": " #Class);
13591
13592#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
13593#define TYPE(Class, Base)
13594#include "clang/AST/TypeNodes.inc"
13595
13596#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
13597 SUGAR_FREE_TYPE(Builtin)
13598 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
13599 SUGAR_FREE_TYPE(DependentBitInt)
13602 SUGAR_FREE_TYPE(ObjCInterface)
13604 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
13605 SUGAR_FREE_TYPE(UnresolvedUsing)
13606 SUGAR_FREE_TYPE(HLSLAttributedResource)
13607#undef SUGAR_FREE_TYPE
13608#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
13609 NON_UNIQUE_TYPE(TypeOfExpr)
13610 NON_UNIQUE_TYPE(VariableArray)
13611#undef NON_UNIQUE_TYPE
13612
13613 UNEXPECTED_TYPE(TypeOf, "sugar")
13614
13615#undef UNEXPECTED_TYPE
13616
13617 case Type::Auto: {
13618 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
13619 assert(AX->getDeducedType().isNull());
13620 assert(AY->getDeducedType().isNull());
13621 assert(AX->getKeyword() == AY->getKeyword());
13622 assert(AX->isInstantiationDependentType() ==
13623 AY->isInstantiationDependentType());
13624 auto As = getCommonTemplateArguments(Ctx, AX->getTypeConstraintArguments(),
13625 AY->getTypeConstraintArguments());
13626 return Ctx.getAutoType(QualType(), AX->getKeyword(),
13628 AX->containsUnexpandedParameterPack(),
13629 getCommonDeclChecked(AX->getTypeConstraintConcept(),
13630 AY->getTypeConstraintConcept()),
13631 As);
13632 }
13633 case Type::IncompleteArray: {
13634 const auto *AX = cast<IncompleteArrayType>(X),
13635 *AY = cast<IncompleteArrayType>(Y);
13636 return Ctx.getIncompleteArrayType(
13637 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
13639 }
13640 case Type::DependentSizedArray: {
13641 const auto *AX = cast<DependentSizedArrayType>(X),
13642 *AY = cast<DependentSizedArrayType>(Y);
13643 return Ctx.getDependentSizedArrayType(
13644 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
13645 getCommonSizeExpr(Ctx, AX, AY), getCommonSizeModifier(AX, AY),
13647 AX->getBracketsRange() == AY->getBracketsRange()
13648 ? AX->getBracketsRange()
13649 : SourceRange());
13650 }
13651 case Type::ConstantArray: {
13652 const auto *AX = cast<ConstantArrayType>(X),
13653 *AY = cast<ConstantArrayType>(Y);
13654 assert(AX->getSize() == AY->getSize());
13655 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
13656 ? AX->getSizeExpr()
13657 : nullptr;
13658 return Ctx.getConstantArrayType(
13659 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
13661 }
13662 case Type::ArrayParameter: {
13663 const auto *AX = cast<ArrayParameterType>(X),
13664 *AY = cast<ArrayParameterType>(Y);
13665 assert(AX->getSize() == AY->getSize());
13666 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
13667 ? AX->getSizeExpr()
13668 : nullptr;
13669 auto ArrayTy = Ctx.getConstantArrayType(
13670 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
13672 return Ctx.getArrayParameterType(ArrayTy);
13673 }
13674 case Type::Atomic: {
13675 const auto *AX = cast<AtomicType>(X), *AY = cast<AtomicType>(Y);
13676 return Ctx.getAtomicType(
13677 Ctx.getCommonSugaredType(AX->getValueType(), AY->getValueType()));
13678 }
13679 case Type::Complex: {
13680 const auto *CX = cast<ComplexType>(X), *CY = cast<ComplexType>(Y);
13681 return Ctx.getComplexType(getCommonArrayElementType(Ctx, CX, QX, CY, QY));
13682 }
13683 case Type::Pointer: {
13684 const auto *PX = cast<PointerType>(X), *PY = cast<PointerType>(Y);
13685 return Ctx.getPointerType(getCommonPointeeType(Ctx, PX, PY));
13686 }
13687 case Type::BlockPointer: {
13688 const auto *PX = cast<BlockPointerType>(X), *PY = cast<BlockPointerType>(Y);
13689 return Ctx.getBlockPointerType(getCommonPointeeType(Ctx, PX, PY));
13690 }
13691 case Type::ObjCObjectPointer: {
13692 const auto *PX = cast<ObjCObjectPointerType>(X),
13693 *PY = cast<ObjCObjectPointerType>(Y);
13694 return Ctx.getObjCObjectPointerType(getCommonPointeeType(Ctx, PX, PY));
13695 }
13696 case Type::MemberPointer: {
13697 const auto *PX = cast<MemberPointerType>(X),
13698 *PY = cast<MemberPointerType>(Y);
13699 return Ctx.getMemberPointerType(
13700 getCommonPointeeType(Ctx, PX, PY),
13701 Ctx.getCommonSugaredType(QualType(PX->getClass(), 0),
13702 QualType(PY->getClass(), 0))
13703 .getTypePtr());
13704 }
13705 case Type::LValueReference: {
13706 const auto *PX = cast<LValueReferenceType>(X),
13707 *PY = cast<LValueReferenceType>(Y);
13708 // FIXME: Preserve PointeeTypeAsWritten.
13709 return Ctx.getLValueReferenceType(getCommonPointeeType(Ctx, PX, PY),
13710 PX->isSpelledAsLValue() ||
13711 PY->isSpelledAsLValue());
13712 }
13713 case Type::RValueReference: {
13714 const auto *PX = cast<RValueReferenceType>(X),
13715 *PY = cast<RValueReferenceType>(Y);
13716 // FIXME: Preserve PointeeTypeAsWritten.
13717 return Ctx.getRValueReferenceType(getCommonPointeeType(Ctx, PX, PY));
13718 }
13719 case Type::DependentAddressSpace: {
13720 const auto *PX = cast<DependentAddressSpaceType>(X),
13721 *PY = cast<DependentAddressSpaceType>(Y);
13722 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
13723 return Ctx.getDependentAddressSpaceType(getCommonPointeeType(Ctx, PX, PY),
13724 PX->getAddrSpaceExpr(),
13725 getCommonAttrLoc(PX, PY));
13726 }
13727 case Type::FunctionNoProto: {
13728 const auto *FX = cast<FunctionNoProtoType>(X),
13729 *FY = cast<FunctionNoProtoType>(Y);
13730 assert(FX->getExtInfo() == FY->getExtInfo());
13731 return Ctx.getFunctionNoProtoType(
13732 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType()),
13733 FX->getExtInfo());
13734 }
13735 case Type::FunctionProto: {
13736 const auto *FX = cast<FunctionProtoType>(X),
13737 *FY = cast<FunctionProtoType>(Y);
13738 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
13739 EPIY = FY->getExtProtoInfo();
13740 assert(EPIX.ExtInfo == EPIY.ExtInfo);
13741 assert(EPIX.ExtParameterInfos == EPIY.ExtParameterInfos);
13742 assert(EPIX.RefQualifier == EPIY.RefQualifier);
13743 assert(EPIX.TypeQuals == EPIY.TypeQuals);
13744 assert(EPIX.Variadic == EPIY.Variadic);
13745
13746 // FIXME: Can we handle an empty EllipsisLoc?
13747 // Use emtpy EllipsisLoc if X and Y differ.
13748
13749 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
13750
13751 QualType R =
13752 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType());
13753 auto P = getCommonTypes(Ctx, FX->param_types(), FY->param_types(),
13754 /*Unqualified=*/true);
13755
13756 SmallVector<QualType, 8> Exceptions;
13758 EPIX.ExceptionSpec, EPIY.ExceptionSpec, Exceptions, true);
13759 return Ctx.getFunctionType(R, P, EPIX);
13760 }
13761 case Type::ObjCObject: {
13762 const auto *OX = cast<ObjCObjectType>(X), *OY = cast<ObjCObjectType>(Y);
13763 assert(
13764 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
13765 OY->getProtocols().begin(), OY->getProtocols().end(),
13766 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
13767 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
13768 }) &&
13769 "protocol lists must be the same");
13770 auto TAs = getCommonTypes(Ctx, OX->getTypeArgsAsWritten(),
13771 OY->getTypeArgsAsWritten());
13772 return Ctx.getObjCObjectType(
13773 Ctx.getCommonSugaredType(OX->getBaseType(), OY->getBaseType()), TAs,
13774 OX->getProtocols(),
13775 OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
13776 }
13777 case Type::ConstantMatrix: {
13778 const auto *MX = cast<ConstantMatrixType>(X),
13779 *MY = cast<ConstantMatrixType>(Y);
13780 assert(MX->getNumRows() == MY->getNumRows());
13781 assert(MX->getNumColumns() == MY->getNumColumns());
13782 return Ctx.getConstantMatrixType(getCommonElementType(Ctx, MX, MY),
13783 MX->getNumRows(), MX->getNumColumns());
13784 }
13785 case Type::DependentSizedMatrix: {
13786 const auto *MX = cast<DependentSizedMatrixType>(X),
13787 *MY = cast<DependentSizedMatrixType>(Y);
13788 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
13789 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
13790 return Ctx.getDependentSizedMatrixType(
13791 getCommonElementType(Ctx, MX, MY), MX->getRowExpr(),
13792 MX->getColumnExpr(), getCommonAttrLoc(MX, MY));
13793 }
13794 case Type::Vector: {
13795 const auto *VX = cast<VectorType>(X), *VY = cast<VectorType>(Y);
13796 assert(VX->getNumElements() == VY->getNumElements());
13797 assert(VX->getVectorKind() == VY->getVectorKind());
13798 return Ctx.getVectorType(getCommonElementType(Ctx, VX, VY),
13799 VX->getNumElements(), VX->getVectorKind());
13800 }
13801 case Type::ExtVector: {
13802 const auto *VX = cast<ExtVectorType>(X), *VY = cast<ExtVectorType>(Y);
13803 assert(VX->getNumElements() == VY->getNumElements());
13804 return Ctx.getExtVectorType(getCommonElementType(Ctx, VX, VY),
13805 VX->getNumElements());
13806 }
13807 case Type::DependentSizedExtVector: {
13808 const auto *VX = cast<DependentSizedExtVectorType>(X),
13809 *VY = cast<DependentSizedExtVectorType>(Y);
13811 getCommonSizeExpr(Ctx, VX, VY),
13812 getCommonAttrLoc(VX, VY));
13813 }
13814 case Type::DependentVector: {
13815 const auto *VX = cast<DependentVectorType>(X),
13816 *VY = cast<DependentVectorType>(Y);
13817 assert(VX->getVectorKind() == VY->getVectorKind());
13818 return Ctx.getDependentVectorType(
13819 getCommonElementType(Ctx, VX, VY), getCommonSizeExpr(Ctx, VX, VY),
13820 getCommonAttrLoc(VX, VY), VX->getVectorKind());
13821 }
13822 case Type::InjectedClassName: {
13823 const auto *IX = cast<InjectedClassNameType>(X),
13824 *IY = cast<InjectedClassNameType>(Y);
13825 return Ctx.getInjectedClassNameType(
13826 getCommonDeclChecked(IX->getDecl(), IY->getDecl()),
13827 Ctx.getCommonSugaredType(IX->getInjectedSpecializationType(),
13828 IY->getInjectedSpecializationType()));
13829 }
13830 case Type::TemplateSpecialization: {
13831 const auto *TX = cast<TemplateSpecializationType>(X),
13832 *TY = cast<TemplateSpecializationType>(Y);
13833 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
13834 TY->template_arguments());
13836 ::getCommonTemplateNameChecked(Ctx, TX->getTemplateName(),
13837 TY->getTemplateName(),
13838 /*IgnoreDeduced=*/true),
13839 As, X->getCanonicalTypeInternal());
13840 }
13841 case Type::Decltype: {
13842 const auto *DX = cast<DecltypeType>(X);
13843 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Y);
13844 assert(DX->isDependentType());
13845 assert(DY->isDependentType());
13846 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
13847 // As Decltype is not uniqued, building a common type would be wasteful.
13848 return QualType(DX, 0);
13849 }
13850 case Type::PackIndexing: {
13851 const auto *DX = cast<PackIndexingType>(X);
13852 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Y);
13853 assert(DX->isDependentType());
13854 assert(DY->isDependentType());
13855 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
13856 return QualType(DX, 0);
13857 }
13858 case Type::DependentName: {
13859 const auto *NX = cast<DependentNameType>(X),
13860 *NY = cast<DependentNameType>(Y);
13861 assert(NX->getIdentifier() == NY->getIdentifier());
13862 return Ctx.getDependentNameType(
13863 getCommonTypeKeyword(NX, NY), getCommonNNS(Ctx, NX, NY),
13864 NX->getIdentifier(), NX->getCanonicalTypeInternal());
13865 }
13866 case Type::DependentTemplateSpecialization: {
13867 const auto *TX = cast<DependentTemplateSpecializationType>(X),
13868 *TY = cast<DependentTemplateSpecializationType>(Y);
13869 assert(TX->getIdentifier() == TY->getIdentifier());
13870 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
13871 TY->template_arguments());
13873 getCommonTypeKeyword(TX, TY), getCommonNNS(Ctx, TX, TY),
13874 TX->getIdentifier(), As);
13875 }
13876 case Type::UnaryTransform: {
13877 const auto *TX = cast<UnaryTransformType>(X),
13878 *TY = cast<UnaryTransformType>(Y);
13879 assert(TX->getUTTKind() == TY->getUTTKind());
13880 return Ctx.getUnaryTransformType(
13881 Ctx.getCommonSugaredType(TX->getBaseType(), TY->getBaseType()),
13882 Ctx.getCommonSugaredType(TX->getUnderlyingType(),
13883 TY->getUnderlyingType()),
13884 TX->getUTTKind());
13885 }
13886 case Type::PackExpansion: {
13887 const auto *PX = cast<PackExpansionType>(X),
13888 *PY = cast<PackExpansionType>(Y);
13889 assert(PX->getNumExpansions() == PY->getNumExpansions());
13890 return Ctx.getPackExpansionType(
13891 Ctx.getCommonSugaredType(PX->getPattern(), PY->getPattern()),
13892 PX->getNumExpansions(), false);
13893 }
13894 case Type::Pipe: {
13895 const auto *PX = cast<PipeType>(X), *PY = cast<PipeType>(Y);
13896 assert(PX->isReadOnly() == PY->isReadOnly());
13897 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
13899 return (Ctx.*MP)(getCommonElementType(Ctx, PX, PY));
13900 }
13901 case Type::TemplateTypeParm: {
13902 const auto *TX = cast<TemplateTypeParmType>(X),
13903 *TY = cast<TemplateTypeParmType>(Y);
13904 assert(TX->getDepth() == TY->getDepth());
13905 assert(TX->getIndex() == TY->getIndex());
13906 assert(TX->isParameterPack() == TY->isParameterPack());
13907 return Ctx.getTemplateTypeParmType(
13908 TX->getDepth(), TX->getIndex(), TX->isParameterPack(),
13909 getCommonDecl(TX->getDecl(), TY->getDecl()));
13910 }
13911 }
13912 llvm_unreachable("Unknown Type Class");
13913}
13914
13916 const Type *Y,
13917 SplitQualType Underlying) {
13918 Type::TypeClass TC = X->getTypeClass();
13919 if (TC != Y->getTypeClass())
13920 return QualType();
13921 switch (TC) {
13922#define UNEXPECTED_TYPE(Class, Kind) \
13923 case Type::Class: \
13924 llvm_unreachable("Unexpected " Kind ": " #Class);
13925#define TYPE(Class, Base)
13926#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
13927#include "clang/AST/TypeNodes.inc"
13928
13929#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
13932 CANONICAL_TYPE(BlockPointer)
13933 CANONICAL_TYPE(Builtin)
13935 CANONICAL_TYPE(ConstantArray)
13936 CANONICAL_TYPE(ArrayParameter)
13937 CANONICAL_TYPE(ConstantMatrix)
13939 CANONICAL_TYPE(ExtVector)
13940 CANONICAL_TYPE(FunctionNoProto)
13941 CANONICAL_TYPE(FunctionProto)
13942 CANONICAL_TYPE(IncompleteArray)
13943 CANONICAL_TYPE(HLSLAttributedResource)
13944 CANONICAL_TYPE(LValueReference)
13945 CANONICAL_TYPE(MemberPointer)
13946 CANONICAL_TYPE(ObjCInterface)
13947 CANONICAL_TYPE(ObjCObject)
13948 CANONICAL_TYPE(ObjCObjectPointer)
13952 CANONICAL_TYPE(RValueReference)
13953 CANONICAL_TYPE(VariableArray)
13955#undef CANONICAL_TYPE
13956
13957#undef UNEXPECTED_TYPE
13958
13959 case Type::Adjusted: {
13960 const auto *AX = cast<AdjustedType>(X), *AY = cast<AdjustedType>(Y);
13961 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
13962 if (!Ctx.hasSameType(OX, OY))
13963 return QualType();
13964 // FIXME: It's inefficient to have to unify the original types.
13965 return Ctx.getAdjustedType(Ctx.getCommonSugaredType(OX, OY),
13966 Ctx.getQualifiedType(Underlying));
13967 }
13968 case Type::Decayed: {
13969 const auto *DX = cast<DecayedType>(X), *DY = cast<DecayedType>(Y);
13970 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
13971 if (!Ctx.hasSameType(OX, OY))
13972 return QualType();
13973 // FIXME: It's inefficient to have to unify the original types.
13974 return Ctx.getDecayedType(Ctx.getCommonSugaredType(OX, OY),
13975 Ctx.getQualifiedType(Underlying));
13976 }
13977 case Type::Attributed: {
13978 const auto *AX = cast<AttributedType>(X), *AY = cast<AttributedType>(Y);
13979 AttributedType::Kind Kind = AX->getAttrKind();
13980 if (Kind != AY->getAttrKind())
13981 return QualType();
13982 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
13983 if (!Ctx.hasSameType(MX, MY))
13984 return QualType();
13985 // FIXME: It's inefficient to have to unify the modified types.
13986 return Ctx.getAttributedType(Kind, Ctx.getCommonSugaredType(MX, MY),
13987 Ctx.getQualifiedType(Underlying),
13988 AX->getAttr());
13989 }
13990 case Type::BTFTagAttributed: {
13991 const auto *BX = cast<BTFTagAttributedType>(X);
13992 const BTFTypeTagAttr *AX = BX->getAttr();
13993 // The attribute is not uniqued, so just compare the tag.
13994 if (AX->getBTFTypeTag() !=
13995 cast<BTFTagAttributedType>(Y)->getAttr()->getBTFTypeTag())
13996 return QualType();
13997 return Ctx.getBTFTagAttributedType(AX, Ctx.getQualifiedType(Underlying));
13998 }
13999 case Type::Auto: {
14000 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14001
14002 AutoTypeKeyword KW = AX->getKeyword();
14003 if (KW != AY->getKeyword())
14004 return QualType();
14005
14006 ConceptDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(),
14007 AY->getTypeConstraintConcept());
14009 if (CD &&
14010 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
14011 AY->getTypeConstraintArguments())) {
14012 CD = nullptr; // The arguments differ, so make it unconstrained.
14013 As.clear();
14014 }
14015
14016 // Both auto types can't be dependent, otherwise they wouldn't have been
14017 // sugar. This implies they can't contain unexpanded packs either.
14018 return Ctx.getAutoType(Ctx.getQualifiedType(Underlying), AX->getKeyword(),
14019 /*IsDependent=*/false, /*IsPack=*/false, CD, As);
14020 }
14021 case Type::PackIndexing:
14022 case Type::Decltype:
14023 return QualType();
14024 case Type::DeducedTemplateSpecialization:
14025 // FIXME: Try to merge these.
14026 return QualType();
14027
14028 case Type::Elaborated: {
14029 const auto *EX = cast<ElaboratedType>(X), *EY = cast<ElaboratedType>(Y);
14030 return Ctx.getElaboratedType(
14031 ::getCommonTypeKeyword(EX, EY), ::getCommonNNS(Ctx, EX, EY),
14032 Ctx.getQualifiedType(Underlying),
14033 ::getCommonDecl(EX->getOwnedTagDecl(), EY->getOwnedTagDecl()));
14034 }
14035 case Type::MacroQualified: {
14036 const auto *MX = cast<MacroQualifiedType>(X),
14037 *MY = cast<MacroQualifiedType>(Y);
14038 const IdentifierInfo *IX = MX->getMacroIdentifier();
14039 if (IX != MY->getMacroIdentifier())
14040 return QualType();
14041 return Ctx.getMacroQualifiedType(Ctx.getQualifiedType(Underlying), IX);
14042 }
14043 case Type::SubstTemplateTypeParm: {
14044 const auto *SX = cast<SubstTemplateTypeParmType>(X),
14045 *SY = cast<SubstTemplateTypeParmType>(Y);
14046 Decl *CD =
14047 ::getCommonDecl(SX->getAssociatedDecl(), SY->getAssociatedDecl());
14048 if (!CD)
14049 return QualType();
14050 unsigned Index = SX->getIndex();
14051 if (Index != SY->getIndex())
14052 return QualType();
14053 auto PackIndex = SX->getPackIndex();
14054 if (PackIndex != SY->getPackIndex())
14055 return QualType();
14056 return Ctx.getSubstTemplateTypeParmType(Ctx.getQualifiedType(Underlying),
14057 CD, Index, PackIndex);
14058 }
14059 case Type::ObjCTypeParam:
14060 // FIXME: Try to merge these.
14061 return QualType();
14062 case Type::Paren:
14063 return Ctx.getParenType(Ctx.getQualifiedType(Underlying));
14064
14065 case Type::TemplateSpecialization: {
14066 const auto *TX = cast<TemplateSpecializationType>(X),
14067 *TY = cast<TemplateSpecializationType>(Y);
14068 TemplateName CTN =
14069 ::getCommonTemplateName(Ctx, TX->getTemplateName(),
14070 TY->getTemplateName(), /*IgnoreDeduced=*/true);
14071 if (!CTN.getAsVoidPointer())
14072 return QualType();
14074 if (getCommonTemplateArguments(Ctx, Args, TX->template_arguments(),
14075 TY->template_arguments()))
14076 return QualType();
14077 return Ctx.getTemplateSpecializationType(CTN, Args,
14078 Ctx.getQualifiedType(Underlying));
14079 }
14080 case Type::Typedef: {
14081 const auto *TX = cast<TypedefType>(X), *TY = cast<TypedefType>(Y);
14082 const TypedefNameDecl *CD = ::getCommonDecl(TX->getDecl(), TY->getDecl());
14083 if (!CD)
14084 return QualType();
14085 return Ctx.getTypedefType(CD, Ctx.getQualifiedType(Underlying));
14086 }
14087 case Type::TypeOf: {
14088 // The common sugar between two typeof expressions, where one is
14089 // potentially a typeof_unqual and the other is not, we unify to the
14090 // qualified type as that retains the most information along with the type.
14091 // We only return a typeof_unqual type when both types are unqual types.
14093 if (cast<TypeOfType>(X)->getKind() == cast<TypeOfType>(Y)->getKind() &&
14094 cast<TypeOfType>(X)->getKind() == TypeOfKind::Unqualified)
14096 return Ctx.getTypeOfType(Ctx.getQualifiedType(Underlying), Kind);
14097 }
14098 case Type::TypeOfExpr:
14099 return QualType();
14100
14101 case Type::UnaryTransform: {
14102 const auto *UX = cast<UnaryTransformType>(X),
14103 *UY = cast<UnaryTransformType>(Y);
14104 UnaryTransformType::UTTKind KX = UX->getUTTKind();
14105 if (KX != UY->getUTTKind())
14106 return QualType();
14107 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
14108 if (!Ctx.hasSameType(BX, BY))
14109 return QualType();
14110 // FIXME: It's inefficient to have to unify the base types.
14111 return Ctx.getUnaryTransformType(Ctx.getCommonSugaredType(BX, BY),
14112 Ctx.getQualifiedType(Underlying), KX);
14113 }
14114 case Type::Using: {
14115 const auto *UX = cast<UsingType>(X), *UY = cast<UsingType>(Y);
14116 const UsingShadowDecl *CD =
14117 ::getCommonDecl(UX->getFoundDecl(), UY->getFoundDecl());
14118 if (!CD)
14119 return QualType();
14120 return Ctx.getUsingType(CD, Ctx.getQualifiedType(Underlying));
14121 }
14122 case Type::CountAttributed: {
14123 const auto *DX = cast<CountAttributedType>(X),
14124 *DY = cast<CountAttributedType>(Y);
14125 if (DX->isCountInBytes() != DY->isCountInBytes())
14126 return QualType();
14127 if (DX->isOrNull() != DY->isOrNull())
14128 return QualType();
14129 Expr *CEX = DX->getCountExpr();
14130 Expr *CEY = DY->getCountExpr();
14131 llvm::ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
14132 if (Ctx.hasSameExpr(CEX, CEY))
14133 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14134 DX->isCountInBytes(), DX->isOrNull(),
14135 CDX);
14136 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
14137 return QualType();
14138 // Two declarations with the same integer constant may still differ in their
14139 // expression pointers, so we need to evaluate them.
14140 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
14141 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
14142 if (VX != VY)
14143 return QualType();
14144 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14145 DX->isCountInBytes(), DX->isOrNull(),
14146 CDX);
14147 }
14148 }
14149 llvm_unreachable("Unhandled Type Class");
14150}
14151
14152static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
14154 while (true) {
14155 QTotal.addConsistentQualifiers(T.Quals);
14157 if (NT == QualType(T.Ty, 0))
14158 break;
14159 R.push_back(T);
14160 T = NT.split();
14161 }
14162 return R;
14163}
14164
14166 bool Unqualified) {
14167 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
14168 if (X == Y)
14169 return X;
14170 if (!Unqualified) {
14171 if (X.isCanonical())
14172 return X;
14173 if (Y.isCanonical())
14174 return Y;
14175 }
14176
14177 SplitQualType SX = X.split(), SY = Y.split();
14178 Qualifiers QX, QY;
14179 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
14180 // until we reach their underlying "canonical nodes". Note these are not
14181 // necessarily canonical types, as they may still have sugared properties.
14182 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
14183 auto Xs = ::unwrapSugar(SX, QX), Ys = ::unwrapSugar(SY, QY);
14184 if (SX.Ty != SY.Ty) {
14185 // The canonical nodes differ. Build a common canonical node out of the two,
14186 // unifying their sugar. This may recurse back here.
14187 SX.Ty =
14188 ::getCommonNonSugarTypeNode(*this, SX.Ty, QX, SY.Ty, QY).getTypePtr();
14189 } else {
14190 // The canonical nodes were identical: We may have desugared too much.
14191 // Add any common sugar back in.
14192 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
14193 QX -= SX.Quals;
14194 QY -= SY.Quals;
14195 SX = Xs.pop_back_val();
14196 SY = Ys.pop_back_val();
14197 }
14198 }
14199 if (Unqualified)
14201 else
14202 assert(QX == QY);
14203
14204 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
14205 // related. Walk up these nodes, unifying them and adding the result.
14206 while (!Xs.empty() && !Ys.empty()) {
14207 auto Underlying = SplitQualType(
14208 SX.Ty, Qualifiers::removeCommonQualifiers(SX.Quals, SY.Quals));
14209 SX = Xs.pop_back_val();
14210 SY = Ys.pop_back_val();
14211 SX.Ty = ::getCommonSugarTypeNode(*this, SX.Ty, SY.Ty, Underlying)
14213 // Stop at the first pair which is unrelated.
14214 if (!SX.Ty) {
14215 SX.Ty = Underlying.Ty;
14216 break;
14217 }
14218 QX -= Underlying.Quals;
14219 };
14220
14221 // Add back the missing accumulated qualifiers, which were stripped off
14222 // with the sugar nodes we could not unify.
14223 QualType R = getQualifiedType(SX.Ty, QX);
14224 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
14225 return R;
14226}
14227
14229 assert(Ty->isFixedPointType());
14230
14232 return Ty;
14233
14234 switch (Ty->castAs<BuiltinType>()->getKind()) {
14235 default:
14236 llvm_unreachable("Not a saturated fixed point type!");
14237 case BuiltinType::SatShortAccum:
14238 return ShortAccumTy;
14239 case BuiltinType::SatAccum:
14240 return AccumTy;
14241 case BuiltinType::SatLongAccum:
14242 return LongAccumTy;
14243 case BuiltinType::SatUShortAccum:
14244 return UnsignedShortAccumTy;
14245 case BuiltinType::SatUAccum:
14246 return UnsignedAccumTy;
14247 case BuiltinType::SatULongAccum:
14248 return UnsignedLongAccumTy;
14249 case BuiltinType::SatShortFract:
14250 return ShortFractTy;
14251 case BuiltinType::SatFract:
14252 return FractTy;
14253 case BuiltinType::SatLongFract:
14254 return LongFractTy;
14255 case BuiltinType::SatUShortFract:
14256 return UnsignedShortFractTy;
14257 case BuiltinType::SatUFract:
14258 return UnsignedFractTy;
14259 case BuiltinType::SatULongFract:
14260 return UnsignedLongFractTy;
14261 }
14262}
14263
14265 assert(Ty->isFixedPointType());
14266
14267 if (Ty->isSaturatedFixedPointType()) return Ty;
14268
14269 switch (Ty->castAs<BuiltinType>()->getKind()) {
14270 default:
14271 llvm_unreachable("Not a fixed point type!");
14272 case BuiltinType::ShortAccum:
14273 return SatShortAccumTy;
14274 case BuiltinType::Accum:
14275 return SatAccumTy;
14276 case BuiltinType::LongAccum:
14277 return SatLongAccumTy;
14278 case BuiltinType::UShortAccum:
14280 case BuiltinType::UAccum:
14281 return SatUnsignedAccumTy;
14282 case BuiltinType::ULongAccum:
14284 case BuiltinType::ShortFract:
14285 return SatShortFractTy;
14286 case BuiltinType::Fract:
14287 return SatFractTy;
14288 case BuiltinType::LongFract:
14289 return SatLongFractTy;
14290 case BuiltinType::UShortFract:
14292 case BuiltinType::UFract:
14293 return SatUnsignedFractTy;
14294 case BuiltinType::ULongFract:
14296 }
14297}
14298
14300 if (LangOpts.OpenCL)
14302
14303 if (LangOpts.CUDA)
14305
14306 return getLangASFromTargetAS(AS);
14307}
14308
14309// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
14310// doesn't include ASTContext.h
14311template
14313 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
14315 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
14316 const clang::ASTContext &Ctx, Decl *Value);
14317
14319 assert(Ty->isFixedPointType());
14320
14321 const TargetInfo &Target = getTargetInfo();
14322 switch (Ty->castAs<BuiltinType>()->getKind()) {
14323 default:
14324 llvm_unreachable("Not a fixed point type!");
14325 case BuiltinType::ShortAccum:
14326 case BuiltinType::SatShortAccum:
14327 return Target.getShortAccumScale();
14328 case BuiltinType::Accum:
14329 case BuiltinType::SatAccum:
14330 return Target.getAccumScale();
14331 case BuiltinType::LongAccum:
14332 case BuiltinType::SatLongAccum:
14333 return Target.getLongAccumScale();
14334 case BuiltinType::UShortAccum:
14335 case BuiltinType::SatUShortAccum:
14336 return Target.getUnsignedShortAccumScale();
14337 case BuiltinType::UAccum:
14338 case BuiltinType::SatUAccum:
14339 return Target.getUnsignedAccumScale();
14340 case BuiltinType::ULongAccum:
14341 case BuiltinType::SatULongAccum:
14342 return Target.getUnsignedLongAccumScale();
14343 case BuiltinType::ShortFract:
14344 case BuiltinType::SatShortFract:
14345 return Target.getShortFractScale();
14346 case BuiltinType::Fract:
14347 case BuiltinType::SatFract:
14348 return Target.getFractScale();
14349 case BuiltinType::LongFract:
14350 case BuiltinType::SatLongFract:
14351 return Target.getLongFractScale();
14352 case BuiltinType::UShortFract:
14353 case BuiltinType::SatUShortFract:
14354 return Target.getUnsignedShortFractScale();
14355 case BuiltinType::UFract:
14356 case BuiltinType::SatUFract:
14357 return Target.getUnsignedFractScale();
14358 case BuiltinType::ULongFract:
14359 case BuiltinType::SatULongFract:
14360 return Target.getUnsignedLongFractScale();
14361 }
14362}
14363
14365 assert(Ty->isFixedPointType());
14366
14367 const TargetInfo &Target = getTargetInfo();
14368 switch (Ty->castAs<BuiltinType>()->getKind()) {
14369 default:
14370 llvm_unreachable("Not a fixed point type!");
14371 case BuiltinType::ShortAccum:
14372 case BuiltinType::SatShortAccum:
14373 return Target.getShortAccumIBits();
14374 case BuiltinType::Accum:
14375 case BuiltinType::SatAccum:
14376 return Target.getAccumIBits();
14377 case BuiltinType::LongAccum:
14378 case BuiltinType::SatLongAccum:
14379 return Target.getLongAccumIBits();
14380 case BuiltinType::UShortAccum:
14381 case BuiltinType::SatUShortAccum:
14382 return Target.getUnsignedShortAccumIBits();
14383 case BuiltinType::UAccum:
14384 case BuiltinType::SatUAccum:
14385 return Target.getUnsignedAccumIBits();
14386 case BuiltinType::ULongAccum:
14387 case BuiltinType::SatULongAccum:
14388 return Target.getUnsignedLongAccumIBits();
14389 case BuiltinType::ShortFract:
14390 case BuiltinType::SatShortFract:
14391 case BuiltinType::Fract:
14392 case BuiltinType::SatFract:
14393 case BuiltinType::LongFract:
14394 case BuiltinType::SatLongFract:
14395 case BuiltinType::UShortFract:
14396 case BuiltinType::SatUShortFract:
14397 case BuiltinType::UFract:
14398 case BuiltinType::SatUFract:
14399 case BuiltinType::ULongFract:
14400 case BuiltinType::SatULongFract:
14401 return 0;
14402 }
14403}
14404
14405llvm::FixedPointSemantics
14407 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
14408 "Can only get the fixed point semantics for a "
14409 "fixed point or integer type.");
14410 if (Ty->isIntegerType())
14411 return llvm::FixedPointSemantics::GetIntegerSemantics(
14412 getIntWidth(Ty), Ty->isSignedIntegerType());
14413
14414 bool isSigned = Ty->isSignedFixedPointType();
14415 return llvm::FixedPointSemantics(
14416 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
14418 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
14419}
14420
14421llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
14422 assert(Ty->isFixedPointType());
14423 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
14424}
14425
14426llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
14427 assert(Ty->isFixedPointType());
14428 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
14429}
14430
14432 assert(Ty->isUnsignedFixedPointType() &&
14433 "Expected unsigned fixed point type");
14434
14435 switch (Ty->castAs<BuiltinType>()->getKind()) {
14436 case BuiltinType::UShortAccum:
14437 return ShortAccumTy;
14438 case BuiltinType::UAccum:
14439 return AccumTy;
14440 case BuiltinType::ULongAccum:
14441 return LongAccumTy;
14442 case BuiltinType::SatUShortAccum:
14443 return SatShortAccumTy;
14444 case BuiltinType::SatUAccum:
14445 return SatAccumTy;
14446 case BuiltinType::SatULongAccum:
14447 return SatLongAccumTy;
14448 case BuiltinType::UShortFract:
14449 return ShortFractTy;
14450 case BuiltinType::UFract:
14451 return FractTy;
14452 case BuiltinType::ULongFract:
14453 return LongFractTy;
14454 case BuiltinType::SatUShortFract:
14455 return SatShortFractTy;
14456 case BuiltinType::SatUFract:
14457 return SatFractTy;
14458 case BuiltinType::SatULongFract:
14459 return SatLongFractTy;
14460 default:
14461 llvm_unreachable("Unexpected unsigned fixed point type");
14462 }
14463}
14464
14465// Given a list of FMV features, return a concatenated list of the
14466// corresponding backend features (which may contain duplicates).
14467static std::vector<std::string> getFMVBackendFeaturesFor(
14468 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) {
14469 std::vector<std::string> BackendFeats;
14470 llvm::AArch64::ExtensionSet FeatureBits;
14471 for (StringRef F : FMVFeatStrings)
14472 if (auto FMVExt = llvm::AArch64::parseFMVExtension(F))
14473 if (FMVExt->ID)
14474 FeatureBits.enable(*FMVExt->ID);
14475 FeatureBits.toLLVMFeatureList(BackendFeats);
14476 return BackendFeats;
14477}
14478
14480ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
14481 assert(TD != nullptr);
14482 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TD->getFeaturesStr());
14483
14484 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
14485 return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
14486 });
14487 return ParsedAttr;
14488}
14489
14490void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
14491 const FunctionDecl *FD) const {
14492 if (FD)
14493 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
14494 else
14495 Target->initFeatureMap(FeatureMap, getDiagnostics(),
14496 Target->getTargetOpts().CPU,
14497 Target->getTargetOpts().Features);
14498}
14499
14500// Fills in the supplied string map with the set of target features for the
14501// passed in function.
14502void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
14503 GlobalDecl GD) const {
14504 StringRef TargetCPU = Target->getTargetOpts().CPU;
14505 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
14506 if (const auto *TD = FD->getAttr<TargetAttr>()) {
14508
14509 // Make a copy of the features as passed on the command line into the
14510 // beginning of the additional features from the function to override.
14511 // AArch64 handles command line option features in parseTargetAttr().
14512 if (!Target->getTriple().isAArch64())
14513 ParsedAttr.Features.insert(
14514 ParsedAttr.Features.begin(),
14515 Target->getTargetOpts().FeaturesAsWritten.begin(),
14516 Target->getTargetOpts().FeaturesAsWritten.end());
14517
14518 if (ParsedAttr.CPU != "" && Target->isValidCPUName(ParsedAttr.CPU))
14519 TargetCPU = ParsedAttr.CPU;
14520
14521 // Now populate the feature map, first with the TargetCPU which is either
14522 // the default or a new one from the target attribute string. Then we'll use
14523 // the passed in features (FeaturesAsWritten) along with the new ones from
14524 // the attribute.
14525 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
14526 ParsedAttr.Features);
14527 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
14529 Target->getCPUSpecificCPUDispatchFeatures(
14530 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
14531 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
14532 Features.insert(Features.begin(),
14533 Target->getTargetOpts().FeaturesAsWritten.begin(),
14534 Target->getTargetOpts().FeaturesAsWritten.end());
14535 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14536 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
14537 if (Target->getTriple().isAArch64()) {
14539 TC->getFeatures(Feats, GD.getMultiVersionIndex());
14540 std::vector<std::string> Features = getFMVBackendFeaturesFor(Feats);
14541 Features.insert(Features.begin(),
14542 Target->getTargetOpts().FeaturesAsWritten.begin(),
14543 Target->getTargetOpts().FeaturesAsWritten.end());
14544 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14545 } else if (Target->getTriple().isRISCV()) {
14546 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
14547 std::vector<std::string> Features;
14548 if (VersionStr != "default") {
14549 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(VersionStr);
14550 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
14551 ParsedAttr.Features.end());
14552 }
14553 Features.insert(Features.begin(),
14554 Target->getTargetOpts().FeaturesAsWritten.begin(),
14555 Target->getTargetOpts().FeaturesAsWritten.end());
14556 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14557 } else {
14558 std::vector<std::string> Features;
14559 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
14560 if (VersionStr.starts_with("arch="))
14561 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
14562 else if (VersionStr != "default")
14563 Features.push_back((StringRef{"+"} + VersionStr).str());
14564 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14565 }
14566 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
14567 std::vector<std::string> Features;
14568 if (Target->getTriple().isRISCV()) {
14569 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TV->getName());
14570 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
14571 ParsedAttr.Features.end());
14572 } else {
14573 assert(Target->getTriple().isAArch64());
14575 TV->getFeatures(Feats);
14576 Features = getFMVBackendFeaturesFor(Feats);
14577 }
14578 Features.insert(Features.begin(),
14579 Target->getTargetOpts().FeaturesAsWritten.begin(),
14580 Target->getTargetOpts().FeaturesAsWritten.end());
14581 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14582 } else {
14583 FeatureMap = Target->getTargetOpts().FeatureMap;
14584 }
14585}
14586
14588 const FunctionDecl *FD) {
14589 return {KernelNameType, FD};
14590}
14591
14593 // If the function declaration to register is invalid or dependent, the
14594 // registration attempt is ignored.
14595 if (FD->isInvalidDecl() || FD->isTemplated())
14596 return;
14597
14598 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
14599 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
14600
14601 // Be tolerant of multiple registration attempts so long as each attempt
14602 // is for the same entity. Callers are obligated to detect and diagnose
14603 // conflicting kernel names prior to calling this function.
14604 CanQualType KernelNameType = getCanonicalType(SKEPAttr->getKernelName());
14605 auto IT = SYCLKernels.find(KernelNameType);
14606 assert((IT == SYCLKernels.end() ||
14607 declaresSameEntity(FD, IT->second.getKernelEntryPointDecl())) &&
14608 "SYCL kernel name conflict");
14609 (void)IT;
14610 SYCLKernels.insert(
14611 std::make_pair(KernelNameType, BuildSYCLKernelInfo(KernelNameType, FD)));
14612}
14613
14615 CanQualType KernelNameType = getCanonicalType(T);
14616 return SYCLKernels.at(KernelNameType);
14617}
14618
14620 CanQualType KernelNameType = getCanonicalType(T);
14621 auto IT = SYCLKernels.find(KernelNameType);
14622 if (IT != SYCLKernels.end())
14623 return &IT->second;
14624 return nullptr;
14625}
14626
14628 OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
14629 return *OMPTraitInfoVector.back();
14630}
14631
14634 const ASTContext::SectionInfo &Section) {
14635 if (Section.Decl)
14636 return DB << Section.Decl;
14637 return DB << "a prior #pragma section";
14638}
14639
14641 bool IsInternalVar =
14642 isa<VarDecl>(D) &&
14643 basicGVALinkageForVariable(*this, cast<VarDecl>(D)) == GVA_Internal;
14644 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
14645 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
14646 (D->hasAttr<CUDAConstantAttr>() &&
14647 !D->getAttr<CUDAConstantAttr>()->isImplicit());
14648 // CUDA/HIP: managed variables need to be externalized since it is
14649 // a declaration in IR, therefore cannot have internal linkage. Kernels in
14650 // anonymous name space needs to be externalized to avoid duplicate symbols.
14651 return (IsInternalVar &&
14652 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
14653 (D->hasAttr<CUDAGlobalAttr>() &&
14654 basicGVALinkageForFunction(*this, cast<FunctionDecl>(D)) ==
14655 GVA_Internal);
14656}
14657
14659 return mayExternalize(D) &&
14660 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
14661 CUDADeviceVarODRUsedByHost.count(cast<VarDecl>(D)));
14662}
14663
14664StringRef ASTContext::getCUIDHash() const {
14665 if (!CUIDHash.empty())
14666 return CUIDHash;
14667 if (LangOpts.CUID.empty())
14668 return StringRef();
14669 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
14670 return CUIDHash;
14671}
14672
14673const CXXRecordDecl *
14675 assert(ThisClass);
14676 assert(ThisClass->isPolymorphic());
14677 const CXXRecordDecl *PrimaryBase = ThisClass;
14678 while (1) {
14679 assert(PrimaryBase);
14680 assert(PrimaryBase->isPolymorphic());
14681 auto &Layout = getASTRecordLayout(PrimaryBase);
14682 auto Base = Layout.getPrimaryBase();
14683 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
14684 break;
14685 PrimaryBase = Base;
14686 }
14687 return PrimaryBase;
14688}
14689
14691 StringRef MangledName) {
14692 auto *Method = cast<CXXMethodDecl>(VirtualMethodDecl.getDecl());
14693 assert(Method->isVirtual());
14694 bool DefaultIncludesPointerAuth =
14695 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics;
14696
14697 if (!DefaultIncludesPointerAuth)
14698 return true;
14699
14700 auto Existing = ThunksToBeAbbreviated.find(VirtualMethodDecl);
14701 if (Existing != ThunksToBeAbbreviated.end())
14702 return Existing->second.contains(MangledName.str());
14703
14704 std::unique_ptr<MangleContext> Mangler(createMangleContext());
14705 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks;
14706 auto VtableContext = getVTableContext();
14707 if (const auto *ThunkInfos = VtableContext->getThunkInfo(VirtualMethodDecl)) {
14708 auto *Destructor = dyn_cast<CXXDestructorDecl>(Method);
14709 for (const auto &Thunk : *ThunkInfos) {
14710 SmallString<256> ElidedName;
14711 llvm::raw_svector_ostream ElidedNameStream(ElidedName);
14712 if (Destructor)
14713 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
14714 Thunk, /* elideOverrideInfo */ true,
14715 ElidedNameStream);
14716 else
14717 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ true,
14718 ElidedNameStream);
14719 SmallString<256> MangledName;
14720 llvm::raw_svector_ostream mangledNameStream(MangledName);
14721 if (Destructor)
14722 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
14723 Thunk, /* elideOverrideInfo */ false,
14724 mangledNameStream);
14725 else
14726 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ false,
14727 mangledNameStream);
14728
14729 Thunks[ElidedName].push_back(std::string(MangledName));
14730 }
14731 }
14732 llvm::StringSet<> SimplifiedThunkNames;
14733 for (auto &ThunkList : Thunks) {
14734 llvm::sort(ThunkList.second);
14735 SimplifiedThunkNames.insert(ThunkList.second[0]);
14736 }
14737 bool Result = SimplifiedThunkNames.contains(MangledName);
14738 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames);
14739 return Result;
14740}
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:1134
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:3357
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3376
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:3747
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3577
ArraySizeModifier getSizeModifier() const
Definition: Type.h:3591
Qualifiers getIndexTypeQualifiers() const
Definition: Type.h:3595
QualType getElementType() const
Definition: Type.h:3589
unsigned getIndexTypeCVRQualifiers() const
Definition: Type.h:3599
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:7766
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7771
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:6132
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6204
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:6561
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.cpp:5204
bool isConstrained() const
Definition: Type.h:6580
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6241
A fixed int type of a specified bitwidth.
Definition: Type.h:7819
void Profile(llvm::FoldingSetNodeID &ID) const
Definition: Type.h:7836
unsigned getNumBits() const
Definition: Type.h:7831
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:3408
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3425
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:3034
Kind getKind() const
Definition: Type.h:3082
StringRef getName(const PrintingPolicy &Policy) const
Definition: Type.cpp:3328
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:3145
QualType getElementType() const
Definition: Type.h:3155
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3160
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:3615
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition: Type.h:3711
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3671
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.h:3730
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition: Type.h:3691
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:4232
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition: Type.h:4253
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4270
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition: Type.h:4250
static constexpr bool isDimensionValid(size_t NumElements)
Returns true if NumElements is a valid matrix dimension.
Definition: Type.h:4261
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition: Type.h:3306
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3342
Represents a pointer type decayed from an array or function type.
Definition: Type.h:3391
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:5879
Represents a C++17 deduced template specialization type.
Definition: Type.h:6609
void Profile(llvm::FoldingSetNodeID &ID) const
Definition: Type.h:6630
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:6527
Represents an extended address space qualifier where the input address space value is dependent.
Definition: Type.h:3920
Expr * getAddrSpaceExpr() const
Definition: Type.h:3931
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:3942
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:7864
Internal representation of canonical, dependent decltype(expr) types.
Definition: Type.h:5907
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:5911
Represents a qualified type name for which the type name is dependent.
Definition: Type.h:7029
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7061
Represents an array type in C++ whose size is a value-dependent expression.
Definition: Type.h:3862
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:3899
Expr * getSizeExpr() const
Definition: Type.h:3882
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3960
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:3985
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition: Type.h:4291
Expr * getRowExpr() const
Definition: Type.h:4303
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:4311
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:7081
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:7108
Internal representation of canonical, dependent typeof(expr) types.
Definition: Type.h:5836
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:5841
Internal representation of canonical, dependent __underlying_type(type) types.
Definition: Type.h:6037
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6042
Represents a vector type where either the type or size is dependent.
Definition: Type.h:4086
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:4111
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:4828
Represents a type that was referred to using an elaborated type keyword, e.g., struct S,...
Definition: Type.h:6948
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7001
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:4974
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:6103
EnumDecl * getDecl() const
Definition: Type.h:6110
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:4126
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:5370
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:4613
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:4566
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:3649
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:3778
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4287
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:4035
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:3948
static FunctionEffectSet getIntersection(FunctionEffectsRef LHS, FunctionEffectsRef RHS)
Definition: Type.cpp:5335
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition: Type.cpp:5373
Represents an abstract function effect, using just an enumeration describing its kind.
Definition: Type.h:4721
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition: Type.h:4908
size_t size() const
Definition: Type.h:4939
ArrayRef< EffectConditionExpr > conditions() const
Definition: Type.h:4942
bool empty() const
Definition: Type.h:4938
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition: Type.h:4686
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4702
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5107
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:5573
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:5387
unsigned getNumParams() const
Definition: Type.h:5360
QualType getParamType(unsigned i) const
Definition: Type.h:5362
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.cpp:3867
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:5393
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5484
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5371
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5367
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition: Type.h:5549
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition: Type.h:5545
Declaration of a template function.
Definition: DeclTemplate.h:958
A class which abstracts out some details necessary for making a call.
Definition: Type.h:4432
CallingConv getCC() const
Definition: Type.h:4494
bool getNoCfCheck() const
Definition: Type.h:4484
unsigned getRegParm() const
Definition: Type.h:4487
bool getNoCallerSavedRegs() const
Definition: Type.h:4483
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4506
bool getHasRegParm() const
Definition: Type.h:4485
bool getNoReturn() const
Definition: Type.h:4480
bool getProducesResult() const
Definition: Type.h:4481
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition: Type.h:4347
ExtParameterInfo withIsNoEscape(bool NoEscape) const
Definition: Type.h:4387
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4321
ExtInfo getExtInfo() const
Definition: Type.h:4660
QualType getReturnType() const
Definition: Type.h:4648
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:6298
const Attributes & getAttrs() const
Definition: Type.h:6301
QualType getContainedType() const
Definition: Type.h:6299
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6306
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:3764
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3781
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:6798
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:3483
@ 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:499
std::optional< TargetCXXABI::Kind > CXXABI
C++ ABI to compile with, if specified by the frontend through -fc++-abi=.
Definition: LangOptions.h:587
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:534
CoreFoundationABI CFRuntime
Definition: LangOptions.h:536
CommentOptions CommentOpts
Options for parsing comments.
Definition: LangOptions.h:563
std::string CUID
The user provided compilation unit ID, if non-empty.
Definition: LangOptions.h:583
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:5770
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:4210
static bool isValidElementType(QualType T)
Valid elements types are the following:
Definition: Type.h:4217
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3519
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3555
QualType getPointeeType() const
Definition: Type.h:3535
const Type * getClass() const
Definition: Type.h:3549
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:3128
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:7529
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:7585
bool isObjCQualifiedClassType() const
True if this is equivalent to 'Class.
Definition: Type.h:7666
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:7660
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7742
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:7622
bool qual_empty() const
Definition: Type.h:7714
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition: Type.h:7643
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:7597
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition: Type.h:7637
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:7704
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition: Type.h:7649
A class providing a concrete implementation of ObjCObjectType, so as to not increase the footprint of...
Definition: Type.h:7482
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:4450
Represents a class type in Objective C.
Definition: Type.h:7331
bool isKindOfTypeAsWritten() const
Whether this is a "__kindof" type as written.
Definition: Type.h:7446
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:7441
bool isObjCQualifiedClass() const
Definition: Type.h:7413
QualType getBaseType() const
Gets the base type of this object type.
Definition: Type.h:7393
bool isObjCClass() const
Definition: Type.h:7399
bool isKindOfType() const
Whether this ia a "__kindof" type (semantically).
Definition: Type.cpp:901
bool isObjCQualifiedId() const
Definition: Type.h:7412
ArrayRef< QualType > getTypeArgs() const
Retrieve the type arguments of this object type (semantically).
Definition: Type.cpp:883
bool isObjCUnqualifiedId() const
Definition: Type.h:7403
ObjCInterfaceDecl * getInterface() const
Gets the interface declaration for this object type, if the base type really is an interface.
Definition: Type.h:7564
QualType getSuperClassType() const
Retrieve the type of the superclass of this object type.
Definition: Type.h:7457
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:7237
qual_iterator qual_end() const
Definition: Type.h:7231
qual_iterator qual_begin() const
Definition: Type.h:7230
qual_range quals() const
Definition: Type.h:7229
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:7257
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:4467
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:7146
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7180
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5973
Sugar for parentheses used when specifying types.
Definition: Type.h:3172
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3186
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:7785
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7802
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3198
QualType getPointeeType() const
Definition: Type.h:3208
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3213
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:8020
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2796
Qualifiers::GC getObjCGCAttr() const
Returns gc attribute of this type.
Definition: Type.h:8067
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:8025
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:7936
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:8062
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7976
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1433
QualType getCanonicalType() const
Definition: Type.h:7988
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:8030
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition: Type.h:7957
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:8009
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:7993
const Type * getTypePtrOrNull() const
Definition: Type.h:7940
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:2933
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:7968
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:7876
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:7883
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:3501
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:5052
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition: Decl.cpp:5118
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:6077
RecordDecl * getDecl() const
Definition: Type.h:6087
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:3439
QualType getPointeeType() const
Definition: Type.h:3457
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3465
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:6469
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:4311
Represents the result of substituting a type for a template type parameter.
Definition: Type.h:6388
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6433
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:4773
bool isUnion() const
Definition: Decl.h:3784
TagDecl * getDecl() const
Definition: Type.cpp:4122
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:6666
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.cpp:4402
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:6360
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:5802
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition: Type.h:5852
A container of type source information.
Definition: Type.h:7907
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:8205
bool isVoidType() const
Definition: Type.h:8515
bool isBooleanType() const
Definition: Type.h:8643
bool isFunctionReferenceType() const
Definition: Type.h:8238
bool isObjCBuiltinType() const
Definition: Type.h:8384
QualType getRVVEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an RVV builtin type.
Definition: Type.cpp:2624
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:773
bool isIncompleteArrayType() const
Definition: Type.h:8271
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:8491
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:8267
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:8263
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:8231
bool isPointerType() const
Definition: Type.h:8191
bool isArrayParameterType() const
Definition: Type.h:8279
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8555
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8805
bool isSpecificPlaceholderType(unsigned K) const
Test for a specific placeholder type.
Definition: Type.h:8504
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:8596
bool isEnumeralType() const
Definition: Type.h:8295
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2554
bool isObjCQualifiedIdType() const
Definition: Type.h:8354
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:8630
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:2593
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2811
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2714
bool isBitIntType() const
Definition: Type.h:8429
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:8484
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:8287
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2706
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8568
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8584
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:2989
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8686
bool isMemberPointerType() const
Definition: Type.h:8245
bool isObjCIdType() const
Definition: Type.h:8366
bool isUnsaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8592
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:8791
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:8187
bool isObjCObjectPointerType() const
Definition: Type.h:8333
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:8610
bool isVectorType() const
Definition: Type.h:8303
bool isObjCClassType() const
Definition: Type.h:8372
bool isRVVVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'riscv_rvv_vector_bits' type attribute,...
Definition: Type.cpp:2606
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2541
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:8199
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:8736
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:8548
bool isRecordType() const
Definition: Type.h:8291
bool isObjCRetainableType() const
Definition: Type.cpp:5028
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4763
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:5569
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:5755
A unary type transform, which is a type constructed from another.
Definition: Type.h:5994
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:5672
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:5723
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:5403
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:3808
Expr * getSizeExpr() const
Definition: Type.h:3827
Represents a GCC generic vector type.
Definition: Type.h:4034
unsigned getNumElements() const
Definition: Type.h:4049
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4058
VectorKind getVectorKind() const
Definition: Type.h:4054
QualType getElementType() const
Definition: Type.h:4048
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:8089
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:3574
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
SubstTemplateTypeParmTypeFlag
Definition: Type.h:1789
TagTypeKind
The kind of a tag type.
Definition: Type.h:6876
@ 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:1096
@ TypeAlignment
Definition: Type.h:76
FloatModeKind
Definition: TargetInfo.h:73
bool isPtrSizeAddressSpace(LangAS AS)
Definition: AddressSpaces.h:91
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:3993
@ 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:86
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:6851
@ 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:5164
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:5166
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition: Type.h:5169
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition: Type.h:5172
Extra information about a function prototype.
Definition: Type.h:5192
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:5199
bool requiresFunctionProtoTypeArmAttributes() const
Definition: Type.h:5224
FunctionEffectsRef FunctionEffects
Definition: Type.h:5202
const ExtParameterInfo * ExtParameterInfos
Definition: Type.h:5200
bool requiresFunctionProtoTypeExtraBitfields() const
Definition: Type.h:5218
FunctionType::ExtInfo ExtInfo
Definition: Type.h:5193
A simple holder for a QualType representing a type in an exception specification.
Definition: Type.h:4559
A holder for Arm type attributes as described in the Arm C/C++ Language extensions which are not part...
Definition: Type.h:4625
A simple holder for various uncommon bits which do not fit in FunctionTypeBitfields.
Definition: Type.h:4564
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
Morty Proxy This is a proxified and sanitized view of the page, visit original site.