clang 24.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"
21#include "clang/AST/Attr.h"
23#include "clang/AST/CharUnits.h"
24#include "clang/AST/Comment.h"
25#include "clang/AST/Decl.h"
26#include "clang/AST/DeclBase.h"
27#include "clang/AST/DeclCXX.h"
29#include "clang/AST/DeclObjC.h"
34#include "clang/AST/Expr.h"
35#include "clang/AST/ExprCXX.h"
37#include "clang/AST/Mangle.h"
43#include "clang/AST/Stmt.h"
46#include "clang/AST/Type.h"
47#include "clang/AST/TypeLoc.h"
56#include "clang/Basic/LLVM.h"
58#include "clang/Basic/Linkage.h"
59#include "clang/Basic/Module.h"
69#include "clang/Lex/MacroInfo.h"
70#include "llvm/ADT/APFixedPoint.h"
71#include "llvm/ADT/APInt.h"
72#include "llvm/ADT/APSInt.h"
73#include "llvm/ADT/ArrayRef.h"
74#include "llvm/ADT/DenseMap.h"
75#include "llvm/ADT/DenseSet.h"
76#include "llvm/ADT/FoldingSet.h"
77#include "llvm/ADT/PointerUnion.h"
78#include "llvm/ADT/STLExtras.h"
79#include "llvm/ADT/SmallPtrSet.h"
80#include "llvm/ADT/SmallVector.h"
81#include "llvm/ADT/StringExtras.h"
82#include "llvm/ADT/StringRef.h"
83#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
84#include "llvm/Support/Capacity.h"
85#include "llvm/Support/Casting.h"
86#include "llvm/Support/Compiler.h"
87#include "llvm/Support/ErrorHandling.h"
88#include "llvm/Support/MD5.h"
89#include "llvm/Support/MathExtras.h"
90#include "llvm/Support/SipHash.h"
91#include "llvm/Support/raw_ostream.h"
92#include "llvm/TargetParser/AArch64TargetParser.h"
93#include "llvm/TargetParser/Triple.h"
94#include <algorithm>
95#include <cassert>
96#include <cstddef>
97#include <cstdint>
98#include <cstdlib>
99#include <map>
100#include <memory>
101#include <optional>
102#include <string>
103#include <tuple>
104#include <utility>
105
106using namespace clang;
107
118
119/// \returns The locations that are relevant when searching for Doc comments
120/// related to \p Key.
123 SourceManager &SourceMgr) {
124 if (const auto *MI = dyn_cast<const MacroInfo *>(Key)) {
125 SourceLocation DefLoc = MI->getDefinitionLoc();
126 if (DefLoc.isInvalid() || !DefLoc.isFileID())
127 return {};
128
129 // The macro's definition location points at its name (e.g. FOO in
130 // `#define FOO 1`). The text between a preceding documentation comment
131 // and the name contains the `#define` directive itself, which would be
132 // rejected by the preprocessor-directive guard in
133 // getRawCommentNoCacheImpl. Walk back to the leading `#` so that
134 // the guard only fires when something *else* sits between the comment
135 // and our directive.
136 FileIDAndOffset Decomposed = SourceMgr.getDecomposedLoc(DefLoc);
137 bool Invalid = false;
138 StringRef Buffer = SourceMgr.getBufferData(Decomposed.first, &Invalid);
139 if (Invalid)
140 return {};
141 unsigned Offset = Decomposed.second;
142 if (size_t Found = Buffer.find_last_of("#\n", Offset);
143 Found != StringRef::npos)
144 Offset = Found;
145 return {SourceMgr.getLocForStartOfFile(Decomposed.first)
146 .getLocWithOffset(Offset)};
147 }
148
149 const auto *D = cast<const Decl *>(Key);
150 assert(D);
151
152 // User can not attach documentation to implicit declarations.
153 if (D->isImplicit())
154 return {};
155
156 // User can not attach documentation to implicit instantiations.
157 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
158 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
159 return {};
160 }
161
162 if (const auto *VD = dyn_cast<VarDecl>(D)) {
163 if (VD->isStaticDataMember() &&
164 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
165 return {};
166 }
167
168 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
169 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
170 return {};
171 }
172
173 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
174 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
175 if (TSK == TSK_ImplicitInstantiation ||
176 TSK == TSK_Undeclared)
177 return {};
178 }
179
180 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
181 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
182 return {};
183 }
184 if (const auto *TD = dyn_cast<TagDecl>(D)) {
185 // When tag declaration (but not definition!) is part of the
186 // decl-specifier-seq of some other declaration, it doesn't get comment
187 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
188 return {};
189 }
190 // TODO: handle comments for function parameters properly.
191 if (isa<ParmVarDecl>(D))
192 return {};
193
194 // TODO: we could look up template parameter documentation in the template
195 // documentation.
199 return {};
200
202 // Find declaration location.
203 // For Objective-C declarations we generally don't expect to have multiple
204 // declarators, thus use declaration starting location as the "declaration
205 // location".
206 // For all other declarations multiple declarators are used quite frequently,
207 // so we use the location of the identifier as the "declaration location".
208 SourceLocation BaseLocation;
212 // Allow association with Y across {} in `typedef struct X {} Y`.
214 BaseLocation = D->getBeginLoc();
215 else
216 BaseLocation = D->getLocation();
217
218 if (!D->getLocation().isMacroID()) {
219 Locations.emplace_back(BaseLocation);
220 } else {
221 const auto *DeclCtx = D->getDeclContext();
222
223 // When encountering definitions generated from a macro (that are not
224 // contained by another declaration in the macro) we need to try and find
225 // the comment at the location of the expansion but if there is no comment
226 // there we should retry to see if there is a comment inside the macro as
227 // well. To this end we return first BaseLocation to first look at the
228 // expansion site, the second value is the spelling location of the
229 // beginning of the declaration defined inside the macro.
230 if (!(DeclCtx &&
231 Decl::castFromDeclContext(DeclCtx)->getLocation().isMacroID())) {
232 Locations.emplace_back(SourceMgr.getExpansionLoc(BaseLocation));
233 }
234
235 // We use Decl::getBeginLoc() and not just BaseLocation here to ensure that
236 // we don't refer to the macro argument location at the expansion site (this
237 // can happen if the name's spelling is provided via macro argument), and
238 // always to the declaration itself.
239 Locations.emplace_back(SourceMgr.getSpellingLoc(D->getBeginLoc()));
240 }
241
242 return Locations;
243}
244
246 RawCommentLookupKey Key, const SourceLocation RepresentativeLoc,
247 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
248 // If the declaration doesn't map directly to a location in a file, we
249 // can't find the comment.
250 if (RepresentativeLoc.isInvalid() || !RepresentativeLoc.isFileID())
251 return nullptr;
252
253 // If there are no comments anywhere, we won't find anything.
254 if (CommentsInTheFile.empty())
255 return nullptr;
256
257 const auto *D = dyn_cast<const Decl *>(Key);
258 const bool IsMacro = isa<const MacroInfo *>(Key);
259
260 // Decompose the location for the declaration and find the beginning of the
261 // file buffer.
262 const FileIDAndOffset LocDecomp =
263 SourceMgr.getDecomposedLoc(RepresentativeLoc);
264
265 // Slow path.
266 auto OffsetCommentBehindDecl =
267 CommentsInTheFile.lower_bound(LocDecomp.second);
268
269 // First check whether we have a trailing comment.
270 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
271 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
272 if ((CommentBehindDecl->isDocumentation() ||
273 LangOpts.CommentOpts.ParseAllComments) &&
274 CommentBehindDecl->isTrailingComment() &&
275 (IsMacro || (D && (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) ||
277 isa<ObjCPropertyDecl>(D))))) {
278
279 // Check that Doxygen trailing comment comes after the declaration, starts
280 // on the same line and in the same file as the declaration.
281 if (SourceMgr.getLineNumber(LocDecomp.first, LocDecomp.second) ==
282 Comments.getCommentBeginLine(CommentBehindDecl, LocDecomp.first,
283 OffsetCommentBehindDecl->first)) {
284 return CommentBehindDecl;
285 }
286 }
287 }
288
289 // The comment just after the declaration was not a trailing comment.
290 // Let's look at the previous comment.
291 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
292 return nullptr;
293
294 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
295 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
296
297 // Check that we actually have a non-member Doxygen comment.
298 if (!(CommentBeforeDecl->isDocumentation() ||
299 LangOpts.CommentOpts.ParseAllComments) ||
300 CommentBeforeDecl->isTrailingComment())
301 return nullptr;
302
303 // Decompose the end of the comment.
304 const unsigned CommentEndOffset =
305 Comments.getCommentEndOffset(CommentBeforeDecl);
306
307 // Get the corresponding buffer.
308 bool Invalid = false;
309 const char *Buffer =
310 SourceMgr.getBufferData(LocDecomp.first, &Invalid).data();
311 if (Invalid)
312 return nullptr;
313
314 // Extract text between the comment and declaration.
315 StringRef Text(Buffer + CommentEndOffset,
316 LocDecomp.second - CommentEndOffset);
317
318 // There should be no other declarations or preprocessor directives between
319 // comment and declaration.
320 if (Text.find_last_of(";{}#@") != StringRef::npos)
321 return nullptr;
322
323 return CommentBeforeDecl;
324}
325
327 const auto Locs = getLocsForCommentSearch(Key, SourceMgr);
328
329 for (const auto Loc : Locs) {
330 // If the declaration or macro doesn't map directly to a location in a file,
331 // we can't find the comment.
332 if (Loc.isInvalid() || !Loc.isFileID())
333 continue;
334
336 ExternalSource->ReadComments();
337 CommentsLoaded = true;
338 }
339
340 if (Comments.empty())
341 continue;
342
343 const FileID File = SourceMgr.getDecomposedLoc(Loc).first;
344 if (!File.isValid())
345 continue;
346
347 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
348 if (!CommentsInThisFile || CommentsInThisFile->empty())
349 continue;
350
351 if (RawComment *Comment =
352 getRawCommentNoCacheImpl(Key, Loc, *CommentsInThisFile))
353 return Comment;
354 }
355
356 return nullptr;
357}
358
360 assert(LangOpts.RetainCommentsFromSystemHeaders ||
361 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
362 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
363}
364
365const RawComment *
367 const Decl **OriginalDecl) const {
368 if (Key.isNull()) {
369 if (OriginalDecl)
370 *OriginalDecl = nullptr;
371 return nullptr;
372 }
373
374 // Macros have no redeclaration chain: look up directly, populate the cache,
375 // and return.
376 if (const auto *MI = dyn_cast<const MacroInfo *>(Key)) {
377 if (OriginalDecl)
378 *OriginalDecl = nullptr;
379 auto Existing = RawComments.find(Key);
380 if (Existing != RawComments.end())
381 return Existing->second;
382 if (const RawComment *RC = getRawCommentNoCache(Key)) {
383 cacheRawComment(MI, *RC);
384 return RC;
385 }
386 return nullptr;
387 }
388
389 const Decl *D = cast<const Decl *>(Key);
390 D = &adjustDeclToTemplate(*D);
391
392 // Any comment directly attached to D?
393 {
394 auto DeclComment = RawComments.find(D);
395 if (DeclComment != RawComments.end()) {
396 if (OriginalDecl)
397 *OriginalDecl = D;
398 return DeclComment->second;
399 }
400 }
401
402 // Any comment attached to any redeclaration of D?
403 const Decl *CanonicalD = D->getCanonicalDecl();
404 if (!CanonicalD)
405 return nullptr;
406
407 {
408 auto RedeclComment = RedeclChainComments.find(CanonicalD);
409 if (RedeclComment != RedeclChainComments.end()) {
410 if (OriginalDecl)
411 *OriginalDecl = RedeclComment->second;
412 auto CommentAtRedecl = RawComments.find(RedeclComment->second);
413 assert(CommentAtRedecl != RawComments.end() &&
414 "This decl is supposed to have comment attached.");
415 return CommentAtRedecl->second;
416 }
417 }
418
419 // Any redeclarations of D that we haven't checked for comments yet?
420 const Decl *LastCheckedRedecl = [&]() {
421 const Decl *LastChecked = CommentlessRedeclChains.lookup(CanonicalD);
422 bool CanUseCommentlessCache = false;
423 if (LastChecked) {
424 for (auto *Redecl : CanonicalD->redecls()) {
425 if (Redecl == D) {
426 CanUseCommentlessCache = true;
427 break;
428 }
429 if (Redecl == LastChecked)
430 break;
431 }
432 }
433 // FIXME: This could be improved so that even if CanUseCommentlessCache
434 // is false, once we've traversed past CanonicalD we still skip ahead
435 // LastChecked.
436 return CanUseCommentlessCache ? LastChecked : nullptr;
437 }();
438
439 for (const Decl *Redecl : D->redecls()) {
440 assert(Redecl);
441 // Skip all redeclarations that have been checked previously.
442 if (LastCheckedRedecl) {
443 if (LastCheckedRedecl == Redecl) {
444 LastCheckedRedecl = nullptr;
445 }
446 continue;
447 }
448 const RawComment *RedeclComment = getRawCommentNoCache(Redecl);
449 if (RedeclComment) {
450 cacheRawComment(Redecl, *RedeclComment);
451 if (OriginalDecl)
452 *OriginalDecl = Redecl;
453 return RedeclComment;
454 }
455 CommentlessRedeclChains[CanonicalD] = Redecl;
456 }
457
458 if (OriginalDecl)
459 *OriginalDecl = nullptr;
460 return nullptr;
461}
462
464 const RawComment &Comment) const {
465 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
466 RawComments.try_emplace(Original, &Comment);
467 if (const auto *D = dyn_cast<const Decl *>(Original)) {
468 const Decl *const CanonicalDecl = D->getCanonicalDecl();
469 RedeclChainComments.try_emplace(CanonicalDecl, D);
470 CommentlessRedeclChains.erase(CanonicalDecl);
471 }
472}
473
474static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
476 const DeclContext *DC = ObjCMethod->getDeclContext();
477 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
478 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
479 if (!ID)
480 return;
481 // Add redeclared method here.
482 for (const auto *Ext : ID->known_extensions()) {
483 if (ObjCMethodDecl *RedeclaredMethod =
484 Ext->getMethod(ObjCMethod->getSelector(),
485 ObjCMethod->isInstanceMethod()))
486 Redeclared.push_back(RedeclaredMethod);
487 }
488 }
489}
490
492 const Preprocessor *PP) {
493 if (Comments.empty() || Decls.empty())
494 return;
495
496 FileID File;
497 for (const Decl *D : Decls) {
498 if (D->isInvalidDecl())
499 continue;
500
501 D = &adjustDeclToTemplate(*D);
502 SourceLocation Loc = D->getLocation();
503 if (Loc.isValid()) {
504 // See if there are any new comments that are not attached to a decl.
505 // The location doesn't have to be precise - we care only about the file.
506 File = SourceMgr.getDecomposedLoc(Loc).first;
507 break;
508 }
509 }
510
511 if (File.isInvalid())
512 return;
513
514 auto CommentsInThisFile = Comments.getCommentsInFile(File);
515 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
516 CommentsInThisFile->rbegin()->second->isAttached())
517 return;
518
519 // There is at least one comment not attached to a decl.
520 // Maybe it should be attached to one of Decls?
521 //
522 // Note that this way we pick up not only comments that precede the
523 // declaration, but also comments that *follow* the declaration -- thanks to
524 // the lookahead in the lexer: we've consumed the semicolon and looked
525 // ahead through comments.
526 for (const Decl *D : Decls) {
527 assert(D);
528 if (D->isInvalidDecl())
529 continue;
530
531 D = &adjustDeclToTemplate(*D);
532
533 if (RawComments.count(D) > 0)
534 continue;
535
536 const auto DeclLocs = getLocsForCommentSearch(D, SourceMgr);
537
538 for (const auto DeclLoc : DeclLocs) {
539 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
540 continue;
541
542 if (RawComment *const DocComment =
543 getRawCommentNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) {
544 cacheRawComment(D, *DocComment);
545 comments::FullComment *FC = DocComment->parse(*this, PP, D);
546 ParsedComments[D->getCanonicalDecl()] = FC;
547 break;
548 }
549 }
550 }
551}
552
554 const Decl *D) const {
555 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
556 ThisDeclInfo->CommentDecl = D;
557 ThisDeclInfo->IsFilled = false;
558 ThisDeclInfo->fill();
559 ThisDeclInfo->CommentDecl = FC->getDecl();
560 if (!ThisDeclInfo->TemplateParameters)
561 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
563 new (*this) comments::FullComment(FC->getBlocks(),
564 ThisDeclInfo);
565 return CFC;
566}
567
569 const RawComment *RC = getRawCommentNoCache(D);
570 return RC ? RC->parse(*this, nullptr, D) : nullptr;
571}
572
574 const Decl *D,
575 const Preprocessor *PP) const {
576 if (!D || D->isInvalidDecl())
577 return nullptr;
578 D = &adjustDeclToTemplate(*D);
579
580 const Decl *Canonical = D->getCanonicalDecl();
581 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
582 ParsedComments.find(Canonical);
583
584 if (Pos != ParsedComments.end()) {
585 if (Canonical != D) {
586 comments::FullComment *FC = Pos->second;
588 return CFC;
589 }
590 return Pos->second;
591 }
592
593 const Decl *OriginalDecl = nullptr;
594
595 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
596 if (!RC) {
599 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
600 if (OMD && OMD->isPropertyAccessor())
601 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
602 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
603 return cloneFullComment(FC, D);
604 if (OMD)
605 addRedeclaredMethods(OMD, Overridden);
606 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
607 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
608 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
609 return cloneFullComment(FC, D);
610 }
611 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
612 // Attach any tag type's documentation to its typedef if latter
613 // does not have one of its own.
614 QualType QT = TD->getUnderlyingType();
615 if (const auto *TT = QT->getAs<TagType>())
616 if (comments::FullComment *FC = getCommentForDecl(TT->getDecl(), PP))
617 return cloneFullComment(FC, D);
618 }
619 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
620 while (IC->getSuperClass()) {
621 IC = IC->getSuperClass();
623 return cloneFullComment(FC, D);
624 }
625 }
626 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
627 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
629 return cloneFullComment(FC, D);
630 }
631 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
632 if (!(RD = RD->getDefinition()))
633 return nullptr;
634 // Check non-virtual bases.
635 for (const auto &I : RD->bases()) {
636 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
637 continue;
638 QualType Ty = I.getType();
639 if (Ty.isNull())
640 continue;
642 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
643 continue;
644
646 return cloneFullComment(FC, D);
647 }
648 }
649 // Check virtual bases.
650 for (const auto &I : RD->vbases()) {
651 if (I.getAccessSpecifier() != AS_public)
652 continue;
653 QualType Ty = I.getType();
654 if (Ty.isNull())
655 continue;
656 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
657 if (!(VirtualBase= VirtualBase->getDefinition()))
658 continue;
660 return cloneFullComment(FC, D);
661 }
662 }
663 }
664 return nullptr;
665 }
666
667 // If the RawComment was attached to other redeclaration of this Decl, we
668 // should parse the comment in context of that other Decl. This is important
669 // because comments can contain references to parameter names which can be
670 // different across redeclarations.
671 if (D != OriginalDecl && OriginalDecl)
672 return getCommentForDecl(OriginalDecl, PP);
673
674 comments::FullComment *FC = RC->parse(*this, PP, D);
675 ParsedComments[Canonical] = FC;
676 return FC;
677}
678
679void ASTContext::CanonicalTemplateTemplateParm::Profile(
680 llvm::FoldingSetNodeID &ID, const ASTContext &C,
682 ID.AddInteger(Parm->getDepth());
683 ID.AddInteger(Parm->getPosition());
684 ID.AddBoolean(Parm->isParameterPack());
685 ID.AddInteger(Parm->templateParameterKind());
686
688 ID.AddInteger(Params->size());
690 PEnd = Params->end();
691 P != PEnd; ++P) {
692 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
693 ID.AddInteger(0);
694 ID.AddBoolean(TTP->isParameterPack());
695 ID.AddInteger(
696 TTP->getNumExpansionParameters().toInternalRepresentation());
697 continue;
698 }
699
700 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
701 ID.AddInteger(1);
702 ID.AddBoolean(NTTP->isParameterPack());
703 ID.AddPointer(C.getUnconstrainedType(C.getCanonicalType(NTTP->getType()))
704 .getAsOpaquePtr());
705 if (NTTP->isExpandedParameterPack()) {
706 ID.AddBoolean(true);
707 ID.AddInteger(NTTP->getNumExpansionTypes());
708 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
709 QualType T = NTTP->getExpansionType(I);
710 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
711 }
712 } else
713 ID.AddBoolean(false);
714 continue;
715 }
716
717 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
718 ID.AddInteger(2);
719 Profile(ID, C, TTP);
720 }
721}
722
723TemplateTemplateParmDecl *
725 TemplateTemplateParmDecl *TTP) const {
726 // Check if we already have a canonical template template parameter.
727 llvm::FoldingSetNodeID ID;
728 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
729 void *InsertPos = nullptr;
730 CanonicalTemplateTemplateParm *Canonical
731 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
732 if (Canonical)
733 return Canonical->getParam();
734
735 // Build a canonical template parameter list.
737 SmallVector<NamedDecl *, 4> CanonParams;
738 CanonParams.reserve(Params->size());
740 PEnd = Params->end();
741 P != PEnd; ++P) {
742 // Note that, per C++20 [temp.over.link]/6, when determining whether
743 // template-parameters are equivalent, constraints are ignored.
744 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
747 TTP->getDepth(), TTP->getIndex(), nullptr, false,
748 TTP->isParameterPack(), /*HasTypeConstraint=*/false,
749 TTP->getNumExpansionParameters());
750 CanonParams.push_back(NewTTP);
751 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
755 if (NTTP->isExpandedParameterPack()) {
756 SmallVector<QualType, 2> ExpandedTypes;
758 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
759 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
760 ExpandedTInfos.push_back(
761 getTrivialTypeSourceInfo(ExpandedTypes.back()));
762 }
763
767 NTTP->getDepth(),
768 NTTP->getPosition(), nullptr,
769 T,
770 TInfo,
771 ExpandedTypes,
772 ExpandedTInfos);
773 } else {
777 NTTP->getDepth(),
778 NTTP->getPosition(), nullptr,
779 T,
780 NTTP->isParameterPack(),
781 TInfo);
782 }
783 CanonParams.push_back(Param);
784 } else
785 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
787 }
788
791 TTP->getPosition(), TTP->isParameterPack(), nullptr,
793 /*Typename=*/false,
795 CanonParams, SourceLocation(),
796 /*RequiresClause=*/nullptr));
797
798 // Get the new insert position for the node we care about.
799 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
800 assert(!Canonical && "Shouldn't be in the map!");
801 (void)Canonical;
802
803 // Create the canonical template template parameter entry.
804 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
805 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
806 return CanonTTP;
807}
808
811 TemplateTemplateParmDecl *TTP) const {
812 llvm::FoldingSetNodeID ID;
813 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
814 void *InsertPos = nullptr;
815 CanonicalTemplateTemplateParm *Canonical =
816 CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
817 return Canonical ? Canonical->getParam() : nullptr;
818}
819
822 TemplateTemplateParmDecl *CanonTTP) const {
823 llvm::FoldingSetNodeID ID;
824 CanonicalTemplateTemplateParm::Profile(ID, *this, CanonTTP);
825 void *InsertPos = nullptr;
826 if (auto *Existing =
827 CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos))
828 return Existing->getParam();
829 CanonTemplateTemplateParms.InsertNode(
830 new (*this) CanonicalTemplateTemplateParm(CanonTTP), InsertPos);
831 return CanonTTP;
832}
833
834/// For the purposes of overflow pattern exclusion, does this match the
835/// while(i--) pattern?
836static bool matchesPostDecrInWhile(const UnaryOperator *UO, ASTContext &Ctx) {
837 if (UO->getOpcode() != UO_PostDec)
838 return false;
839
840 if (!UO->getType()->isUnsignedIntegerType())
841 return false;
842
843 // -fsanitize-undefined-ignore-overflow-pattern=unsigned-post-decr-while
846 return false;
847
848 // all Parents (usually just one) must be a WhileStmt
849 return llvm::all_of(
851 [](const DynTypedNode &P) { return P.get<WhileStmt>() != nullptr; });
852}
853
855 // -fsanitize-undefined-ignore-overflow-pattern=negated-unsigned-const
856 // ... like -1UL;
857 if (UO->getOpcode() == UO_Minus &&
858 getLangOpts().isOverflowPatternExcluded(
860 UO->isIntegerConstantExpr(*this)) {
861 return true;
862 }
863
864 if (matchesPostDecrInWhile(UO, *this))
865 return true;
866
867 return false;
868}
869
870/// Check if a type can have its sanitizer instrumentation elided based on its
871/// presence within an ignorelist.
873 const QualType &Ty) const {
874 std::string TyName = Ty.getUnqualifiedType().getAsString(getPrintingPolicy());
875 return NoSanitizeL->containsType(Mask, TyName);
876}
877
879 auto Kind = getTargetInfo().getCXXABI().getKind();
880 return getLangOpts().CXXABI.value_or(Kind);
881}
882
883CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
884 if (!LangOpts.CPlusPlus) return nullptr;
885
886 switch (getCXXABIKind()) {
887 case TargetCXXABI::AppleARM64:
888 case TargetCXXABI::Fuchsia:
889 case TargetCXXABI::GenericARM: // Same as Itanium at this level
890 case TargetCXXABI::iOS:
891 case TargetCXXABI::WatchOS:
892 case TargetCXXABI::GenericAArch64:
893 case TargetCXXABI::GenericMIPS:
894 case TargetCXXABI::GenericItanium:
895 case TargetCXXABI::WebAssembly:
896 case TargetCXXABI::XL:
897 return CreateItaniumCXXABI(*this);
898 case TargetCXXABI::Microsoft:
899 return CreateMicrosoftCXXABI(*this);
900 }
901 llvm_unreachable("Invalid CXXABI type!");
902}
903
905 if (!InterpContext) {
906 InterpContext.reset(new interp::Context(const_cast<ASTContext &>(*this)));
907 }
908 return *InterpContext;
909}
910
912 if (!ParentMapCtx)
913 ParentMapCtx.reset(new ParentMapContext(*this));
914 return *ParentMapCtx;
915}
916
918 const LangOptions &LangOpts) {
919 switch (LangOpts.getAddressSpaceMapMangling()) {
921 return TI.useAddressSpaceMapMangling();
923 return true;
925 return false;
926 }
927 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
928}
929
931 IdentifierTable &idents, SelectorTable &sels,
933 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize),
934 DependentSizedArrayTypes(this_()), DependentSizedExtVectorTypes(this_()),
935 DependentAddressSpaceTypes(this_()), DependentVectorTypes(this_()),
936 DependentSizedMatrixTypes(this_()),
937 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize),
938 DependentTypeOfExprTypes(this_()), DependentDecltypeTypes(this_()),
939 DependentPackIndexingTypes(this_()), TemplateSpecializationTypes(this_()),
940 AttributedTypes(this_()), DependentBitIntTypes(this_()),
941 SubstTemplateTemplateParmPacks(this_()), DeducedTemplates(this_()),
942 ArrayParameterTypes(this_()), CanonTemplateTemplateParms(this_()),
943 SourceMgr(SM), LangOpts(LOpts),
944 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
945 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
946 LangOpts.XRayNeverInstrumentFiles,
947 LangOpts.XRayAttrListFiles, SM)),
948 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
949 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
950 BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this),
951 Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
952 CompCategories(this_()), LastSDM(nullptr, 0) {
954}
955
957 // Release the DenseMaps associated with DeclContext objects.
958 // FIXME: Is this the ideal solution?
959 ReleaseDeclContextMaps();
960
961 // Call all of the deallocation functions on all of their targets.
962 for (auto &Pair : Deallocations)
963 (Pair.first)(Pair.second);
964 Deallocations.clear();
965
966 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
967 // because they can contain DenseMaps.
968 for (llvm::DenseMap<const ObjCInterfaceDecl *,
970 I = ObjCLayouts.begin(),
971 E = ObjCLayouts.end();
972 I != E;)
973 // Increment in loop to prevent using deallocated memory.
974 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
975 R->Destroy(*this);
976 ObjCLayouts.clear();
977
978 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
979 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
980 // Increment in loop to prevent using deallocated memory.
981 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
982 R->Destroy(*this);
983 }
984 ASTRecordLayouts.clear();
985
986 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
987 AEnd = DeclAttrs.end();
988 A != AEnd; ++A)
989 A->second->~AttrVec();
990 DeclAttrs.clear();
991
992 CtorClosureDefaultArgs.clear();
993
994 for (const auto &Value : ModuleInitializers)
995 Value.second->~PerModuleInitializers();
996 ModuleInitializers.clear();
997
998 TUDecl = nullptr;
999 XRayFilter.reset();
1000 NoSanitizeL.reset();
1001}
1002
1004
1005void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
1006 TraversalScope = TopLevelDecls;
1008}
1009
1010void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
1011 Deallocations.push_back({Callback, Data});
1012}
1013
1014void
1018
1020 llvm::errs() << "\n*** AST Context Stats:\n";
1021 llvm::errs() << " " << Types.size() << " types total.\n";
1022
1023 unsigned counts[] = {
1024#define TYPE(Name, Parent) 0,
1025#define ABSTRACT_TYPE(Name, Parent)
1026#include "clang/AST/TypeNodes.inc"
1027 0 // Extra
1028 };
1029
1030 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1031 Type *T = Types[i];
1032 counts[(unsigned)T->getTypeClass()]++;
1033 }
1034
1035 unsigned Idx = 0;
1036 unsigned TotalBytes = 0;
1037#define TYPE(Name, Parent) \
1038 if (counts[Idx]) \
1039 llvm::errs() << " " << counts[Idx] << " " << #Name \
1040 << " types, " << sizeof(Name##Type) << " each " \
1041 << "(" << counts[Idx] * sizeof(Name##Type) \
1042 << " bytes)\n"; \
1043 TotalBytes += counts[Idx] * sizeof(Name##Type); \
1044 ++Idx;
1045#define ABSTRACT_TYPE(Name, Parent)
1046#include "clang/AST/TypeNodes.inc"
1047
1048 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1049
1050 // Implicit special member functions.
1051 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1053 << " implicit default constructors created\n";
1054 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1056 << " implicit copy constructors created\n";
1057 if (getLangOpts().CPlusPlus)
1058 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1060 << " implicit move constructors created\n";
1061 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1063 << " implicit copy assignment operators created\n";
1064 if (getLangOpts().CPlusPlus)
1065 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1067 << " implicit move assignment operators created\n";
1068 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1070 << " implicit destructors created\n";
1071
1072 if (ExternalSource) {
1073 llvm::errs() << "\n";
1074 ExternalSource->PrintStats();
1075 }
1076
1077 BumpAlloc.PrintStats();
1078}
1079
1081 bool NotifyListeners) {
1082 if (NotifyListeners)
1083 if (auto *Listener = getASTMutationListener();
1085 Listener->RedefinedHiddenDefinition(ND, M);
1086
1087 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1088}
1089
1091 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1092 if (It == MergedDefModules.end())
1093 return;
1094
1095 auto &Merged = It->second;
1096 llvm::DenseSet<Module*> Found;
1097 for (Module *&M : Merged)
1098 if (!Found.insert(M).second)
1099 M = nullptr;
1100 llvm::erase(Merged, nullptr);
1101}
1102
1105 auto MergedIt =
1106 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1107 if (MergedIt == MergedDefModules.end())
1108 return {};
1109 return MergedIt->second;
1110}
1111
1112void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1113 if (LazyInitializers.empty())
1114 return;
1115
1116 auto *Source = Ctx.getExternalSource();
1117 assert(Source && "lazy initializers but no external source");
1118
1119 auto LazyInits = std::move(LazyInitializers);
1120 LazyInitializers.clear();
1121
1122 for (auto ID : LazyInits)
1123 Initializers.push_back(Source->GetExternalDecl(ID));
1124
1125 assert(LazyInitializers.empty() &&
1126 "GetExternalDecl for lazy module initializer added more inits");
1127}
1128
1130 // One special case: if we add a module initializer that imports another
1131 // module, and that module's only initializer is an ImportDecl, simplify.
1132 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1133 auto It = ModuleInitializers.find(ID->getImportedModule());
1134
1135 // Maybe the ImportDecl does nothing at all. (Common case.)
1136 if (It == ModuleInitializers.end())
1137 return;
1138
1139 // Maybe the ImportDecl only imports another ImportDecl.
1140 auto &Imported = *It->second;
1141 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1142 Imported.resolve(*this);
1143 auto *OnlyDecl = Imported.Initializers.front();
1144 if (isa<ImportDecl>(OnlyDecl))
1145 D = OnlyDecl;
1146 }
1147 }
1148
1149 auto *&Inits = ModuleInitializers[M];
1150 if (!Inits)
1151 Inits = new (*this) PerModuleInitializers;
1152 Inits->Initializers.push_back(D);
1153}
1154
1157 auto *&Inits = ModuleInitializers[M];
1158 if (!Inits)
1159 Inits = new (*this) PerModuleInitializers;
1160 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1161 IDs.begin(), IDs.end());
1162}
1163
1165 auto It = ModuleInitializers.find(M);
1166 if (It == ModuleInitializers.end())
1167 return {};
1168
1169 auto *Inits = It->second;
1170 Inits->resolve(*this);
1171 return Inits->Initializers;
1172}
1173
1175 assert(M->isNamedModule());
1176 assert(!CurrentCXXNamedModule &&
1177 "We should set named module for ASTContext for only once");
1178 CurrentCXXNamedModule = M;
1179}
1180
1181bool ASTContext::isInSameModule(const Module *M1, const Module *M2) const {
1182 if (!M1 != !M2)
1183 return false;
1184
1185 /// Get the representative module for M. The representative module is the
1186 /// first module unit for a specific primary module name. So that the module
1187 /// units have the same representative module belongs to the same module.
1188 ///
1189 /// The process is helpful to reduce the expensive string operations.
1190 auto GetRepresentativeModule = [this](const Module *M) {
1191 auto Iter = SameModuleLookupSet.find(M);
1192 if (Iter != SameModuleLookupSet.end())
1193 return Iter->second;
1194
1195 const Module *RepresentativeModule =
1196 PrimaryModuleNameMap.try_emplace(M->getPrimaryModuleInterfaceName(), M)
1197 .first->second;
1198 SameModuleLookupSet[M] = RepresentativeModule;
1199 return RepresentativeModule;
1200 };
1201
1202 assert(M1 && "Shouldn't call `isInSameModule` if both M1 and M2 are none.");
1203 return GetRepresentativeModule(M1) == GetRepresentativeModule(M2);
1204}
1205
1207 if (!ExternCContext)
1208 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1209
1210 return ExternCContext;
1211}
1212
1223
1224#define BuiltinTemplate(BTName) \
1225 BuiltinTemplateDecl *ASTContext::get##BTName##Decl() const { \
1226 if (!Decl##BTName) \
1227 Decl##BTName = \
1228 buildBuiltinTemplateDecl(BTK##BTName, get##BTName##Name()); \
1229 return Decl##BTName; \
1230 }
1231#include "clang/Basic/BuiltinTemplates.inc"
1232
1234 RecordDecl::TagKind TK) const {
1235 SourceLocation Loc;
1236 RecordDecl *NewDecl;
1237 if (getLangOpts().CPlusPlus)
1238 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1239 Loc, &Idents.get(Name));
1240 else
1241 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1242 &Idents.get(Name));
1243 NewDecl->setImplicit();
1244 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1245 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1246 return NewDecl;
1247}
1248
1250 StringRef Name) const {
1253 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1254 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1255 NewDecl->setImplicit();
1256 return NewDecl;
1257}
1258
1260 if (!Int128Decl)
1261 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1262 return Int128Decl;
1263}
1264
1266 if (!UInt128Decl)
1267 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1268 return UInt128Decl;
1269}
1270
1271void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1272 auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K);
1274 Types.push_back(Ty);
1275}
1276
1278 const TargetInfo *AuxTarget) {
1279 assert((!this->Target || this->Target == &Target) &&
1280 "Incorrect target reinitialization");
1281 assert(VoidTy.isNull() && "Context reinitialized?");
1282
1283 this->Target = &Target;
1284 this->AuxTarget = AuxTarget;
1285
1286 ABI.reset(createCXXABI(Target));
1287 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1288
1289 // C99 6.2.5p19.
1290 InitBuiltinType(VoidTy, BuiltinType::Void);
1291
1292 // C99 6.2.5p2.
1293 InitBuiltinType(BoolTy, BuiltinType::Bool);
1294 // C99 6.2.5p3.
1295 if (LangOpts.CharIsSigned)
1296 InitBuiltinType(CharTy, BuiltinType::Char_S);
1297 else
1298 InitBuiltinType(CharTy, BuiltinType::Char_U);
1299 // C99 6.2.5p4.
1300 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1301 InitBuiltinType(ShortTy, BuiltinType::Short);
1302 InitBuiltinType(IntTy, BuiltinType::Int);
1303 InitBuiltinType(LongTy, BuiltinType::Long);
1304 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1305
1306 // C99 6.2.5p6.
1307 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1308 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1309 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1310 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1311 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1312
1313 // C99 6.2.5p10.
1314 InitBuiltinType(FloatTy, BuiltinType::Float);
1315 InitBuiltinType(DoubleTy, BuiltinType::Double);
1316 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1317
1318 // GNU extension, __float128 for IEEE quadruple precision
1319 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1320
1321 // __ibm128 for IBM extended precision
1322 InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128);
1323
1324 // C11 extension ISO/IEC TS 18661-3
1325 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1326
1327 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1328 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1329 InitBuiltinType(AccumTy, BuiltinType::Accum);
1330 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1331 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1332 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1333 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1334 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1335 InitBuiltinType(FractTy, BuiltinType::Fract);
1336 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1337 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1338 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1339 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1340 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1341 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1342 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1343 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1344 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1345 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1346 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1347 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1348 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1349 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1350 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1351 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
1352
1353 // GNU extension, 128-bit integers.
1354 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1355 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1356
1357 // C++ 3.9.1p5
1358 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1359 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1360 else // -fshort-wchar makes wchar_t be unsigned.
1361 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1362 if (LangOpts.CPlusPlus && LangOpts.WChar)
1364 else {
1365 // C99 (or C++ using -fno-wchar).
1366 WideCharTy = getFromTargetType(Target.getWCharType());
1367 }
1368
1369 WIntTy = getFromTargetType(Target.getWIntType());
1370
1371 // C++20 (proposed)
1372 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1373
1374 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1375 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1376 else // C99
1377 Char16Ty = getFromTargetType(Target.getChar16Type());
1378
1379 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1380 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1381 else // C99
1382 Char32Ty = getFromTargetType(Target.getChar32Type());
1383
1384 // Placeholder type for type-dependent expressions whose type is
1385 // completely unknown. No code should ever check a type against
1386 // DependentTy and users should never see it; however, it is here to
1387 // help diagnose failures to properly check for type-dependent
1388 // expressions.
1389 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1390
1391 // Placeholder type for functions.
1392 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1393
1394 // Placeholder type for bound members.
1395 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1396
1397 // Placeholder type for unresolved templates.
1398 InitBuiltinType(UnresolvedTemplateTy, BuiltinType::UnresolvedTemplate);
1399
1400 // Placeholder type for pseudo-objects.
1401 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1402
1403 // "any" type; useful for debugger-like clients.
1404 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1405
1406 // Placeholder type for unbridged ARC casts.
1407 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1408
1409 // Placeholder type for builtin functions.
1410 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1411
1412 // Placeholder type for OMP array sections.
1413 if (LangOpts.OpenMP) {
1414 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1415 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1416 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1417 }
1418 // Placeholder type for OpenACC array sections, if we are ALSO in OMP mode,
1419 // don't bother, as we're just using the same type as OMP.
1420 if (LangOpts.OpenACC && !LangOpts.OpenMP) {
1421 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1422 }
1423 if (LangOpts.MatrixTypes)
1424 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1425
1426 // Builtin types for 'id', 'Class', and 'SEL'.
1427 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1428 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1429 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1430
1431 if (LangOpts.OpenCL) {
1432#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1433 InitBuiltinType(SingletonId, BuiltinType::Id);
1434#include "clang/Basic/OpenCLImageTypes.def"
1435
1436 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1437 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1438 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1439 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1440 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1441
1442#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1443 InitBuiltinType(Id##Ty, BuiltinType::Id);
1444#include "clang/Basic/OpenCLExtensionTypes.def"
1445 }
1446
1447 if (LangOpts.HLSL) {
1448#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1449 InitBuiltinType(SingletonId, BuiltinType::Id);
1450#include "clang/Basic/HLSLIntangibleTypes.def"
1451 }
1452
1453 if (Target.hasAArch64ACLETypes() ||
1454 (AuxTarget && AuxTarget->hasAArch64ACLETypes())) {
1455#define SVE_TYPE(Name, Id, SingletonId) \
1456 InitBuiltinType(SingletonId, BuiltinType::Id);
1457#include "clang/Basic/AArch64ACLETypes.def"
1458 }
1459
1460 if (Target.getTriple().isPPC64()) {
1461#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1462 InitBuiltinType(Id##Ty, BuiltinType::Id);
1463#include "clang/Basic/PPCTypes.def"
1464#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1465 InitBuiltinType(Id##Ty, BuiltinType::Id);
1466#include "clang/Basic/PPCTypes.def"
1467 }
1468
1469 if (Target.hasRISCVVTypes()) {
1470#define RVV_TYPE(Name, Id, SingletonId) \
1471 InitBuiltinType(SingletonId, BuiltinType::Id);
1472#include "clang/Basic/RISCVVTypes.def"
1473 }
1474
1475 if (Target.getTriple().isWasm() && Target.hasFeature("reference-types")) {
1476#define WASM_TYPE(Name, Id, SingletonId) \
1477 InitBuiltinType(SingletonId, BuiltinType::Id);
1478#include "clang/Basic/WebAssemblyReferenceTypes.def"
1479 }
1480
1481 if (Target.getTriple().isAMDGPU() ||
1482 (Target.getTriple().isSPIRV() &&
1483 Target.getTriple().getVendor() == llvm::Triple::AMD) ||
1484 (AuxTarget &&
1485 (AuxTarget->getTriple().isAMDGPU() ||
1486 ((AuxTarget->getTriple().isSPIRV() &&
1487 AuxTarget->getTriple().getVendor() == llvm::Triple::AMD))))) {
1488#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
1489 InitBuiltinType(SingletonId, BuiltinType::Id);
1490#include "clang/Basic/AMDGPUTypes.def"
1491 }
1492
1493 // Builtin type for __objc_yes and __objc_no
1494 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1496
1497 ObjCConstantStringType = QualType();
1498
1499 ObjCSuperType = QualType();
1500
1501 // void * type
1502 if (LangOpts.OpenCLGenericAddressSpace) {
1503 auto Q = VoidTy.getQualifiers();
1504 Q.setAddressSpace(LangAS::opencl_generic);
1506 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1507 } else {
1509 }
1510
1511 // nullptr type (C++0x 2.14.7)
1512 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1513
1514 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1515 InitBuiltinType(HalfTy, BuiltinType::Half);
1516
1517 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1518
1519 // Builtin type used to help define __builtin_va_list.
1520 VaListTagDecl = nullptr;
1521
1522 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1523 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1526 }
1527}
1528
1530 return SourceMgr.getDiagnostics();
1531}
1532
1534 AttrVec *&Result = DeclAttrs[D];
1535 if (!Result) {
1536 void *Mem = Allocate(sizeof(AttrVec));
1537 Result = new (Mem) AttrVec;
1538 }
1539
1540 return *Result;
1541}
1542
1543/// Erase the attributes corresponding to the given declaration.
1545 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1546 if (Pos != DeclAttrs.end()) {
1547 Pos->second->~AttrVec();
1548 DeclAttrs.erase(Pos);
1549 }
1550}
1551
1554 return CtorClosureDefaultArgs.lookup(CD);
1555}
1556
1559 assert(!CtorClosureDefaultArgs.contains(CD));
1560 CtorClosureDefaultArgs[CD] = Args;
1561}
1562
1565 auto It =
1566 ExplicitInstantiations.find(cast<NamedDecl>(Spec->getCanonicalDecl()));
1567 if (It != ExplicitInstantiations.end())
1568 return It->second;
1569 return {};
1570}
1571
1574 ExplicitInstantiations[cast<NamedDecl>(Spec->getCanonicalDecl())].push_back(
1575 EID);
1576}
1577
1578// FIXME: Remove ?
1581 assert(Var->isStaticDataMember() && "Not a static data member");
1583 .dyn_cast<MemberSpecializationInfo *>();
1584}
1585
1588 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1589 TemplateOrInstantiation.find(Var);
1590 if (Pos == TemplateOrInstantiation.end())
1591 return {};
1592
1593 return Pos->second;
1594}
1595
1596void
1599 SourceLocation PointOfInstantiation) {
1600 assert(Inst->isStaticDataMember() && "Not a static data member");
1601 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1603 Tmpl, TSK, PointOfInstantiation));
1604}
1605
1606void
1609 assert(!TemplateOrInstantiation[Inst] &&
1610 "Already noted what the variable was instantiated from");
1611 TemplateOrInstantiation[Inst] = TSI;
1612}
1613
1614NamedDecl *
1616 return InstantiatedFromUsingDecl.lookup(UUD);
1617}
1618
1619void
1621 assert((isa<UsingDecl>(Pattern) ||
1624 "pattern decl is not a using decl");
1625 assert((isa<UsingDecl>(Inst) ||
1628 "instantiation did not produce a using decl");
1629 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1630 InstantiatedFromUsingDecl[Inst] = Pattern;
1631}
1632
1635 return InstantiatedFromUsingEnumDecl.lookup(UUD);
1636}
1637
1639 UsingEnumDecl *Pattern) {
1640 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1641 InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1642}
1643
1646 return InstantiatedFromUsingShadowDecl.lookup(Inst);
1647}
1648
1649void
1651 UsingShadowDecl *Pattern) {
1652 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1653 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1654}
1655
1656FieldDecl *
1658 return InstantiatedFromUnnamedFieldDecl.lookup(Field);
1659}
1660
1662 FieldDecl *Tmpl) {
1663 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1664 "Instantiated field decl is not unnamed");
1665 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1666 "Template field decl is not unnamed");
1667 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1668 "Already noted what unnamed field was instantiated from");
1669
1670 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1671}
1672
1677
1682
1683unsigned
1685 auto Range = overridden_methods(Method);
1686 return Range.end() - Range.begin();
1687}
1688
1691 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1692 OverriddenMethods.find(Method->getCanonicalDecl());
1693 if (Pos == OverriddenMethods.end())
1694 return overridden_method_range(nullptr, nullptr);
1695 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1696}
1697
1699 const CXXMethodDecl *Overridden) {
1700 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1701 OverriddenMethods[Method].push_back(Overridden);
1702}
1703
1705 const NamedDecl *D,
1706 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1707 assert(D);
1708
1709 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1710 Overridden.append(overridden_methods_begin(CXXMethod),
1711 overridden_methods_end(CXXMethod));
1712 return;
1713 }
1714
1715 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1716 if (!Method)
1717 return;
1718
1720 Method->getOverriddenMethods(OverDecls);
1721 Overridden.append(OverDecls.begin(), OverDecls.end());
1722}
1723
1724std::optional<ASTContext::CXXRecordDeclRelocationInfo>
1726 assert(RD);
1727 CXXRecordDecl *D = RD->getDefinition();
1728 auto it = RelocatableClasses.find(D);
1729 if (it != RelocatableClasses.end())
1730 return it->getSecond();
1731 return std::nullopt;
1732}
1733
1736 assert(RD);
1737 CXXRecordDecl *D = RD->getDefinition();
1738 assert(RelocatableClasses.find(D) == RelocatableClasses.end());
1739 RelocatableClasses.insert({D, Info});
1740}
1741
1743 const ASTContext &Context, const CXXRecordDecl *Class) {
1744 if (!Class->isPolymorphic())
1745 return false;
1746 const CXXRecordDecl *BaseType = Context.baseForVTableAuthentication(Class);
1747 using AuthAttr = VTablePointerAuthenticationAttr;
1748 const AuthAttr *ExplicitAuth = BaseType->getAttr<AuthAttr>();
1749 if (!ExplicitAuth)
1750 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1751 AuthAttr::AddressDiscriminationMode AddressDiscrimination =
1752 ExplicitAuth->getAddressDiscrimination();
1753 if (AddressDiscrimination == AuthAttr::DefaultAddressDiscrimination)
1754 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1755 return AddressDiscrimination == AuthAttr::AddressDiscrimination;
1756}
1757
1758ASTContext::PointerAuthContent
1759ASTContext::findPointerAuthContent(QualType T) const {
1760 assert(isPointerAuthenticationAvailable());
1761
1762 T = T.getCanonicalType();
1763 if (T->isDependentType())
1764 return PointerAuthContent::None;
1765
1766 if (T.hasAddressDiscriminatedPointerAuth())
1767 return PointerAuthContent::AddressDiscriminatedData;
1768 const RecordDecl *RD = T->getAsRecordDecl();
1769 if (!RD)
1770 return PointerAuthContent::None;
1771
1772 if (RD->isInvalidDecl())
1773 return PointerAuthContent::None;
1774
1775 if (auto Existing = RecordContainsAddressDiscriminatedPointerAuth.find(RD);
1776 Existing != RecordContainsAddressDiscriminatedPointerAuth.end())
1777 return Existing->second;
1778
1779 PointerAuthContent Result = PointerAuthContent::None;
1780
1781 auto SaveResultAndReturn = [&]() -> PointerAuthContent {
1782 auto [ResultIter, DidAdd] =
1783 RecordContainsAddressDiscriminatedPointerAuth.try_emplace(RD, Result);
1784 (void)ResultIter;
1785 (void)DidAdd;
1786 assert(DidAdd);
1787 return Result;
1788 };
1789 auto ShouldContinueAfterUpdate = [&](PointerAuthContent NewResult) {
1790 static_assert(PointerAuthContent::None <
1791 PointerAuthContent::AddressDiscriminatedVTable);
1792 static_assert(PointerAuthContent::AddressDiscriminatedVTable <
1793 PointerAuthContent::AddressDiscriminatedData);
1794 if (NewResult > Result)
1795 Result = NewResult;
1796 return Result != PointerAuthContent::AddressDiscriminatedData;
1797 };
1798 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1800 !ShouldContinueAfterUpdate(
1801 PointerAuthContent::AddressDiscriminatedVTable))
1802 return SaveResultAndReturn();
1803 for (auto Base : CXXRD->bases()) {
1804 if (!ShouldContinueAfterUpdate(findPointerAuthContent(Base.getType())))
1805 return SaveResultAndReturn();
1806 }
1807 }
1808 for (auto *FieldDecl : RD->fields()) {
1809 if (!ShouldContinueAfterUpdate(
1810 findPointerAuthContent(FieldDecl->getType())))
1811 return SaveResultAndReturn();
1812 }
1813 return SaveResultAndReturn();
1814}
1815
1817 assert(!Import->getNextLocalImport() &&
1818 "Import declaration already in the chain");
1819 assert(!Import->isFromASTFile() && "Non-local import declaration");
1820 if (!FirstLocalImport) {
1821 FirstLocalImport = Import;
1822 LastLocalImport = Import;
1823 return;
1824 }
1825
1826 LastLocalImport->setNextLocalImport(Import);
1827 LastLocalImport = Import;
1828}
1829
1830//===----------------------------------------------------------------------===//
1831// Type Sizing and Analysis
1832//===----------------------------------------------------------------------===//
1833
1834/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1835/// scalar floating point type.
1836const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1837 switch (T->castAs<BuiltinType>()->getKind()) {
1838 default:
1839 llvm_unreachable("Not a floating point type!");
1840 case BuiltinType::BFloat16:
1841 return Target->getBFloat16Format();
1842 case BuiltinType::Float16:
1843 return Target->getHalfFormat();
1844 case BuiltinType::Half:
1845 return Target->getHalfFormat();
1846 case BuiltinType::Float: return Target->getFloatFormat();
1847 case BuiltinType::Double: return Target->getDoubleFormat();
1848 case BuiltinType::Ibm128:
1849 return Target->getIbm128Format();
1850 case BuiltinType::LongDouble:
1851 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1852 return AuxTarget->getLongDoubleFormat();
1853 return Target->getLongDoubleFormat();
1854 case BuiltinType::Float128:
1855 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1856 return AuxTarget->getFloat128Format();
1857 return Target->getFloat128Format();
1858 }
1859}
1860
1861CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1862 unsigned Align = Target->getCharWidth();
1863
1864 const unsigned AlignFromAttr = D->getMaxAlignment();
1865 if (AlignFromAttr)
1866 Align = AlignFromAttr;
1867
1868 // __attribute__((aligned)) can increase or decrease alignment
1869 // *except* on a struct or struct member, where it only increases
1870 // alignment unless 'packed' is also specified.
1871 //
1872 // It is an error for alignas to decrease alignment, so we can
1873 // ignore that possibility; Sema should diagnose it.
1874 bool UseAlignAttrOnly;
1875 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D))
1876 UseAlignAttrOnly =
1877 FD->hasAttr<PackedAttr>() || FD->getParent()->hasAttr<PackedAttr>();
1878 else
1879 UseAlignAttrOnly = AlignFromAttr != 0;
1880 // If we're using the align attribute only, just ignore everything
1881 // else about the declaration and its type.
1882 if (UseAlignAttrOnly) {
1883 // do nothing
1884 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1885 QualType T = VD->getType();
1886 if (const auto *RT = T->getAs<ReferenceType>()) {
1887 if (ForAlignof)
1888 T = RT->getPointeeType();
1889 else
1890 T = getPointerType(RT->getPointeeType());
1891 }
1892 QualType BaseT = getBaseElementType(T);
1893 if (T->isFunctionType())
1894 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1895 else if (!BaseT->isIncompleteType()) {
1896 // Adjust alignments of declarations with array type by the
1897 // large-array alignment on the target.
1898 if (const ArrayType *arrayType = getAsArrayType(T)) {
1899 unsigned MinWidth = Target->getLargeArrayMinWidth();
1900 if (!ForAlignof && MinWidth) {
1902 Align = std::max(Align, Target->getLargeArrayAlign());
1905 Align = std::max(Align, Target->getLargeArrayAlign());
1906 }
1907 }
1908 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1909 if (BaseT.getQualifiers().hasUnaligned())
1910 Align = Target->getCharWidth();
1911 }
1912
1913 // Ensure minimum alignment for global variables.
1914 if (const auto *VD = dyn_cast<VarDecl>(D))
1915 if (VD->hasGlobalStorage() && !ForAlignof) {
1916 uint64_t TypeSize =
1917 !BaseT->isIncompleteType() ? getTypeSize(T.getTypePtr()) : 0;
1918 Align = std::max(Align, getMinGlobalAlignOfVar(TypeSize, VD));
1919 }
1920
1921 // Fields can be subject to extra alignment constraints, like if
1922 // the field is packed, the struct is packed, or the struct has a
1923 // a max-field-alignment constraint (#pragma pack). So calculate
1924 // the actual alignment of the field within the struct, and then
1925 // (as we're expected to) constrain that by the alignment of the type.
1926 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1927 const RecordDecl *Parent = Field->getParent();
1928 // We can only produce a sensible answer if the record is valid.
1929 if (!Parent->isInvalidDecl()) {
1930 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1931
1932 // Start with the record's overall alignment.
1933 unsigned FieldAlign = toBits(Layout.getAlignment());
1934
1935 // Use the GCD of that and the offset within the record.
1936 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1937 if (Offset > 0) {
1938 // Alignment is always a power of 2, so the GCD will be a power of 2,
1939 // which means we get to do this crazy thing instead of Euclid's.
1940 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1941 if (LowBitOfOffset < FieldAlign)
1942 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1943 }
1944
1945 Align = std::min(Align, FieldAlign);
1946 }
1947 }
1948 }
1949
1950 // Some targets have hard limitation on the maximum requestable alignment in
1951 // aligned attribute for static variables.
1952 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1953 const auto *VD = dyn_cast<VarDecl>(D);
1954 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1955 Align = std::min(Align, MaxAlignedAttr);
1956
1957 return toCharUnitsFromBits(Align);
1958}
1959
1961 return toCharUnitsFromBits(Target->getExnObjectAlignment());
1962}
1963
1964// getTypeInfoDataSizeInChars - Return the size of a type, in
1965// chars. If the type is a record, its data size is returned. This is
1966// the size of the memcpy that's performed when assigning this type
1967// using a trivial copy/move assignment operator.
1970
1971 // In C++, objects can sometimes be allocated into the tail padding
1972 // of a base-class subobject. We decide whether that's possible
1973 // during class layout, so here we can just trust the layout results.
1974 if (getLangOpts().CPlusPlus) {
1975 if (const auto *RD = T->getAsCXXRecordDecl(); RD && !RD->isInvalidDecl()) {
1976 const ASTRecordLayout &layout = getASTRecordLayout(RD);
1977 Info.Width = layout.getDataSize();
1978 }
1979 }
1980
1981 return Info;
1982}
1983
1984/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1985/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1988 const ConstantArrayType *CAT) {
1989 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1990 uint64_t Size = CAT->getZExtSize();
1991 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1992 (uint64_t)(-1)/Size) &&
1993 "Overflow in array type char size evaluation");
1994 uint64_t Width = EltInfo.Width.getQuantity() * Size;
1995 unsigned Align = EltInfo.Align.getQuantity();
1996 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1997 Context.getTargetInfo().getPointerWidth(LangAS::Default) == 64)
1998 Width = llvm::alignTo(Width, Align);
2001 EltInfo.AlignRequirement);
2002}
2003
2005 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
2006 return getConstantArrayInfoInChars(*this, CAT);
2007 TypeInfo Info = getTypeInfo(T);
2010}
2011
2015
2017 // HLSL doesn't promote all small integer types to int, it
2018 // just uses the rank-based promotion rules for all types.
2019 if (getLangOpts().HLSL)
2020 return false;
2021
2022 if (const auto *BT = T->getAs<BuiltinType>())
2023 switch (BT->getKind()) {
2024 case BuiltinType::Bool:
2025 case BuiltinType::Char_S:
2026 case BuiltinType::Char_U:
2027 case BuiltinType::SChar:
2028 case BuiltinType::UChar:
2029 case BuiltinType::Short:
2030 case BuiltinType::UShort:
2031 case BuiltinType::WChar_S:
2032 case BuiltinType::WChar_U:
2033 case BuiltinType::Char8:
2034 case BuiltinType::Char16:
2035 case BuiltinType::Char32:
2036 return true;
2037 default:
2038 return false;
2039 }
2040
2041 // Enumerated types are promotable to their compatible integer types
2042 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
2043 if (const auto *ED = T->getAsEnumDecl()) {
2044 if (T->isDependentType() || ED->getPromotionType().isNull() ||
2045 ED->isScoped())
2046 return false;
2047
2048 return true;
2049 }
2050
2051 // OverflowBehaviorTypes are promotable if their underlying type is promotable
2052 if (const auto *OBT = T->getAs<OverflowBehaviorType>()) {
2053 return isPromotableIntegerType(OBT->getUnderlyingType());
2054 }
2055
2056 return false;
2057}
2058
2062
2064 return isAlignmentRequired(T.getTypePtr());
2065}
2066
2068 bool NeedsPreferredAlignment) const {
2069 // An alignment on a typedef overrides anything else.
2070 if (const auto *TT = T->getAs<TypedefType>())
2071 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2072 return Align;
2073
2074 // If we have an (array of) complete type, we're done.
2076 if (!T->isIncompleteType())
2077 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
2078
2079 // If we had an array type, its element type might be a typedef
2080 // type with an alignment attribute.
2081 if (const auto *TT = T->getAs<TypedefType>())
2082 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2083 return Align;
2084
2085 // Otherwise, see if the declaration of the type had an attribute.
2086 if (const auto *TD = T->getAsTagDecl())
2087 return TD->getMaxAlignment();
2088
2089 return 0;
2090}
2091
2093 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
2094 if (I != MemoizedTypeInfo.end())
2095 return I->second;
2096
2097 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
2098 TypeInfo TI = getTypeInfoImpl(T);
2099 MemoizedTypeInfo[T] = TI;
2100 return TI;
2101}
2102
2103/// getTypeInfoImpl - Return the size of the specified type, in bits. This
2104/// method does not work on incomplete types.
2105///
2106/// FIXME: Pointers into different addr spaces could have different sizes and
2107/// alignment requirements: getPointerInfo should take an AddrSpace, this
2108/// should take a QualType, &c.
2109TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
2110 uint64_t Width = 0;
2111 unsigned Align = 8;
2114 switch (T->getTypeClass()) {
2115#define TYPE(Class, Base)
2116#define ABSTRACT_TYPE(Class, Base)
2117#define NON_CANONICAL_TYPE(Class, Base)
2118#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2119#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
2120 case Type::Class: \
2121 assert(!T->isDependentType() && "should not see dependent types here"); \
2122 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
2123#include "clang/AST/TypeNodes.inc"
2124 llvm_unreachable("Should not see dependent types");
2125
2126 case Type::FunctionNoProto:
2127 case Type::FunctionProto:
2128 // GCC extension: alignof(function) = 32 bits
2129 Width = 0;
2130 Align = 32;
2131 break;
2132
2133 case Type::IncompleteArray:
2134 case Type::VariableArray:
2135 case Type::ConstantArray:
2136 case Type::ArrayParameter: {
2137 // Model non-constant sized arrays as size zero, but track the alignment.
2138 uint64_t Size = 0;
2139 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
2140 Size = CAT->getZExtSize();
2141
2142 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
2143 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
2144 "Overflow in array type bit size evaluation");
2145 Width = EltInfo.Width * Size;
2146 Align = EltInfo.Align;
2147 AlignRequirement = EltInfo.AlignRequirement;
2148 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
2149 getTargetInfo().getPointerWidth(LangAS::Default) == 64)
2150 Width = llvm::alignTo(Width, Align);
2151 break;
2152 }
2153
2154 case Type::ExtVector:
2155 case Type::Vector: {
2156 const auto *VT = cast<VectorType>(T);
2157 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
2158 Width = VT->isPackedVectorBoolType(*this)
2159 ? VT->getNumElements()
2160 : EltInfo.Width * VT->getNumElements();
2161 // Enforce at least byte size and alignment.
2162 Width = std::max<unsigned>(8, Width);
2163 Align = std::max<unsigned>(
2164 8, Target->vectorsAreElementAligned() ? EltInfo.Width : Width);
2165
2166 // If the alignment is not a power of 2, round up to the next power of 2.
2167 // This happens for non-power-of-2 length vectors.
2168 if (Align & (Align-1)) {
2169 Align = llvm::bit_ceil(Align);
2170 Width = llvm::alignTo(Width, Align);
2171 }
2172 // Adjust the alignment based on the target max.
2173 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
2174 if (TargetVectorAlign && TargetVectorAlign < Align)
2175 Align = TargetVectorAlign;
2176 if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
2177 // Adjust the alignment for fixed-length SVE vectors. This is important
2178 // for non-power-of-2 vector lengths.
2179 Align = 128;
2180 else if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
2181 // Adjust the alignment for fixed-length SVE predicates.
2182 Align = 16;
2183 else if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
2184 VT->getVectorKind() == VectorKind::RVVFixedLengthMask ||
2185 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
2186 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
2187 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4)
2188 // Adjust the alignment for fixed-length RVV vectors.
2189 Align = std::min<unsigned>(64, Width);
2190 break;
2191 }
2192
2193 case Type::ConstantMatrix: {
2194 const auto *MT = cast<ConstantMatrixType>(T);
2195 TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
2196 // The internal layout of a matrix value is implementation defined.
2197 // Initially be ABI compatible with arrays with respect to alignment and
2198 // size.
2199 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
2200 Align = ElementInfo.Align;
2201 break;
2202 }
2203
2204 case Type::Builtin:
2205 switch (cast<BuiltinType>(T)->getKind()) {
2206 default: llvm_unreachable("Unknown builtin type!");
2207 case BuiltinType::Void:
2208 // GCC extension: alignof(void) = 8 bits.
2209 Width = 0;
2210 Align = 8;
2211 break;
2212 case BuiltinType::Bool:
2213 Width = Target->getBoolWidth();
2214 Align = Target->getBoolAlign();
2215 break;
2216 case BuiltinType::Char_S:
2217 case BuiltinType::Char_U:
2218 case BuiltinType::UChar:
2219 case BuiltinType::SChar:
2220 case BuiltinType::Char8:
2221 Width = Target->getCharWidth();
2222 Align = Target->getCharAlign();
2223 break;
2224 case BuiltinType::WChar_S:
2225 case BuiltinType::WChar_U:
2226 Width = Target->getWCharWidth();
2227 Align = Target->getWCharAlign();
2228 break;
2229 case BuiltinType::Char16:
2230 Width = Target->getChar16Width();
2231 Align = Target->getChar16Align();
2232 break;
2233 case BuiltinType::Char32:
2234 Width = Target->getChar32Width();
2235 Align = Target->getChar32Align();
2236 break;
2237 case BuiltinType::UShort:
2238 case BuiltinType::Short:
2239 Width = Target->getShortWidth();
2240 Align = Target->getShortAlign();
2241 break;
2242 case BuiltinType::UInt:
2243 case BuiltinType::Int:
2244 Width = Target->getIntWidth();
2245 Align = Target->getIntAlign();
2246 break;
2247 case BuiltinType::ULong:
2248 case BuiltinType::Long:
2249 Width = Target->getLongWidth();
2250 Align = Target->getLongAlign();
2251 break;
2252 case BuiltinType::ULongLong:
2253 case BuiltinType::LongLong:
2254 Width = Target->getLongLongWidth();
2255 Align = Target->getLongLongAlign();
2256 break;
2257 case BuiltinType::Int128:
2258 case BuiltinType::UInt128:
2259 Width = 128;
2260 Align = Target->getInt128Align();
2261 break;
2262 case BuiltinType::ShortAccum:
2263 case BuiltinType::UShortAccum:
2264 case BuiltinType::SatShortAccum:
2265 case BuiltinType::SatUShortAccum:
2266 Width = Target->getShortAccumWidth();
2267 Align = Target->getShortAccumAlign();
2268 break;
2269 case BuiltinType::Accum:
2270 case BuiltinType::UAccum:
2271 case BuiltinType::SatAccum:
2272 case BuiltinType::SatUAccum:
2273 Width = Target->getAccumWidth();
2274 Align = Target->getAccumAlign();
2275 break;
2276 case BuiltinType::LongAccum:
2277 case BuiltinType::ULongAccum:
2278 case BuiltinType::SatLongAccum:
2279 case BuiltinType::SatULongAccum:
2280 Width = Target->getLongAccumWidth();
2281 Align = Target->getLongAccumAlign();
2282 break;
2283 case BuiltinType::ShortFract:
2284 case BuiltinType::UShortFract:
2285 case BuiltinType::SatShortFract:
2286 case BuiltinType::SatUShortFract:
2287 Width = Target->getShortFractWidth();
2288 Align = Target->getShortFractAlign();
2289 break;
2290 case BuiltinType::Fract:
2291 case BuiltinType::UFract:
2292 case BuiltinType::SatFract:
2293 case BuiltinType::SatUFract:
2294 Width = Target->getFractWidth();
2295 Align = Target->getFractAlign();
2296 break;
2297 case BuiltinType::LongFract:
2298 case BuiltinType::ULongFract:
2299 case BuiltinType::SatLongFract:
2300 case BuiltinType::SatULongFract:
2301 Width = Target->getLongFractWidth();
2302 Align = Target->getLongFractAlign();
2303 break;
2304 case BuiltinType::BFloat16:
2305 if (Target->hasBFloat16Type()) {
2306 Width = Target->getBFloat16Width();
2307 Align = Target->getBFloat16Align();
2308 } else if ((getLangOpts().SYCLIsDevice ||
2309 (getLangOpts().OpenMP &&
2310 getLangOpts().OpenMPIsTargetDevice)) &&
2311 AuxTarget->hasBFloat16Type()) {
2312 Width = AuxTarget->getBFloat16Width();
2313 Align = AuxTarget->getBFloat16Align();
2314 }
2315 break;
2316 case BuiltinType::Float16:
2317 case BuiltinType::Half:
2318 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2319 !getLangOpts().OpenMPIsTargetDevice) {
2320 Width = Target->getHalfWidth();
2321 Align = Target->getHalfAlign();
2322 } else {
2323 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2324 "Expected OpenMP device compilation.");
2325 Width = AuxTarget->getHalfWidth();
2326 Align = AuxTarget->getHalfAlign();
2327 }
2328 break;
2329 case BuiltinType::Float:
2330 Width = Target->getFloatWidth();
2331 Align = Target->getFloatAlign();
2332 break;
2333 case BuiltinType::Double:
2334 Width = Target->getDoubleWidth();
2335 Align = Target->getDoubleAlign();
2336 break;
2337 case BuiltinType::Ibm128:
2338 Width = Target->getIbm128Width();
2339 Align = Target->getIbm128Align();
2340 break;
2341 case BuiltinType::LongDouble:
2342 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2343 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2344 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2345 Width = AuxTarget->getLongDoubleWidth();
2346 Align = AuxTarget->getLongDoubleAlign();
2347 } else {
2348 Width = Target->getLongDoubleWidth();
2349 Align = Target->getLongDoubleAlign();
2350 }
2351 break;
2352 case BuiltinType::Float128:
2353 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2354 !getLangOpts().OpenMPIsTargetDevice) {
2355 Width = Target->getFloat128Width();
2356 Align = Target->getFloat128Align();
2357 } else {
2358 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2359 "Expected OpenMP device compilation.");
2360 Width = AuxTarget->getFloat128Width();
2361 Align = AuxTarget->getFloat128Align();
2362 }
2363 break;
2364 case BuiltinType::NullPtr:
2365 // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
2366 Width = Target->getPointerWidth(LangAS::Default);
2367 Align = Target->getPointerAlign(LangAS::Default);
2368 break;
2369 case BuiltinType::ObjCId:
2370 case BuiltinType::ObjCClass:
2371 case BuiltinType::ObjCSel:
2372 Width = Target->getPointerWidth(LangAS::Default);
2373 Align = Target->getPointerAlign(LangAS::Default);
2374 break;
2375 case BuiltinType::OCLSampler:
2376 case BuiltinType::OCLEvent:
2377 case BuiltinType::OCLClkEvent:
2378 case BuiltinType::OCLQueue:
2379 case BuiltinType::OCLReserveID:
2380#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2381 case BuiltinType::Id:
2382#include "clang/Basic/OpenCLImageTypes.def"
2383#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2384 case BuiltinType::Id:
2385#include "clang/Basic/OpenCLExtensionTypes.def"
2386 AS = Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
2387 Width = Target->getPointerWidth(AS);
2388 Align = Target->getPointerAlign(AS);
2389 break;
2390 // The SVE types are effectively target-specific. The length of an
2391 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2392 // of 128 bits. There is one predicate bit for each vector byte, so the
2393 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2394 //
2395 // Because the length is only known at runtime, we use a dummy value
2396 // of 0 for the static length. The alignment values are those defined
2397 // by the Procedure Call Standard for the Arm Architecture.
2398#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
2399 case BuiltinType::Id: \
2400 Width = 0; \
2401 Align = 128; \
2402 break;
2403#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
2404 case BuiltinType::Id: \
2405 Width = 0; \
2406 Align = 16; \
2407 break;
2408#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
2409 case BuiltinType::Id: \
2410 Width = 0; \
2411 Align = 16; \
2412 break;
2413#define SVE_SCALAR_TYPE(Name, MangledName, Id, SingletonId, Bits) \
2414 case BuiltinType::Id: \
2415 Width = Bits; \
2416 Align = Bits; \
2417 break;
2418#include "clang/Basic/AArch64ACLETypes.def"
2419#define PPC_VECTOR_TYPE(Name, Id, Size) \
2420 case BuiltinType::Id: \
2421 Width = Size; \
2422 Align = Size; \
2423 break;
2424#include "clang/Basic/PPCTypes.def"
2425#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
2426 IsFP, IsBF) \
2427 case BuiltinType::Id: \
2428 Width = 0; \
2429 Align = ElBits; \
2430 break;
2431#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2432 case BuiltinType::Id: \
2433 Width = 0; \
2434 Align = 8; \
2435 break;
2436#include "clang/Basic/RISCVVTypes.def"
2437#define WASM_TYPE(Name, Id, SingletonId) \
2438 case BuiltinType::Id: \
2439 Width = 0; \
2440 Align = 8; \
2441 break;
2442#include "clang/Basic/WebAssemblyReferenceTypes.def"
2443#define AMDGPU_TYPE(NAME, ID, SINGLETONID, WIDTH, ALIGN) \
2444 case BuiltinType::ID: \
2445 Width = WIDTH; \
2446 Align = ALIGN; \
2447 break;
2448#include "clang/Basic/AMDGPUTypes.def"
2449#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2450#include "clang/Basic/HLSLIntangibleTypes.def"
2451 Width = Target->getPointerWidth(LangAS::Default);
2452 Align = Target->getPointerAlign(LangAS::Default);
2453 break;
2454 }
2455 break;
2456 case Type::ObjCObjectPointer:
2457 Width = Target->getPointerWidth(LangAS::Default);
2458 Align = Target->getPointerAlign(LangAS::Default);
2459 break;
2460 case Type::BlockPointer:
2461 AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
2462 Width = Target->getPointerWidth(AS);
2463 Align = Target->getPointerAlign(AS);
2464 break;
2465 case Type::LValueReference:
2466 case Type::RValueReference:
2467 // alignof and sizeof should never enter this code path here, so we go
2468 // the pointer route.
2469 AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
2470 Width = Target->getPointerWidth(AS);
2471 Align = Target->getPointerAlign(AS);
2472 break;
2473 case Type::Pointer:
2474 AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
2475 Width = Target->getPointerWidth(AS);
2476 Align = Target->getPointerAlign(AS);
2477 break;
2478 case Type::MemberPointer: {
2479 const auto *MPT = cast<MemberPointerType>(T);
2480 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2481 Width = MPI.Width;
2482 Align = MPI.Align;
2483 break;
2484 }
2485 case Type::Complex: {
2486 // Complex types have the same alignment as their elements, but twice the
2487 // size.
2488 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2489 Width = EltInfo.Width * 2;
2490 Align = EltInfo.Align;
2491 break;
2492 }
2493 case Type::ObjCObject:
2494 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2495 case Type::Adjusted:
2496 case Type::Decayed:
2497 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2498 case Type::ObjCInterface: {
2499 const auto *ObjCI = cast<ObjCInterfaceType>(T);
2500 if (ObjCI->getDecl()->isInvalidDecl()) {
2501 Width = 8;
2502 Align = 8;
2503 break;
2504 }
2505 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2506 Width = toBits(Layout.getSize());
2507 Align = toBits(Layout.getAlignment());
2508 break;
2509 }
2510 case Type::BitInt: {
2511 const auto *EIT = cast<BitIntType>(T);
2512 Align = Target->getBitIntAlign(EIT->getNumBits());
2513 Width = Target->getBitIntWidth(EIT->getNumBits());
2514 break;
2515 }
2516 case Type::Record:
2517 case Type::Enum: {
2518 const auto *TT = cast<TagType>(T);
2519 const TagDecl *TD = TT->getDecl()->getDefinitionOrSelf();
2520
2521 if (TD->isInvalidDecl()) {
2522 Width = 8;
2523 Align = 8;
2524 break;
2525 }
2526
2527 if (isa<EnumType>(TT)) {
2528 const EnumDecl *ED = cast<EnumDecl>(TD);
2529 TypeInfo Info =
2531 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2532 Info.Align = AttrAlign;
2534 }
2535 return Info;
2536 }
2537
2538 const auto *RD = cast<RecordDecl>(TD);
2539 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2540 Width = toBits(Layout.getSize());
2541 Align = toBits(Layout.getAlignment());
2542 AlignRequirement = RD->hasAttr<AlignedAttr>()
2544 : AlignRequirementKind::None;
2545 break;
2546 }
2547
2548 case Type::SubstTemplateTypeParm:
2550 getReplacementType().getTypePtr());
2551
2552 case Type::Auto:
2553 case Type::DeducedTemplateSpecialization: {
2554 const auto *A = cast<DeducedType>(T);
2555 assert(!A->getDeducedType().isNull() &&
2556 "cannot request the size of an undeduced or dependent auto type");
2557 return getTypeInfo(A->getDeducedType().getTypePtr());
2558 }
2559
2560 case Type::Paren:
2561 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2562
2563 case Type::MacroQualified:
2564 return getTypeInfo(
2566
2567 case Type::ObjCTypeParam:
2568 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2569
2570 case Type::Using:
2571 return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr());
2572
2573 case Type::Typedef: {
2574 const auto *TT = cast<TypedefType>(T);
2575 TypeInfo Info = getTypeInfo(TT->desugar().getTypePtr());
2576 // If the typedef has an aligned attribute on it, it overrides any computed
2577 // alignment we have. This violates the GCC documentation (which says that
2578 // attribute(aligned) can only round up) but matches its implementation.
2579 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2580 Align = AttrAlign;
2581 AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2582 } else {
2583 Align = Info.Align;
2584 AlignRequirement = Info.AlignRequirement;
2585 }
2586 Width = Info.Width;
2587 break;
2588 }
2589
2590 case Type::Attributed:
2591 return getTypeInfo(
2592 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2593
2594 case Type::CountAttributed:
2595 return getTypeInfo(cast<CountAttributedType>(T)->desugar().getTypePtr());
2596
2597 case Type::LateParsedAttr:
2598 return getTypeInfo(cast<LateParsedAttrType>(T)->desugar().getTypePtr());
2599
2600 case Type::BTFTagAttributed:
2601 return getTypeInfo(
2602 cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr());
2603
2604 case Type::OverflowBehavior:
2605 return getTypeInfo(
2607
2608 case Type::HLSLAttributedResource:
2609 return getTypeInfo(
2610 cast<HLSLAttributedResourceType>(T)->getWrappedType().getTypePtr());
2611
2612 case Type::HLSLInlineSpirv: {
2613 const auto *ST = cast<HLSLInlineSpirvType>(T);
2614 // Size is specified in bytes, convert to bits
2615 Width = ST->getSize() * 8;
2616 Align = ST->getAlignment();
2617 if (Width == 0 && Align == 0) {
2618 // We are defaulting to laying out opaque SPIR-V types as 32-bit ints.
2619 Width = 32;
2620 Align = 32;
2621 }
2622 break;
2623 }
2624
2625 case Type::Atomic: {
2626 // Start with the base type information.
2627 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2628 Width = Info.Width;
2629 Align = Info.Align;
2630
2631 if (!Width) {
2632 // An otherwise zero-sized type should still generate an
2633 // atomic operation.
2634 Width = Target->getCharWidth();
2635 assert(Align);
2636 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2637 // If the size of the type doesn't exceed the platform's max
2638 // atomic promotion width, make the size and alignment more
2639 // favorable to atomic operations:
2640
2641 // Round the size up to a power of 2.
2642 Width = llvm::bit_ceil(Width);
2643
2644 // Set the alignment equal to the size.
2645 Align = static_cast<unsigned>(Width);
2646 }
2647 }
2648 break;
2649
2650 case Type::PredefinedSugar:
2651 return getTypeInfo(cast<PredefinedSugarType>(T)->desugar().getTypePtr());
2652
2653 case Type::Pipe:
2654 Width = Target->getPointerWidth(LangAS::opencl_global);
2655 Align = Target->getPointerAlign(LangAS::opencl_global);
2656 break;
2657 }
2658
2659 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2660 return TypeInfo(Width, Align, AlignRequirement);
2661}
2662
2664 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2665 if (I != MemoizedUnadjustedAlign.end())
2666 return I->second;
2667
2668 unsigned UnadjustedAlign;
2669 if (const auto *RT = T->getAsCanonical<RecordType>()) {
2670 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
2671 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2672 } else if (const auto *ObjCI = T->getAsCanonical<ObjCInterfaceType>()) {
2673 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2674 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2675 } else {
2676 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2677 }
2678
2679 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2680 return UnadjustedAlign;
2681}
2682
2684 unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign(
2685 getTargetInfo().getTriple(), Target->getTargetOpts().FeatureMap);
2686 return SimdAlign;
2687}
2688
2689/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2691 return CharUnits::fromQuantity(BitSize / getCharWidth());
2692}
2693
2694/// toBits - Convert a size in characters to a size in characters.
2695int64_t ASTContext::toBits(CharUnits CharSize) const {
2696 return CharSize.getQuantity() * getCharWidth();
2697}
2698
2699/// getTypeSizeInChars - Return the size of the specified type, in characters.
2700/// This method does not work on incomplete types.
2707
2708/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2709/// characters. This method does not work on incomplete types.
2716
2717/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2718/// type, in characters, before alignment adjustments. This method does
2719/// not work on incomplete types.
2726
2727/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2728/// type for the current target in bits. This can be different than the ABI
2729/// alignment in cases where it is beneficial for performance or backwards
2730/// compatibility preserving to overalign a data type. (Note: despite the name,
2731/// the preferred alignment is ABI-impacting, and not an optimization.)
2733 TypeInfo TI = getTypeInfo(T);
2734 unsigned ABIAlign = TI.Align;
2735
2736 T = T->getBaseElementTypeUnsafe();
2737
2738 // The preferred alignment of member pointers is that of a pointer.
2739 if (T->isMemberPointerType())
2740 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2741
2742 if (!Target->allowsLargerPreferedTypeAlignment())
2743 return ABIAlign;
2744
2745 if (const auto *RD = T->getAsRecordDecl()) {
2746 // When used as part of a typedef, or together with a 'packed' attribute,
2747 // the 'aligned' attribute can be used to decrease alignment. Note that the
2748 // 'packed' case is already taken into consideration when computing the
2749 // alignment, we only need to handle the typedef case here.
2751 RD->isInvalidDecl())
2752 return ABIAlign;
2753
2754 unsigned PreferredAlign = static_cast<unsigned>(
2755 toBits(getASTRecordLayout(RD).PreferredAlignment));
2756 assert(PreferredAlign >= ABIAlign &&
2757 "PreferredAlign should be at least as large as ABIAlign.");
2758 return PreferredAlign;
2759 }
2760
2761 // Double (and, for targets supporting AIX `power` alignment, long double) and
2762 // long long should be naturally aligned (despite requiring less alignment) if
2763 // possible.
2764 if (const auto *CT = T->getAs<ComplexType>())
2765 T = CT->getElementType().getTypePtr();
2766 if (const auto *ED = T->getAsEnumDecl())
2767 T = ED->getIntegerType().getTypePtr();
2768 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2769 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2770 T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2771 (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2772 Target->defaultsToAIXPowerAlignment()))
2773 // Don't increase the alignment if an alignment attribute was specified on a
2774 // typedef declaration.
2775 if (!TI.isAlignRequired())
2776 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2777
2778 return ABIAlign;
2779}
2780
2781/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2782/// for __attribute__((aligned)) on this target, to be used if no alignment
2783/// value is specified.
2787
2788/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2789/// to a global variable of the specified type.
2791 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2792 return std::max(getPreferredTypeAlign(T),
2793 getMinGlobalAlignOfVar(TypeSize, VD));
2794}
2795
2796/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2797/// should be given to a global variable of the specified type.
2802
2804 const VarDecl *VD) const {
2805 // Make the default handling as that of a non-weak definition in the
2806 // current translation unit.
2807 bool HasNonWeakDef = !VD || (VD->hasDefinition() && !VD->isWeak());
2808 return getTargetInfo().getMinGlobalAlign(Size, HasNonWeakDef);
2809}
2810
2812 CharUnits Offset = CharUnits::Zero();
2813 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2814 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2815 Offset += Layout->getBaseClassOffset(Base);
2816 Layout = &getASTRecordLayout(Base);
2817 }
2818 return Offset;
2819}
2820
2822 const ValueDecl *MPD = MP.getMemberPointerDecl();
2825 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2827 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2828 const CXXRecordDecl *Base = RD;
2829 const CXXRecordDecl *Derived = Path[I];
2830 if (DerivedMember)
2831 std::swap(Base, Derived);
2833 RD = Path[I];
2834 }
2835 if (DerivedMember)
2837 return ThisAdjustment;
2838}
2839
2840/// DeepCollectObjCIvars -
2841/// This routine first collects all declared, but not synthesized, ivars in
2842/// super class and then collects all ivars, including those synthesized for
2843/// current class. This routine is used for implementation of current class
2844/// when all ivars, declared and synthesized are known.
2846 bool leafClass,
2848 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2849 DeepCollectObjCIvars(SuperClass, false, Ivars);
2850 if (!leafClass) {
2851 llvm::append_range(Ivars, OI->ivars());
2852 } else {
2853 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2854 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2855 Iv= Iv->getNextIvar())
2856 Ivars.push_back(Iv);
2857 }
2858}
2859
2860/// CollectInheritedProtocols - Collect all protocols in current class and
2861/// those inherited by it.
2864 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2865 // We can use protocol_iterator here instead of
2866 // all_referenced_protocol_iterator since we are walking all categories.
2867 for (auto *Proto : OI->all_referenced_protocols()) {
2868 CollectInheritedProtocols(Proto, Protocols);
2869 }
2870
2871 // Categories of this Interface.
2872 for (const auto *Cat : OI->visible_categories())
2873 CollectInheritedProtocols(Cat, Protocols);
2874
2875 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2876 while (SD) {
2877 CollectInheritedProtocols(SD, Protocols);
2878 SD = SD->getSuperClass();
2879 }
2880 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2881 for (auto *Proto : OC->protocols()) {
2882 CollectInheritedProtocols(Proto, Protocols);
2883 }
2884 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2885 // Insert the protocol.
2886 if (!Protocols.insert(
2887 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2888 return;
2889
2890 for (auto *Proto : OP->protocols())
2891 CollectInheritedProtocols(Proto, Protocols);
2892 }
2893}
2894
2896 const RecordDecl *RD,
2897 bool CheckIfTriviallyCopyable) {
2898 assert(RD->isUnion() && "Must be union type");
2899 CharUnits UnionSize =
2900 Context.getTypeSizeInChars(Context.getCanonicalTagType(RD));
2901
2902 for (const auto *Field : RD->fields()) {
2903 if (!Context.hasUniqueObjectRepresentations(Field->getType(),
2904 CheckIfTriviallyCopyable))
2905 return false;
2906 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2907 if (FieldSize != UnionSize)
2908 return false;
2909 }
2910 return !RD->field_empty();
2911}
2912
2913static int64_t getSubobjectOffset(const FieldDecl *Field,
2914 const ASTContext &Context,
2915 const clang::ASTRecordLayout & /*Layout*/) {
2916 return Context.getFieldOffset(Field);
2917}
2918
2919static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2920 const ASTContext &Context,
2921 const clang::ASTRecordLayout &Layout) {
2922 return Context.toBits(Layout.getBaseClassOffset(RD));
2923}
2924
2925static std::optional<int64_t>
2927 const RecordDecl *RD,
2928 bool CheckIfTriviallyCopyable);
2929
2930static std::optional<int64_t>
2931getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context,
2932 bool CheckIfTriviallyCopyable) {
2933 if (const auto *RD = Field->getType()->getAsRecordDecl();
2934 RD && !RD->isUnion())
2935 return structHasUniqueObjectRepresentations(Context, RD,
2936 CheckIfTriviallyCopyable);
2937
2938 // A _BitInt type may not be unique if it has padding bits
2939 // but if it is a bitfield the padding bits are not used.
2940 bool IsBitIntType = Field->getType()->isBitIntType();
2941 if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2942 !Context.hasUniqueObjectRepresentations(Field->getType(),
2943 CheckIfTriviallyCopyable))
2944 return std::nullopt;
2945
2946 int64_t FieldSizeInBits =
2947 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2948 if (Field->isBitField()) {
2949 // If we have explicit padding bits, they don't contribute bits
2950 // to the actual object representation, so return 0.
2951 if (Field->isUnnamedBitField())
2952 return 0;
2953
2954 int64_t BitfieldSize = Field->getBitWidthValue();
2955 if (IsBitIntType) {
2956 if ((unsigned)BitfieldSize >
2957 cast<BitIntType>(Field->getType())->getNumBits())
2958 return std::nullopt;
2959 } else if (BitfieldSize > FieldSizeInBits) {
2960 return std::nullopt;
2961 }
2962 FieldSizeInBits = BitfieldSize;
2963 } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations(
2964 Field->getType(), CheckIfTriviallyCopyable)) {
2965 return std::nullopt;
2966 }
2967 return FieldSizeInBits;
2968}
2969
2970static std::optional<int64_t>
2972 bool CheckIfTriviallyCopyable) {
2973 return structHasUniqueObjectRepresentations(Context, RD,
2974 CheckIfTriviallyCopyable);
2975}
2976
2977template <typename RangeT>
2979 const RangeT &Subobjects, int64_t CurOffsetInBits,
2980 const ASTContext &Context, const clang::ASTRecordLayout &Layout,
2981 bool CheckIfTriviallyCopyable) {
2982 for (const auto *Subobject : Subobjects) {
2983 std::optional<int64_t> SizeInBits =
2984 getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable);
2985 if (!SizeInBits)
2986 return std::nullopt;
2987 if (*SizeInBits != 0) {
2988 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2989 if (Offset != CurOffsetInBits)
2990 return std::nullopt;
2991 CurOffsetInBits += *SizeInBits;
2992 }
2993 }
2994 return CurOffsetInBits;
2995}
2996
2997static std::optional<int64_t>
2999 const RecordDecl *RD,
3000 bool CheckIfTriviallyCopyable) {
3001 assert(!RD->isUnion() && "Must be struct/class type");
3002 const auto &Layout = Context.getASTRecordLayout(RD);
3003
3004 int64_t CurOffsetInBits = 0;
3005 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
3006 if (ClassDecl->isDynamicClass())
3007 return std::nullopt;
3008
3010 for (const auto &Base : ClassDecl->bases()) {
3011 // Empty types can be inherited from, and non-empty types can potentially
3012 // have tail padding, so just make sure there isn't an error.
3013 Bases.emplace_back(Base.getType()->getAsCXXRecordDecl());
3014 }
3015
3016 llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
3017 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
3018 });
3019
3020 std::optional<int64_t> OffsetAfterBases =
3022 Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable);
3023 if (!OffsetAfterBases)
3024 return std::nullopt;
3025 CurOffsetInBits = *OffsetAfterBases;
3026 }
3027
3028 std::optional<int64_t> OffsetAfterFields =
3030 RD->fields(), CurOffsetInBits, Context, Layout,
3031 CheckIfTriviallyCopyable);
3032 if (!OffsetAfterFields)
3033 return std::nullopt;
3034 CurOffsetInBits = *OffsetAfterFields;
3035
3036 return CurOffsetInBits;
3037}
3038
3040 QualType Ty, bool CheckIfTriviallyCopyable) const {
3041 // C++17 [meta.unary.prop]:
3042 // The predicate condition for a template specialization
3043 // has_unique_object_representations<T> shall be satisfied if and only if:
3044 // (9.1) - T is trivially copyable, and
3045 // (9.2) - any two objects of type T with the same value have the same
3046 // object representation, where:
3047 // - two objects of array or non-union class type are considered to have
3048 // the same value if their respective sequences of direct subobjects
3049 // have the same values, and
3050 // - two objects of union type are considered to have the same value if
3051 // they have the same active member and the corresponding members have
3052 // the same value.
3053 // The set of scalar types for which this condition holds is
3054 // implementation-defined. [ Note: If a type has padding bits, the condition
3055 // does not hold; otherwise, the condition holds true for unsigned integral
3056 // types. -- end note ]
3057 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
3058
3059 // Arrays are unique only if their element type is unique.
3060 if (Ty->isArrayType())
3062 CheckIfTriviallyCopyable);
3063
3064 assert((Ty->isVoidType() || !Ty->isIncompleteType()) &&
3065 "hasUniqueObjectRepresentations should not be called with an "
3066 "incomplete type");
3067
3068 // (9.1) - T is trivially copyable...
3069 if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(*this))
3070 return false;
3071
3072 // All integrals and enums are unique.
3073 if (Ty->isIntegralOrEnumerationType()) {
3074 // Address discriminated integer types are not unique.
3076 return false;
3077 // Except _BitInt types that have padding bits.
3078 if (const auto *BIT = Ty->getAs<BitIntType>())
3079 return getTypeSize(BIT) == BIT->getNumBits();
3080
3081 return true;
3082 }
3083
3084 // All other pointers are unique.
3085 if (Ty->isPointerType())
3087
3088 if (const auto *MPT = Ty->getAs<MemberPointerType>())
3089 return !ABI->getMemberPointerInfo(MPT).HasPadding;
3090
3091 if (const auto *Record = Ty->getAsRecordDecl()) {
3092 if (Record->isInvalidDecl())
3093 return false;
3094
3095 if (Record->isUnion())
3097 CheckIfTriviallyCopyable);
3098
3099 std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(
3100 *this, Record, CheckIfTriviallyCopyable);
3101
3102 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(Ty));
3103 }
3104
3105 // FIXME: More cases to handle here (list by rsmith):
3106 // vectors (careful about, eg, vector of 3 foo)
3107 // _Complex int and friends
3108 // _Atomic T
3109 // Obj-C block pointers
3110 // Obj-C object pointers
3111 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
3112 // clk_event_t, queue_t, reserve_id_t)
3113 // There're also Obj-C class types and the Obj-C selector type, but I think it
3114 // makes sense for those to return false here.
3115
3116 return false;
3117}
3118
3120 unsigned count = 0;
3121 // Count ivars declared in class extension.
3122 for (const auto *Ext : OI->known_extensions())
3123 count += Ext->ivar_size();
3124
3125 // Count ivar defined in this class's implementation. This
3126 // includes synthesized ivars.
3127 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
3128 count += ImplDecl->ivar_size();
3129
3130 return count;
3131}
3132
3134 if (!E)
3135 return false;
3136
3137 // nullptr_t is always treated as null.
3138 if (E->getType()->isNullPtrType()) return true;
3139
3140 if (E->getType()->isAnyPointerType() &&
3143 return true;
3144
3145 // Unfortunately, __null has type 'int'.
3146 if (isa<GNUNullExpr>(E)) return true;
3147
3148 return false;
3149}
3150
3151/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
3152/// exists.
3154 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3155 I = ObjCImpls.find(D);
3156 if (I != ObjCImpls.end())
3157 return cast<ObjCImplementationDecl>(I->second);
3158 return nullptr;
3159}
3160
3161/// Get the implementation of ObjCCategoryDecl, or nullptr if none
3162/// exists.
3164 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3165 I = ObjCImpls.find(D);
3166 if (I != ObjCImpls.end())
3167 return cast<ObjCCategoryImplDecl>(I->second);
3168 return nullptr;
3169}
3170
3171/// Set the implementation of ObjCInterfaceDecl.
3173 ObjCImplementationDecl *ImplD) {
3174 assert(IFaceD && ImplD && "Passed null params");
3175 ObjCImpls[IFaceD] = ImplD;
3176}
3177
3178/// Set the implementation of ObjCCategoryDecl.
3180 ObjCCategoryImplDecl *ImplD) {
3181 assert(CatD && ImplD && "Passed null params");
3182 ObjCImpls[CatD] = ImplD;
3183}
3184
3185const ObjCMethodDecl *
3187 return ObjCMethodRedecls.lookup(MD);
3188}
3189
3191 const ObjCMethodDecl *Redecl) {
3192 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
3193 ObjCMethodRedecls[MD] = Redecl;
3194}
3195
3197 const NamedDecl *ND) const {
3198 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
3199 return ID;
3200 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
3201 return CD->getClassInterface();
3202 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
3203 return IMD->getClassInterface();
3204
3205 return nullptr;
3206}
3207
3208/// Get the copy initialization expression of VarDecl, or nullptr if
3209/// none exists.
3211 assert(VD && "Passed null params");
3212 assert(VD->hasAttr<BlocksAttr>() &&
3213 "getBlockVarCopyInits - not __block var");
3214 auto I = BlockVarCopyInits.find(VD);
3215 if (I != BlockVarCopyInits.end())
3216 return I->second;
3217 return {nullptr, false};
3218}
3219
3220/// Set the copy initialization expression of a block var decl.
3222 bool CanThrow) {
3223 assert(VD && CopyExpr && "Passed null params");
3224 assert(VD->hasAttr<BlocksAttr>() &&
3225 "setBlockVarCopyInits - not __block var");
3226 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
3227}
3228
3230 unsigned DataSize) const {
3231 if (!DataSize)
3233 else
3234 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
3235 "incorrect data size provided to CreateTypeSourceInfo!");
3236
3237 auto *TInfo =
3238 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
3239 new (TInfo) TypeSourceInfo(T, DataSize);
3240 return TInfo;
3241}
3242
3244 SourceLocation L) const {
3246 TSI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
3247 return TSI;
3248}
3249
3250const ASTRecordLayout &
3252 return getObjCLayout(D);
3253}
3254
3257 bool &AnyNonCanonArgs) {
3258 SmallVector<TemplateArgument, 16> CanonArgs(Args);
3259 AnyNonCanonArgs |= C.canonicalizeTemplateArguments(CanonArgs);
3260 return CanonArgs;
3261}
3262
3265 bool AnyNonCanonArgs = false;
3266 for (auto &Arg : Args) {
3267 TemplateArgument OrigArg = Arg;
3269 AnyNonCanonArgs |= !Arg.structurallyEquals(OrigArg);
3270 }
3271 return AnyNonCanonArgs;
3272}
3273
3274//===----------------------------------------------------------------------===//
3275// Type creation/memoization methods
3276//===----------------------------------------------------------------------===//
3277
3279ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3280 unsigned fastQuals = quals.getFastQualifiers();
3281 quals.removeFastQualifiers();
3282
3283 // Check if we've already instantiated this type.
3284 llvm::FoldingSetNodeID ID;
3285 ExtQuals::Profile(ID, baseType, quals);
3286 void *insertPos = nullptr;
3287 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
3288 assert(eq->getQualifiers() == quals);
3289 return QualType(eq, fastQuals);
3290 }
3291
3292 // If the base type is not canonical, make the appropriate canonical type.
3293 QualType canon;
3294 if (!baseType->isCanonicalUnqualified()) {
3295 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3296 canonSplit.Quals.addConsistentQualifiers(quals);
3297 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
3298
3299 // Re-find the insert position.
3300 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
3301 }
3302
3303 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3304 ExtQualNodes.InsertNode(eq, insertPos);
3305 return QualType(eq, fastQuals);
3306}
3307
3309 LangAS AddressSpace) const {
3310 QualType CanT = getCanonicalType(T);
3311 if (CanT.getAddressSpace() == AddressSpace)
3312 return T;
3313
3314 // If we are composing extended qualifiers together, merge together
3315 // into one ExtQuals node.
3316 QualifierCollector Quals;
3317 const Type *TypeNode = Quals.strip(T);
3318
3319 // If this type already has an address space specified, it cannot get
3320 // another one.
3321 assert(!Quals.hasAddressSpace() &&
3322 "Type cannot be in multiple addr spaces!");
3323 Quals.addAddressSpace(AddressSpace);
3324
3325 return getExtQualType(TypeNode, Quals);
3326}
3327
3329 // If the type is not qualified with an address space, just return it
3330 // immediately.
3331 if (!T.hasAddressSpace())
3332 return T;
3333
3334 QualifierCollector Quals;
3335 const Type *TypeNode;
3336 // For arrays, strip the qualifier off the element type, then reconstruct the
3337 // array type
3338 if (T.getTypePtr()->isArrayType()) {
3339 T = getUnqualifiedArrayType(T, Quals);
3340 TypeNode = T.getTypePtr();
3341 } else {
3342 // If we are composing extended qualifiers together, merge together
3343 // into one ExtQuals node.
3344 while (T.hasAddressSpace()) {
3345 TypeNode = Quals.strip(T);
3346
3347 // If the type no longer has an address space after stripping qualifiers,
3348 // jump out.
3349 if (!QualType(TypeNode, 0).hasAddressSpace())
3350 break;
3351
3352 // There might be sugar in the way. Strip it and try again.
3353 T = T.getSingleStepDesugaredType(*this);
3354 }
3355 }
3356
3357 Quals.removeAddressSpace();
3358
3359 // Removal of the address space can mean there are no longer any
3360 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3361 // or required.
3362 if (Quals.hasNonFastQualifiers())
3363 return getExtQualType(TypeNode, Quals);
3364 else
3365 return QualType(TypeNode, Quals.getFastQualifiers());
3366}
3367
3368uint16_t
3370 assert(RD->isPolymorphic() &&
3371 "Attempted to get vtable pointer discriminator on a monomorphic type");
3372 std::unique_ptr<MangleContext> MC(createMangleContext());
3373 SmallString<256> Str;
3374 llvm::raw_svector_ostream Out(Str);
3375 MC->mangleCXXVTable(RD, Out);
3376 return llvm::getPointerAuthStableSipHash(Str);
3377}
3378
3379/// Encode a function type for use in the discriminator of a function pointer
3380/// type. We can't use the itanium scheme for this since C has quite permissive
3381/// rules for type compatibility that we need to be compatible with.
3382///
3383/// Formally, this function associates every function pointer type T with an
3384/// encoded string E(T). Let the equivalence relation T1 ~ T2 be defined as
3385/// E(T1) == E(T2). E(T) is part of the ABI of values of type T. C type
3386/// compatibility requires equivalent treatment under the ABI, so
3387/// CCompatible(T1, T2) must imply E(T1) == E(T2), that is, CCompatible must be
3388/// a subset of ~. Crucially, however, it must be a proper subset because
3389/// CCompatible is not an equivalence relation: for example, int[] is compatible
3390/// with both int[1] and int[2], but the latter are not compatible with each
3391/// other. Therefore this encoding function must be careful to only distinguish
3392/// types if there is no third type with which they are both required to be
3393/// compatible.
3395 raw_ostream &OS, QualType QT) {
3396 // FIXME: Consider address space qualifiers.
3397 const Type *T = QT.getCanonicalType().getTypePtr();
3398
3399 // FIXME: Consider using the C++ type mangling when we encounter a construct
3400 // that is incompatible with C.
3401
3402 switch (T->getTypeClass()) {
3403 case Type::Atomic:
3405 Ctx, OS, cast<AtomicType>(T)->getValueType());
3406
3407 case Type::LValueReference:
3408 OS << "R";
3411 return;
3412 case Type::RValueReference:
3413 OS << "O";
3416 return;
3417
3418 case Type::Pointer:
3419 // C11 6.7.6.1p2:
3420 // For two pointer types to be compatible, both shall be identically
3421 // qualified and both shall be pointers to compatible types.
3422 // FIXME: we should also consider pointee types.
3423 OS << "P";
3424 return;
3425
3426 case Type::ObjCObjectPointer:
3427 case Type::BlockPointer:
3428 OS << "P";
3429 return;
3430
3431 case Type::Complex:
3432 OS << "C";
3434 Ctx, OS, cast<ComplexType>(T)->getElementType());
3435
3436 case Type::VariableArray:
3437 case Type::ConstantArray:
3438 case Type::IncompleteArray:
3439 case Type::ArrayParameter:
3440 // C11 6.7.6.2p6:
3441 // For two array types to be compatible, both shall have compatible
3442 // element types, and if both size specifiers are present, and are integer
3443 // constant expressions, then both size specifiers shall have the same
3444 // constant value [...]
3445 //
3446 // So since ElemType[N] has to be compatible ElemType[], we can't encode the
3447 // width of the array.
3448 OS << "A";
3450 Ctx, OS, cast<ArrayType>(T)->getElementType());
3451
3452 case Type::ObjCInterface:
3453 case Type::ObjCObject:
3454 OS << "<objc_object>";
3455 return;
3456
3457 case Type::Enum: {
3458 // C11 6.7.2.2p4:
3459 // Each enumerated type shall be compatible with char, a signed integer
3460 // type, or an unsigned integer type.
3461 //
3462 // So we have to treat enum types as integers.
3463 QualType UnderlyingType = T->castAsEnumDecl()->getIntegerType();
3465 Ctx, OS, UnderlyingType.isNull() ? Ctx.IntTy : UnderlyingType);
3466 }
3467
3468 case Type::FunctionNoProto:
3469 case Type::FunctionProto: {
3470 // C11 6.7.6.3p15:
3471 // For two function types to be compatible, both shall specify compatible
3472 // return types. Moreover, the parameter type lists, if both are present,
3473 // shall agree in the number of parameters and in the use of the ellipsis
3474 // terminator; corresponding parameters shall have compatible types.
3475 //
3476 // That paragraph goes on to describe how unprototyped functions are to be
3477 // handled, which we ignore here. Unprototyped function pointers are hashed
3478 // as though they were prototyped nullary functions since thats probably
3479 // what the user meant. This behavior is non-conforming.
3480 // FIXME: If we add a "custom discriminator" function type attribute we
3481 // should encode functions as their discriminators.
3482 OS << "F";
3483 const auto *FuncType = cast<FunctionType>(T);
3484 encodeTypeForFunctionPointerAuth(Ctx, OS, FuncType->getReturnType());
3485 if (const auto *FPT = dyn_cast<FunctionProtoType>(FuncType)) {
3486 for (QualType Param : FPT->param_types()) {
3487 Param = Ctx.getSignatureParameterType(Param);
3488 encodeTypeForFunctionPointerAuth(Ctx, OS, Param);
3489 }
3490 if (FPT->isVariadic())
3491 OS << "z";
3492 }
3493 OS << "E";
3494 return;
3495 }
3496
3497 case Type::MemberPointer: {
3498 OS << "M";
3499 const auto *MPT = T->castAs<MemberPointerType>();
3501 Ctx, OS, QualType(MPT->getQualifier().getAsType(), 0));
3502 encodeTypeForFunctionPointerAuth(Ctx, OS, MPT->getPointeeType());
3503 return;
3504 }
3505 case Type::ExtVector:
3506 case Type::Vector:
3507 OS << "Dv" << Ctx.getTypeSizeInChars(T).getQuantity();
3508 break;
3509
3510 // Don't bother discriminating based on these types.
3511 case Type::Pipe:
3512 case Type::BitInt:
3513 case Type::ConstantMatrix:
3514 OS << "?";
3515 return;
3516
3517 case Type::Builtin: {
3518 const auto *BTy = T->castAs<BuiltinType>();
3519 switch (BTy->getKind()) {
3520#define SIGNED_TYPE(Id, SingletonId) \
3521 case BuiltinType::Id: \
3522 OS << "i"; \
3523 return;
3524#define UNSIGNED_TYPE(Id, SingletonId) \
3525 case BuiltinType::Id: \
3526 OS << "i"; \
3527 return;
3528#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
3529#define BUILTIN_TYPE(Id, SingletonId)
3530#include "clang/AST/BuiltinTypes.def"
3531 llvm_unreachable("placeholder types should not appear here.");
3532
3533 case BuiltinType::Half:
3534 OS << "Dh";
3535 return;
3536 case BuiltinType::Float:
3537 OS << "f";
3538 return;
3539 case BuiltinType::Double:
3540 OS << "d";
3541 return;
3542 case BuiltinType::LongDouble:
3543 OS << "e";
3544 return;
3545 case BuiltinType::Float16:
3546 OS << "DF16_";
3547 return;
3548 case BuiltinType::Float128:
3549 OS << "g";
3550 return;
3551
3552 case BuiltinType::Void:
3553 OS << "v";
3554 return;
3555
3556 case BuiltinType::ObjCId:
3557 case BuiltinType::ObjCClass:
3558 case BuiltinType::ObjCSel:
3559 case BuiltinType::NullPtr:
3560 OS << "P";
3561 return;
3562
3563 // Don't bother discriminating based on OpenCL types.
3564 case BuiltinType::OCLSampler:
3565 case BuiltinType::OCLEvent:
3566 case BuiltinType::OCLClkEvent:
3567 case BuiltinType::OCLQueue:
3568 case BuiltinType::OCLReserveID:
3569 case BuiltinType::BFloat16:
3570 case BuiltinType::VectorQuad:
3571 case BuiltinType::VectorPair:
3572 case BuiltinType::DMR1024:
3573 case BuiltinType::DMR2048:
3574 OS << "?";
3575 return;
3576
3577 // Don't bother discriminating based on these seldom-used types.
3578 case BuiltinType::Ibm128:
3579 return;
3580#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3581 case BuiltinType::Id: \
3582 return;
3583#include "clang/Basic/OpenCLImageTypes.def"
3584#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3585 case BuiltinType::Id: \
3586 return;
3587#include "clang/Basic/OpenCLExtensionTypes.def"
3588#define SVE_TYPE(Name, Id, SingletonId) \
3589 case BuiltinType::Id: \
3590 return;
3591#include "clang/Basic/AArch64ACLETypes.def"
3592#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3593 case BuiltinType::Id: \
3594 return;
3595#include "clang/Basic/HLSLIntangibleTypes.def"
3596 case BuiltinType::Dependent:
3597 llvm_unreachable("should never get here");
3598#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
3599#include "clang/Basic/AMDGPUTypes.def"
3600 case BuiltinType::WasmExternRef:
3601#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3602#include "clang/Basic/RISCVVTypes.def"
3603 llvm_unreachable("not yet implemented");
3604 }
3605 llvm_unreachable("should never get here");
3606 }
3607 case Type::Record: {
3608 const RecordDecl *RD = T->castAsCanonical<RecordType>()->getDecl();
3609 const IdentifierInfo *II = RD->getIdentifier();
3610
3611 // In C++, an immediate typedef of an anonymous struct or union
3612 // is considered to name it for ODR purposes, but C's specification
3613 // of type compatibility does not have a similar rule. Using the typedef
3614 // name in function type discriminators anyway, as we do here,
3615 // therefore technically violates the C standard: two function pointer
3616 // types defined in terms of two typedef'd anonymous structs with
3617 // different names are formally still compatible, but we are assigning
3618 // them different discriminators and therefore incompatible ABIs.
3619 //
3620 // This is a relatively minor violation that significantly improves
3621 // discrimination in some cases and has not caused problems in
3622 // practice. Regardless, it is now part of the ABI in places where
3623 // function type discrimination is used, and it can no longer be
3624 // changed except on new platforms.
3625
3626 if (!II)
3627 if (const TypedefNameDecl *Typedef = RD->getTypedefNameForAnonDecl())
3628 II = Typedef->getDeclName().getAsIdentifierInfo();
3629
3630 if (!II) {
3631 OS << "<anonymous_record>";
3632 return;
3633 }
3634 OS << II->getLength() << II->getName();
3635 return;
3636 }
3637 case Type::HLSLAttributedResource:
3638 case Type::HLSLInlineSpirv:
3639 llvm_unreachable("should never get here");
3640 break;
3641 case Type::OverflowBehavior:
3642 llvm_unreachable("should never get here");
3643 break;
3644 case Type::DeducedTemplateSpecialization:
3645 case Type::Auto:
3646#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3647#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3648#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3649#define ABSTRACT_TYPE(Class, Base)
3650#define TYPE(Class, Base)
3651#include "clang/AST/TypeNodes.inc"
3652 llvm_unreachable("unexpected non-canonical or dependent type!");
3653 return;
3654 }
3655}
3656
3658 assert(!T->isDependentType() &&
3659 "cannot compute type discriminator of a dependent type");
3660 SmallString<256> Str;
3661 llvm::raw_svector_ostream Out(Str);
3662
3663 if (T->isFunctionPointerType() || T->isFunctionReferenceType())
3664 T = T->getPointeeType();
3665
3666 if (T->isFunctionType()) {
3668 } else {
3669 T = T.getUnqualifiedType();
3670 // Calls to member function pointers don't need to worry about
3671 // language interop or the laxness of the C type compatibility rules.
3672 // We just mangle the member pointer type directly, which is
3673 // implicitly much stricter about type matching. However, we do
3674 // strip any top-level exception specification before this mangling.
3675 // C++23 requires calls to work when the function type is convertible
3676 // to the pointer type by a function pointer conversion, which can
3677 // change the exception specification. This does not technically
3678 // require the exception specification to not affect representation,
3679 // because the function pointer conversion is still always a direct
3680 // value conversion and therefore an opportunity to resign the
3681 // pointer. (This is in contrast to e.g. qualification conversions,
3682 // which can be applied in nested pointer positions, effectively
3683 // requiring qualified and unqualified representations to match.)
3684 // However, it is pragmatic to ignore exception specifications
3685 // because it allows a certain amount of `noexcept` mismatching
3686 // to not become a visible ODR problem. This also leaves some
3687 // room for the committee to add laxness to function pointer
3688 // conversions in future standards.
3689 if (auto *MPT = T->getAs<MemberPointerType>())
3690 if (MPT->isMemberFunctionPointer()) {
3691 QualType PointeeType = MPT->getPointeeType();
3692 if (PointeeType->castAs<FunctionProtoType>()->getExceptionSpecType() !=
3693 EST_None) {
3695 T = getMemberPointerType(FT, MPT->getQualifier(),
3696 MPT->getMostRecentCXXRecordDecl());
3697 }
3698 }
3699 std::unique_ptr<MangleContext> MC(createMangleContext());
3700 MC->mangleCanonicalTypeName(T, Out);
3701 }
3702
3703 return llvm::getPointerAuthStableSipHash(Str);
3704}
3705
3707 Qualifiers::GC GCAttr) const {
3708 QualType CanT = getCanonicalType(T);
3709 if (CanT.getObjCGCAttr() == GCAttr)
3710 return T;
3711
3712 if (const auto *ptr = T->getAs<PointerType>()) {
3713 QualType Pointee = ptr->getPointeeType();
3714 if (Pointee->isAnyPointerType()) {
3715 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
3716 return getPointerType(ResultType);
3717 }
3718 }
3719
3720 // If we are composing extended qualifiers together, merge together
3721 // into one ExtQuals node.
3722 QualifierCollector Quals;
3723 const Type *TypeNode = Quals.strip(T);
3724
3725 // If this type already has an ObjCGC specified, it cannot get
3726 // another one.
3727 assert(!Quals.hasObjCGCAttr() &&
3728 "Type cannot have multiple ObjCGCs!");
3729 Quals.addObjCGCAttr(GCAttr);
3730
3731 return getExtQualType(TypeNode, Quals);
3732}
3733
3735 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3736 QualType Pointee = Ptr->getPointeeType();
3737 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3738 return getPointerType(removeAddrSpaceQualType(Pointee));
3739 }
3740 }
3741 return T;
3742}
3743
3745 QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull,
3746 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3747 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3748
3749 llvm::FoldingSetNodeID ID;
3750 CountAttributedType::Profile(ID, WrappedTy, CountExpr, CountInBytes, OrNull);
3751
3752 void *InsertPos = nullptr;
3753 CountAttributedType *CATy =
3754 CountAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
3755 if (CATy)
3756 return QualType(CATy, 0);
3757
3758 QualType CanonTy = getCanonicalType(WrappedTy);
3759 size_t Size = CountAttributedType::totalSizeToAlloc<TypeCoupledDeclRefInfo>(
3760 DependentDecls.size());
3762 new (CATy) CountAttributedType(WrappedTy, CanonTy, CountExpr, CountInBytes,
3763 OrNull, DependentDecls);
3764 Types.push_back(CATy);
3765 CountAttributedTypes.InsertNode(CATy, InsertPos);
3766
3767 return QualType(CATy, 0);
3768}
3769
3771 QualType WrappedTy, LateParsedTypeAttribute *LateParsedAttr) const {
3772 QualType CanonTy = getCanonicalType(WrappedTy);
3773
3774 auto *LPATy = new (*this, alignof(LateParsedAttrType))
3775 LateParsedAttrType(WrappedTy, CanonTy, LateParsedAttr);
3776
3777 Types.push_back(LPATy);
3778 return QualType(LPATy, 0);
3779}
3780
3783 llvm::function_ref<QualType(QualType)> Adjust) const {
3784 switch (Orig->getTypeClass()) {
3785 case Type::Attributed: {
3786 const auto *AT = cast<AttributedType>(Orig);
3787 return getAttributedType(AT->getAttrKind(),
3788 adjustType(AT->getModifiedType(), Adjust),
3789 adjustType(AT->getEquivalentType(), Adjust),
3790 AT->getAttr());
3791 }
3792
3793 case Type::BTFTagAttributed: {
3794 const auto *BTFT = dyn_cast<BTFTagAttributedType>(Orig);
3795 return getBTFTagAttributedType(BTFT->getAttr(),
3796 adjustType(BTFT->getWrappedType(), Adjust));
3797 }
3798
3799 case Type::OverflowBehavior: {
3800 const auto *OB = dyn_cast<OverflowBehaviorType>(Orig);
3801 return getOverflowBehaviorType(OB->getBehaviorKind(),
3802 adjustType(OB->getUnderlyingType(), Adjust));
3803 }
3804
3805 case Type::Paren:
3806 return getParenType(
3807 adjustType(cast<ParenType>(Orig)->getInnerType(), Adjust));
3808
3809 case Type::Adjusted: {
3810 const auto *AT = cast<AdjustedType>(Orig);
3811 return getAdjustedType(AT->getOriginalType(),
3812 adjustType(AT->getAdjustedType(), Adjust));
3813 }
3814
3815 case Type::MacroQualified: {
3816 const auto *MQT = cast<MacroQualifiedType>(Orig);
3817 return getMacroQualifiedType(adjustType(MQT->getUnderlyingType(), Adjust),
3818 MQT->getMacroIdentifier());
3819 }
3820
3821 default:
3822 return Adjust(Orig);
3823 }
3824}
3825
3827 FunctionType::ExtInfo Info) {
3828 if (T->getExtInfo() == Info)
3829 return T;
3830
3832 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3833 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3834 } else {
3835 const auto *FPT = cast<FunctionProtoType>(T);
3836 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3837 EPI.ExtInfo = Info;
3838 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3839 }
3840
3841 return cast<FunctionType>(Result.getTypePtr());
3842}
3843
3845 QualType ResultType) {
3846 return adjustType(FunctionType, [&](QualType Orig) {
3847 if (const auto *FNPT = Orig->getAs<FunctionNoProtoType>())
3848 return getFunctionNoProtoType(ResultType, FNPT->getExtInfo());
3849
3850 const auto *FPT = Orig->castAs<FunctionProtoType>();
3851 return getFunctionType(ResultType, FPT->getParamTypes(),
3852 FPT->getExtProtoInfo());
3853 });
3854}
3855
3857 QualType ResultType) {
3858 FD = FD->getMostRecentDecl();
3859 while (true) {
3860 FD->setType(adjustFunctionResultType(FD->getType(), ResultType));
3861 if (FunctionDecl *Next = FD->getPreviousDecl())
3862 FD = Next;
3863 else
3864 break;
3865 }
3867 L->DeducedReturnType(FD, ResultType);
3868}
3869
3870/// Get a function type and produce the equivalent function type with the
3871/// specified exception specification. Type sugar that can be present on a
3872/// declaration of a function with an exception specification is permitted
3873/// and preserved. Other type sugar (for instance, typedefs) is not.
3875 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3876 return adjustType(Orig, [&](QualType Ty) {
3877 const auto *Proto = Ty->castAs<FunctionProtoType>();
3878 return getFunctionType(Proto->getReturnType(), Proto->getParamTypes(),
3879 Proto->getExtProtoInfo().withExceptionSpec(ESI));
3880 });
3881}
3882
3890
3892 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3893 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3894 SmallVector<QualType, 16> Args(Proto->param_types().size());
3895 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3896 Args[i] = removePtrSizeAddrSpace(Proto->param_types()[i]);
3897 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3898 }
3899
3900 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3901 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3902 return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3903 }
3904
3905 return T;
3906}
3907
3913
3915 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3916 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3917 EPI.ExtParameterInfos = nullptr;
3918 return getFunctionType(Proto->getReturnType(), Proto->param_types(), EPI);
3919 }
3920 return T;
3921}
3922
3928
3931 bool AsWritten) {
3932 // Update the type.
3933 QualType Updated =
3935 FD->setType(Updated);
3936
3937 if (!AsWritten)
3938 return;
3939
3940 // Update the type in the type source information too.
3941 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3942 // If the type and the type-as-written differ, we may need to update
3943 // the type-as-written too.
3944 if (TSInfo->getType() != FD->getType())
3945 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3946
3947 // FIXME: When we get proper type location information for exceptions,
3948 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3949 // up the TypeSourceInfo;
3950 assert(TypeLoc::getFullDataSizeForType(Updated) ==
3951 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3952 "TypeLoc size mismatch from updating exception specification");
3953 TSInfo->overrideType(Updated);
3954 }
3955}
3956
3957/// getComplexType - Return the uniqued reference to the type for a complex
3958/// number with the specified element type.
3960 // Unique pointers, to guarantee there is only one pointer of a particular
3961 // structure.
3962 llvm::FoldingSetNodeID ID;
3964
3965 void *InsertPos = nullptr;
3966 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3967 return QualType(CT, 0);
3968
3969 // If the pointee type isn't canonical, this won't be a canonical type either,
3970 // so fill in the canonical type field.
3971 QualType Canonical;
3972 if (!T.isCanonical()) {
3973 Canonical = getComplexType(getCanonicalType(T));
3974
3975 // Get the new insert position for the node we care about.
3976 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3977 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3978 }
3979 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
3980 Types.push_back(New);
3981 ComplexTypes.InsertNode(New, InsertPos);
3982 return QualType(New, 0);
3983}
3984
3985/// getPointerType - Return the uniqued reference to the type for a pointer to
3986/// the specified type.
3988 // Unique pointers, to guarantee there is only one pointer of a particular
3989 // structure.
3990 llvm::FoldingSetNodeID ID;
3992
3993 void *InsertPos = nullptr;
3994 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3995 return QualType(PT, 0);
3996
3997 // If the pointee type isn't canonical, this won't be a canonical type either,
3998 // so fill in the canonical type field.
3999 QualType Canonical;
4000 if (!T.isCanonical()) {
4001 Canonical = getPointerType(getCanonicalType(T));
4002
4003 // Get the new insert position for the node we care about.
4004 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4005 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4006 }
4007 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
4008 Types.push_back(New);
4009 PointerTypes.InsertNode(New, InsertPos);
4010 return QualType(New, 0);
4011}
4012
4014 llvm::FoldingSetNodeID ID;
4015 AdjustedType::Profile(ID, Orig, New);
4016 void *InsertPos = nullptr;
4017 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
4018 if (AT)
4019 return QualType(AT, 0);
4020
4021 QualType Canonical = getCanonicalType(New);
4022
4023 // Get the new insert position for the node we care about.
4024 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
4025 assert(!AT && "Shouldn't be in the map!");
4026
4027 AT = new (*this, alignof(AdjustedType))
4028 AdjustedType(Type::Adjusted, Orig, New, Canonical);
4029 Types.push_back(AT);
4030 AdjustedTypes.InsertNode(AT, InsertPos);
4031 return QualType(AT, 0);
4032}
4033
4035 llvm::FoldingSetNodeID ID;
4036 AdjustedType::Profile(ID, Orig, Decayed);
4037 void *InsertPos = nullptr;
4038 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
4039 if (AT)
4040 return QualType(AT, 0);
4041
4042 QualType Canonical = getCanonicalType(Decayed);
4043
4044 // Get the new insert position for the node we care about.
4045 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
4046 assert(!AT && "Shouldn't be in the map!");
4047
4048 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
4049 Types.push_back(AT);
4050 AdjustedTypes.InsertNode(AT, InsertPos);
4051 return QualType(AT, 0);
4052}
4053
4055 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
4056
4057 QualType Decayed;
4058
4059 // C99 6.7.5.3p7:
4060 // A declaration of a parameter as "array of type" shall be
4061 // adjusted to "qualified pointer to type", where the type
4062 // qualifiers (if any) are those specified within the [ and ] of
4063 // the array type derivation.
4064 if (T->isArrayType())
4065 Decayed = getArrayDecayedType(T);
4066
4067 // C99 6.7.5.3p8:
4068 // A declaration of a parameter as "function returning type"
4069 // shall be adjusted to "pointer to function returning type", as
4070 // in 6.3.2.1.
4071 if (T->isFunctionType())
4072 Decayed = getPointerType(T);
4073
4074 return getDecayedType(T, Decayed);
4075}
4076
4078 if (Ty->isArrayParameterType())
4079 return Ty;
4080 assert(Ty->isConstantArrayType() && "Ty must be an array type.");
4081 QualType DTy = Ty.getDesugaredType(*this);
4082 const auto *ATy = cast<ConstantArrayType>(DTy);
4083 llvm::FoldingSetNodeID ID;
4084 ATy->Profile(ID, *this, ATy->getElementType(), ATy->getZExtSize(),
4085 ATy->getSizeExpr(), ATy->getSizeModifier(),
4086 ATy->getIndexTypeQualifiers().getAsOpaqueValue());
4087 void *InsertPos = nullptr;
4088 ArrayParameterType *AT =
4089 ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
4090 if (AT)
4091 return QualType(AT, 0);
4092
4093 QualType Canonical;
4094 if (!DTy.isCanonical()) {
4095 Canonical = getArrayParameterType(getCanonicalType(Ty));
4096
4097 // Get the new insert position for the node we care about.
4098 AT = ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
4099 assert(!AT && "Shouldn't be in the map!");
4100 }
4101
4102 AT = new (*this, alignof(ArrayParameterType))
4103 ArrayParameterType(ATy, Canonical);
4104 Types.push_back(AT);
4105 ArrayParameterTypes.InsertNode(AT, InsertPos);
4106 return QualType(AT, 0);
4107}
4108
4109/// getBlockPointerType - Return the uniqued reference to the type for
4110/// a pointer to the specified block.
4112 assert(T->isFunctionType() && "block of function types only");
4113 // Unique pointers, to guarantee there is only one block of a particular
4114 // structure.
4115 llvm::FoldingSetNodeID ID;
4117
4118 void *InsertPos = nullptr;
4119 if (BlockPointerType *PT =
4120 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4121 return QualType(PT, 0);
4122
4123 // If the block pointee type isn't canonical, this won't be a canonical
4124 // type either so fill in the canonical type field.
4125 QualType Canonical;
4126 if (!T.isCanonical()) {
4128
4129 // Get the new insert position for the node we care about.
4130 BlockPointerType *NewIP =
4131 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4132 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4133 }
4134 auto *New =
4135 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
4136 Types.push_back(New);
4137 BlockPointerTypes.InsertNode(New, InsertPos);
4138 return QualType(New, 0);
4139}
4140
4141/// getLValueReferenceType - Return the uniqued reference to the type for an
4142/// lvalue reference to the specified type.
4144ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
4145 assert((!T->isPlaceholderType() ||
4146 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4147 "Unresolved placeholder type");
4148
4149 // Unique pointers, to guarantee there is only one pointer of a particular
4150 // structure.
4151 llvm::FoldingSetNodeID ID;
4152 ReferenceType::Profile(ID, T, SpelledAsLValue);
4153
4154 void *InsertPos = nullptr;
4155 if (LValueReferenceType *RT =
4156 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4157 return QualType(RT, 0);
4158
4159 const auto *InnerRef = T->getAs<ReferenceType>();
4160
4161 // If the referencee type isn't canonical, this won't be a canonical type
4162 // either, so fill in the canonical type field.
4163 QualType Canonical;
4164 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
4165 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4166 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
4167
4168 // Get the new insert position for the node we care about.
4169 LValueReferenceType *NewIP =
4170 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4171 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4172 }
4173
4174 auto *New = new (*this, alignof(LValueReferenceType))
4175 LValueReferenceType(T, Canonical, SpelledAsLValue);
4176 Types.push_back(New);
4177 LValueReferenceTypes.InsertNode(New, InsertPos);
4178
4179 return QualType(New, 0);
4180}
4181
4182/// getRValueReferenceType - Return the uniqued reference to the type for an
4183/// rvalue reference to the specified type.
4185 assert((!T->isPlaceholderType() ||
4186 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4187 "Unresolved placeholder type");
4188
4189 // Unique pointers, to guarantee there is only one pointer of a particular
4190 // structure.
4191 llvm::FoldingSetNodeID ID;
4192 ReferenceType::Profile(ID, T, false);
4193
4194 void *InsertPos = nullptr;
4195 if (RValueReferenceType *RT =
4196 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4197 return QualType(RT, 0);
4198
4199 const auto *InnerRef = T->getAs<ReferenceType>();
4200
4201 // If the referencee type isn't canonical, this won't be a canonical type
4202 // either, so fill in the canonical type field.
4203 QualType Canonical;
4204 if (InnerRef || !T.isCanonical()) {
4205 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4206 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
4207
4208 // Get the new insert position for the node we care about.
4209 RValueReferenceType *NewIP =
4210 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4211 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4212 }
4213
4214 auto *New = new (*this, alignof(RValueReferenceType))
4215 RValueReferenceType(T, Canonical);
4216 Types.push_back(New);
4217 RValueReferenceTypes.InsertNode(New, InsertPos);
4218 return QualType(New, 0);
4219}
4220
4222 NestedNameSpecifier Qualifier,
4223 const CXXRecordDecl *Cls) const {
4224 if (!Qualifier) {
4225 assert(Cls && "At least one of Qualifier or Cls must be provided");
4226 Qualifier = NestedNameSpecifier(getCanonicalTagType(Cls).getTypePtr());
4227 } else if (!Cls) {
4228 Cls = Qualifier.getAsRecordDecl();
4229 }
4230 // Unique pointers, to guarantee there is only one pointer of a particular
4231 // structure.
4232 llvm::FoldingSetNodeID ID;
4233 MemberPointerType::Profile(ID, T, Qualifier, Cls);
4234
4235 void *InsertPos = nullptr;
4236 if (MemberPointerType *PT =
4237 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4238 return QualType(PT, 0);
4239
4240 NestedNameSpecifier CanonicalQualifier = [&] {
4241 if (!Cls)
4242 return Qualifier.getCanonical();
4243 NestedNameSpecifier R(getCanonicalTagType(Cls).getTypePtr());
4244 assert(R.isCanonical());
4245 return R;
4246 }();
4247 // If the pointee or class type isn't canonical, this won't be a canonical
4248 // type either, so fill in the canonical type field.
4249 QualType Canonical;
4250 if (!T.isCanonical() || Qualifier != CanonicalQualifier) {
4251 Canonical =
4252 getMemberPointerType(getCanonicalType(T), CanonicalQualifier, Cls);
4253 assert(!cast<MemberPointerType>(Canonical)->isSugared());
4254 // Get the new insert position for the node we care about.
4255 [[maybe_unused]] MemberPointerType *NewIP =
4256 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4257 assert(!NewIP && "Shouldn't be in the map!");
4258 }
4259 auto *New = new (*this, alignof(MemberPointerType))
4260 MemberPointerType(T, Qualifier, Canonical);
4261 Types.push_back(New);
4262 MemberPointerTypes.InsertNode(New, InsertPos);
4263 return QualType(New, 0);
4264}
4265
4266/// getConstantArrayType - Return the unique reference to the type for an
4267/// array of the specified element type.
4269 const llvm::APInt &ArySizeIn,
4270 const Expr *SizeExpr,
4272 unsigned IndexTypeQuals) const {
4273 assert((EltTy->isDependentType() ||
4274 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
4275 "Constant array of VLAs is illegal!");
4276
4277 // We only need the size as part of the type if it's instantiation-dependent.
4278 if (SizeExpr && !SizeExpr->isInstantiationDependent())
4279 SizeExpr = nullptr;
4280
4281 // Convert the array size into a canonical width matching the pointer size for
4282 // the target.
4283 llvm::APInt ArySize(ArySizeIn);
4284 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
4285
4286 llvm::FoldingSetNodeID ID;
4287 ConstantArrayType::Profile(ID, *this, EltTy, ArySize.getZExtValue(), SizeExpr,
4288 ASM, IndexTypeQuals);
4289
4290 void *InsertPos = nullptr;
4291 if (ConstantArrayType *ATP =
4292 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
4293 return QualType(ATP, 0);
4294
4295 // If the element type isn't canonical or has qualifiers, or the array bound
4296 // is instantiation-dependent, this won't be a canonical type either, so fill
4297 // in the canonical type field.
4298 QualType Canon;
4299 // FIXME: Check below should look for qualifiers behind sugar.
4300 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
4301 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4302 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
4303 ASM, IndexTypeQuals);
4304 Canon = getQualifiedType(Canon, canonSplit.Quals);
4305
4306 // Get the new insert position for the node we care about.
4307 ConstantArrayType *NewIP =
4308 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
4309 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4310 }
4311
4312 auto *New = ConstantArrayType::Create(*this, EltTy, Canon, ArySize, SizeExpr,
4313 ASM, IndexTypeQuals);
4314 ConstantArrayTypes.InsertNode(New, InsertPos);
4315 Types.push_back(New);
4316 return QualType(New, 0);
4317}
4318
4319/// getVariableArrayDecayedType - Turns the given type, which may be
4320/// variably-modified, into the corresponding type with all the known
4321/// sizes replaced with [*].
4323 // Vastly most common case.
4324 if (!type->isVariablyModifiedType()) return type;
4325
4326 QualType result;
4327
4328 SplitQualType split = type.getSplitDesugaredType();
4329 const Type *ty = split.Ty;
4330 switch (ty->getTypeClass()) {
4331#define TYPE(Class, Base)
4332#define ABSTRACT_TYPE(Class, Base)
4333#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4334#include "clang/AST/TypeNodes.inc"
4335 llvm_unreachable("didn't desugar past all non-canonical types?");
4336
4337 // These types should never be variably-modified.
4338 case Type::Builtin:
4339 case Type::Complex:
4340 case Type::Vector:
4341 case Type::DependentVector:
4342 case Type::ExtVector:
4343 case Type::DependentSizedExtVector:
4344 case Type::ConstantMatrix:
4345 case Type::DependentSizedMatrix:
4346 case Type::DependentAddressSpace:
4347 case Type::ObjCObject:
4348 case Type::ObjCInterface:
4349 case Type::ObjCObjectPointer:
4350 case Type::Record:
4351 case Type::Enum:
4352 case Type::UnresolvedUsing:
4353 case Type::TypeOfExpr:
4354 case Type::TypeOf:
4355 case Type::Decltype:
4356 case Type::UnaryTransform:
4357 case Type::DependentName:
4358 case Type::InjectedClassName:
4359 case Type::TemplateSpecialization:
4360 case Type::TemplateTypeParm:
4361 case Type::SubstTemplateTypeParmPack:
4362 case Type::SubstBuiltinTemplatePack:
4363 case Type::Auto:
4364 case Type::DeducedTemplateSpecialization:
4365 case Type::PackExpansion:
4366 case Type::PackIndexing:
4367 case Type::BitInt:
4368 case Type::DependentBitInt:
4369 case Type::ArrayParameter:
4370 case Type::HLSLAttributedResource:
4371 case Type::HLSLInlineSpirv:
4372 case Type::OverflowBehavior:
4373 llvm_unreachable("type should never be variably-modified");
4374
4375 // These types can be variably-modified but should never need to
4376 // further decay.
4377 case Type::FunctionNoProto:
4378 case Type::FunctionProto:
4379 case Type::BlockPointer:
4380 case Type::MemberPointer:
4381 case Type::Pipe:
4382 return type;
4383
4384 // These types can be variably-modified. All these modifications
4385 // preserve structure except as noted by comments.
4386 // TODO: if we ever care about optimizing VLAs, there are no-op
4387 // optimizations available here.
4388 case Type::Pointer:
4391 break;
4392
4393 case Type::LValueReference: {
4394 const auto *lv = cast<LValueReferenceType>(ty);
4395 result = getLValueReferenceType(
4396 getVariableArrayDecayedType(lv->getPointeeType()),
4397 lv->isSpelledAsLValue());
4398 break;
4399 }
4400
4401 case Type::RValueReference: {
4402 const auto *lv = cast<RValueReferenceType>(ty);
4403 result = getRValueReferenceType(
4404 getVariableArrayDecayedType(lv->getPointeeType()));
4405 break;
4406 }
4407
4408 case Type::Atomic: {
4409 const auto *at = cast<AtomicType>(ty);
4410 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
4411 break;
4412 }
4413
4414 case Type::ConstantArray: {
4415 const auto *cat = cast<ConstantArrayType>(ty);
4416 result = getConstantArrayType(
4417 getVariableArrayDecayedType(cat->getElementType()),
4418 cat->getSize(),
4419 cat->getSizeExpr(),
4420 cat->getSizeModifier(),
4421 cat->getIndexTypeCVRQualifiers());
4422 break;
4423 }
4424
4425 case Type::DependentSizedArray: {
4426 const auto *dat = cast<DependentSizedArrayType>(ty);
4428 getVariableArrayDecayedType(dat->getElementType()), dat->getSizeExpr(),
4429 dat->getSizeModifier(), dat->getIndexTypeCVRQualifiers());
4430 break;
4431 }
4432
4433 // Turn incomplete types into [*] types.
4434 case Type::IncompleteArray: {
4435 const auto *iat = cast<IncompleteArrayType>(ty);
4436 result =
4438 /*size*/ nullptr, ArraySizeModifier::Normal,
4439 iat->getIndexTypeCVRQualifiers());
4440 break;
4441 }
4442
4443 // Turn VLA types into [*] types.
4444 case Type::VariableArray: {
4445 const auto *vat = cast<VariableArrayType>(ty);
4446 result =
4448 /*size*/ nullptr, ArraySizeModifier::Star,
4449 vat->getIndexTypeCVRQualifiers());
4450 break;
4451 }
4452 }
4453
4454 // Apply the top-level qualifiers from the original.
4455 return getQualifiedType(result, split.Quals);
4456}
4457
4458/// getVariableArrayType - Returns a non-unique reference to the type for a
4459/// variable array of the specified element type.
4462 unsigned IndexTypeQuals) const {
4463 // Since we don't unique expressions, it isn't possible to unique VLA's
4464 // that have an expression provided for their size.
4465 QualType Canon;
4466
4467 // Be sure to pull qualifiers off the element type.
4468 // FIXME: Check below should look for qualifiers behind sugar.
4469 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
4470 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4471 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
4472 IndexTypeQuals);
4473 Canon = getQualifiedType(Canon, canonSplit.Quals);
4474 }
4475
4476 auto *New = new (*this, alignof(VariableArrayType))
4477 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals);
4478
4479 VariableArrayTypes.push_back(New);
4480 Types.push_back(New);
4481 return QualType(New, 0);
4482}
4483
4484/// getDependentSizedArrayType - Returns a non-unique reference to
4485/// the type for a dependently-sized array of the specified element
4486/// type.
4490 unsigned elementTypeQuals) const {
4491 assert((!numElements || numElements->isTypeDependent() ||
4492 numElements->isValueDependent()) &&
4493 "Size must be type- or value-dependent!");
4494
4495 SplitQualType canonElementType = getCanonicalType(elementType).split();
4496
4497 void *insertPos = nullptr;
4498 llvm::FoldingSetNodeID ID;
4500 ID, *this, numElements ? QualType(canonElementType.Ty, 0) : elementType,
4501 ASM, elementTypeQuals, numElements);
4502
4503 // Look for an existing type with these properties.
4504 DependentSizedArrayType *canonTy =
4505 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4506
4507 // Dependently-sized array types that do not have a specified number
4508 // of elements will have their sizes deduced from a dependent
4509 // initializer.
4510 if (!numElements) {
4511 if (canonTy)
4512 return QualType(canonTy, 0);
4513
4514 auto *newType = new (*this, alignof(DependentSizedArrayType))
4515 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
4516 elementTypeQuals);
4517 DependentSizedArrayTypes.InsertNode(newType, insertPos);
4518 Types.push_back(newType);
4519 return QualType(newType, 0);
4520 }
4521
4522 // If we don't have one, build one.
4523 if (!canonTy) {
4524 canonTy = new (*this, alignof(DependentSizedArrayType))
4525 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
4526 numElements, ASM, elementTypeQuals);
4527 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
4528 Types.push_back(canonTy);
4529 }
4530
4531 // Apply qualifiers from the element type to the array.
4532 QualType canon = getQualifiedType(QualType(canonTy,0),
4533 canonElementType.Quals);
4534
4535 // If we didn't need extra canonicalization for the element type or the size
4536 // expression, then just use that as our result.
4537 if (QualType(canonElementType.Ty, 0) == elementType &&
4538 canonTy->getSizeExpr() == numElements)
4539 return canon;
4540
4541 // Otherwise, we need to build a type which follows the spelling
4542 // of the element type.
4543 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
4544 DependentSizedArrayType(elementType, canon, numElements, ASM,
4545 elementTypeQuals);
4546 Types.push_back(sugaredType);
4547 return QualType(sugaredType, 0);
4548}
4549
4552 unsigned elementTypeQuals) const {
4553 llvm::FoldingSetNodeID ID;
4554 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
4555
4556 void *insertPos = nullptr;
4557 if (IncompleteArrayType *iat =
4558 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
4559 return QualType(iat, 0);
4560
4561 // If the element type isn't canonical, this won't be a canonical type
4562 // either, so fill in the canonical type field. We also have to pull
4563 // qualifiers off the element type.
4564 QualType canon;
4565
4566 // FIXME: Check below should look for qualifiers behind sugar.
4567 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
4568 SplitQualType canonSplit = getCanonicalType(elementType).split();
4569 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
4570 ASM, elementTypeQuals);
4571 canon = getQualifiedType(canon, canonSplit.Quals);
4572
4573 // Get the new insert position for the node we care about.
4574 IncompleteArrayType *existing =
4575 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4576 assert(!existing && "Shouldn't be in the map!"); (void) existing;
4577 }
4578
4579 auto *newType = new (*this, alignof(IncompleteArrayType))
4580 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
4581
4582 IncompleteArrayTypes.InsertNode(newType, insertPos);
4583 Types.push_back(newType);
4584 return QualType(newType, 0);
4585}
4586
4589#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
4590 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
4591 NUMVECTORS};
4592
4593#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
4594 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
4595
4596 switch (Ty->getKind()) {
4597 default:
4598 llvm_unreachable("Unsupported builtin vector type");
4599
4600#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4601 ElBits, NF, IsSigned) \
4602 case BuiltinType::Id: \
4603 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4604 llvm::ElementCount::getScalable(NumEls), NF};
4605#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4606 ElBits, NF) \
4607 case BuiltinType::Id: \
4608 return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy), \
4609 llvm::ElementCount::getScalable(NumEls), NF};
4610#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4611 ElBits, NF) \
4612 case BuiltinType::Id: \
4613 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4614#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4615 ElBits, NF) \
4616 case BuiltinType::Id: \
4617 return {MFloat8Ty, llvm::ElementCount::getScalable(NumEls), NF};
4618#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4619 case BuiltinType::Id: \
4620 return {BoolTy, llvm::ElementCount::getScalable(NumEls), NF};
4621#include "clang/Basic/AArch64ACLETypes.def"
4622
4623#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4624 IsSigned) \
4625 case BuiltinType::Id: \
4626 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4627 llvm::ElementCount::getScalable(NumEls), NF};
4628#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4629 case BuiltinType::Id: \
4630 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4631 llvm::ElementCount::getScalable(NumEls), NF};
4632#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4633 case BuiltinType::Id: \
4634 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4635#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4636 case BuiltinType::Id: \
4637 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4638#include "clang/Basic/RISCVVTypes.def"
4639 }
4640}
4641
4642/// getExternrefType - Return a WebAssembly externref type, which represents an
4643/// opaque reference to a host value.
4645 if (Target->getTriple().isWasm() && Target->hasFeature("reference-types")) {
4646#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4647 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4648 return SingletonId;
4649#include "clang/Basic/WebAssemblyReferenceTypes.def"
4650 }
4651 llvm_unreachable(
4652 "shouldn't try to generate type externref outside WebAssembly target");
4653}
4654
4655/// getScalableVectorType - Return the unique reference to a scalable vector
4656/// type of the specified element type and size. VectorType must be a built-in
4657/// type.
4659 unsigned NumFields) const {
4660 auto K = llvm::ScalableVecTyKey{EltTy, NumElts, NumFields};
4661 if (auto It = ScalableVecTyMap.find(K); It != ScalableVecTyMap.end())
4662 return It->second;
4663
4664 if (Target->hasAArch64ACLETypes()) {
4665 uint64_t EltTySize = getTypeSize(EltTy);
4666
4667#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4668 ElBits, NF, IsSigned) \
4669 if (EltTy->hasIntegerRepresentation() && !EltTy->isBooleanType() && \
4670 EltTy->hasSignedIntegerRepresentation() == IsSigned && \
4671 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4672 return ScalableVecTyMap[K] = SingletonId; \
4673 }
4674#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4675 ElBits, NF) \
4676 if (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4677 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4678 return ScalableVecTyMap[K] = SingletonId; \
4679 }
4680#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4681 ElBits, NF) \
4682 if (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4683 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4684 return ScalableVecTyMap[K] = SingletonId; \
4685 }
4686#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4687 ElBits, NF) \
4688 if (EltTy->isMFloat8Type() && EltTySize == ElBits && \
4689 NumElts == (NumEls * NF) && NumFields == 1) { \
4690 return ScalableVecTyMap[K] = SingletonId; \
4691 }
4692#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4693 if (EltTy->isBooleanType() && NumElts == (NumEls * NF) && NumFields == 1) \
4694 return ScalableVecTyMap[K] = SingletonId;
4695#include "clang/Basic/AArch64ACLETypes.def"
4696 } else if (Target->hasRISCVVTypes()) {
4697 uint64_t EltTySize = getTypeSize(EltTy);
4698#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4699 IsFP, IsBF) \
4700 if (!EltTy->isBooleanType() && \
4701 ((EltTy->hasIntegerRepresentation() && \
4702 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4703 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4704 IsFP && !IsBF) || \
4705 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4706 IsBF && !IsFP)) && \
4707 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4708 return ScalableVecTyMap[K] = SingletonId;
4709#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4710 if (EltTy->isBooleanType() && NumElts == NumEls) \
4711 return ScalableVecTyMap[K] = SingletonId;
4712#include "clang/Basic/RISCVVTypes.def"
4713 }
4714 return QualType();
4715}
4716
4717/// getVectorType - Return the unique reference to a vector type of
4718/// the specified element type and size. VectorType must be a built-in type.
4720 VectorKind VecKind) const {
4721 assert(vecType->isBuiltinType() ||
4722 (vecType->isBitIntType() &&
4723 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4724 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4725
4726 // Check if we've already instantiated a vector of this type.
4727 llvm::FoldingSetNodeID ID;
4728 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
4729
4730 void *InsertPos = nullptr;
4731 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4732 return QualType(VTP, 0);
4733
4734 // If the element type isn't canonical, this won't be a canonical type either,
4735 // so fill in the canonical type field.
4736 QualType Canonical;
4737 if (!vecType.isCanonical()) {
4738 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4739
4740 // Get the new insert position for the node we care about.
4741 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4742 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4743 }
4744 auto *New = new (*this, alignof(VectorType))
4745 VectorType(vecType, NumElts, Canonical, VecKind);
4746 VectorTypes.InsertNode(New, InsertPos);
4747 Types.push_back(New);
4748 return QualType(New, 0);
4749}
4750
4752 SourceLocation AttrLoc,
4753 VectorKind VecKind) const {
4754 llvm::FoldingSetNodeID ID;
4755 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4756 VecKind);
4757 void *InsertPos = nullptr;
4758 DependentVectorType *Canon =
4759 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4761
4762 if (Canon) {
4763 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4764 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4765 } else {
4766 QualType CanonVecTy = getCanonicalType(VecType);
4767 if (CanonVecTy == VecType) {
4768 New = new (*this, alignof(DependentVectorType))
4769 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4770
4771 DependentVectorType *CanonCheck =
4772 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4773 assert(!CanonCheck &&
4774 "Dependent-sized vector_size canonical type broken");
4775 (void)CanonCheck;
4776 DependentVectorTypes.InsertNode(New, InsertPos);
4777 } else {
4778 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4779 SourceLocation(), VecKind);
4780 New = new (*this, alignof(DependentVectorType))
4781 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4782 }
4783 }
4784
4785 Types.push_back(New);
4786 return QualType(New, 0);
4787}
4788
4789/// getExtVectorType - Return the unique reference to an extended vector type of
4790/// the specified element type and size. VectorType must be a built-in type.
4792 unsigned NumElts) const {
4793 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4794 (vecType->isBitIntType() &&
4795 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4796 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4797
4798 // Check if we've already instantiated a vector of this type.
4799 llvm::FoldingSetNodeID ID;
4800 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4802 void *InsertPos = nullptr;
4803 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4804 return QualType(VTP, 0);
4805
4806 // If the element type isn't canonical, this won't be a canonical type either,
4807 // so fill in the canonical type field.
4808 QualType Canonical;
4809 if (!vecType.isCanonical()) {
4810 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4811
4812 // Get the new insert position for the node we care about.
4813 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4814 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4815 }
4816 auto *New = new (*this, alignof(ExtVectorType))
4817 ExtVectorType(vecType, NumElts, Canonical);
4818 VectorTypes.InsertNode(New, InsertPos);
4819 Types.push_back(New);
4820 return QualType(New, 0);
4821}
4822
4825 Expr *SizeExpr,
4826 SourceLocation AttrLoc) const {
4827 llvm::FoldingSetNodeID ID;
4829 SizeExpr);
4830
4831 void *InsertPos = nullptr;
4833 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4835 if (Canon) {
4836 // We already have a canonical version of this array type; use it as
4837 // the canonical type for a newly-built type.
4838 New = new (*this, alignof(DependentSizedExtVectorType))
4839 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4840 AttrLoc);
4841 } else {
4842 QualType CanonVecTy = getCanonicalType(vecType);
4843 if (CanonVecTy == vecType) {
4844 New = new (*this, alignof(DependentSizedExtVectorType))
4845 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4846
4847 DependentSizedExtVectorType *CanonCheck
4848 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4849 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4850 (void)CanonCheck;
4851 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4852 } else {
4853 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4854 SourceLocation());
4855 New = new (*this, alignof(DependentSizedExtVectorType))
4856 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4857 }
4858 }
4859
4860 Types.push_back(New);
4861 return QualType(New, 0);
4862}
4863
4865 unsigned NumColumns) const {
4866 llvm::FoldingSetNodeID ID;
4867 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4868 Type::ConstantMatrix);
4869
4870 assert(MatrixType::isValidElementType(ElementTy, getLangOpts()) &&
4871 "need a valid element type");
4872 assert(NumRows > 0 && NumRows <= LangOpts.MaxMatrixDimension &&
4873 NumColumns > 0 && NumColumns <= LangOpts.MaxMatrixDimension &&
4874 "need valid matrix dimensions");
4875 void *InsertPos = nullptr;
4876 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4877 return QualType(MTP, 0);
4878
4879 QualType Canonical;
4880 if (!ElementTy.isCanonical()) {
4881 Canonical =
4882 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4883
4884 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4885 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4886 (void)NewIP;
4887 }
4888
4889 auto *New = new (*this, alignof(ConstantMatrixType))
4890 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4891 MatrixTypes.InsertNode(New, InsertPos);
4892 Types.push_back(New);
4893 return QualType(New, 0);
4894}
4895
4897 Expr *RowExpr,
4898 Expr *ColumnExpr,
4899 SourceLocation AttrLoc) const {
4900 QualType CanonElementTy = getCanonicalType(ElementTy);
4901 llvm::FoldingSetNodeID ID;
4902 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4903 ColumnExpr);
4904
4905 void *InsertPos = nullptr;
4907 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4908
4909 if (!Canon) {
4910 Canon = new (*this, alignof(DependentSizedMatrixType))
4911 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4912 ColumnExpr, AttrLoc);
4913#ifndef NDEBUG
4914 DependentSizedMatrixType *CanonCheck =
4915 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4916 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4917#endif
4918 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4919 Types.push_back(Canon);
4920 }
4921
4922 // Already have a canonical version of the matrix type
4923 //
4924 // If it exactly matches the requested type, use it directly.
4925 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4926 Canon->getRowExpr() == ColumnExpr)
4927 return QualType(Canon, 0);
4928
4929 // Use Canon as the canonical type for newly-built type.
4931 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4932 ColumnExpr, AttrLoc);
4933 Types.push_back(New);
4934 return QualType(New, 0);
4935}
4936
4938 Expr *AddrSpaceExpr,
4939 SourceLocation AttrLoc) const {
4940 assert(AddrSpaceExpr->isInstantiationDependent());
4941
4942 QualType canonPointeeType = getCanonicalType(PointeeType);
4943
4944 void *insertPos = nullptr;
4945 llvm::FoldingSetNodeID ID;
4946 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4947 AddrSpaceExpr);
4948
4949 DependentAddressSpaceType *canonTy =
4950 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4951
4952 if (!canonTy) {
4953 canonTy = new (*this, alignof(DependentAddressSpaceType))
4954 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
4955 AttrLoc);
4956 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4957 Types.push_back(canonTy);
4958 }
4959
4960 if (canonPointeeType == PointeeType &&
4961 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4962 return QualType(canonTy, 0);
4963
4964 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
4965 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
4966 AddrSpaceExpr, AttrLoc);
4967 Types.push_back(sugaredType);
4968 return QualType(sugaredType, 0);
4969}
4970
4971/// Determine whether \p T is canonical as the result type of a function.
4973 return T.isCanonical() &&
4974 (T.getObjCLifetime() == Qualifiers::OCL_None ||
4975 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4976}
4977
4978/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4979QualType
4981 const FunctionType::ExtInfo &Info) const {
4982 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
4983 // functionality creates a function without a prototype regardless of
4984 // language mode (so it makes them even in C++). Once the rewriter has been
4985 // fixed, this assertion can be enabled again.
4986 //assert(!LangOpts.requiresStrictPrototypes() &&
4987 // "strict prototypes are disabled");
4988
4989 // Unique functions, to guarantee there is only one function of a particular
4990 // structure.
4991 llvm::FoldingSetNodeID ID;
4992 FunctionNoProtoType::Profile(ID, ResultTy, Info);
4993
4994 void *InsertPos = nullptr;
4995 if (FunctionNoProtoType *FT =
4996 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4997 return QualType(FT, 0);
4998
4999 QualType Canonical;
5000 if (!isCanonicalResultType(ResultTy)) {
5001 Canonical =
5003
5004 // Get the new insert position for the node we care about.
5005 FunctionNoProtoType *NewIP =
5006 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
5007 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5008 }
5009
5010 auto *New = new (*this, alignof(FunctionNoProtoType))
5011 FunctionNoProtoType(ResultTy, Canonical, Info);
5012 Types.push_back(New);
5013 FunctionNoProtoTypes.InsertNode(New, InsertPos);
5014 return QualType(New, 0);
5015}
5016
5019 CanQualType CanResultType = getCanonicalType(ResultType);
5020
5021 // Canonical result types do not have ARC lifetime qualifiers.
5022 if (CanResultType.getQualifiers().hasObjCLifetime()) {
5023 Qualifiers Qs = CanResultType.getQualifiers();
5024 Qs.removeObjCLifetime();
5026 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
5027 }
5028
5029 return CanResultType;
5030}
5031
5033 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
5034 if (ESI.Type == EST_None)
5035 return true;
5036 if (!NoexceptInType)
5037 return false;
5038
5039 // C++17 onwards: exception specification is part of the type, as a simple
5040 // boolean "can this function type throw".
5041 if (ESI.Type == EST_BasicNoexcept)
5042 return true;
5043
5044 // A noexcept(expr) specification is (possibly) canonical if expr is
5045 // value-dependent.
5046 if (ESI.Type == EST_DependentNoexcept)
5047 return true;
5048
5049 // A dynamic exception specification is canonical if it only contains pack
5050 // expansions (so we can't tell whether it's non-throwing) and all its
5051 // contained types are canonical.
5052 if (ESI.Type == EST_Dynamic) {
5053 bool AnyPackExpansions = false;
5054 for (QualType ET : ESI.Exceptions) {
5055 if (!ET.isCanonical())
5056 return false;
5057 if (ET->getAs<PackExpansionType>())
5058 AnyPackExpansions = true;
5059 }
5060 return AnyPackExpansions;
5061 }
5062
5063 return false;
5064}
5065
5066QualType ASTContext::getFunctionTypeInternal(
5067 QualType ResultTy, ArrayRef<QualType> ArgArray,
5068 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
5069 size_t NumArgs = ArgArray.size();
5070
5071 // Unique functions, to guarantee there is only one function of a particular
5072 // structure.
5073 llvm::FoldingSetNodeID ID;
5074 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
5075 *this, true);
5076
5077 QualType Canonical;
5078 bool Unique = false;
5079
5080 void *InsertPos = nullptr;
5081 if (FunctionProtoType *FPT =
5082 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
5083 QualType Existing = QualType(FPT, 0);
5084
5085 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
5086 // it so long as our exception specification doesn't contain a dependent
5087 // noexcept expression, or we're just looking for a canonical type.
5088 // Otherwise, we're going to need to create a type
5089 // sugar node to hold the concrete expression.
5090 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
5091 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
5092 return Existing;
5093
5094 // We need a new type sugar node for this one, to hold the new noexcept
5095 // expression. We do no canonicalization here, but that's OK since we don't
5096 // expect to see the same noexcept expression much more than once.
5097 Canonical = getCanonicalType(Existing);
5098 Unique = true;
5099 }
5100
5101 bool NoexceptInType = getLangOpts().CPlusPlus17;
5102 bool IsCanonicalExceptionSpec =
5104
5105 // Determine whether the type being created is already canonical or not.
5106 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
5107 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
5108 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
5109 if (!ArgArray[i].isCanonicalAsParam())
5110 isCanonical = false;
5111
5112 if (OnlyWantCanonical)
5113 assert(isCanonical &&
5114 "given non-canonical parameters constructing canonical type");
5115
5116 // If this type isn't canonical, get the canonical version of it if we don't
5117 // already have it. The exception spec is only partially part of the
5118 // canonical type, and only in C++17 onwards.
5119 if (!isCanonical && Canonical.isNull()) {
5120 SmallVector<QualType, 16> CanonicalArgs;
5121 CanonicalArgs.reserve(NumArgs);
5122 for (unsigned i = 0; i != NumArgs; ++i)
5123 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
5124
5125 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
5126 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
5127 CanonicalEPI.HasTrailingReturn = false;
5128
5129 if (IsCanonicalExceptionSpec) {
5130 // Exception spec is already OK.
5131 } else if (NoexceptInType) {
5132 switch (EPI.ExceptionSpec.Type) {
5134 // We don't know yet. It shouldn't matter what we pick here; no-one
5135 // should ever look at this.
5136 [[fallthrough]];
5137 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
5138 CanonicalEPI.ExceptionSpec.Type = EST_None;
5139 break;
5140
5141 // A dynamic exception specification is almost always "not noexcept",
5142 // with the exception that a pack expansion might expand to no types.
5143 case EST_Dynamic: {
5144 bool AnyPacks = false;
5145 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
5146 if (ET->getAs<PackExpansionType>())
5147 AnyPacks = true;
5148 ExceptionTypeStorage.push_back(getCanonicalType(ET));
5149 }
5150 if (!AnyPacks)
5151 CanonicalEPI.ExceptionSpec.Type = EST_None;
5152 else {
5153 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
5154 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
5155 }
5156 break;
5157 }
5158
5159 case EST_DynamicNone:
5160 case EST_BasicNoexcept:
5161 case EST_NoexceptTrue:
5162 case EST_NoThrow:
5163 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
5164 break;
5165
5167 llvm_unreachable("dependent noexcept is already canonical");
5168 }
5169 } else {
5170 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
5171 }
5172
5173 // Adjust the canonical function result type.
5174 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
5175 Canonical =
5176 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
5177
5178 // Get the new insert position for the node we care about.
5179 FunctionProtoType *NewIP =
5180 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
5181 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5182 }
5183
5184 // Compute the needed size to hold this FunctionProtoType and the
5185 // various trailing objects.
5186 auto ESH = FunctionProtoType::getExceptionSpecSize(
5187 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
5188 size_t Size = FunctionProtoType::totalSizeToAlloc<
5189 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
5190 FunctionType::FunctionTypeExtraAttributeInfo,
5191 FunctionType::FunctionTypeArmAttributes, FunctionType::ExceptionType,
5192 Expr *, FunctionDecl *, FunctionProtoType::ExtParameterInfo, Qualifiers,
5193 FunctionEffect, EffectConditionExpr>(
5196 EPI.requiresFunctionProtoTypeArmAttributes(), ESH.NumExceptionType,
5197 ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
5198 EPI.ExtParameterInfos ? NumArgs : 0,
5200 EPI.FunctionEffects.conditions().size());
5201
5202 auto *FTP = (FunctionProtoType *)Allocate(Size, alignof(FunctionProtoType));
5203 FunctionProtoType::ExtProtoInfo newEPI = EPI;
5204 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
5205 Types.push_back(FTP);
5206 if (!Unique)
5207 FunctionProtoTypes.InsertNode(FTP, InsertPos);
5208 if (!EPI.FunctionEffects.empty())
5209 AnyFunctionEffects = true;
5210 return QualType(FTP, 0);
5211}
5212
5213QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
5214 llvm::FoldingSetNodeID ID;
5215 PipeType::Profile(ID, T, ReadOnly);
5216
5217 void *InsertPos = nullptr;
5218 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
5219 return QualType(PT, 0);
5220
5221 // If the pipe element type isn't canonical, this won't be a canonical type
5222 // either, so fill in the canonical type field.
5223 QualType Canonical;
5224 if (!T.isCanonical()) {
5225 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
5226
5227 // Get the new insert position for the node we care about.
5228 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
5229 assert(!NewIP && "Shouldn't be in the map!");
5230 (void)NewIP;
5231 }
5232 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
5233 Types.push_back(New);
5234 PipeTypes.InsertNode(New, InsertPos);
5235 return QualType(New, 0);
5236}
5237
5239 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
5240 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
5241 : Ty;
5242}
5243
5245 return getPipeType(T, true);
5246}
5247
5249 return getPipeType(T, false);
5250}
5251
5252QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
5253 llvm::FoldingSetNodeID ID;
5254 BitIntType::Profile(ID, IsUnsigned, NumBits);
5255
5256 void *InsertPos = nullptr;
5257 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5258 return QualType(EIT, 0);
5259
5260 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
5261 BitIntTypes.InsertNode(New, InsertPos);
5262 Types.push_back(New);
5263 return QualType(New, 0);
5264}
5265
5267 Expr *NumBitsExpr) const {
5268 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
5269 llvm::FoldingSetNodeID ID;
5270 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
5271
5272 void *InsertPos = nullptr;
5273 if (DependentBitIntType *Existing =
5274 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5275 return QualType(Existing, 0);
5276
5277 auto *New = new (*this, alignof(DependentBitIntType))
5278 DependentBitIntType(IsUnsigned, NumBitsExpr);
5279 DependentBitIntTypes.InsertNode(New, InsertPos);
5280
5281 Types.push_back(New);
5282 return QualType(New, 0);
5283}
5284
5287 using Kind = PredefinedSugarType::Kind;
5288
5289 if (auto *Target = PredefinedSugarTypes[llvm::to_underlying(KD)];
5290 Target != nullptr)
5291 return QualType(Target, 0);
5292
5293 auto getCanonicalType = [](const ASTContext &Ctx, Kind KDI) -> QualType {
5294 switch (KDI) {
5295 // size_t (C99TC3 6.5.3.4), signed size_t (C++23 5.13.2) and
5296 // ptrdiff_t (C99TC3 6.5.6) Although these types are not built-in, they
5297 // are part of the core language and are widely used. Using
5298 // PredefinedSugarType makes these types as named sugar types rather than
5299 // standard integer types, enabling better hints and diagnostics.
5300 case Kind::SizeT:
5301 return Ctx.getFromTargetType(Ctx.Target->getSizeType());
5302 case Kind::SignedSizeT:
5303 return Ctx.getFromTargetType(Ctx.Target->getSignedSizeType());
5304 case Kind::PtrdiffT:
5305 return Ctx.getFromTargetType(Ctx.Target->getPtrDiffType(LangAS::Default));
5306 }
5307 llvm_unreachable("unexpected kind");
5308 };
5309 auto *New = new (*this, alignof(PredefinedSugarType))
5310 PredefinedSugarType(KD, &Idents.get(PredefinedSugarType::getName(KD)),
5311 getCanonicalType(*this, static_cast<Kind>(KD)));
5312 Types.push_back(New);
5313 PredefinedSugarTypes[llvm::to_underlying(KD)] = New;
5314 return QualType(New, 0);
5315}
5316
5318 NestedNameSpecifier Qualifier,
5319 const TypeDecl *Decl) const {
5320 if (auto *Tag = dyn_cast<TagDecl>(Decl))
5321 return getTagType(Keyword, Qualifier, Tag,
5322 /*OwnsTag=*/false);
5323 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
5324 return getTypedefType(Keyword, Qualifier, Typedef);
5325 if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5326 return getUnresolvedUsingType(Keyword, Qualifier, UD);
5327
5329 assert(!Qualifier);
5330 return QualType(Decl->TypeForDecl, 0);
5331}
5332
5334 if (auto *Tag = dyn_cast<TagDecl>(TD))
5335 return getCanonicalTagType(Tag);
5336 if (auto *TN = dyn_cast<TypedefNameDecl>(TD))
5337 return getCanonicalType(TN->getUnderlyingType());
5338 if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD))
5340 assert(TD->TypeForDecl);
5341 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5342}
5343
5345 if (const auto *TD = dyn_cast<TagDecl>(Decl))
5346 return getCanonicalTagType(TD);
5347 if (const auto *TD = dyn_cast<TypedefNameDecl>(Decl);
5348 isa_and_nonnull<TypedefDecl, TypeAliasDecl>(TD))
5350 /*Qualifier=*/std::nullopt, TD);
5351 if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5352 return getCanonicalUnresolvedUsingType(Using);
5353
5354 assert(Decl->TypeForDecl);
5355 return QualType(Decl->TypeForDecl, 0);
5356}
5357
5358/// getTypedefType - Return the unique reference to the type for the
5359/// specified typedef name decl.
5362 NestedNameSpecifier Qualifier,
5363 const TypedefNameDecl *Decl, QualType UnderlyingType,
5364 std::optional<bool> TypeMatchesDeclOrNone) const {
5365 if (!TypeMatchesDeclOrNone) {
5366 QualType DeclUnderlyingType = Decl->getUnderlyingType();
5367 assert(!DeclUnderlyingType.isNull());
5368 if (UnderlyingType.isNull())
5369 UnderlyingType = DeclUnderlyingType;
5370 else
5371 assert(hasSameType(UnderlyingType, DeclUnderlyingType));
5372 TypeMatchesDeclOrNone = UnderlyingType == DeclUnderlyingType;
5373 } else {
5374 // FIXME: This is a workaround for a serialization cycle: assume the decl
5375 // underlying type is not available; don't touch it.
5376 assert(!UnderlyingType.isNull());
5377 }
5378
5379 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier &&
5380 *TypeMatchesDeclOrNone) {
5381 if (Decl->TypeForDecl)
5382 return QualType(Decl->TypeForDecl, 0);
5383
5384 auto *NewType = new (*this, alignof(TypedefType))
5385 TypedefType(Type::Typedef, Keyword, Qualifier, Decl, UnderlyingType,
5386 !*TypeMatchesDeclOrNone);
5387
5388 Types.push_back(NewType);
5389 Decl->TypeForDecl = NewType;
5390 return QualType(NewType, 0);
5391 }
5392
5393 llvm::FoldingSetNodeID ID;
5394 TypedefType::Profile(ID, Keyword, Qualifier, Decl,
5395 *TypeMatchesDeclOrNone ? QualType() : UnderlyingType);
5396
5397 void *InsertPos = nullptr;
5398 if (FoldingSetPlaceholder<TypedefType> *Placeholder =
5399 TypedefTypes.FindNodeOrInsertPos(ID, InsertPos))
5400 return QualType(Placeholder->getType(), 0);
5401
5402 void *Mem =
5403 Allocate(TypedefType::totalSizeToAlloc<FoldingSetPlaceholder<TypedefType>,
5405 1, !!Qualifier, !*TypeMatchesDeclOrNone),
5406 alignof(TypedefType));
5407 auto *NewType =
5408 new (Mem) TypedefType(Type::Typedef, Keyword, Qualifier, Decl,
5409 UnderlyingType, !*TypeMatchesDeclOrNone);
5410 auto *Placeholder = new (NewType->getFoldingSetPlaceholder())
5412 TypedefTypes.InsertNode(Placeholder, InsertPos);
5413 Types.push_back(NewType);
5414 return QualType(NewType, 0);
5415}
5416
5418 NestedNameSpecifier Qualifier,
5419 const UsingShadowDecl *D,
5420 QualType UnderlyingType) const {
5421 // FIXME: This is expensive to compute every time!
5422 if (UnderlyingType.isNull()) {
5423 const auto *UD = cast<UsingDecl>(D->getIntroducer());
5424 UnderlyingType =
5427 UD->getQualifier(), cast<TypeDecl>(D->getTargetDecl()));
5428 }
5429
5430 llvm::FoldingSetNodeID ID;
5431 UsingType::Profile(ID, Keyword, Qualifier, D, UnderlyingType);
5432
5433 void *InsertPos = nullptr;
5434 if (const UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5435 return QualType(T, 0);
5436
5437 assert(!UnderlyingType.hasLocalQualifiers());
5438
5439 assert(
5441 UnderlyingType));
5442
5443 void *Mem =
5444 Allocate(UsingType::totalSizeToAlloc<NestedNameSpecifier>(!!Qualifier),
5445 alignof(UsingType));
5446 UsingType *T = new (Mem) UsingType(Keyword, Qualifier, D, UnderlyingType);
5447 Types.push_back(T);
5448 UsingTypes.InsertNode(T, InsertPos);
5449 return QualType(T, 0);
5450}
5451
5452TagType *ASTContext::getTagTypeInternal(ElaboratedTypeKeyword Keyword,
5453 NestedNameSpecifier Qualifier,
5454 const TagDecl *TD, bool OwnsTag,
5455 bool IsInjected,
5456 const Type *CanonicalType,
5457 bool WithFoldingSetNode) const {
5458 auto [TC, Size] = [&] {
5459 switch (TD->getDeclKind()) {
5460 case Decl::Enum:
5461 static_assert(alignof(EnumType) == alignof(TagType));
5462 return std::make_tuple(Type::Enum, sizeof(EnumType));
5463 case Decl::ClassTemplatePartialSpecialization:
5464 case Decl::ClassTemplateSpecialization:
5465 case Decl::CXXRecord:
5466 static_assert(alignof(RecordType) == alignof(TagType));
5467 static_assert(alignof(InjectedClassNameType) == alignof(TagType));
5468 if (cast<CXXRecordDecl>(TD)->hasInjectedClassType())
5469 return std::make_tuple(Type::InjectedClassName,
5470 sizeof(InjectedClassNameType));
5471 [[fallthrough]];
5472 case Decl::Record:
5473 return std::make_tuple(Type::Record, sizeof(RecordType));
5474 default:
5475 llvm_unreachable("unexpected decl kind");
5476 }
5477 }();
5478
5479 if (Qualifier) {
5480 static_assert(alignof(NestedNameSpecifier) <= alignof(TagType));
5481 Size = llvm::alignTo(Size, alignof(NestedNameSpecifier)) +
5482 sizeof(NestedNameSpecifier);
5483 }
5484 void *Mem;
5485 if (WithFoldingSetNode) {
5486 // FIXME: It would be more profitable to tail allocate the folding set node
5487 // from the type, instead of the other way around, due to the greater
5488 // alignment requirements of the type. But this makes it harder to deal with
5489 // the different type node sizes. This would require either uniquing from
5490 // different folding sets, or having the folding setaccept a
5491 // contextual parameter which is not fixed at construction.
5492 Mem = Allocate(
5493 sizeof(TagTypeFoldingSetPlaceholder) +
5494 TagTypeFoldingSetPlaceholder::getOffset() + Size,
5495 std::max(alignof(TagTypeFoldingSetPlaceholder), alignof(TagType)));
5496 auto *T = new (Mem) TagTypeFoldingSetPlaceholder();
5497 Mem = T->getTagType();
5498 } else {
5499 Mem = Allocate(Size, alignof(TagType));
5500 }
5501
5502 auto *T = [&, TC = TC]() -> TagType * {
5503 switch (TC) {
5504 case Type::Enum: {
5505 assert(isa<EnumDecl>(TD));
5506 auto *T = new (Mem) EnumType(TC, Keyword, Qualifier, TD, OwnsTag,
5507 IsInjected, CanonicalType);
5508 assert(reinterpret_cast<void *>(T) ==
5509 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5510 "TagType must be the first base of EnumType");
5511 return T;
5512 }
5513 case Type::Record: {
5514 assert(isa<RecordDecl>(TD));
5515 auto *T = new (Mem) RecordType(TC, Keyword, Qualifier, TD, OwnsTag,
5516 IsInjected, CanonicalType);
5517 assert(reinterpret_cast<void *>(T) ==
5518 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5519 "TagType must be the first base of RecordType");
5520 return T;
5521 }
5522 case Type::InjectedClassName: {
5523 auto *T = new (Mem) InjectedClassNameType(Keyword, Qualifier, TD,
5524 IsInjected, CanonicalType);
5525 assert(reinterpret_cast<void *>(T) ==
5526 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5527 "TagType must be the first base of InjectedClassNameType");
5528 return T;
5529 }
5530 default:
5531 llvm_unreachable("unexpected type class");
5532 }
5533 }();
5534 assert(T->getKeyword() == Keyword);
5535 assert(T->getQualifier() == Qualifier);
5536 assert(T->getDecl() == TD);
5537 assert(T->isInjected() == IsInjected);
5538 assert(T->isTagOwned() == OwnsTag);
5539 assert((T->isCanonicalUnqualified()
5540 ? QualType()
5541 : T->getCanonicalTypeInternal()) == QualType(CanonicalType, 0));
5542 Types.push_back(T);
5543 return T;
5544}
5545
5546static const TagDecl *getNonInjectedClassName(const TagDecl *TD) {
5547 if (const auto *RD = dyn_cast<CXXRecordDecl>(TD);
5548 RD && RD->isInjectedClassName())
5549 return cast<TagDecl>(RD->getDeclContext());
5550 return TD;
5551}
5552
5555 if (TD->TypeForDecl)
5556 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5557
5558 const Type *CanonicalType = getTagTypeInternal(
5560 /*Qualifier=*/std::nullopt, TD,
5561 /*OwnsTag=*/false, /*IsInjected=*/false, /*CanonicalType=*/nullptr,
5562 /*WithFoldingSetNode=*/false);
5563 TD->TypeForDecl = CanonicalType;
5564 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5565}
5566
5568 NestedNameSpecifier Qualifier,
5569 const TagDecl *TD, bool OwnsTag) const {
5570
5571 const TagDecl *NonInjectedTD = ::getNonInjectedClassName(TD);
5572 bool IsInjected = TD != NonInjectedTD;
5573
5574 ElaboratedTypeKeyword PreferredKeyword =
5577 NonInjectedTD->getTagKind());
5578
5579 if (Keyword == PreferredKeyword && !Qualifier && !OwnsTag) {
5580 if (const Type *T = TD->TypeForDecl; T && !T->isCanonicalUnqualified())
5581 return QualType(T, 0);
5582
5583 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5584 const Type *T =
5585 getTagTypeInternal(Keyword,
5586 /*Qualifier=*/std::nullopt, NonInjectedTD,
5587 /*OwnsTag=*/false, IsInjected, CanonicalType,
5588 /*WithFoldingSetNode=*/false);
5589 TD->TypeForDecl = T;
5590 return QualType(T, 0);
5591 }
5592
5593 llvm::FoldingSetNodeID ID;
5594 TagTypeFoldingSetPlaceholder::Profile(ID, Keyword, Qualifier, NonInjectedTD,
5595 OwnsTag, IsInjected);
5596
5597 void *InsertPos = nullptr;
5598 if (TagTypeFoldingSetPlaceholder *T =
5599 TagTypes.FindNodeOrInsertPos(ID, InsertPos))
5600 return QualType(T->getTagType(), 0);
5601
5602 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5603 TagType *T =
5604 getTagTypeInternal(Keyword, Qualifier, NonInjectedTD, OwnsTag, IsInjected,
5605 CanonicalType, /*WithFoldingSetNode=*/true);
5606 TagTypes.InsertNode(TagTypeFoldingSetPlaceholder::fromTagType(T), InsertPos);
5607 return QualType(T, 0);
5608}
5609
5610bool ASTContext::computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits,
5611 unsigned NumPositiveBits,
5612 QualType &BestType,
5613 QualType &BestPromotionType) {
5614 unsigned IntWidth = Target->getIntWidth();
5615 unsigned CharWidth = Target->getCharWidth();
5616 unsigned ShortWidth = Target->getShortWidth();
5617 bool EnumTooLarge = false;
5618 unsigned BestWidth;
5619 if (NumNegativeBits) {
5620 // If there is a negative value, figure out the smallest integer type (of
5621 // int/long/longlong) that fits.
5622 // If it's packed, check also if it fits a char or a short.
5623 if (IsPacked && NumNegativeBits <= CharWidth &&
5624 NumPositiveBits < CharWidth) {
5625 BestType = SignedCharTy;
5626 BestWidth = CharWidth;
5627 } else if (IsPacked && NumNegativeBits <= ShortWidth &&
5628 NumPositiveBits < ShortWidth) {
5629 BestType = ShortTy;
5630 BestWidth = ShortWidth;
5631 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5632 BestType = IntTy;
5633 BestWidth = IntWidth;
5634 } else {
5635 BestWidth = Target->getLongWidth();
5636
5637 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
5638 BestType = LongTy;
5639 } else {
5640 BestWidth = Target->getLongLongWidth();
5641
5642 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5643 EnumTooLarge = true;
5644 BestType = LongLongTy;
5645 }
5646 }
5647 BestPromotionType = (BestWidth <= IntWidth ? IntTy : BestType);
5648 } else {
5649 // If there is no negative value, figure out the smallest type that fits
5650 // all of the enumerator values.
5651 // If it's packed, check also if it fits a char or a short.
5652 if (IsPacked && NumPositiveBits <= CharWidth) {
5653 BestType = UnsignedCharTy;
5654 BestPromotionType = IntTy;
5655 BestWidth = CharWidth;
5656 } else if (IsPacked && NumPositiveBits <= ShortWidth) {
5657 BestType = UnsignedShortTy;
5658 BestPromotionType = IntTy;
5659 BestWidth = ShortWidth;
5660 } else if (NumPositiveBits <= IntWidth) {
5661 BestType = UnsignedIntTy;
5662 BestWidth = IntWidth;
5663 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5665 : IntTy;
5666 } else if (NumPositiveBits <= (BestWidth = Target->getLongWidth())) {
5667 BestType = UnsignedLongTy;
5668 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5670 : LongTy;
5671 } else {
5672 BestWidth = Target->getLongLongWidth();
5673 if (NumPositiveBits > BestWidth) {
5674 // This can happen with bit-precise integer types, but those are not
5675 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
5676 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
5677 // a 128-bit integer, we should consider doing the same.
5678 EnumTooLarge = true;
5679 }
5680 BestType = UnsignedLongLongTy;
5681 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5683 : LongLongTy;
5684 }
5685 }
5686 return EnumTooLarge;
5687}
5688
5690 assert((T->isIntegralType(*this) || T->isEnumeralType()) &&
5691 "Integral type required!");
5692 unsigned BitWidth = getIntWidth(T);
5693
5694 if (Value.isUnsigned() || Value.isNonNegative()) {
5695 if (T->isSignedIntegerOrEnumerationType())
5696 --BitWidth;
5697 return Value.getActiveBits() <= BitWidth;
5698 }
5699 return Value.getSignificantBits() <= BitWidth;
5700}
5701
5702UnresolvedUsingType *ASTContext::getUnresolvedUsingTypeInternal(
5704 const UnresolvedUsingTypenameDecl *D, void *InsertPos,
5705 const Type *CanonicalType) const {
5706 void *Mem = Allocate(
5707 UnresolvedUsingType::totalSizeToAlloc<
5709 !!InsertPos, !!Qualifier),
5710 alignof(UnresolvedUsingType));
5711 auto *T = new (Mem) UnresolvedUsingType(Keyword, Qualifier, D, CanonicalType);
5712 if (InsertPos) {
5713 auto *Placeholder = new (T->getFoldingSetPlaceholder())
5715 TypedefTypes.InsertNode(Placeholder, InsertPos);
5716 }
5717 Types.push_back(T);
5718 return T;
5719}
5720
5722 const UnresolvedUsingTypenameDecl *D) const {
5723 D = D->getCanonicalDecl();
5724 if (D->TypeForDecl)
5725 return D->TypeForDecl->getCanonicalTypeUnqualified();
5726
5727 const Type *CanonicalType = getUnresolvedUsingTypeInternal(
5729 /*Qualifier=*/std::nullopt, D,
5730 /*InsertPos=*/nullptr, /*CanonicalType=*/nullptr);
5731 D->TypeForDecl = CanonicalType;
5732 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5733}
5734
5737 NestedNameSpecifier Qualifier,
5738 const UnresolvedUsingTypenameDecl *D) const {
5739 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier) {
5740 if (const Type *T = D->TypeForDecl; T && !T->isCanonicalUnqualified())
5741 return QualType(T, 0);
5742
5743 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5744 const Type *T =
5745 getUnresolvedUsingTypeInternal(ElaboratedTypeKeyword::None,
5746 /*Qualifier=*/std::nullopt, D,
5747 /*InsertPos=*/nullptr, CanonicalType);
5748 D->TypeForDecl = T;
5749 return QualType(T, 0);
5750 }
5751
5752 llvm::FoldingSetNodeID ID;
5753 UnresolvedUsingType::Profile(ID, Keyword, Qualifier, D);
5754
5755 void *InsertPos = nullptr;
5757 UnresolvedUsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5758 return QualType(Placeholder->getType(), 0);
5759 assert(InsertPos);
5760
5761 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5762 const Type *T = getUnresolvedUsingTypeInternal(Keyword, Qualifier, D,
5763 InsertPos, CanonicalType);
5764 return QualType(T, 0);
5765}
5766
5768 QualType modifiedType,
5769 QualType equivalentType,
5770 const Attr *attr) const {
5771 llvm::FoldingSetNodeID id;
5772 AttributedType::Profile(id, *this, attrKind, modifiedType, equivalentType,
5773 attr);
5774
5775 void *insertPos = nullptr;
5776 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
5777 if (type) return QualType(type, 0);
5778
5779 assert(!attr || attr->getKind() == attrKind);
5780
5781 QualType canon = getCanonicalType(equivalentType);
5782 type = new (*this, alignof(AttributedType))
5783 AttributedType(canon, attrKind, attr, modifiedType, equivalentType);
5784
5785 Types.push_back(type);
5786 AttributedTypes.InsertNode(type, insertPos);
5787
5788 return QualType(type, 0);
5789}
5790
5792 QualType equivalentType) const {
5793 return getAttributedType(attr->getKind(), modifiedType, equivalentType, attr);
5794}
5795
5797 QualType modifiedType,
5798 QualType equivalentType) {
5799 switch (nullability) {
5801 return getAttributedType(attr::TypeNonNull, modifiedType, equivalentType);
5802
5804 return getAttributedType(attr::TypeNullable, modifiedType, equivalentType);
5805
5807 return getAttributedType(attr::TypeNullableResult, modifiedType,
5808 equivalentType);
5809
5811 return getAttributedType(attr::TypeNullUnspecified, modifiedType,
5812 equivalentType);
5813 }
5814
5815 llvm_unreachable("Unknown nullability kind");
5816}
5817
5818QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
5819 QualType Wrapped) const {
5820 llvm::FoldingSetNodeID ID;
5821 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
5822
5823 void *InsertPos = nullptr;
5824 BTFTagAttributedType *Ty =
5825 BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
5826 if (Ty)
5827 return QualType(Ty, 0);
5828
5829 QualType Canon = getCanonicalType(Wrapped);
5830 Ty = new (*this, alignof(BTFTagAttributedType))
5831 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
5832
5833 Types.push_back(Ty);
5834 BTFTagAttributedTypes.InsertNode(Ty, InsertPos);
5835
5836 return QualType(Ty, 0);
5837}
5838
5840 QualType Underlying) const {
5841 const IdentifierInfo *II = Attr->getBehaviorKind();
5842 StringRef IdentName = II->getName();
5843 OverflowBehaviorType::OverflowBehaviorKind Kind;
5844 if (IdentName == "wrap") {
5845 Kind = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
5846 } else if (IdentName == "trap") {
5847 Kind = OverflowBehaviorType::OverflowBehaviorKind::Trap;
5848 } else {
5849 return Underlying;
5850 }
5851
5852 return getOverflowBehaviorType(Kind, Underlying);
5853}
5854
5856 OverflowBehaviorType::OverflowBehaviorKind Kind,
5857 QualType Underlying) const {
5858 assert(!Underlying->isOverflowBehaviorType() &&
5859 "Cannot have underlying types that are themselves OBTs");
5860 llvm::FoldingSetNodeID ID;
5861 OverflowBehaviorType::Profile(ID, Underlying, Kind);
5862 void *InsertPos = nullptr;
5863
5864 if (OverflowBehaviorType *OBT =
5865 OverflowBehaviorTypes.FindNodeOrInsertPos(ID, InsertPos)) {
5866 return QualType(OBT, 0);
5867 }
5868
5869 QualType Canonical;
5870 if (!Underlying.isCanonical() || Underlying.hasLocalQualifiers()) {
5871 SplitQualType canonSplit = getCanonicalType(Underlying).split();
5872 Canonical = getOverflowBehaviorType(Kind, QualType(canonSplit.Ty, 0));
5873 Canonical = getQualifiedType(Canonical, canonSplit.Quals);
5874 assert(!OverflowBehaviorTypes.FindNodeOrInsertPos(ID, InsertPos) &&
5875 "Shouldn't be in the map");
5876 }
5877
5878 OverflowBehaviorType *Ty = new (*this, alignof(OverflowBehaviorType))
5879 OverflowBehaviorType(Canonical, Underlying, Kind);
5880
5881 Types.push_back(Ty);
5882 OverflowBehaviorTypes.InsertNode(Ty, InsertPos);
5883 return QualType(Ty, 0);
5884}
5885
5887 QualType Wrapped, QualType Contained,
5888 const HLSLAttributedResourceType::Attributes &Attrs) {
5889
5890 llvm::FoldingSetNodeID ID;
5891 HLSLAttributedResourceType::Profile(ID, Wrapped, Contained, Attrs);
5892
5893 void *InsertPos = nullptr;
5894 HLSLAttributedResourceType *Ty =
5895 HLSLAttributedResourceTypes.FindNodeOrInsertPos(ID, InsertPos);
5896 if (Ty)
5897 return QualType(Ty, 0);
5898
5899 Ty = new (*this, alignof(HLSLAttributedResourceType))
5900 HLSLAttributedResourceType(Wrapped, Contained, Attrs);
5901
5902 Types.push_back(Ty);
5903 HLSLAttributedResourceTypes.InsertNode(Ty, InsertPos);
5904
5905 return QualType(Ty, 0);
5906}
5907
5908QualType ASTContext::getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size,
5909 uint32_t Alignment,
5910 ArrayRef<SpirvOperand> Operands) {
5911 llvm::FoldingSetNodeID ID;
5912 HLSLInlineSpirvType::Profile(ID, Opcode, Size, Alignment, Operands);
5913
5914 void *InsertPos = nullptr;
5915 HLSLInlineSpirvType *Ty =
5916 HLSLInlineSpirvTypes.FindNodeOrInsertPos(ID, InsertPos);
5917 if (Ty)
5918 return QualType(Ty, 0);
5919
5920 void *Mem = Allocate(
5921 HLSLInlineSpirvType::totalSizeToAlloc<SpirvOperand>(Operands.size()),
5922 alignof(HLSLInlineSpirvType));
5923
5924 Ty = new (Mem) HLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
5925
5926 Types.push_back(Ty);
5927 HLSLInlineSpirvTypes.InsertNode(Ty, InsertPos);
5928
5929 return QualType(Ty, 0);
5930}
5931
5932/// Retrieve a substitution-result type.
5934 Decl *AssociatedDecl,
5935 unsigned Index,
5937 bool Final) const {
5938 llvm::FoldingSetNodeID ID;
5939 SubstTemplateTypeParmType::Profile(ID, Replacement, AssociatedDecl, Index,
5940 PackIndex, Final);
5941 void *InsertPos = nullptr;
5942 SubstTemplateTypeParmType *SubstParm =
5943 SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5944
5945 if (!SubstParm) {
5946 void *Mem = Allocate(SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
5947 !Replacement.isCanonical()),
5948 alignof(SubstTemplateTypeParmType));
5949 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
5950 Index, PackIndex, Final);
5951 Types.push_back(SubstParm);
5952 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
5953 }
5954
5955 return QualType(SubstParm, 0);
5956}
5957
5960 unsigned Index, bool Final,
5961 const TemplateArgument &ArgPack) {
5962#ifndef NDEBUG
5963 for (const auto &P : ArgPack.pack_elements())
5964 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
5965#endif
5966
5967 llvm::FoldingSetNodeID ID;
5968 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
5969 ArgPack);
5970 void *InsertPos = nullptr;
5971 if (SubstTemplateTypeParmPackType *SubstParm =
5972 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
5973 return QualType(SubstParm, 0);
5974
5975 QualType Canon;
5976 {
5977 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5978 if (!AssociatedDecl->isCanonicalDecl() ||
5979 !CanonArgPack.structurallyEquals(ArgPack)) {
5981 AssociatedDecl->getCanonicalDecl(), Index, Final, CanonArgPack);
5982 [[maybe_unused]] const auto *Nothing =
5983 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
5984 assert(!Nothing);
5985 }
5986 }
5987
5988 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
5989 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
5990 ArgPack);
5991 Types.push_back(SubstParm);
5992 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
5993 return QualType(SubstParm, 0);
5994}
5995
5998 assert(llvm::all_of(ArgPack.pack_elements(),
5999 [](const auto &P) {
6000 return P.getKind() == TemplateArgument::Type;
6001 }) &&
6002 "Pack contains a non-type");
6003
6004 llvm::FoldingSetNodeID ID;
6005 SubstBuiltinTemplatePackType::Profile(ID, ArgPack);
6006
6007 void *InsertPos = nullptr;
6008 if (auto *T =
6009 SubstBuiltinTemplatePackTypes.FindNodeOrInsertPos(ID, InsertPos))
6010 return QualType(T, 0);
6011
6012 QualType Canon;
6013 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
6014 if (!CanonArgPack.structurallyEquals(ArgPack)) {
6015 Canon = getSubstBuiltinTemplatePack(CanonArgPack);
6016 // Refresh InsertPos, in case the recursive call above caused rehashing,
6017 // which would invalidate the bucket pointer.
6018 [[maybe_unused]] const auto *Nothing =
6019 SubstBuiltinTemplatePackTypes.FindNodeOrInsertPos(ID, InsertPos);
6020 assert(!Nothing);
6021 }
6022
6023 auto *PackType = new (*this, alignof(SubstBuiltinTemplatePackType))
6024 SubstBuiltinTemplatePackType(Canon, ArgPack);
6025 Types.push_back(PackType);
6026 SubstBuiltinTemplatePackTypes.InsertNode(PackType, InsertPos);
6027 return QualType(PackType, 0);
6028}
6029
6030/// Retrieve the template type parameter type for a template
6031/// parameter or parameter pack with the given depth, index, and (optionally)
6032/// name.
6034ASTContext::getTemplateTypeParmType(int Depth, int Index, bool ParameterPack,
6035 TemplateTypeParmDecl *TTPDecl) const {
6036 assert(Depth >= 0 && "Depth must be non-negative");
6037 assert(Index >= 0 && "Index must be non-negative");
6038
6039 llvm::FoldingSetNodeID ID;
6040 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
6041 void *InsertPos = nullptr;
6042 TemplateTypeParmType *TypeParm
6043 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
6044
6045 if (TypeParm)
6046 return QualType(TypeParm, 0);
6047
6048 if (TTPDecl) {
6049 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
6050 TypeParm = new (*this, alignof(TemplateTypeParmType))
6051 TemplateTypeParmType(Depth, Index, ParameterPack, TTPDecl, Canon);
6052
6053 TemplateTypeParmType *TypeCheck
6054 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
6055 assert(!TypeCheck && "Template type parameter canonical type broken");
6056 (void)TypeCheck;
6057 } else
6058 TypeParm = new (*this, alignof(TemplateTypeParmType)) TemplateTypeParmType(
6059 Depth, Index, ParameterPack, /*TTPDecl=*/nullptr, /*Canon=*/QualType());
6060
6061 Types.push_back(TypeParm);
6062 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
6063
6064 return QualType(TypeParm, 0);
6065}
6066
6069 switch (Keyword) {
6070 // These are just themselves.
6076 return Keyword;
6077
6078 // These are equivalent.
6081
6082 // These are functionally equivalent, so relying on their equivalence is
6083 // IFNDR. By making them equivalent, we disallow overloading, which at least
6084 // can produce a diagnostic.
6087 }
6088 llvm_unreachable("unexpected keyword kind");
6089}
6090
6092 ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc,
6093 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc,
6094 TemplateName Name, SourceLocation NameLoc,
6095 const TemplateArgumentListInfo &SpecifiedArgs,
6096 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6098 Keyword, Name, SpecifiedArgs.arguments(), CanonicalArgs, Underlying);
6099
6102 ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
6103 SpecifiedArgs);
6104 return TSI;
6105}
6106
6109 ArrayRef<TemplateArgumentLoc> SpecifiedArgs,
6110 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6111 SmallVector<TemplateArgument, 4> SpecifiedArgVec;
6112 SpecifiedArgVec.reserve(SpecifiedArgs.size());
6113 for (const TemplateArgumentLoc &Arg : SpecifiedArgs)
6114 SpecifiedArgVec.push_back(Arg.getArgument());
6115
6116 return getTemplateSpecializationType(Keyword, Template, SpecifiedArgVec,
6117 CanonicalArgs, Underlying);
6118}
6119
6120[[maybe_unused]] static bool
6122 for (const TemplateArgument &Arg : Args)
6123 if (Arg.isPackExpansion())
6124 return true;
6125 return false;
6126}
6127
6130 ArrayRef<TemplateArgument> Args) const {
6131 assert(Template ==
6132 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true));
6134 Template.getAsDependentTemplateName()));
6135#ifndef NDEBUG
6136 for (const auto &Arg : Args)
6137 assert(Arg.structurallyEquals(getCanonicalTemplateArgument(Arg)));
6138#endif
6139
6140 llvm::FoldingSetNodeID ID;
6141 TemplateSpecializationType::Profile(ID, Keyword, Template, Args, QualType(),
6142 *this);
6143 void *InsertPos = nullptr;
6144 if (auto *T = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6145 return QualType(T, 0);
6146
6147 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
6148 sizeof(TemplateArgument) * Args.size(),
6149 alignof(TemplateSpecializationType));
6150 auto *Spec =
6151 new (Mem) TemplateSpecializationType(Keyword, Template,
6152 /*IsAlias=*/false, Args, QualType());
6153 assert(Spec->isDependentType() &&
6154 "canonical template specialization must be dependent");
6155 Types.push_back(Spec);
6156 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
6157 return QualType(Spec, 0);
6158}
6159
6162 ArrayRef<TemplateArgument> SpecifiedArgs,
6163 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6164 const auto *TD = Template.getAsTemplateDecl(/*IgnoreDeduced=*/true);
6165 bool IsTypeAlias = TD && TD->isTypeAlias();
6166 if (Underlying.isNull()) {
6167 TemplateName CanonTemplate =
6168 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true);
6169 ElaboratedTypeKeyword CanonKeyword =
6170 CanonTemplate.getAsDependentTemplateName()
6173 bool NonCanonical = Template != CanonTemplate || Keyword != CanonKeyword;
6175 if (CanonicalArgs.empty()) {
6176 CanonArgsVec = SmallVector<TemplateArgument, 4>(SpecifiedArgs);
6177 NonCanonical |= canonicalizeTemplateArguments(CanonArgsVec);
6178 CanonicalArgs = CanonArgsVec;
6179 } else {
6180 NonCanonical |= !llvm::equal(
6181 SpecifiedArgs, CanonicalArgs,
6182 [](const TemplateArgument &A, const TemplateArgument &B) {
6183 return A.structurallyEquals(B);
6184 });
6185 }
6186
6187 // We can get here with an alias template when the specialization
6188 // contains a pack expansion that does not match up with a parameter
6189 // pack, or a builtin template which cannot be resolved due to dependency.
6190 assert((!isa_and_nonnull<TypeAliasTemplateDecl>(TD) ||
6191 hasAnyPackExpansions(CanonicalArgs)) &&
6192 "Caller must compute aliased type");
6193 IsTypeAlias = false;
6194
6196 CanonKeyword, CanonTemplate, CanonicalArgs);
6197 if (!NonCanonical)
6198 return Underlying;
6199 }
6200 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
6201 sizeof(TemplateArgument) * SpecifiedArgs.size() +
6202 (IsTypeAlias ? sizeof(QualType) : 0),
6203 alignof(TemplateSpecializationType));
6204 auto *Spec = new (Mem) TemplateSpecializationType(
6205 Keyword, Template, IsTypeAlias, SpecifiedArgs, Underlying);
6206 Types.push_back(Spec);
6207 return QualType(Spec, 0);
6208}
6209
6212 llvm::FoldingSetNodeID ID;
6213 ParenType::Profile(ID, InnerType);
6214
6215 void *InsertPos = nullptr;
6216 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6217 if (T)
6218 return QualType(T, 0);
6219
6220 QualType Canon = InnerType;
6221 if (!Canon.isCanonical()) {
6222 Canon = getCanonicalType(InnerType);
6223 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6224 assert(!CheckT && "Paren canonical type broken");
6225 (void)CheckT;
6226 }
6227
6228 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
6229 Types.push_back(T);
6230 ParenTypes.InsertNode(T, InsertPos);
6231 return QualType(T, 0);
6232}
6233
6236 const IdentifierInfo *MacroII) const {
6237 QualType Canon = UnderlyingTy;
6238 if (!Canon.isCanonical())
6239 Canon = getCanonicalType(UnderlyingTy);
6240
6241 auto *newType = new (*this, alignof(MacroQualifiedType))
6242 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
6243 Types.push_back(newType);
6244 return QualType(newType, 0);
6245}
6246
6249 const IdentifierInfo *Name) const {
6250 llvm::FoldingSetNodeID ID;
6251 DependentNameType::Profile(ID, Keyword, NNS, Name);
6252
6253 void *InsertPos = nullptr;
6254 if (DependentNameType *T =
6255 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos))
6256 return QualType(T, 0);
6257
6258 ElaboratedTypeKeyword CanonKeyword =
6260 NestedNameSpecifier CanonNNS = NNS.getCanonical();
6261
6262 QualType Canon;
6263 if (CanonKeyword != Keyword || CanonNNS != NNS) {
6264 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
6265 [[maybe_unused]] DependentNameType *T =
6266 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
6267 assert(!T && "broken canonicalization");
6268 assert(Canon.isCanonical());
6269 }
6270
6271 DependentNameType *T = new (*this, alignof(DependentNameType))
6272 DependentNameType(Keyword, NNS, Name, Canon);
6273 Types.push_back(T);
6274 DependentNameTypes.InsertNode(T, InsertPos);
6275 return QualType(T, 0);
6276}
6277
6279 TemplateArgument Arg;
6280 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6282 if (TTP->isParameterPack())
6283 ArgType = getPackExpansionType(ArgType, std::nullopt);
6284
6286 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6287 QualType T =
6288 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
6289 // For class NTTPs, ensure we include the 'const' so the type matches that
6290 // of a real template argument.
6291 // FIXME: It would be more faithful to model this as something like an
6292 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
6294 if (T->isRecordType()) {
6295 // C++ [temp.param]p8: An id-expression naming a non-type
6296 // template-parameter of class type T denotes a static storage duration
6297 // object of type const T.
6298 T.addConst();
6299 VK = VK_LValue;
6300 } else {
6301 VK = Expr::getValueKindForType(NTTP->getType());
6302 }
6303 Expr *E = new (*this)
6304 DeclRefExpr(*this, NTTP, /*RefersToEnclosingVariableOrCapture=*/false,
6305 T, VK, NTTP->getLocation());
6306
6307 if (NTTP->isParameterPack())
6308 E = new (*this) PackExpansionExpr(E, NTTP->getLocation(), std::nullopt);
6309 Arg = TemplateArgument(E, /*IsCanonical=*/false);
6310 } else {
6311 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
6313 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
6314 TemplateName(TTP));
6315 if (TTP->isParameterPack())
6316 Arg = TemplateArgument(Name, /*NumExpansions=*/std::nullopt);
6317 else
6318 Arg = TemplateArgument(Name);
6319 }
6320
6321 if (Param->isTemplateParameterPack())
6322 Arg =
6323 TemplateArgument::CreatePackCopy(const_cast<ASTContext &>(*this), Arg);
6324
6325 return Arg;
6326}
6327
6329 UnsignedOrNone NumExpansions,
6330 bool ExpectPackInType) const {
6331 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
6332 "Pack expansions must expand one or more parameter packs");
6333
6334 llvm::FoldingSetNodeID ID;
6335 PackExpansionType::Profile(ID, Pattern, NumExpansions);
6336
6337 void *InsertPos = nullptr;
6338 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6339 if (T)
6340 return QualType(T, 0);
6341
6342 QualType Canon;
6343 if (!Pattern.isCanonical()) {
6344 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
6345 /*ExpectPackInType=*/false);
6346
6347 // Find the insert position again, in case we inserted an element into
6348 // PackExpansionTypes and invalidated our insert position.
6349 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6350 }
6351
6352 T = new (*this, alignof(PackExpansionType))
6353 PackExpansionType(Pattern, Canon, NumExpansions);
6354 Types.push_back(T);
6355 PackExpansionTypes.InsertNode(T, InsertPos);
6356 return QualType(T, 0);
6357}
6358
6359/// CmpProtocolNames - Comparison predicate for sorting protocols
6360/// alphabetically.
6361static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
6362 ObjCProtocolDecl *const *RHS) {
6363 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
6364}
6365
6367 if (Protocols.empty()) return true;
6368
6369 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
6370 return false;
6371
6372 for (unsigned i = 1; i != Protocols.size(); ++i)
6373 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
6374 Protocols[i]->getCanonicalDecl() != Protocols[i])
6375 return false;
6376 return true;
6377}
6378
6379static void
6381 // Sort protocols, keyed by name.
6382 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
6383
6384 // Canonicalize.
6385 for (ObjCProtocolDecl *&P : Protocols)
6386 P = P->getCanonicalDecl();
6387
6388 // Remove duplicates.
6389 auto ProtocolsEnd = llvm::unique(Protocols);
6390 Protocols.erase(ProtocolsEnd, Protocols.end());
6391}
6392
6394 ObjCProtocolDecl * const *Protocols,
6395 unsigned NumProtocols) const {
6396 return getObjCObjectType(BaseType, {}, ArrayRef(Protocols, NumProtocols),
6397 /*isKindOf=*/false);
6398}
6399
6401 QualType baseType,
6402 ArrayRef<QualType> typeArgs,
6404 bool isKindOf) const {
6405 // If the base type is an interface and there aren't any protocols or
6406 // type arguments to add, then the interface type will do just fine.
6407 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
6408 isa<ObjCInterfaceType>(baseType))
6409 return baseType;
6410
6411 // Look in the folding set for an existing type.
6412 llvm::FoldingSetNodeID ID;
6413 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
6414 void *InsertPos = nullptr;
6415 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
6416 return QualType(QT, 0);
6417
6418 // Determine the type arguments to be used for canonicalization,
6419 // which may be explicitly specified here or written on the base
6420 // type.
6421 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
6422 if (effectiveTypeArgs.empty()) {
6423 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
6424 effectiveTypeArgs = baseObject->getTypeArgs();
6425 }
6426
6427 // Build the canonical type, which has the canonical base type and a
6428 // sorted-and-uniqued list of protocols and the type arguments
6429 // canonicalized.
6430 QualType canonical;
6431 bool typeArgsAreCanonical = llvm::all_of(
6432 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
6433 bool protocolsSorted = areSortedAndUniqued(protocols);
6434 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
6435 // Determine the canonical type arguments.
6436 ArrayRef<QualType> canonTypeArgs;
6437 SmallVector<QualType, 4> canonTypeArgsVec;
6438 if (!typeArgsAreCanonical) {
6439 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
6440 for (auto typeArg : effectiveTypeArgs)
6441 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
6442 canonTypeArgs = canonTypeArgsVec;
6443 } else {
6444 canonTypeArgs = effectiveTypeArgs;
6445 }
6446
6447 ArrayRef<ObjCProtocolDecl *> canonProtocols;
6448 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
6449 if (!protocolsSorted) {
6450 canonProtocolsVec.append(protocols.begin(), protocols.end());
6451 SortAndUniqueProtocols(canonProtocolsVec);
6452 canonProtocols = canonProtocolsVec;
6453 } else {
6454 canonProtocols = protocols;
6455 }
6456
6457 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
6458 canonProtocols, isKindOf);
6459
6460 // Regenerate InsertPos.
6461 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
6462 }
6463
6464 unsigned size = sizeof(ObjCObjectTypeImpl);
6465 size += typeArgs.size() * sizeof(QualType);
6466 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6467 void *mem = Allocate(size, alignof(ObjCObjectTypeImpl));
6468 auto *T =
6469 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
6470 isKindOf);
6471
6472 Types.push_back(T);
6473 ObjCObjectTypes.InsertNode(T, InsertPos);
6474 return QualType(T, 0);
6475}
6476
6477/// Apply Objective-C protocol qualifiers to the given type.
6478/// If this is for the canonical type of a type parameter, we can apply
6479/// protocol qualifiers on the ObjCObjectPointerType.
6482 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
6483 bool allowOnPointerType) const {
6484 hasError = false;
6485
6486 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
6487 return getObjCTypeParamType(objT->getDecl(), protocols);
6488 }
6489
6490 // Apply protocol qualifiers to ObjCObjectPointerType.
6491 if (allowOnPointerType) {
6492 if (const auto *objPtr =
6493 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
6494 const ObjCObjectType *objT = objPtr->getObjectType();
6495 // Merge protocol lists and construct ObjCObjectType.
6497 protocolsVec.append(objT->qual_begin(),
6498 objT->qual_end());
6499 protocolsVec.append(protocols.begin(), protocols.end());
6500 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
6502 objT->getBaseType(),
6503 objT->getTypeArgsAsWritten(),
6504 protocols,
6505 objT->isKindOfTypeAsWritten());
6507 }
6508 }
6509
6510 // Apply protocol qualifiers to ObjCObjectType.
6511 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
6512 // FIXME: Check for protocols to which the class type is already
6513 // known to conform.
6514
6515 return getObjCObjectType(objT->getBaseType(),
6516 objT->getTypeArgsAsWritten(),
6517 protocols,
6518 objT->isKindOfTypeAsWritten());
6519 }
6520
6521 // If the canonical type is ObjCObjectType, ...
6522 if (type->isObjCObjectType()) {
6523 // Silently overwrite any existing protocol qualifiers.
6524 // TODO: determine whether that's the right thing to do.
6525
6526 // FIXME: Check for protocols to which the class type is already
6527 // known to conform.
6528 return getObjCObjectType(type, {}, protocols, false);
6529 }
6530
6531 // id<protocol-list>
6532 if (type->isObjCIdType()) {
6533 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6534 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
6535 objPtr->isKindOfType());
6537 }
6538
6539 // Class<protocol-list>
6540 if (type->isObjCClassType()) {
6541 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6542 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
6543 objPtr->isKindOfType());
6545 }
6546
6547 hasError = true;
6548 return type;
6549}
6550
6553 ArrayRef<ObjCProtocolDecl *> protocols) const {
6554 // Look in the folding set for an existing type.
6555 llvm::FoldingSetNodeID ID;
6556 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
6557 void *InsertPos = nullptr;
6558 if (ObjCTypeParamType *TypeParam =
6559 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
6560 return QualType(TypeParam, 0);
6561
6562 // We canonicalize to the underlying type.
6563 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
6564 if (!protocols.empty()) {
6565 // Apply the protocol qualifers.
6566 bool hasError;
6568 Canonical, protocols, hasError, true /*allowOnPointerType*/));
6569 assert(!hasError && "Error when apply protocol qualifier to bound type");
6570 }
6571
6572 unsigned size = sizeof(ObjCTypeParamType);
6573 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6574 void *mem = Allocate(size, alignof(ObjCTypeParamType));
6575 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
6576
6577 Types.push_back(newType);
6578 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
6579 return QualType(newType, 0);
6580}
6581
6583 ObjCTypeParamDecl *New) const {
6584 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
6585 // Update TypeForDecl after updating TypeSourceInfo.
6586 auto *NewTypeParamTy = cast<ObjCTypeParamType>(New->TypeForDecl);
6588 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
6589 QualType UpdatedTy = getObjCTypeParamType(New, protocols);
6590 New->TypeForDecl = UpdatedTy.getTypePtr();
6591}
6592
6593/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
6594/// protocol list adopt all protocols in QT's qualified-id protocol
6595/// list.
6597 ObjCInterfaceDecl *IC) {
6598 if (!QT->isObjCQualifiedIdType())
6599 return false;
6600
6601 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
6602 // If both the right and left sides have qualifiers.
6603 for (auto *Proto : OPT->quals()) {
6604 if (!IC->ClassImplementsProtocol(Proto, false))
6605 return false;
6606 }
6607 return true;
6608 }
6609 return false;
6610}
6611
6612/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
6613/// QT's qualified-id protocol list adopt all protocols in IDecl's list
6614/// of protocols.
6616 ObjCInterfaceDecl *IDecl) {
6617 if (!QT->isObjCQualifiedIdType())
6618 return false;
6619 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
6620 if (!OPT)
6621 return false;
6622 if (!IDecl->hasDefinition())
6623 return false;
6625 CollectInheritedProtocols(IDecl, InheritedProtocols);
6626 if (InheritedProtocols.empty())
6627 return false;
6628 // Check that if every protocol in list of id<plist> conforms to a protocol
6629 // of IDecl's, then bridge casting is ok.
6630 bool Conforms = false;
6631 for (auto *Proto : OPT->quals()) {
6632 Conforms = false;
6633 for (auto *PI : InheritedProtocols) {
6634 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
6635 Conforms = true;
6636 break;
6637 }
6638 }
6639 if (!Conforms)
6640 break;
6641 }
6642 if (Conforms)
6643 return true;
6644
6645 for (auto *PI : InheritedProtocols) {
6646 // If both the right and left sides have qualifiers.
6647 bool Adopts = false;
6648 for (auto *Proto : OPT->quals()) {
6649 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
6650 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
6651 break;
6652 }
6653 if (!Adopts)
6654 return false;
6655 }
6656 return true;
6657}
6658
6659/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
6660/// the given object type.
6662 llvm::FoldingSetNodeID ID;
6663 ObjCObjectPointerType::Profile(ID, ObjectT);
6664
6665 void *InsertPos = nullptr;
6666 if (ObjCObjectPointerType *QT =
6667 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
6668 return QualType(QT, 0);
6669
6670 // Find the canonical object type.
6671 QualType Canonical;
6672 if (!ObjectT.isCanonical()) {
6673 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
6674
6675 // Regenerate InsertPos.
6676 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
6677 }
6678
6679 // No match.
6680 void *Mem =
6682 auto *QType =
6683 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
6684
6685 Types.push_back(QType);
6686 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
6687 return QualType(QType, 0);
6688}
6689
6690/// getObjCInterfaceType - Return the unique reference to the type for the
6691/// specified ObjC interface decl. The list of protocols is optional.
6693 ObjCInterfaceDecl *PrevDecl) const {
6694 if (Decl->TypeForDecl)
6695 return QualType(Decl->TypeForDecl, 0);
6696
6697 if (PrevDecl) {
6698 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
6699 Decl->TypeForDecl = PrevDecl->TypeForDecl;
6700 return QualType(PrevDecl->TypeForDecl, 0);
6701 }
6702
6703 // Prefer the definition, if there is one.
6704 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
6705 Decl = Def;
6706
6707 void *Mem = Allocate(sizeof(ObjCInterfaceType), alignof(ObjCInterfaceType));
6708 auto *T = new (Mem) ObjCInterfaceType(Decl);
6709 Decl->TypeForDecl = T;
6710 Types.push_back(T);
6711 return QualType(T, 0);
6712}
6713
6714/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
6715/// TypeOfExprType AST's (since expression's are never shared). For example,
6716/// multiple declarations that refer to "typeof(x)" all contain different
6717/// DeclRefExpr's. This doesn't effect the type checker, since it operates
6718/// on canonical type's (which are always unique).
6720 TypeOfExprType *toe;
6721 if (tofExpr->isTypeDependent()) {
6722 llvm::FoldingSetNodeID ID;
6723 DependentTypeOfExprType::Profile(ID, *this, tofExpr,
6724 Kind == TypeOfKind::Unqualified);
6725
6726 void *InsertPos = nullptr;
6728 DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
6729 if (Canon) {
6730 // We already have a "canonical" version of an identical, dependent
6731 // typeof(expr) type. Use that as our canonical type.
6732 toe = new (*this, alignof(TypeOfExprType)) TypeOfExprType(
6733 *this, tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
6734 } else {
6735 // Build a new, canonical typeof(expr) type.
6736 Canon = new (*this, alignof(DependentTypeOfExprType))
6737 DependentTypeOfExprType(*this, tofExpr, Kind);
6738 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
6739 toe = Canon;
6740 }
6741 } else {
6742 QualType Canonical = getCanonicalType(tofExpr->getType());
6743 toe = new (*this, alignof(TypeOfExprType))
6744 TypeOfExprType(*this, tofExpr, Kind, Canonical);
6745 }
6746 Types.push_back(toe);
6747 return QualType(toe, 0);
6748}
6749
6750/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
6751/// TypeOfType nodes. The only motivation to unique these nodes would be
6752/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
6753/// an issue. This doesn't affect the type checker, since it operates
6754/// on canonical types (which are always unique).
6756 QualType Canonical = getCanonicalType(tofType);
6757 auto *tot = new (*this, alignof(TypeOfType))
6758 TypeOfType(*this, tofType, Canonical, Kind);
6759 Types.push_back(tot);
6760 return QualType(tot, 0);
6761}
6762
6763/// getReferenceQualifiedType - Given an expr, will return the type for
6764/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
6765/// and class member access into account.
6767 // C++11 [dcl.type.simple]p4:
6768 // [...]
6769 QualType T = E->getType();
6770 switch (E->getValueKind()) {
6771 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6772 // type of e;
6773 case VK_XValue:
6774 return getRValueReferenceType(T);
6775 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6776 // type of e;
6777 case VK_LValue:
6778 return getLValueReferenceType(T);
6779 // - otherwise, decltype(e) is the type of e.
6780 case VK_PRValue:
6781 return T;
6782 }
6783 llvm_unreachable("Unknown value kind");
6784}
6785
6786/// Unlike many "get<Type>" functions, we don't unique DecltypeType
6787/// nodes. This would never be helpful, since each such type has its own
6788/// expression, and would not give a significant memory saving, since there
6789/// is an Expr tree under each such type.
6791 // C++11 [temp.type]p2:
6792 // If an expression e involves a template parameter, decltype(e) denotes a
6793 // unique dependent type. Two such decltype-specifiers refer to the same
6794 // type only if their expressions are equivalent (14.5.6.1).
6795 QualType CanonType;
6796 if (!E->isInstantiationDependent()) {
6797 CanonType = getCanonicalType(UnderlyingType);
6798 } else if (!UnderlyingType.isNull()) {
6799 CanonType = getDecltypeType(E, QualType());
6800 } else {
6801 llvm::FoldingSetNodeID ID;
6802 DependentDecltypeType::Profile(ID, *this, E);
6803
6804 void *InsertPos = nullptr;
6805 if (DependentDecltypeType *Canon =
6806 DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos))
6807 return QualType(Canon, 0);
6808
6809 // Build a new, canonical decltype(expr) type.
6810 auto *DT =
6811 new (*this, alignof(DependentDecltypeType)) DependentDecltypeType(E);
6812 DependentDecltypeTypes.InsertNode(DT, InsertPos);
6813 Types.push_back(DT);
6814 return QualType(DT, 0);
6815 }
6816 auto *DT = new (*this, alignof(DecltypeType))
6817 DecltypeType(E, UnderlyingType, CanonType);
6818 Types.push_back(DT);
6819 return QualType(DT, 0);
6820}
6821
6823 bool FullySubstituted,
6824 ArrayRef<QualType> Expansions,
6825 UnsignedOrNone Index) const {
6826 QualType Canonical;
6827 if (FullySubstituted && Index) {
6828 Canonical = getCanonicalType(Expansions[*Index]);
6829 } else {
6830 llvm::FoldingSetNodeID ID;
6831 PackIndexingType::Profile(ID, *this, Pattern.getCanonicalType(), IndexExpr,
6832 FullySubstituted, Expansions);
6833 void *InsertPos = nullptr;
6834 PackIndexingType *Canon =
6835 DependentPackIndexingTypes.FindNodeOrInsertPos(ID, InsertPos);
6836 if (!Canon) {
6837 void *Mem = Allocate(
6838 PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6840 Canon =
6841 new (Mem) PackIndexingType(QualType(), Pattern.getCanonicalType(),
6842 IndexExpr, FullySubstituted, Expansions);
6843 DependentPackIndexingTypes.InsertNode(Canon, InsertPos);
6844 }
6845 Canonical = QualType(Canon, 0);
6846 }
6847
6848 void *Mem =
6849 Allocate(PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6851 auto *T = new (Mem) PackIndexingType(Canonical, Pattern, IndexExpr,
6852 FullySubstituted, Expansions);
6853 Types.push_back(T);
6854 return QualType(T, 0);
6855}
6856
6857/// getUnaryTransformationType - We don't unique these, since the memory
6858/// savings are minimal and these are rare.
6861 UnaryTransformType::UTTKind Kind) const {
6862
6863 llvm::FoldingSetNodeID ID;
6864 UnaryTransformType::Profile(ID, BaseType, UnderlyingType, Kind);
6865
6866 void *InsertPos = nullptr;
6867 if (UnaryTransformType *UT =
6868 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos))
6869 return QualType(UT, 0);
6870
6871 QualType CanonType;
6872 if (!BaseType->isDependentType()) {
6873 CanonType = UnderlyingType.getCanonicalType();
6874 } else {
6875 assert(UnderlyingType.isNull() || BaseType == UnderlyingType);
6876 UnderlyingType = QualType();
6877 if (QualType CanonBase = BaseType.getCanonicalType();
6878 BaseType != CanonBase) {
6879 CanonType = getUnaryTransformType(CanonBase, QualType(), Kind);
6880 assert(CanonType.isCanonical());
6881
6882 // Find the insertion position again.
6883 [[maybe_unused]] UnaryTransformType *UT =
6884 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
6885 assert(!UT && "broken canonicalization");
6886 }
6887 }
6888
6889 auto *UT = new (*this, alignof(UnaryTransformType))
6890 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
6891 UnaryTransformTypes.InsertNode(UT, InsertPos);
6892 Types.push_back(UT);
6893 return QualType(UT, 0);
6894}
6895
6896/// getAutoType - Return the uniqued reference to the 'auto' type which has been
6897/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
6898/// canonical deduced-but-dependent 'auto' type.
6902 TemplateDecl *TypeConstraintConcept,
6903 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
6905 !TypeConstraintConcept) {
6906 assert(DeducedAsType.isNull() && "");
6907 assert(TypeConstraintArgs.empty() && "");
6908 return getAutoDeductType();
6909 }
6910
6911 // Look in the folding set for an existing type.
6912 llvm::FoldingSetNodeID ID;
6913 AutoType::Profile(ID, *this, DK, DeducedAsType, Keyword,
6914 TypeConstraintConcept, TypeConstraintArgs);
6915 if (auto const AT_iter = AutoTypes.find(ID); AT_iter != AutoTypes.end())
6916 return QualType(AT_iter->getSecond(), 0);
6917
6918 if (DK == DeducedKind::Deduced) {
6919 assert(!DeducedAsType.isNull() && "deduced type must be provided");
6920 } else {
6921 assert(DeducedAsType.isNull() && "deduced type must not be provided");
6922 if (TypeConstraintConcept) {
6923 bool AnyNonCanonArgs = false;
6924 auto *CanonicalConcept =
6925 cast<TemplateDecl>(TypeConstraintConcept->getCanonicalDecl());
6926 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
6927 *this, TypeConstraintArgs, AnyNonCanonArgs);
6928 if (TypeConstraintConcept != CanonicalConcept || AnyNonCanonArgs)
6929 DeducedAsType = getAutoType(DK, QualType(), Keyword, CanonicalConcept,
6930 CanonicalConceptArgs);
6931 }
6932 }
6933
6934 void *Mem = Allocate(sizeof(AutoType) +
6935 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
6936 alignof(AutoType));
6937 auto *AT = new (Mem) AutoType(DK, DeducedAsType, Keyword,
6938 TypeConstraintConcept, TypeConstraintArgs);
6939#ifndef NDEBUG
6940 llvm::FoldingSetNodeID InsertedID;
6941 AT->Profile(InsertedID, *this);
6942 assert(InsertedID == ID && "ID does not match");
6943#endif
6944 Types.push_back(AT);
6945 AutoTypes.try_emplace(ID, AT);
6946 return QualType(AT, 0);
6947}
6948
6950 QualType CanonT = T.getNonPackExpansionType().getCanonicalType();
6951
6952 // Remove a type-constraint from a top-level auto or decltype(auto).
6953 if (auto *AT = CanonT->getAs<AutoType>()) {
6954 if (!AT->isConstrained())
6955 return T;
6956 return getQualifiedType(
6957 getAutoType(AT->getDeducedKind(), QualType(), AT->getKeyword()),
6958 T.getQualifiers());
6959 }
6960
6961 // FIXME: We only support constrained auto at the top level in the type of a
6962 // non-type template parameter at the moment. Once we lift that restriction,
6963 // we'll need to recursively build types containing auto here.
6964 assert(!CanonT->getContainedAutoType() ||
6965 !CanonT->getContainedAutoType()->isConstrained());
6966 return T;
6967}
6968
6969/// Return the uniqued reference to the deduced template specialization type
6970/// which has been deduced to the given type, or to the canonical undeduced
6971/// such type, or the canonical deduced-but-dependent such type.
6974 TemplateName Template) const {
6975 // Look in the folding set for an existing type.
6976 void *InsertPos = nullptr;
6977 llvm::FoldingSetNodeID ID;
6978 DeducedTemplateSpecializationType::Profile(ID, DK, DeducedAsType, Keyword,
6979 Template);
6980 if (DeducedTemplateSpecializationType *DTST =
6981 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6982 return QualType(DTST, 0);
6983
6984 if (DK == DeducedKind::Deduced) {
6985 assert(!DeducedAsType.isNull() && "deduced type must be provided");
6986 } else {
6987 assert(DeducedAsType.isNull() && "deduced type must not be provided");
6988 TemplateName CanonTemplateName = getCanonicalTemplateName(Template);
6989 // FIXME: Can this be formed from a DependentTemplateName, such that the
6990 // keyword should be part of the canonical type?
6992 Template != CanonTemplateName) {
6994 DK, QualType(), ElaboratedTypeKeyword::None, CanonTemplateName);
6995 // Find the insertion position again.
6996 [[maybe_unused]] DeducedTemplateSpecializationType *DTST =
6997 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
6998 assert(!DTST && "broken canonicalization");
6999 }
7000 }
7001
7002 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
7003 DeducedTemplateSpecializationType(DK, DeducedAsType, Keyword, Template);
7004
7005#ifndef NDEBUG
7006 llvm::FoldingSetNodeID TempID;
7007 DTST->Profile(TempID);
7008 assert(ID == TempID && "ID does not match");
7009#endif
7010 Types.push_back(DTST);
7011 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
7012 return QualType(DTST, 0);
7013}
7014
7015/// getAtomicType - Return the uniqued reference to the atomic type for
7016/// the given value type.
7018 // Unique pointers, to guarantee there is only one pointer of a particular
7019 // structure.
7020 llvm::FoldingSetNodeID ID;
7022
7023 void *InsertPos = nullptr;
7024 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
7025 return QualType(AT, 0);
7026
7027 // If the atomic value type isn't canonical, this won't be a canonical type
7028 // either, so fill in the canonical type field.
7029 QualType Canonical;
7030 if (!T.isCanonical()) {
7031 Canonical = getAtomicType(getCanonicalType(T));
7032
7033 // Get the new insert position for the node we care about.
7034 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
7035 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
7036 }
7037 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
7038 Types.push_back(New);
7039 AtomicTypes.InsertNode(New, InsertPos);
7040 return QualType(New, 0);
7041}
7042
7043/// getAutoDeductType - Get type pattern for deducing against 'auto'.
7045 if (AutoDeductTy.isNull())
7046 AutoDeductTy = QualType(new (*this, alignof(AutoType))
7047 AutoType(DeducedKind::Undeduced, QualType(),
7049 /*TypeConstraintConcept=*/nullptr,
7050 /*TypeConstraintArgs=*/{}),
7051 0);
7052 return AutoDeductTy;
7053}
7054
7055/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
7057 if (AutoRRefDeductTy.isNull())
7059 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
7060 return AutoRRefDeductTy;
7061}
7062
7063/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
7064/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
7065/// needs to agree with the definition in <stddef.h>.
7069
7071 return getFromTargetType(Target->getSizeType());
7072}
7073
7074/// Return the unique signed counterpart of the integer type
7075/// corresponding to size_t.
7079
7080/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
7081/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
7085
7086/// Return the unique unsigned counterpart of "ptrdiff_t"
7087/// integer type. The standard (C11 7.21.6.1p7) refers to this type
7088/// in the definition of %tu format specifier.
7090 return getFromTargetType(Target->getUnsignedPtrDiffType(LangAS::Default));
7091}
7092
7093/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
7095 return getFromTargetType(Target->getIntMaxType());
7096}
7097
7098/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
7100 return getFromTargetType(Target->getUIntMaxType());
7101}
7102
7103/// getSignedWCharType - Return the type of "signed wchar_t".
7104/// Used when in C++, as a GCC extension.
7106 // FIXME: derive from "Target" ?
7107 return WCharTy;
7108}
7109
7110/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
7111/// Used when in C++, as a GCC extension.
7113 // FIXME: derive from "Target" ?
7114 return UnsignedIntTy;
7115}
7116
7118 return getFromTargetType(Target->getIntPtrType());
7119}
7120
7124
7125/// Return the unique type for "pid_t" defined in
7126/// <sys/types.h>. We need this to compute the correct type for vfork().
7128 return getFromTargetType(Target->getProcessIDType());
7129}
7130
7131//===----------------------------------------------------------------------===//
7132// Type Operators
7133//===----------------------------------------------------------------------===//
7134
7136 // Push qualifiers into arrays, and then discard any remaining
7137 // qualifiers.
7138 T = getCanonicalType(T);
7140 const Type *Ty = T.getTypePtr();
7144 } else if (isa<ArrayType>(Ty)) {
7146 } else if (isa<FunctionType>(Ty)) {
7147 Result = getPointerType(QualType(Ty, 0));
7148 } else {
7149 Result = QualType(Ty, 0);
7150 }
7151
7153}
7154
7156 Qualifiers &quals) const {
7157 SplitQualType splitType = type.getSplitUnqualifiedType();
7158
7159 // FIXME: getSplitUnqualifiedType() actually walks all the way to
7160 // the unqualified desugared type and then drops it on the floor.
7161 // We then have to strip that sugar back off with
7162 // getUnqualifiedDesugaredType(), which is silly.
7163 const auto *AT =
7164 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
7165
7166 // If we don't have an array, just use the results in splitType.
7167 if (!AT) {
7168 quals = splitType.Quals;
7169 return QualType(splitType.Ty, 0);
7170 }
7171
7172 // Otherwise, recurse on the array's element type.
7173 QualType elementType = AT->getElementType();
7174 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
7175
7176 // If that didn't change the element type, AT has no qualifiers, so we
7177 // can just use the results in splitType.
7178 if (elementType == unqualElementType) {
7179 assert(quals.empty()); // from the recursive call
7180 quals = splitType.Quals;
7181 return QualType(splitType.Ty, 0);
7182 }
7183
7184 // Otherwise, add in the qualifiers from the outermost type, then
7185 // build the type back up.
7186 quals.addConsistentQualifiers(splitType.Quals);
7187
7188 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
7189 return getConstantArrayType(unqualElementType, CAT->getSize(),
7190 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
7191 }
7192
7193 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
7194 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
7195 }
7196
7197 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
7198 return getVariableArrayType(unqualElementType, VAT->getSizeExpr(),
7199 VAT->getSizeModifier(),
7200 VAT->getIndexTypeCVRQualifiers());
7201 }
7202
7203 const auto *DSAT = cast<DependentSizedArrayType>(AT);
7204 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
7205 DSAT->getSizeModifier(), 0);
7206}
7207
7208/// Attempt to unwrap two types that may both be array types with the same bound
7209/// (or both be array types of unknown bound) for the purpose of comparing the
7210/// cv-decomposition of two types per C++ [conv.qual].
7211///
7212/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7213/// C++20 [conv.qual], if permitted by the current language mode.
7215 bool AllowPiMismatch) const {
7216 while (true) {
7217 auto *AT1 = getAsArrayType(T1);
7218 if (!AT1)
7219 return;
7220
7221 auto *AT2 = getAsArrayType(T2);
7222 if (!AT2)
7223 return;
7224
7225 // If we don't have two array types with the same constant bound nor two
7226 // incomplete array types, we've unwrapped everything we can.
7227 // C++20 also permits one type to be a constant array type and the other
7228 // to be an incomplete array type.
7229 // FIXME: Consider also unwrapping array of unknown bound and VLA.
7230 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
7231 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
7232 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
7233 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7235 return;
7236 } else if (isa<IncompleteArrayType>(AT1)) {
7237 if (!(isa<IncompleteArrayType>(AT2) ||
7238 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7240 return;
7241 } else {
7242 return;
7243 }
7244
7245 T1 = AT1->getElementType();
7246 T2 = AT2->getElementType();
7247 }
7248}
7249
7250/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
7251///
7252/// If T1 and T2 are both pointer types of the same kind, or both array types
7253/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
7254/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
7255///
7256/// This function will typically be called in a loop that successively
7257/// "unwraps" pointer and pointer-to-member types to compare them at each
7258/// level.
7259///
7260/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7261/// C++20 [conv.qual], if permitted by the current language mode.
7262///
7263/// \return \c true if a pointer type was unwrapped, \c false if we reached a
7264/// pair of types that can't be unwrapped further.
7266 bool AllowPiMismatch) const {
7267 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
7268
7269 const auto *T1PtrType = T1->getAs<PointerType>();
7270 const auto *T2PtrType = T2->getAs<PointerType>();
7271 if (T1PtrType && T2PtrType) {
7272 T1 = T1PtrType->getPointeeType();
7273 T2 = T2PtrType->getPointeeType();
7274 return true;
7275 }
7276
7277 if (const auto *T1MPType = T1->getAsCanonical<MemberPointerType>(),
7278 *T2MPType = T2->getAsCanonical<MemberPointerType>();
7279 T1MPType && T2MPType) {
7280 // Compare the qualifiers of the canonical type, as the non-canonical type
7281 // may have qualifiers pointing to a base or derived class.
7282 if (T1MPType->getQualifier() != T2MPType->getQualifier())
7283 return false;
7284 // Get the pointee types of the non-canonical type, in order to preserve
7285 // their sugar.
7286 T1 = T1->getAs<MemberPointerType>()->getPointeeType();
7287 T2 = T2->getAs<MemberPointerType>()->getPointeeType();
7288 return true;
7289 }
7290
7291 if (getLangOpts().ObjC) {
7292 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
7293 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
7294 if (T1OPType && T2OPType) {
7295 T1 = T1OPType->getPointeeType();
7296 T2 = T2OPType->getPointeeType();
7297 return true;
7298 }
7299 }
7300
7301 // FIXME: Block pointers, too?
7302
7303 return false;
7304}
7305
7307 while (true) {
7308 Qualifiers Quals;
7309 T1 = getUnqualifiedArrayType(T1, Quals);
7310 T2 = getUnqualifiedArrayType(T2, Quals);
7311 if (hasSameType(T1, T2))
7312 return true;
7313 if (!UnwrapSimilarTypes(T1, T2))
7314 return false;
7315 }
7316}
7317
7319 while (true) {
7320 Qualifiers Quals1, Quals2;
7321 T1 = getUnqualifiedArrayType(T1, Quals1);
7322 T2 = getUnqualifiedArrayType(T2, Quals2);
7323
7324 Quals1.removeCVRQualifiers();
7325 Quals2.removeCVRQualifiers();
7326 if (Quals1 != Quals2)
7327 return false;
7328
7329 if (hasSameType(T1, T2))
7330 return true;
7331
7332 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
7333 return false;
7334 }
7335}
7336
7339 SourceLocation NameLoc) const {
7340 switch (Name.getKind()) {
7343 // DNInfo work in progress: CHECKME: what about DNLoc?
7345 NameLoc);
7346
7349 // DNInfo work in progress: CHECKME: what about DNLoc?
7350 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
7351 }
7352
7355 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
7356 }
7357
7361 DeclarationName DName;
7362 if (const IdentifierInfo *II = TN.getIdentifier()) {
7363 DName = DeclarationNames.getIdentifier(II);
7364 return DeclarationNameInfo(DName, NameLoc);
7365 } else {
7366 DName = DeclarationNames.getCXXOperatorName(TN.getOperator());
7367 // DNInfo work in progress: FIXME: source locations?
7368 DeclarationNameLoc DNLoc =
7370 return DeclarationNameInfo(DName, NameLoc, DNLoc);
7371 }
7372 }
7373
7377 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
7378 NameLoc);
7379 }
7380
7385 NameLoc);
7386 }
7389 NameLoc);
7392 return getNameForTemplate(DTS->getUnderlying(), NameLoc);
7393 }
7394 }
7395
7396 llvm_unreachable("bad template name kind!");
7397}
7398
7399const TemplateArgument *
7401 auto handleParam = [](auto *TP) -> const TemplateArgument * {
7402 if (!TP->hasDefaultArgument())
7403 return nullptr;
7404 return &TP->getDefaultArgument().getArgument();
7405 };
7406 switch (P->getKind()) {
7407 case NamedDecl::TemplateTypeParm:
7408 return handleParam(cast<TemplateTypeParmDecl>(P));
7409 case NamedDecl::NonTypeTemplateParm:
7410 return handleParam(cast<NonTypeTemplateParmDecl>(P));
7411 case NamedDecl::TemplateTemplateParm:
7412 return handleParam(cast<TemplateTemplateParmDecl>(P));
7413 default:
7414 llvm_unreachable("Unexpected template parameter kind");
7415 }
7416}
7417
7419 bool IgnoreDeduced) const {
7420 while (std::optional<TemplateName> UnderlyingOrNone =
7421 Name.desugar(IgnoreDeduced))
7422 Name = *UnderlyingOrNone;
7423
7424 switch (Name.getKind()) {
7427 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
7429
7430 // The canonical template name is the canonical template declaration.
7431 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
7432 }
7433
7435 // An assumed template is just a name, so it is already canonical.
7436 return Name;
7437
7439 llvm_unreachable("cannot canonicalize overloaded template");
7440
7443 assert(DTN && "Non-dependent template names must refer to template decls.");
7444 NestedNameSpecifier Qualifier = DTN->getQualifier();
7445 NestedNameSpecifier CanonQualifier = Qualifier.getCanonical();
7446 if (Qualifier != CanonQualifier || !DTN->hasTemplateKeyword())
7447 return getDependentTemplateName({CanonQualifier, DTN->getName(),
7448 /*HasTemplateKeyword=*/true});
7449 return Name;
7450 }
7451
7455 TemplateArgument canonArgPack =
7458 canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
7459 subst->getIndex(), subst->getFinal());
7460 }
7462 assert(IgnoreDeduced == false);
7464 DefaultArguments DefArgs = DTS->getDefaultArguments();
7465 TemplateName Underlying = DTS->getUnderlying();
7466
7467 TemplateName CanonUnderlying =
7468 getCanonicalTemplateName(Underlying, /*IgnoreDeduced=*/true);
7469 bool NonCanonical = CanonUnderlying != Underlying;
7470 auto CanonArgs =
7471 getCanonicalTemplateArguments(*this, DefArgs.Args, NonCanonical);
7472
7473 ArrayRef<NamedDecl *> Params =
7474 CanonUnderlying.getAsTemplateDecl()->getTemplateParameters()->asArray();
7475 assert(CanonArgs.size() <= Params.size());
7476 // A deduced template name which deduces the same default arguments already
7477 // declared in the underlying template is the same template as the
7478 // underlying template. We need need to note any arguments which differ from
7479 // the corresponding declaration. If any argument differs, we must build a
7480 // deduced template name.
7481 for (int I = CanonArgs.size() - 1; I >= 0; --I) {
7483 if (!A)
7484 break;
7485 auto CanonParamDefArg = getCanonicalTemplateArgument(*A);
7486 TemplateArgument &CanonDefArg = CanonArgs[I];
7487 if (CanonDefArg.structurallyEquals(CanonParamDefArg))
7488 continue;
7489 // Keep popping from the back any deault arguments which are the same.
7490 if (I == int(CanonArgs.size() - 1))
7491 CanonArgs.pop_back();
7492 NonCanonical = true;
7493 }
7494 return NonCanonical ? getDeducedTemplateName(
7495 CanonUnderlying,
7496 /*DefaultArgs=*/{DefArgs.StartPos, CanonArgs})
7497 : Name;
7498 }
7502 llvm_unreachable("always sugar node");
7503 }
7504
7505 llvm_unreachable("bad template name!");
7506}
7507
7509 const TemplateName &Y,
7510 bool IgnoreDeduced) const {
7511 return getCanonicalTemplateName(X, IgnoreDeduced) ==
7512 getCanonicalTemplateName(Y, IgnoreDeduced);
7513}
7514
7516 const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const {
7517 if (ACX.ArgPackSubstIndex != ACY.ArgPackSubstIndex)
7518 return false;
7520 return false;
7521 return true;
7522}
7523
7524bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
7525 if (!XCE != !YCE)
7526 return false;
7527
7528 if (!XCE)
7529 return true;
7530
7531 llvm::FoldingSetNodeID XCEID, YCEID;
7532 XCE->Profile(XCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7533 YCE->Profile(YCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7534 return XCEID == YCEID;
7535}
7536
7538 const TypeConstraint *YTC) const {
7539 if (!XTC != !YTC)
7540 return false;
7541
7542 if (!XTC)
7543 return true;
7544
7545 auto *NCX = XTC->getNamedConcept();
7546 auto *NCY = YTC->getNamedConcept();
7547 if (!NCX || !NCY || !isSameEntity(NCX, NCY))
7548 return false;
7551 return false;
7553 if (XTC->getConceptReference()
7555 ->NumTemplateArgs !=
7557 return false;
7558
7559 // Compare slowly by profiling.
7560 //
7561 // We couldn't compare the profiling result for the template
7562 // args here. Consider the following example in different modules:
7563 //
7564 // template <__integer_like _Tp, C<_Tp> Sentinel>
7565 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
7566 // return __t;
7567 // }
7568 //
7569 // When we compare the profiling result for `C<_Tp>` in different
7570 // modules, it will compare the type of `_Tp` in different modules.
7571 // However, the type of `_Tp` in different modules refer to different
7572 // types here naturally. So we couldn't compare the profiling result
7573 // for the template args directly.
7576}
7577
7579 const NamedDecl *Y) const {
7580 if (X->getKind() != Y->getKind())
7581 return false;
7582
7583 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
7584 auto *TY = cast<TemplateTypeParmDecl>(Y);
7585 if (TX->isParameterPack() != TY->isParameterPack())
7586 return false;
7587 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
7588 return false;
7589 return isSameTypeConstraint(TX->getTypeConstraint(),
7590 TY->getTypeConstraint());
7591 }
7592
7593 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7594 auto *TY = cast<NonTypeTemplateParmDecl>(Y);
7595 return TX->isParameterPack() == TY->isParameterPack() &&
7596 TX->getASTContext().hasSameType(TX->getType(), TY->getType()) &&
7597 isSameConstraintExpr(TX->getPlaceholderTypeConstraint(),
7598 TY->getPlaceholderTypeConstraint());
7599 }
7600
7602 auto *TY = cast<TemplateTemplateParmDecl>(Y);
7603 return TX->isParameterPack() == TY->isParameterPack() &&
7604 isSameTemplateParameterList(TX->getTemplateParameters(),
7605 TY->getTemplateParameters());
7606}
7607
7609 const TemplateParameterList *X, const TemplateParameterList *Y) const {
7610 if (X->size() != Y->size())
7611 return false;
7612
7613 for (unsigned I = 0, N = X->size(); I != N; ++I)
7614 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
7615 return false;
7616
7617 return isSameConstraintExpr(X->getRequiresClause(), Y->getRequiresClause());
7618}
7619
7621 const NamedDecl *Y) const {
7622 // If the type parameter isn't the same already, we don't need to check the
7623 // default argument further.
7624 if (!isSameTemplateParameter(X, Y))
7625 return false;
7626
7627 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(X)) {
7628 auto *TTPY = cast<TemplateTypeParmDecl>(Y);
7629 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7630 return false;
7631
7632 return hasSameType(TTPX->getDefaultArgument().getArgument().getAsType(),
7633 TTPY->getDefaultArgument().getArgument().getAsType());
7634 }
7635
7636 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7637 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Y);
7638 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
7639 return false;
7640
7641 Expr *DefaultArgumentX =
7642 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7643 Expr *DefaultArgumentY =
7644 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7645 llvm::FoldingSetNodeID XID, YID;
7646 DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true);
7647 DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true);
7648 return XID == YID;
7649 }
7650
7651 auto *TTPX = cast<TemplateTemplateParmDecl>(X);
7652 auto *TTPY = cast<TemplateTemplateParmDecl>(Y);
7653
7654 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7655 return false;
7656
7657 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
7658 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
7659 return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate());
7660}
7661
7663 const NestedNameSpecifier Y) {
7664 if (X == Y)
7665 return true;
7666 if (!X || !Y)
7667 return false;
7668
7669 auto Kind = X.getKind();
7670 if (Kind != Y.getKind())
7671 return false;
7672
7673 // FIXME: For namespaces and types, we're permitted to check that the entity
7674 // is named via the same tokens. We should probably do so.
7675 switch (Kind) {
7677 auto [NamespaceX, PrefixX] = X.getAsNamespaceAndPrefix();
7678 auto [NamespaceY, PrefixY] = Y.getAsNamespaceAndPrefix();
7679 if (!declaresSameEntity(NamespaceX->getNamespace(),
7680 NamespaceY->getNamespace()))
7681 return false;
7682 return isSameQualifier(PrefixX, PrefixY);
7683 }
7685 const auto *TX = X.getAsType(), *TY = Y.getAsType();
7686 if (TX->getCanonicalTypeInternal() != TY->getCanonicalTypeInternal())
7687 return false;
7688 return isSameQualifier(TX->getPrefix(), TY->getPrefix());
7689 }
7693 return true;
7694 }
7695 llvm_unreachable("unhandled qualifier kind");
7696}
7697
7698static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B) {
7699 if (!A->getASTContext().getLangOpts().CUDA)
7700 return true; // Target attributes are overloadable in CUDA compilation only.
7701 if (A->hasAttr<CUDADeviceAttr>() != B->hasAttr<CUDADeviceAttr>())
7702 return false;
7703 if (A->hasAttr<CUDADeviceAttr>() && B->hasAttr<CUDADeviceAttr>())
7704 return A->hasAttr<CUDAHostAttr>() == B->hasAttr<CUDAHostAttr>();
7705 return true; // unattributed and __host__ functions are the same.
7706}
7707
7708/// Determine whether the attributes we can overload on are identical for A and
7709/// B. Will ignore any overloadable attrs represented in the type of A and B.
7711 const FunctionDecl *B) {
7712 // Note that pass_object_size attributes are represented in the function's
7713 // ExtParameterInfo, so we don't need to check them here.
7714
7715 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
7716 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
7717 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
7718
7719 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
7720 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
7721 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
7722
7723 // Return false if the number of enable_if attributes is different.
7724 if (!Cand1A || !Cand2A)
7725 return false;
7726
7727 Cand1ID.clear();
7728 Cand2ID.clear();
7729
7730 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
7731 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
7732
7733 // Return false if any of the enable_if expressions of A and B are
7734 // different.
7735 if (Cand1ID != Cand2ID)
7736 return false;
7737 }
7738 return hasSameCudaAttrs(A, B);
7739}
7740
7741bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
7742 // Caution: this function is called by the AST reader during deserialization,
7743 // so it cannot rely on AST invariants being met. Non-trivial accessors
7744 // should be avoided, along with any traversal of redeclaration chains.
7745
7746 if (X == Y)
7747 return true;
7748
7749 if (X->getDeclName() != Y->getDeclName())
7750 return false;
7751
7752 // Must be in the same context.
7753 //
7754 // Note that we can't use DeclContext::Equals here, because the DeclContexts
7755 // could be two different declarations of the same function. (We will fix the
7756 // semantic DC to refer to the primary definition after merging.)
7757 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
7759 return false;
7760
7761 // If either X or Y are local to the owning module, they are only possible to
7762 // be the same entity if they are in the same module.
7763 if (X->isModuleLocal() || Y->isModuleLocal())
7764 if (!isInSameModule(X->getOwningModule(), Y->getOwningModule()))
7765 return false;
7766
7767 // Two typedefs refer to the same entity if they have the same underlying
7768 // type.
7769 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
7770 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
7771 return hasSameType(TypedefX->getUnderlyingType(),
7772 TypedefY->getUnderlyingType());
7773
7774 // Must have the same kind.
7775 if (X->getKind() != Y->getKind())
7776 return false;
7777
7778 // Objective-C classes and protocols with the same name always match.
7780 return true;
7781
7783 // No need to handle these here: we merge them when adding them to the
7784 // template.
7785 return false;
7786 }
7787
7788 // Compatible tags match.
7789 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
7790 const auto *TagY = cast<TagDecl>(Y);
7791 return (TagX->getTagKind() == TagY->getTagKind()) ||
7792 ((TagX->getTagKind() == TagTypeKind::Struct ||
7793 TagX->getTagKind() == TagTypeKind::Class ||
7794 TagX->getTagKind() == TagTypeKind::Interface) &&
7795 (TagY->getTagKind() == TagTypeKind::Struct ||
7796 TagY->getTagKind() == TagTypeKind::Class ||
7797 TagY->getTagKind() == TagTypeKind::Interface));
7798 }
7799
7800 // Functions with the same type and linkage match.
7801 // FIXME: This needs to cope with merging of prototyped/non-prototyped
7802 // functions, etc.
7803 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
7804 const auto *FuncY = cast<FunctionDecl>(Y);
7805 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
7806 const auto *CtorY = cast<CXXConstructorDecl>(Y);
7807 if (CtorX->getInheritedConstructor() &&
7808 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
7809 CtorY->getInheritedConstructor().getConstructor()))
7810 return false;
7811 }
7812
7813 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
7814 return false;
7815
7816 // Multiversioned functions with different feature strings are represented
7817 // as separate declarations.
7818 if (FuncX->isMultiVersion()) {
7819 const auto *TAX = FuncX->getAttr<TargetAttr>();
7820 const auto *TAY = FuncY->getAttr<TargetAttr>();
7821 assert(TAX && TAY && "Multiversion Function without target attribute");
7822
7823 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
7824 return false;
7825 }
7826
7827 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
7828 // not the same entity if they are constrained.
7829 if ((FuncX->isMemberLikeConstrainedFriend() ||
7830 FuncY->isMemberLikeConstrainedFriend()) &&
7831 !FuncX->getLexicalDeclContext()->Equals(
7832 FuncY->getLexicalDeclContext())) {
7833 return false;
7834 }
7835
7836 if (!isSameAssociatedConstraint(FuncX->getTrailingRequiresClause(),
7837 FuncY->getTrailingRequiresClause()))
7838 return false;
7839
7840 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
7841 // Map to the first declaration that we've already merged into this one.
7842 // The TSI of redeclarations might not match (due to calling conventions
7843 // being inherited onto the type but not the TSI), but the TSI type of
7844 // the first declaration of the function should match across modules.
7845 FD = FD->getCanonicalDecl();
7846 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
7847 : FD->getType();
7848 };
7849 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
7850 if (!hasSameType(XT, YT)) {
7851 // We can get functions with different types on the redecl chain in C++17
7852 // if they have differing exception specifications and at least one of
7853 // the excpetion specs is unresolved.
7854 auto *XFPT = XT->getAs<FunctionProtoType>();
7855 auto *YFPT = YT->getAs<FunctionProtoType>();
7856 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
7857 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
7860 return true;
7861 return false;
7862 }
7863
7864 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
7865 hasSameOverloadableAttrs(FuncX, FuncY);
7866 }
7867
7868 // Variables with the same type and linkage match.
7869 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
7870 const auto *VarY = cast<VarDecl>(Y);
7871 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
7872 // During deserialization, we might compare variables before we load
7873 // their types. Assume the types will end up being the same.
7874 if (VarX->getType().isNull() || VarY->getType().isNull())
7875 return true;
7876
7877 if (hasSameType(VarX->getType(), VarY->getType()))
7878 return true;
7879
7880 // We can get decls with different types on the redecl chain. Eg.
7881 // template <typename T> struct S { static T Var[]; }; // #1
7882 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
7883 // Only? happens when completing an incomplete array type. In this case
7884 // when comparing #1 and #2 we should go through their element type.
7885 const ArrayType *VarXTy = getAsArrayType(VarX->getType());
7886 const ArrayType *VarYTy = getAsArrayType(VarY->getType());
7887 if (!VarXTy || !VarYTy)
7888 return false;
7889 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
7890 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
7891 }
7892 return false;
7893 }
7894
7895 // Namespaces with the same name and inlinedness match.
7896 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
7897 const auto *NamespaceY = cast<NamespaceDecl>(Y);
7898 return NamespaceX->isInline() == NamespaceY->isInline();
7899 }
7900
7901 // Identical template names and kinds match if their template parameter lists
7902 // and patterns match.
7903 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
7904 const auto *TemplateY = cast<TemplateDecl>(Y);
7905
7906 // ConceptDecl wouldn't be the same if their constraint expression differs.
7907 if (const auto *ConceptX = dyn_cast<ConceptDecl>(X)) {
7908 const auto *ConceptY = cast<ConceptDecl>(Y);
7909 if (!isSameConstraintExpr(ConceptX->getConstraintExpr(),
7910 ConceptY->getConstraintExpr()))
7911 return false;
7912 }
7913
7914 return isSameEntity(TemplateX->getTemplatedDecl(),
7915 TemplateY->getTemplatedDecl()) &&
7916 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
7917 TemplateY->getTemplateParameters());
7918 }
7919
7920 // Fields with the same name and the same type match.
7921 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
7922 const auto *FDY = cast<FieldDecl>(Y);
7923 // FIXME: Also check the bitwidth is odr-equivalent, if any.
7924 return hasSameType(FDX->getType(), FDY->getType());
7925 }
7926
7927 // Indirect fields with the same target field match.
7928 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
7929 const auto *IFDY = cast<IndirectFieldDecl>(Y);
7930 return IFDX->getAnonField()->getCanonicalDecl() ==
7931 IFDY->getAnonField()->getCanonicalDecl();
7932 }
7933
7934 // Enumerators with the same name match.
7936 // FIXME: Also check the value is odr-equivalent.
7937 return true;
7938
7939 // Using shadow declarations with the same target match.
7940 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
7941 const auto *USY = cast<UsingShadowDecl>(Y);
7942 return declaresSameEntity(USX->getTargetDecl(), USY->getTargetDecl());
7943 }
7944
7945 // Using declarations with the same qualifier match. (We already know that
7946 // the name matches.)
7947 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
7948 const auto *UY = cast<UsingDecl>(Y);
7949 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7950 UX->hasTypename() == UY->hasTypename() &&
7951 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7952 }
7953 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
7954 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
7955 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7956 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7957 }
7958 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
7959 return isSameQualifier(
7960 UX->getQualifier(),
7961 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
7962 }
7963
7964 // Using-pack declarations are only created by instantiation, and match if
7965 // they're instantiated from matching UnresolvedUsing...Decls.
7966 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
7967 return declaresSameEntity(
7968 UX->getInstantiatedFromUsingDecl(),
7969 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
7970 }
7971
7972 // Namespace alias definitions with the same target match.
7973 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
7974 const auto *NAY = cast<NamespaceAliasDecl>(Y);
7975 return NAX->getNamespace()->Equals(NAY->getNamespace());
7976 }
7977
7978 if (const auto *UX = dyn_cast<UsingEnumDecl>(X)) {
7979 const auto *UY = cast<UsingEnumDecl>(Y);
7980 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7981 declaresSameEntity(UX->getEnumDecl(), UY->getEnumDecl());
7982 }
7983
7984 return false;
7985}
7986
7989 switch (Arg.getKind()) {
7991 return Arg;
7992
7994 return TemplateArgument(Arg.getAsExpr(), /*IsCanonical=*/true,
7995 Arg.getIsDefaulted());
7996
7998 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
8000 Arg.getIsDefaulted());
8001 }
8002
8005 /*isNullPtr*/ true, Arg.getIsDefaulted());
8006
8009 Arg.getIsDefaulted());
8010
8012 return TemplateArgument(
8015
8018
8020 return TemplateArgument(*this,
8023
8026 /*isNullPtr*/ false, Arg.getIsDefaulted());
8027
8029 bool AnyNonCanonArgs = false;
8030 auto CanonArgs = ::getCanonicalTemplateArguments(
8031 *this, Arg.pack_elements(), AnyNonCanonArgs);
8032 if (!AnyNonCanonArgs)
8033 return Arg;
8035 const_cast<ASTContext &>(*this), CanonArgs);
8036 NewArg.setIsDefaulted(Arg.getIsDefaulted());
8037 return NewArg;
8038 }
8039 }
8040
8041 // Silence GCC warning
8042 llvm_unreachable("Unhandled template argument kind");
8043}
8044
8046 const TemplateArgument &Arg2) const {
8047 if (Arg1.getKind() != Arg2.getKind())
8048 return false;
8049
8050 switch (Arg1.getKind()) {
8052 llvm_unreachable("Comparing NULL template argument");
8053
8055 return hasSameType(Arg1.getAsType(), Arg2.getAsType());
8056
8058 return Arg1.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl() ==
8060
8062 return hasSameType(Arg1.getNullPtrType(), Arg2.getNullPtrType());
8063
8068
8070 return llvm::APSInt::isSameValue(Arg1.getAsIntegral(),
8071 Arg2.getAsIntegral());
8072
8074 return Arg1.structurallyEquals(Arg2);
8075
8077 llvm::FoldingSetNodeID ID1, ID2;
8078 Arg1.getAsExpr()->Profile(ID1, *this, /*Canonical=*/true);
8079 Arg2.getAsExpr()->Profile(ID2, *this, /*Canonical=*/true);
8080 return ID1 == ID2;
8081 }
8082
8084 return llvm::equal(
8085 Arg1.getPackAsArray(), Arg2.getPackAsArray(),
8086 [&](const TemplateArgument &Arg1, const TemplateArgument &Arg2) {
8087 return isSameTemplateArgument(Arg1, Arg2);
8088 });
8089 }
8090
8091 llvm_unreachable("Unhandled template argument kind");
8092}
8093
8095 // Handle the non-qualified case efficiently.
8096 if (!T.hasLocalQualifiers()) {
8097 // Handle the common positive case fast.
8098 if (const auto *AT = dyn_cast<ArrayType>(T))
8099 return AT;
8100 }
8101
8102 // Handle the common negative case fast.
8103 if (!isa<ArrayType>(T.getCanonicalType()))
8104 return nullptr;
8105
8106 // Apply any qualifiers from the array type to the element type. This
8107 // implements C99 6.7.3p8: "If the specification of an array type includes
8108 // any type qualifiers, the element type is so qualified, not the array type."
8109
8110 // If we get here, we either have type qualifiers on the type, or we have
8111 // sugar such as a typedef in the way. If we have type qualifiers on the type
8112 // we must propagate them down into the element type.
8113
8114 SplitQualType split = T.getSplitDesugaredType();
8115 Qualifiers qs = split.Quals;
8116
8117 // If we have a simple case, just return now.
8118 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
8119 if (!ATy || qs.empty())
8120 return ATy;
8121
8122 // Otherwise, we have an array and we have qualifiers on it. Push the
8123 // qualifiers into the array element type and return a new array type.
8124 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
8125
8126 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
8127 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
8128 CAT->getSizeExpr(),
8129 CAT->getSizeModifier(),
8130 CAT->getIndexTypeCVRQualifiers()));
8131 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
8133 IAT->getSizeModifier(),
8134 IAT->getIndexTypeCVRQualifiers()));
8135
8136 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
8138 NewEltTy, DSAT->getSizeExpr(), DSAT->getSizeModifier(),
8139 DSAT->getIndexTypeCVRQualifiers()));
8140
8141 const auto *VAT = cast<VariableArrayType>(ATy);
8142 return cast<ArrayType>(
8143 getVariableArrayType(NewEltTy, VAT->getSizeExpr(), VAT->getSizeModifier(),
8144 VAT->getIndexTypeCVRQualifiers()));
8145}
8146
8148 if (getLangOpts().HLSL && T.getAddressSpace() == LangAS::hlsl_groupshared)
8149 return getLValueReferenceType(T);
8150 if (getLangOpts().HLSL && T->isConstantArrayType())
8151 return getArrayParameterType(T);
8152 if (T->isArrayType() || T->isFunctionType())
8153 return getDecayedType(T);
8154 return T;
8155}
8156
8160 return T.getUnqualifiedType();
8161}
8162
8164 // C++ [except.throw]p3:
8165 // A throw-expression initializes a temporary object, called the exception
8166 // object, the type of which is determined by removing any top-level
8167 // cv-qualifiers from the static type of the operand of throw and adjusting
8168 // the type from "array of T" or "function returning T" to "pointer to T"
8169 // or "pointer to function returning T", [...]
8171 if (T->isArrayType() || T->isFunctionType())
8172 T = getDecayedType(T);
8173 return T.getUnqualifiedType();
8174}
8175
8176/// getArrayDecayedType - Return the properly qualified result of decaying the
8177/// specified array type to a pointer. This operation is non-trivial when
8178/// handling typedefs etc. The canonical type of "T" must be an array type,
8179/// this returns a pointer to a properly qualified element of the array.
8180///
8181/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
8183 // Get the element type with 'getAsArrayType' so that we don't lose any
8184 // typedefs in the element type of the array. This also handles propagation
8185 // of type qualifiers from the array type into the element type if present
8186 // (C99 6.7.3p8).
8187 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
8188 assert(PrettyArrayType && "Not an array type!");
8189
8190 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
8191
8192 // int x[restrict 4] -> int *restrict
8194 PrettyArrayType->getIndexTypeQualifiers());
8195
8196 // int x[_Nullable] -> int * _Nullable
8197 if (auto Nullability = Ty->getNullability()) {
8198 Result = const_cast<ASTContext *>(this)->getAttributedType(*Nullability,
8199 Result, Result);
8200 }
8201 return Result;
8202}
8203
8205 return getBaseElementType(array->getElementType());
8206}
8207
8209 Qualifiers qs;
8210 while (true) {
8211 SplitQualType split = type.getSplitDesugaredType();
8212 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
8213 if (!array) break;
8214
8215 type = array->getElementType();
8217 }
8218
8219 return getQualifiedType(type, qs);
8220}
8221
8222/// getConstantArrayElementCount - Returns number of constant array elements.
8223uint64_t
8225 uint64_t ElementCount = 1;
8226 do {
8227 ElementCount *= CA->getZExtSize();
8228 CA = dyn_cast_or_null<ConstantArrayType>(
8230 } while (CA);
8231 return ElementCount;
8232}
8233
8235 const ArrayInitLoopExpr *AILE) const {
8236 if (!AILE)
8237 return 0;
8238
8239 uint64_t ElementCount = 1;
8240
8241 do {
8242 ElementCount *= AILE->getArraySize().getZExtValue();
8243 AILE = dyn_cast<ArrayInitLoopExpr>(AILE->getSubExpr());
8244 } while (AILE);
8245
8246 return ElementCount;
8247}
8248
8249/// getFloatingRank - Return a relative rank for floating point types.
8250/// This routine will assert if passed a built-in type that isn't a float.
8252 if (const auto *CT = T->getAs<ComplexType>())
8253 return getFloatingRank(CT->getElementType());
8254
8255 switch (T->castAs<BuiltinType>()->getKind()) {
8256 default: llvm_unreachable("getFloatingRank(): not a floating type");
8257 case BuiltinType::Float16: return Float16Rank;
8258 case BuiltinType::Half: return HalfRank;
8259 case BuiltinType::Float: return FloatRank;
8260 case BuiltinType::Double: return DoubleRank;
8261 case BuiltinType::LongDouble: return LongDoubleRank;
8262 case BuiltinType::Float128: return Float128Rank;
8263 case BuiltinType::BFloat16: return BFloat16Rank;
8264 case BuiltinType::Ibm128: return Ibm128Rank;
8265 }
8266}
8267
8268/// getFloatingTypeOrder - Compare the rank of the two specified floating
8269/// point types, ignoring the domain of the type (i.e. 'double' ==
8270/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
8271/// LHS < RHS, return -1.
8273 FloatingRank LHSR = getFloatingRank(LHS);
8274 FloatingRank RHSR = getFloatingRank(RHS);
8275
8276 if (LHSR == RHSR)
8277 return 0;
8278 if (LHSR > RHSR)
8279 return 1;
8280 return -1;
8281}
8282
8285 return 0;
8286 return getFloatingTypeOrder(LHS, RHS);
8287}
8288
8289/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
8290/// routine will assert if passed a built-in type that isn't an integer or enum,
8291/// or if it is not canonicalized.
8292unsigned ASTContext::getIntegerRank(const Type *T) const {
8293 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
8294
8295 // Results in this 'losing' to any type of the same size, but winning if
8296 // larger.
8297 if (const auto *EIT = dyn_cast<BitIntType>(T))
8298 return 0 + (EIT->getNumBits() << 3);
8299
8300 if (const auto *OBT = dyn_cast<OverflowBehaviorType>(T))
8301 return getIntegerRank(OBT->getUnderlyingType().getTypePtr());
8302
8303 switch (cast<BuiltinType>(T)->getKind()) {
8304 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
8305 case BuiltinType::Bool:
8306 return 1 + (getIntWidth(BoolTy) << 3);
8307 case BuiltinType::Char_S:
8308 case BuiltinType::Char_U:
8309 case BuiltinType::SChar:
8310 case BuiltinType::UChar:
8311 return 2 + (getIntWidth(CharTy) << 3);
8312 case BuiltinType::Short:
8313 case BuiltinType::UShort:
8314 return 3 + (getIntWidth(ShortTy) << 3);
8315 case BuiltinType::Int:
8316 case BuiltinType::UInt:
8317 return 4 + (getIntWidth(IntTy) << 3);
8318 case BuiltinType::Long:
8319 case BuiltinType::ULong:
8320 return 5 + (getIntWidth(LongTy) << 3);
8321 case BuiltinType::LongLong:
8322 case BuiltinType::ULongLong:
8323 return 6 + (getIntWidth(LongLongTy) << 3);
8324 case BuiltinType::Int128:
8325 case BuiltinType::UInt128:
8326 return 7 + (getIntWidth(Int128Ty) << 3);
8327
8328 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
8329 // their underlying types" [c++20 conv.rank]
8330 case BuiltinType::Char8:
8331 return getIntegerRank(UnsignedCharTy.getTypePtr());
8332 case BuiltinType::Char16:
8333 return getIntegerRank(
8334 getFromTargetType(Target->getChar16Type()).getTypePtr());
8335 case BuiltinType::Char32:
8336 return getIntegerRank(
8337 getFromTargetType(Target->getChar32Type()).getTypePtr());
8338 case BuiltinType::WChar_S:
8339 case BuiltinType::WChar_U:
8340 return getIntegerRank(
8341 getFromTargetType(Target->getWCharType()).getTypePtr());
8342 }
8343}
8344
8345/// Whether this is a promotable bitfield reference according
8346/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
8347///
8348/// \returns the type this bit-field will promote to, or NULL if no
8349/// promotion occurs.
8351 if (E->isTypeDependent() || E->isValueDependent())
8352 return {};
8353
8354 // C++ [conv.prom]p5:
8355 // If the bit-field has an enumerated type, it is treated as any other
8356 // value of that type for promotion purposes.
8358 return {};
8359
8360 // FIXME: We should not do this unless E->refersToBitField() is true. This
8361 // matters in C where getSourceBitField() will find bit-fields for various
8362 // cases where the source expression is not a bit-field designator.
8363
8364 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
8365 if (!Field)
8366 return {};
8367
8368 QualType FT = Field->getType();
8369
8370 uint64_t BitWidth = Field->getBitWidthValue();
8371 uint64_t IntSize = getTypeSize(IntTy);
8372 // C++ [conv.prom]p5:
8373 // A prvalue for an integral bit-field can be converted to a prvalue of type
8374 // int if int can represent all the values of the bit-field; otherwise, it
8375 // can be converted to unsigned int if unsigned int can represent all the
8376 // values of the bit-field. If the bit-field is larger yet, no integral
8377 // promotion applies to it.
8378 // C11 6.3.1.1/2:
8379 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
8380 // If an int can represent all values of the original type (as restricted by
8381 // the width, for a bit-field), the value is converted to an int; otherwise,
8382 // it is converted to an unsigned int.
8383 //
8384 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
8385 // We perform that promotion here to match GCC and C++.
8386 // FIXME: C does not permit promotion of an enum bit-field whose rank is
8387 // greater than that of 'int'. We perform that promotion to match GCC.
8388 //
8389 // C23 6.3.1.1p2:
8390 // The value from a bit-field of a bit-precise integer type is converted to
8391 // the corresponding bit-precise integer type. (The rest is the same as in
8392 // C11.)
8393 if (QualType QT = Field->getType(); QT->isBitIntType())
8394 return QT;
8395
8396 if (BitWidth < IntSize)
8397 return IntTy;
8398
8399 if (BitWidth == IntSize)
8400 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
8401
8402 // Bit-fields wider than int are not subject to promotions, and therefore act
8403 // like the base type. GCC has some weird bugs in this area that we
8404 // deliberately do not follow (GCC follows a pre-standard resolution to
8405 // C's DR315 which treats bit-width as being part of the type, and this leaks
8406 // into their semantics in some cases).
8407 return {};
8408}
8409
8410/// getPromotedIntegerType - Returns the type that Promotable will
8411/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
8412/// integer type.
8414 assert(!Promotable.isNull());
8415 assert(isPromotableIntegerType(Promotable));
8416 if (const auto *ED = Promotable->getAsEnumDecl())
8417 return ED->getPromotionType();
8418
8419 // OverflowBehaviorTypes promote their underlying type and preserve OBT
8420 // qualifier.
8421 if (const auto *OBT = Promotable->getAs<OverflowBehaviorType>()) {
8422 QualType PromotedUnderlying =
8423 getPromotedIntegerType(OBT->getUnderlyingType());
8424 return getOverflowBehaviorType(OBT->getBehaviorKind(), PromotedUnderlying);
8425 }
8426
8427 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
8428 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
8429 // (3.9.1) can be converted to a prvalue of the first of the following
8430 // types that can represent all the values of its underlying type:
8431 // int, unsigned int, long int, unsigned long int, long long int, or
8432 // unsigned long long int [...]
8433 // FIXME: Is there some better way to compute this?
8434 if (BT->getKind() == BuiltinType::WChar_S ||
8435 BT->getKind() == BuiltinType::WChar_U ||
8436 BT->getKind() == BuiltinType::Char8 ||
8437 BT->getKind() == BuiltinType::Char16 ||
8438 BT->getKind() == BuiltinType::Char32) {
8439 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
8440 uint64_t FromSize = getTypeSize(BT);
8441 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
8443 for (const auto &PT : PromoteTypes) {
8444 uint64_t ToSize = getTypeSize(PT);
8445 if (FromSize < ToSize ||
8446 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
8447 return PT;
8448 }
8449 llvm_unreachable("char type should fit into long long");
8450 }
8451 }
8452
8453 // At this point, we should have a signed or unsigned integer type.
8454 if (Promotable->isSignedIntegerType())
8455 return IntTy;
8456 uint64_t PromotableSize = getIntWidth(Promotable);
8457 uint64_t IntSize = getIntWidth(IntTy);
8458 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
8459 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
8460}
8461
8462/// Recurses in pointer/array types until it finds an objc retainable
8463/// type and returns its ownership.
8465 while (!T.isNull()) {
8466 if (T.getObjCLifetime() != Qualifiers::OCL_None)
8467 return T.getObjCLifetime();
8468 if (T->isArrayType())
8470 else if (const auto *PT = T->getAs<PointerType>())
8471 T = PT->getPointeeType();
8472 else if (const auto *RT = T->getAs<ReferenceType>())
8473 T = RT->getPointeeType();
8474 else
8475 break;
8476 }
8477
8478 return Qualifiers::OCL_None;
8479}
8480
8481static const Type *getIntegerTypeForEnum(const EnumType *ET) {
8482 // Incomplete enum types are not treated as integer types.
8483 // FIXME: In C++, enum types are never integer types.
8484 const EnumDecl *ED = ET->getDecl()->getDefinitionOrSelf();
8485 if (ED->isComplete() && !ED->isScoped())
8486 return ED->getIntegerType().getTypePtr();
8487 return nullptr;
8488}
8489
8490/// getIntegerTypeOrder - Returns the highest ranked integer type:
8491/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
8492/// LHS < RHS, return -1.
8494 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
8495 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
8496
8497 // Unwrap enums to their underlying type.
8498 if (const auto *ET = dyn_cast<EnumType>(LHSC))
8499 LHSC = getIntegerTypeForEnum(ET);
8500 if (const auto *ET = dyn_cast<EnumType>(RHSC))
8501 RHSC = getIntegerTypeForEnum(ET);
8502
8503 if (LHSC == RHSC) return 0;
8504
8505 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
8506 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
8507
8508 unsigned LHSRank = getIntegerRank(LHSC);
8509 unsigned RHSRank = getIntegerRank(RHSC);
8510
8511 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
8512 if (LHSRank == RHSRank) return 0;
8513 return LHSRank > RHSRank ? 1 : -1;
8514 }
8515
8516 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
8517 if (LHSUnsigned) {
8518 // If the unsigned [LHS] type is larger, return it.
8519 if (LHSRank >= RHSRank)
8520 return 1;
8521
8522 // If the signed type can represent all values of the unsigned type, it
8523 // wins. Because we are dealing with 2's complement and types that are
8524 // powers of two larger than each other, this is always safe.
8525 return -1;
8526 }
8527
8528 // If the unsigned [RHS] type is larger, return it.
8529 if (RHSRank >= LHSRank)
8530 return -1;
8531
8532 // If the signed type can represent all values of the unsigned type, it
8533 // wins. Because we are dealing with 2's complement and types that are
8534 // powers of two larger than each other, this is always safe.
8535 return 1;
8536}
8537
8539 if (CFConstantStringTypeDecl)
8540 return CFConstantStringTypeDecl;
8541
8542 assert(!CFConstantStringTagDecl &&
8543 "tag and typedef should be initialized together");
8544 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
8545 CFConstantStringTagDecl->startDefinition();
8546
8547 struct {
8548 QualType Type;
8549 const char *Name;
8550 } Fields[5];
8551 unsigned Count = 0;
8552
8553 /// Objective-C ABI
8554 ///
8555 /// typedef struct __NSConstantString_tag {
8556 /// const int *isa;
8557 /// int flags;
8558 /// const char *str;
8559 /// long length;
8560 /// } __NSConstantString;
8561 ///
8562 /// Swift ABI (4.1, 4.2)
8563 ///
8564 /// typedef struct __NSConstantString_tag {
8565 /// uintptr_t _cfisa;
8566 /// uintptr_t _swift_rc;
8567 /// _Atomic(uint64_t) _cfinfoa;
8568 /// const char *_ptr;
8569 /// uint32_t _length;
8570 /// } __NSConstantString;
8571 ///
8572 /// Swift ABI (5.0)
8573 ///
8574 /// typedef struct __NSConstantString_tag {
8575 /// uintptr_t _cfisa;
8576 /// uintptr_t _swift_rc;
8577 /// _Atomic(uint64_t) _cfinfoa;
8578 /// const char *_ptr;
8579 /// uintptr_t _length;
8580 /// } __NSConstantString;
8581
8582 const auto CFRuntime = getLangOpts().CFRuntime;
8583 if (static_cast<unsigned>(CFRuntime) <
8584 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
8585 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
8586 Fields[Count++] = { IntTy, "flags" };
8587 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
8588 Fields[Count++] = { LongTy, "length" };
8589 } else {
8590 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
8591 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
8592 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
8593 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
8596 Fields[Count++] = { IntTy, "_ptr" };
8597 else
8598 Fields[Count++] = { getUIntPtrType(), "_ptr" };
8599 }
8600
8601 // Create fields
8602 for (unsigned i = 0; i < Count; ++i) {
8603 FieldDecl *Field =
8604 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
8605 SourceLocation(), &Idents.get(Fields[i].Name),
8606 Fields[i].Type, /*TInfo=*/nullptr,
8607 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8608 Field->setAccess(AS_public);
8609 CFConstantStringTagDecl->addDecl(Field);
8610 }
8611
8612 CFConstantStringTagDecl->completeDefinition();
8613 // This type is designed to be compatible with NSConstantString, but cannot
8614 // use the same name, since NSConstantString is an interface.
8615 CanQualType tagType = getCanonicalTagType(CFConstantStringTagDecl);
8616 CFConstantStringTypeDecl =
8617 buildImplicitTypedef(tagType, "__NSConstantString");
8618
8619 return CFConstantStringTypeDecl;
8620}
8621
8623 if (!CFConstantStringTagDecl)
8624 getCFConstantStringDecl(); // Build the tag and the typedef.
8625 return CFConstantStringTagDecl;
8626}
8627
8628// getCFConstantStringType - Return the type used for constant CFStrings.
8633
8635 if (ObjCSuperType.isNull()) {
8636 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
8637 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
8638 ObjCSuperType = getCanonicalTagType(ObjCSuperTypeDecl);
8639 }
8640 return ObjCSuperType;
8641}
8642
8644 const auto *TT = T->castAs<TypedefType>();
8645 CFConstantStringTypeDecl = cast<TypedefDecl>(TT->getDecl());
8646 CFConstantStringTagDecl = TT->castAsRecordDecl();
8647}
8648
8650 if (BlockDescriptorType)
8651 return getCanonicalTagType(BlockDescriptorType);
8652
8653 RecordDecl *RD;
8654 // FIXME: Needs the FlagAppleBlock bit.
8655 RD = buildImplicitRecord("__block_descriptor");
8656 RD->startDefinition();
8657
8658 QualType FieldTypes[] = {
8661 };
8662
8663 static const char *const FieldNames[] = {
8664 "reserved",
8665 "Size"
8666 };
8667
8668 for (size_t i = 0; i < 2; ++i) {
8670 *this, RD, SourceLocation(), SourceLocation(),
8671 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8672 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8673 Field->setAccess(AS_public);
8674 RD->addDecl(Field);
8675 }
8676
8677 RD->completeDefinition();
8678
8679 BlockDescriptorType = RD;
8680
8681 return getCanonicalTagType(BlockDescriptorType);
8682}
8683
8685 if (BlockDescriptorExtendedType)
8686 return getCanonicalTagType(BlockDescriptorExtendedType);
8687
8688 RecordDecl *RD;
8689 // FIXME: Needs the FlagAppleBlock bit.
8690 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
8691 RD->startDefinition();
8692
8693 QualType FieldTypes[] = {
8698 };
8699
8700 static const char *const FieldNames[] = {
8701 "reserved",
8702 "Size",
8703 "CopyFuncPtr",
8704 "DestroyFuncPtr"
8705 };
8706
8707 for (size_t i = 0; i < 4; ++i) {
8709 *this, RD, SourceLocation(), SourceLocation(),
8710 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8711 /*BitWidth=*/nullptr,
8712 /*Mutable=*/false, ICIS_NoInit);
8713 Field->setAccess(AS_public);
8714 RD->addDecl(Field);
8715 }
8716
8717 RD->completeDefinition();
8718
8719 BlockDescriptorExtendedType = RD;
8720 return getCanonicalTagType(BlockDescriptorExtendedType);
8721}
8722
8724 const auto *BT = dyn_cast<BuiltinType>(T);
8725
8726 if (!BT) {
8727 if (isa<PipeType>(T))
8728 return OCLTK_Pipe;
8729
8730 return OCLTK_Default;
8731 }
8732
8733 switch (BT->getKind()) {
8734#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8735 case BuiltinType::Id: \
8736 return OCLTK_Image;
8737#include "clang/Basic/OpenCLImageTypes.def"
8738
8739 case BuiltinType::OCLClkEvent:
8740 return OCLTK_ClkEvent;
8741
8742 case BuiltinType::OCLEvent:
8743 return OCLTK_Event;
8744
8745 case BuiltinType::OCLQueue:
8746 return OCLTK_Queue;
8747
8748 case BuiltinType::OCLReserveID:
8749 return OCLTK_ReserveID;
8750
8751 case BuiltinType::OCLSampler:
8752 return OCLTK_Sampler;
8753
8754 default:
8755 return OCLTK_Default;
8756 }
8757}
8758
8760 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
8761}
8762
8763/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
8764/// requires copy/dispose. Note that this must match the logic
8765/// in buildByrefHelpers.
8767 const VarDecl *D) {
8768 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
8769 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
8770 if (!copyExpr && record->hasTrivialDestructor()) return false;
8771
8772 return true;
8773 }
8774
8776 return true;
8777
8778 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
8779 // move or destroy.
8781 return true;
8782
8783 if (!Ty->isObjCRetainableType()) return false;
8784
8785 Qualifiers qs = Ty.getQualifiers();
8786
8787 // If we have lifetime, that dominates.
8788 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
8789 switch (lifetime) {
8790 case Qualifiers::OCL_None: llvm_unreachable("impossible");
8791
8792 // These are just bits as far as the runtime is concerned.
8795 return false;
8796
8797 // These cases should have been taken care of when checking the type's
8798 // non-triviality.
8801 llvm_unreachable("impossible");
8802 }
8803 llvm_unreachable("fell out of lifetime switch!");
8804 }
8805 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
8807}
8808
8810 Qualifiers::ObjCLifetime &LifeTime,
8811 bool &HasByrefExtendedLayout) const {
8812 if (!getLangOpts().ObjC ||
8813 getLangOpts().getGC() != LangOptions::NonGC)
8814 return false;
8815
8816 HasByrefExtendedLayout = false;
8817 if (Ty->isRecordType()) {
8818 HasByrefExtendedLayout = true;
8819 LifeTime = Qualifiers::OCL_None;
8820 } else if ((LifeTime = Ty.getObjCLifetime())) {
8821 // Honor the ARC qualifiers.
8822 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
8823 // The MRR rule.
8825 } else {
8826 LifeTime = Qualifiers::OCL_None;
8827 }
8828 return true;
8829}
8830
8832 assert(Target && "Expected target to be initialized");
8833 const llvm::Triple &T = Target->getTriple();
8834 // Windows is LLP64 rather than LP64
8835 if (T.isOSWindows() && T.isArch64Bit())
8836 return UnsignedLongLongTy;
8837 return UnsignedLongTy;
8838}
8839
8841 assert(Target && "Expected target to be initialized");
8842 const llvm::Triple &T = Target->getTriple();
8843 // Windows is LLP64 rather than LP64
8844 if (T.isOSWindows() && T.isArch64Bit())
8845 return LongLongTy;
8846 return LongTy;
8847}
8848
8850 if (!ObjCInstanceTypeDecl)
8851 ObjCInstanceTypeDecl =
8852 buildImplicitTypedef(getObjCIdType(), "instancetype");
8853 return ObjCInstanceTypeDecl;
8854}
8855
8856// This returns true if a type has been typedefed to BOOL:
8857// typedef <type> BOOL;
8859 if (const auto *TT = dyn_cast<TypedefType>(T))
8860 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
8861 return II->isStr("BOOL");
8862
8863 return false;
8864}
8865
8866/// getObjCEncodingTypeSize returns size of type for objective-c encoding
8867/// purpose.
8869 if (!type->isIncompleteArrayType() && type->isIncompleteType())
8870 return CharUnits::Zero();
8871
8873
8874 // Make all integer and enum types at least as large as an int
8875 if (sz.isPositive() && type->isIntegralOrEnumerationType())
8876 sz = std::max(sz, getTypeSizeInChars(IntTy));
8877 // Treat arrays as pointers, since that's how they're passed in.
8878 else if (type->isArrayType())
8880 return sz;
8881}
8882
8889
8892 if (!VD->isInline())
8894
8895 // In almost all cases, it's a weak definition.
8896 auto *First = VD->getFirstDecl();
8897 if (First->isInlineSpecified() || !First->isStaticDataMember())
8899
8900 // If there's a file-context declaration in this translation unit, it's a
8901 // non-discardable definition.
8902 for (auto *D : VD->redecls())
8904 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
8906
8907 // If we've not seen one yet, we don't know.
8909}
8910
8911static std::string charUnitsToString(const CharUnits &CU) {
8912 return llvm::itostr(CU.getQuantity());
8913}
8914
8915/// getObjCEncodingForBlock - Return the encoded type for this block
8916/// declaration.
8918 std::string S;
8919
8920 const BlockDecl *Decl = Expr->getBlockDecl();
8921 QualType BlockTy =
8923 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
8924 // Encode result type.
8925 if (getLangOpts().EncodeExtendedBlockSig)
8927 true /*Extended*/);
8928 else
8929 getObjCEncodingForType(BlockReturnTy, S);
8930 // Compute size of all parameters.
8931 // Start with computing size of a pointer in number of bytes.
8932 // FIXME: There might(should) be a better way of doing this computation!
8934 CharUnits ParmOffset = PtrSize;
8935 for (auto *PI : Decl->parameters()) {
8936 QualType PType = PI->getType();
8938 if (sz.isZero())
8939 continue;
8940 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
8941 ParmOffset += sz;
8942 }
8943 // Size of the argument frame
8944 S += charUnitsToString(ParmOffset);
8945 // Block pointer and offset.
8946 S += "@?0";
8947
8948 // Argument types.
8949 ParmOffset = PtrSize;
8950 for (auto *PVDecl : Decl->parameters()) {
8951 QualType PType = PVDecl->getOriginalType();
8952 if (const auto *AT =
8953 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8954 // Use array's original type only if it has known number of
8955 // elements.
8956 if (!isa<ConstantArrayType>(AT))
8957 PType = PVDecl->getType();
8958 } else if (PType->isFunctionType())
8959 PType = PVDecl->getType();
8960 if (getLangOpts().EncodeExtendedBlockSig)
8962 S, true /*Extended*/);
8963 else
8964 getObjCEncodingForType(PType, S);
8965 S += charUnitsToString(ParmOffset);
8966 ParmOffset += getObjCEncodingTypeSize(PType);
8967 }
8968
8969 return S;
8970}
8971
8972std::string
8974 std::string S;
8975 // Encode result type.
8976 getObjCEncodingForType(Decl->getReturnType(), S);
8977 CharUnits ParmOffset;
8978 // Compute size of all parameters.
8979 for (auto *PI : Decl->parameters()) {
8980 QualType PType = PI->getType();
8982 if (sz.isZero())
8983 continue;
8984
8985 assert(sz.isPositive() &&
8986 "getObjCEncodingForFunctionDecl - Incomplete param type");
8987 ParmOffset += sz;
8988 }
8989 S += charUnitsToString(ParmOffset);
8990 ParmOffset = CharUnits::Zero();
8991
8992 // Argument types.
8993 for (auto *PVDecl : Decl->parameters()) {
8994 QualType PType = PVDecl->getOriginalType();
8995 if (const auto *AT =
8996 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8997 // Use array's original type only if it has known number of
8998 // elements.
8999 if (!isa<ConstantArrayType>(AT))
9000 PType = PVDecl->getType();
9001 } else if (PType->isFunctionType())
9002 PType = PVDecl->getType();
9003 getObjCEncodingForType(PType, S);
9004 S += charUnitsToString(ParmOffset);
9005 ParmOffset += getObjCEncodingTypeSize(PType);
9006 }
9007
9008 return S;
9009}
9010
9011/// getObjCEncodingForMethodParameter - Return the encoded type for a single
9012/// method parameter or return type. If Extended, include class names and
9013/// block object types.
9015 QualType T, std::string& S,
9016 bool Extended) const {
9017 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
9019 // Encode parameter type.
9020 ObjCEncOptions Options = ObjCEncOptions()
9021 .setExpandPointedToStructures()
9022 .setExpandStructures()
9023 .setIsOutermostType();
9024 if (Extended)
9025 Options.setEncodeBlockParameters().setEncodeClassNames();
9026 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
9027}
9028
9029/// getObjCEncodingForMethodDecl - Return the encoded type for this method
9030/// declaration.
9032 bool Extended) const {
9033 // FIXME: This is not very efficient.
9034 // Encode return type.
9035 std::string S;
9036 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
9037 Decl->getReturnType(), S, Extended);
9038 // Compute size of all parameters.
9039 // Start with computing size of a pointer in number of bytes.
9040 // FIXME: There might(should) be a better way of doing this computation!
9042 // The first two arguments (self and _cmd) are pointers; account for
9043 // their size.
9044 CharUnits ParmOffset = 2 * PtrSize;
9045 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
9046 E = Decl->sel_param_end(); PI != E; ++PI) {
9047 QualType PType = (*PI)->getType();
9049 if (sz.isZero())
9050 continue;
9051
9052 assert(sz.isPositive() &&
9053 "getObjCEncodingForMethodDecl - Incomplete param type");
9054 ParmOffset += sz;
9055 }
9056 S += charUnitsToString(ParmOffset);
9057 S += "@0:";
9058 S += charUnitsToString(PtrSize);
9059
9060 // Argument types.
9061 ParmOffset = 2 * PtrSize;
9062 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
9063 E = Decl->sel_param_end(); PI != E; ++PI) {
9064 const ParmVarDecl *PVDecl = *PI;
9065 QualType PType = PVDecl->getOriginalType();
9066 if (const auto *AT =
9067 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
9068 // Use array's original type only if it has known number of
9069 // elements.
9070 if (!isa<ConstantArrayType>(AT))
9071 PType = PVDecl->getType();
9072 } else if (PType->isFunctionType())
9073 PType = PVDecl->getType();
9075 PType, S, Extended);
9076 S += charUnitsToString(ParmOffset);
9077 ParmOffset += getObjCEncodingTypeSize(PType);
9078 }
9079
9080 return S;
9081}
9082
9085 const ObjCPropertyDecl *PD,
9086 const Decl *Container) const {
9087 if (!Container)
9088 return nullptr;
9089 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
9090 for (auto *PID : CID->property_impls())
9091 if (PID->getPropertyDecl() == PD)
9092 return PID;
9093 } else {
9094 const auto *OID = cast<ObjCImplementationDecl>(Container);
9095 for (auto *PID : OID->property_impls())
9096 if (PID->getPropertyDecl() == PD)
9097 return PID;
9098 }
9099 return nullptr;
9100}
9101
9102/// getObjCEncodingForPropertyDecl - Return the encoded type for this
9103/// property declaration. If non-NULL, Container must be either an
9104/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
9105/// NULL when getting encodings for protocol properties.
9106/// Property attributes are stored as a comma-delimited C string. The simple
9107/// attributes readonly and bycopy are encoded as single characters. The
9108/// parametrized attributes, getter=name, setter=name, and ivar=name, are
9109/// encoded as single characters, followed by an identifier. Property types
9110/// are also encoded as a parametrized attribute. The characters used to encode
9111/// these attributes are defined by the following enumeration:
9112/// @code
9113/// enum PropertyAttributes {
9114/// kPropertyReadOnly = 'R', // property is read-only.
9115/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
9116/// kPropertyByref = '&', // property is a reference to the value last assigned
9117/// kPropertyDynamic = 'D', // property is dynamic
9118/// kPropertyGetter = 'G', // followed by getter selector name
9119/// kPropertySetter = 'S', // followed by setter selector name
9120/// kPropertyInstanceVariable = 'V' // followed by instance variable name
9121/// kPropertyType = 'T' // followed by old-style type encoding.
9122/// kPropertyWeak = 'W' // 'weak' property
9123/// kPropertyStrong = 'P' // property GC'able
9124/// kPropertyNonAtomic = 'N' // property non-atomic
9125/// kPropertyOptional = '?' // property optional
9126/// };
9127/// @endcode
9128std::string
9130 const Decl *Container) const {
9131 // Collect information from the property implementation decl(s).
9132 bool Dynamic = false;
9133 ObjCPropertyImplDecl *SynthesizePID = nullptr;
9134
9135 if (ObjCPropertyImplDecl *PropertyImpDecl =
9137 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
9138 Dynamic = true;
9139 else
9140 SynthesizePID = PropertyImpDecl;
9141 }
9142
9143 // FIXME: This is not very efficient.
9144 std::string S = "T";
9145
9146 // Encode result type.
9147 // GCC has some special rules regarding encoding of properties which
9148 // closely resembles encoding of ivars.
9150
9151 if (PD->isOptional())
9152 S += ",?";
9153
9154 if (PD->isReadOnly()) {
9155 S += ",R";
9157 S += ",C";
9159 S += ",&";
9161 S += ",W";
9162 } else {
9163 switch (PD->getSetterKind()) {
9164 case ObjCPropertyDecl::Assign: break;
9165 case ObjCPropertyDecl::Copy: S += ",C"; break;
9166 case ObjCPropertyDecl::Retain: S += ",&"; break;
9167 case ObjCPropertyDecl::Weak: S += ",W"; break;
9168 }
9169 }
9170
9171 // It really isn't clear at all what this means, since properties
9172 // are "dynamic by default".
9173 if (Dynamic)
9174 S += ",D";
9175
9177 S += ",N";
9178
9180 S += ",G";
9181 S += PD->getGetterName().getAsString();
9182 }
9183
9185 S += ",S";
9186 S += PD->getSetterName().getAsString();
9187 }
9188
9189 if (SynthesizePID) {
9190 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
9191 S += ",V";
9192 S += OID->getNameAsString();
9193 }
9194
9195 // FIXME: OBJCGC: weak & strong
9196 return S;
9197}
9198
9199/// getLegacyIntegralTypeEncoding -
9200/// Another legacy compatibility encoding: 32-bit longs are encoded as
9201/// 'l' or 'L' , but not always. For typedefs, we need to use
9202/// 'i' or 'I' instead if encoding a struct field, or a pointer!
9204 if (PointeeTy->getAs<TypedefType>()) {
9205 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
9206 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
9207 PointeeTy = UnsignedIntTy;
9208 else
9209 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
9210 PointeeTy = IntTy;
9211 }
9212 }
9213}
9214
9216 const FieldDecl *Field,
9217 QualType *NotEncodedT) const {
9218 // We follow the behavior of gcc, expanding structures which are
9219 // directly pointed to, and expanding embedded structures. Note that
9220 // these rules are sufficient to prevent recursive encoding of the
9221 // same type.
9222 getObjCEncodingForTypeImpl(T, S,
9223 ObjCEncOptions()
9224 .setExpandPointedToStructures()
9225 .setExpandStructures()
9226 .setIsOutermostType(),
9227 Field, NotEncodedT);
9228}
9229
9231 std::string& S) const {
9232 // Encode result type.
9233 // GCC has some special rules regarding encoding of properties which
9234 // closely resembles encoding of ivars.
9235 getObjCEncodingForTypeImpl(T, S,
9236 ObjCEncOptions()
9237 .setExpandPointedToStructures()
9238 .setExpandStructures()
9239 .setIsOutermostType()
9240 .setEncodingProperty(),
9241 /*Field=*/nullptr);
9242}
9243
9245 const BuiltinType *BT) {
9247 switch (kind) {
9248 case BuiltinType::Void: return 'v';
9249 case BuiltinType::Bool: return 'B';
9250 case BuiltinType::Char8:
9251 case BuiltinType::Char_U:
9252 case BuiltinType::UChar: return 'C';
9253 case BuiltinType::Char16:
9254 case BuiltinType::UShort: return 'S';
9255 case BuiltinType::Char32:
9256 case BuiltinType::UInt: return 'I';
9257 case BuiltinType::ULong:
9258 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
9259 case BuiltinType::UInt128: return 'T';
9260 case BuiltinType::ULongLong: return 'Q';
9261 case BuiltinType::Char_S:
9262 case BuiltinType::SChar: return 'c';
9263 case BuiltinType::Short: return 's';
9264 case BuiltinType::WChar_S:
9265 case BuiltinType::WChar_U:
9266 case BuiltinType::Int: return 'i';
9267 case BuiltinType::Long:
9268 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
9269 case BuiltinType::LongLong: return 'q';
9270 case BuiltinType::Int128: return 't';
9271 case BuiltinType::Float: return 'f';
9272 case BuiltinType::Double: return 'd';
9273 case BuiltinType::LongDouble: return 'D';
9274 case BuiltinType::NullPtr: return '*'; // like char*
9275
9276 case BuiltinType::BFloat16:
9277 case BuiltinType::Float16:
9278 case BuiltinType::Float128:
9279 case BuiltinType::Ibm128:
9280 case BuiltinType::Half:
9281 case BuiltinType::ShortAccum:
9282 case BuiltinType::Accum:
9283 case BuiltinType::LongAccum:
9284 case BuiltinType::UShortAccum:
9285 case BuiltinType::UAccum:
9286 case BuiltinType::ULongAccum:
9287 case BuiltinType::ShortFract:
9288 case BuiltinType::Fract:
9289 case BuiltinType::LongFract:
9290 case BuiltinType::UShortFract:
9291 case BuiltinType::UFract:
9292 case BuiltinType::ULongFract:
9293 case BuiltinType::SatShortAccum:
9294 case BuiltinType::SatAccum:
9295 case BuiltinType::SatLongAccum:
9296 case BuiltinType::SatUShortAccum:
9297 case BuiltinType::SatUAccum:
9298 case BuiltinType::SatULongAccum:
9299 case BuiltinType::SatShortFract:
9300 case BuiltinType::SatFract:
9301 case BuiltinType::SatLongFract:
9302 case BuiltinType::SatUShortFract:
9303 case BuiltinType::SatUFract:
9304 case BuiltinType::SatULongFract:
9305 // FIXME: potentially need @encodes for these!
9306 return ' ';
9307
9308#define SVE_TYPE(Name, Id, SingletonId) \
9309 case BuiltinType::Id:
9310#include "clang/Basic/AArch64ACLETypes.def"
9311#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9312#include "clang/Basic/RISCVVTypes.def"
9313#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9314#include "clang/Basic/WebAssemblyReferenceTypes.def"
9315#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
9316#include "clang/Basic/AMDGPUTypes.def"
9317 {
9318 DiagnosticsEngine &Diags = C->getDiagnostics();
9319 Diags.Report(diag::err_unsupported_objc_primitive_encoding)
9320 << QualType(BT, 0);
9321 return ' ';
9322 }
9323
9324 case BuiltinType::ObjCId:
9325 case BuiltinType::ObjCClass:
9326 case BuiltinType::ObjCSel:
9327 llvm_unreachable("@encoding ObjC primitive type");
9328
9329 // OpenCL and placeholder types don't need @encodings.
9330#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
9331 case BuiltinType::Id:
9332#include "clang/Basic/OpenCLImageTypes.def"
9333#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9334 case BuiltinType::Id:
9335#include "clang/Basic/OpenCLExtensionTypes.def"
9336 case BuiltinType::OCLEvent:
9337 case BuiltinType::OCLClkEvent:
9338 case BuiltinType::OCLQueue:
9339 case BuiltinType::OCLReserveID:
9340 case BuiltinType::OCLSampler:
9341 case BuiltinType::Dependent:
9342#define PPC_VECTOR_TYPE(Name, Id, Size) \
9343 case BuiltinType::Id:
9344#include "clang/Basic/PPCTypes.def"
9345#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9346#include "clang/Basic/HLSLIntangibleTypes.def"
9347#define BUILTIN_TYPE(KIND, ID)
9348#define PLACEHOLDER_TYPE(KIND, ID) \
9349 case BuiltinType::KIND:
9350#include "clang/AST/BuiltinTypes.def"
9351 llvm_unreachable("invalid builtin type for @encode");
9352 }
9353 llvm_unreachable("invalid BuiltinType::Kind value");
9354}
9355
9356static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED) {
9358
9359 // The encoding of an non-fixed enum type is always 'i', regardless of size.
9360 if (!Enum->isFixed())
9361 return 'i';
9362
9363 // The encoding of a fixed enum type matches its fixed underlying type.
9364 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
9366}
9367
9368static void EncodeBitField(const ASTContext *Ctx, std::string& S,
9369 QualType T, const FieldDecl *FD) {
9370 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
9371 S += 'b';
9372 // The NeXT runtime encodes bit fields as b followed by the number of bits.
9373 // The GNU runtime requires more information; bitfields are encoded as b,
9374 // then the offset (in bits) of the first element, then the type of the
9375 // bitfield, then the size in bits. For example, in this structure:
9376 //
9377 // struct
9378 // {
9379 // int integer;
9380 // int flags:2;
9381 // };
9382 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
9383 // runtime, but b32i2 for the GNU runtime. The reason for this extra
9384 // information is not especially sensible, but we're stuck with it for
9385 // compatibility with GCC, although providing it breaks anything that
9386 // actually uses runtime introspection and wants to work on both runtimes...
9387 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
9388 uint64_t Offset;
9389
9390 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
9391 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), IVD);
9392 } else {
9393 const RecordDecl *RD = FD->getParent();
9394 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
9395 Offset = RL.getFieldOffset(FD->getFieldIndex());
9396 }
9397
9398 S += llvm::utostr(Offset);
9399
9400 if (const auto *ET = T->getAsCanonical<EnumType>())
9401 S += ObjCEncodingForEnumDecl(Ctx, ET->getDecl());
9402 else {
9403 const auto *BT = T->castAs<BuiltinType>();
9404 S += getObjCEncodingForPrimitiveType(Ctx, BT);
9405 }
9406 }
9407 S += llvm::utostr(FD->getBitWidthValue());
9408}
9409
9410// Helper function for determining whether the encoded type string would include
9411// a template specialization type.
9413 bool VisitBasesAndFields) {
9414 T = T->getBaseElementTypeUnsafe();
9415
9416 if (auto *PT = T->getAs<PointerType>())
9418 PT->getPointeeType().getTypePtr(), false);
9419
9420 auto *CXXRD = T->getAsCXXRecordDecl();
9421
9422 if (!CXXRD)
9423 return false;
9424
9426 return true;
9427
9428 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
9429 return false;
9430
9431 for (const auto &B : CXXRD->bases())
9432 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
9433 true))
9434 return true;
9435
9436 for (auto *FD : CXXRD->fields())
9437 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
9438 true))
9439 return true;
9440
9441 return false;
9442}
9443
9444// FIXME: Use SmallString for accumulating string.
9445void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
9446 const ObjCEncOptions Options,
9447 const FieldDecl *FD,
9448 QualType *NotEncodedT) const {
9450 switch (CT->getTypeClass()) {
9451 case Type::Builtin:
9452 case Type::Enum:
9453 if (FD && FD->isBitField())
9454 return EncodeBitField(this, S, T, FD);
9455 if (const auto *BT = dyn_cast<BuiltinType>(CT))
9456 S += getObjCEncodingForPrimitiveType(this, BT);
9457 else
9458 S += ObjCEncodingForEnumDecl(this, cast<EnumType>(CT)->getDecl());
9459 return;
9460
9461 case Type::Complex:
9462 S += 'j';
9463 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
9464 ObjCEncOptions(),
9465 /*Field=*/nullptr);
9466 return;
9467
9468 case Type::Atomic:
9469 S += 'A';
9470 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
9471 ObjCEncOptions(),
9472 /*Field=*/nullptr);
9473 return;
9474
9475 // encoding for pointer or reference types.
9476 case Type::Pointer:
9477 case Type::LValueReference:
9478 case Type::RValueReference: {
9479 QualType PointeeTy;
9480 if (isa<PointerType>(CT)) {
9481 const auto *PT = T->castAs<PointerType>();
9482 if (PT->isObjCSelType()) {
9483 S += ':';
9484 return;
9485 }
9486 PointeeTy = PT->getPointeeType();
9487 } else {
9488 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
9489 }
9490
9491 bool isReadOnly = false;
9492 // For historical/compatibility reasons, the read-only qualifier of the
9493 // pointee gets emitted _before_ the '^'. The read-only qualifier of
9494 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
9495 // Also, do not emit the 'r' for anything but the outermost type!
9496 if (T->getAs<TypedefType>()) {
9497 if (Options.IsOutermostType() && T.isConstQualified()) {
9498 isReadOnly = true;
9499 S += 'r';
9500 }
9501 } else if (Options.IsOutermostType()) {
9502 QualType P = PointeeTy;
9503 while (auto PT = P->getAs<PointerType>())
9504 P = PT->getPointeeType();
9505 if (P.isConstQualified()) {
9506 isReadOnly = true;
9507 S += 'r';
9508 }
9509 }
9510 if (isReadOnly) {
9511 // Another legacy compatibility encoding. Some ObjC qualifier and type
9512 // combinations need to be rearranged.
9513 // Rewrite "in const" from "nr" to "rn"
9514 if (StringRef(S).ends_with("nr"))
9515 S.replace(S.end()-2, S.end(), "rn");
9516 }
9517
9518 if (PointeeTy->isCharType()) {
9519 // char pointer types should be encoded as '*' unless it is a
9520 // type that has been typedef'd to 'BOOL'.
9521 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
9522 S += '*';
9523 return;
9524 }
9525 } else if (const auto *RTy = PointeeTy->getAsCanonical<RecordType>()) {
9526 const IdentifierInfo *II = RTy->getDecl()->getIdentifier();
9527 // GCC binary compat: Need to convert "struct objc_class *" to "#".
9528 if (II == &Idents.get("objc_class")) {
9529 S += '#';
9530 return;
9531 }
9532 // GCC binary compat: Need to convert "struct objc_object *" to "@".
9533 if (II == &Idents.get("objc_object")) {
9534 S += '@';
9535 return;
9536 }
9537 // If the encoded string for the class includes template names, just emit
9538 // "^v" for pointers to the class.
9539 if (getLangOpts().CPlusPlus &&
9540 (!getLangOpts().EncodeCXXClassTemplateSpec &&
9542 RTy, Options.ExpandPointedToStructures()))) {
9543 S += "^v";
9544 return;
9545 }
9546 // fall through...
9547 }
9548 S += '^';
9550
9551 ObjCEncOptions NewOptions;
9552 if (Options.ExpandPointedToStructures())
9553 NewOptions.setExpandStructures();
9554 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
9555 /*Field=*/nullptr, NotEncodedT);
9556 return;
9557 }
9558
9559 case Type::ConstantArray:
9560 case Type::IncompleteArray:
9561 case Type::VariableArray: {
9562 const auto *AT = cast<ArrayType>(CT);
9563
9564 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
9565 // Incomplete arrays are encoded as a pointer to the array element.
9566 S += '^';
9567
9568 getObjCEncodingForTypeImpl(
9569 AT->getElementType(), S,
9570 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
9571 } else {
9572 S += '[';
9573
9574 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
9575 S += llvm::utostr(CAT->getZExtSize());
9576 else {
9577 //Variable length arrays are encoded as a regular array with 0 elements.
9579 "Unknown array type!");
9580 S += '0';
9581 }
9582
9583 getObjCEncodingForTypeImpl(
9584 AT->getElementType(), S,
9585 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
9586 NotEncodedT);
9587 S += ']';
9588 }
9589 return;
9590 }
9591
9592 case Type::FunctionNoProto:
9593 case Type::FunctionProto:
9594 S += '?';
9595 return;
9596
9597 case Type::Record: {
9598 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
9599 S += RDecl->isUnion() ? '(' : '{';
9600 // Anonymous structures print as '?'
9601 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
9602 S += II->getName();
9603 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
9604 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
9605 llvm::raw_string_ostream OS(S);
9606 printTemplateArgumentList(OS, TemplateArgs.asArray(),
9608 }
9609 } else {
9610 S += '?';
9611 }
9612 if (Options.ExpandStructures()) {
9613 S += '=';
9614 if (!RDecl->isUnion()) {
9615 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
9616 } else {
9617 for (const auto *Field : RDecl->fields()) {
9618 if (FD) {
9619 S += '"';
9620 S += Field->getNameAsString();
9621 S += '"';
9622 }
9623
9624 // Special case bit-fields.
9625 if (Field->isBitField()) {
9626 getObjCEncodingForTypeImpl(Field->getType(), S,
9627 ObjCEncOptions().setExpandStructures(),
9628 Field);
9629 } else {
9630 QualType qt = Field->getType();
9632 getObjCEncodingForTypeImpl(
9633 qt, S,
9634 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
9635 NotEncodedT);
9636 }
9637 }
9638 }
9639 }
9640 S += RDecl->isUnion() ? ')' : '}';
9641 return;
9642 }
9643
9644 case Type::BlockPointer: {
9645 const auto *BT = T->castAs<BlockPointerType>();
9646 S += "@?"; // Unlike a pointer-to-function, which is "^?".
9647 if (Options.EncodeBlockParameters()) {
9648 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
9649
9650 S += '<';
9651 // Block return type
9652 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
9653 Options.forComponentType(), FD, NotEncodedT);
9654 // Block self
9655 S += "@?";
9656 // Block parameters
9657 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
9658 for (const auto &I : FPT->param_types())
9659 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
9660 NotEncodedT);
9661 }
9662 S += '>';
9663 }
9664 return;
9665 }
9666
9667 case Type::ObjCObject: {
9668 // hack to match legacy encoding of *id and *Class
9669 QualType Ty = getObjCObjectPointerType(CT);
9670 if (Ty->isObjCIdType()) {
9671 S += "{objc_object=}";
9672 return;
9673 }
9674 else if (Ty->isObjCClassType()) {
9675 S += "{objc_class=}";
9676 return;
9677 }
9678 // TODO: Double check to make sure this intentionally falls through.
9679 [[fallthrough]];
9680 }
9681
9682 case Type::ObjCInterface: {
9683 // Ignore protocol qualifiers when mangling at this level.
9684 // @encode(class_name)
9685 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
9686 S += '{';
9687 S += OI->getObjCRuntimeNameAsString();
9688 if (Options.ExpandStructures()) {
9689 S += '=';
9690 SmallVector<const ObjCIvarDecl*, 32> Ivars;
9691 DeepCollectObjCIvars(OI, true, Ivars);
9692 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
9693 const FieldDecl *Field = Ivars[i];
9694 if (Field->isBitField())
9695 getObjCEncodingForTypeImpl(Field->getType(), S,
9696 ObjCEncOptions().setExpandStructures(),
9697 Field);
9698 else
9699 getObjCEncodingForTypeImpl(Field->getType(), S,
9700 ObjCEncOptions().setExpandStructures(), FD,
9701 NotEncodedT);
9702 }
9703 }
9704 S += '}';
9705 return;
9706 }
9707
9708 case Type::ObjCObjectPointer: {
9709 const auto *OPT = T->castAs<ObjCObjectPointerType>();
9710 if (OPT->isObjCIdType()) {
9711 S += '@';
9712 return;
9713 }
9714
9715 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
9716 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
9717 // Since this is a binary compatibility issue, need to consult with
9718 // runtime folks. Fortunately, this is a *very* obscure construct.
9719 S += '#';
9720 return;
9721 }
9722
9723 if (OPT->isObjCQualifiedIdType()) {
9724 getObjCEncodingForTypeImpl(
9725 getObjCIdType(), S,
9726 Options.keepingOnly(ObjCEncOptions()
9727 .setExpandPointedToStructures()
9728 .setExpandStructures()),
9729 FD);
9730 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
9731 // Note that we do extended encoding of protocol qualifier list
9732 // Only when doing ivar or property encoding.
9733 S += '"';
9734 for (const auto *I : OPT->quals()) {
9735 S += '<';
9736 S += I->getObjCRuntimeNameAsString();
9737 S += '>';
9738 }
9739 S += '"';
9740 }
9741 return;
9742 }
9743
9744 S += '@';
9745 if (OPT->getInterfaceDecl() &&
9746 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
9747 S += '"';
9748 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
9749 for (const auto *I : OPT->quals()) {
9750 S += '<';
9751 S += I->getObjCRuntimeNameAsString();
9752 S += '>';
9753 }
9754 S += '"';
9755 }
9756 return;
9757 }
9758
9759 // gcc just blithely ignores member pointers.
9760 // FIXME: we should do better than that. 'M' is available.
9761 case Type::MemberPointer:
9762 // This matches gcc's encoding, even though technically it is insufficient.
9763 //FIXME. We should do a better job than gcc.
9764 case Type::Vector:
9765 case Type::ExtVector:
9766 // Until we have a coherent encoding of these three types, issue warning.
9767 if (NotEncodedT)
9768 *NotEncodedT = T;
9769 return;
9770
9771 case Type::ConstantMatrix:
9772 if (NotEncodedT)
9773 *NotEncodedT = T;
9774 return;
9775
9776 case Type::BitInt:
9777 if (NotEncodedT)
9778 *NotEncodedT = T;
9779 return;
9780
9781 // We could see an undeduced auto type here during error recovery.
9782 // Just ignore it.
9783 case Type::Auto:
9784 case Type::DeducedTemplateSpecialization:
9785 return;
9786
9787 case Type::HLSLAttributedResource:
9788 case Type::HLSLInlineSpirv:
9789 case Type::OverflowBehavior:
9790 llvm_unreachable("unexpected type");
9791
9792 case Type::ArrayParameter:
9793 case Type::Pipe:
9794#define ABSTRACT_TYPE(KIND, BASE)
9795#define TYPE(KIND, BASE)
9796#define DEPENDENT_TYPE(KIND, BASE) \
9797 case Type::KIND:
9798#define NON_CANONICAL_TYPE(KIND, BASE) \
9799 case Type::KIND:
9800#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
9801 case Type::KIND:
9802#include "clang/AST/TypeNodes.inc"
9803 llvm_unreachable("@encode for dependent type!");
9804 }
9805 llvm_unreachable("bad type kind!");
9806}
9807
9808void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
9809 std::string &S,
9810 const FieldDecl *FD,
9811 bool includeVBases,
9812 QualType *NotEncodedT) const {
9813 assert(RDecl && "Expected non-null RecordDecl");
9814 assert(!RDecl->isUnion() && "Should not be called for unions");
9815 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
9816 return;
9817
9818 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
9819 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
9820 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
9821
9822 if (CXXRec) {
9823 for (const auto &BI : CXXRec->bases()) {
9824 if (!BI.isVirtual()) {
9825 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9826 if (base->isEmpty())
9827 continue;
9828 uint64_t offs = toBits(layout.getBaseClassOffset(base));
9829 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9830 std::make_pair(offs, base));
9831 }
9832 }
9833 }
9834
9835 for (FieldDecl *Field : RDecl->fields()) {
9836 if (!Field->isZeroLengthBitField() && Field->isZeroSize(*this))
9837 continue;
9838 uint64_t offs = layout.getFieldOffset(Field->getFieldIndex());
9839 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9840 std::make_pair(offs, Field));
9841 }
9842
9843 if (CXXRec && includeVBases) {
9844 for (const auto &BI : CXXRec->vbases()) {
9845 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9846 if (base->isEmpty())
9847 continue;
9848 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
9849 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
9850 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
9851 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
9852 std::make_pair(offs, base));
9853 }
9854 }
9855
9856 CharUnits size;
9857 if (CXXRec) {
9858 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
9859 } else {
9860 size = layout.getSize();
9861 }
9862
9863#ifndef NDEBUG
9864 uint64_t CurOffs = 0;
9865#endif
9866 std::multimap<uint64_t, NamedDecl *>::iterator
9867 CurLayObj = FieldOrBaseOffsets.begin();
9868
9869 if (CXXRec && CXXRec->isDynamicClass() &&
9870 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
9871 if (FD) {
9872 S += "\"_vptr$";
9873 std::string recname = CXXRec->getNameAsString();
9874 if (recname.empty()) recname = "?";
9875 S += recname;
9876 S += '"';
9877 }
9878 S += "^^?";
9879#ifndef NDEBUG
9880 CurOffs += getTypeSize(VoidPtrTy);
9881#endif
9882 }
9883
9884 if (!RDecl->hasFlexibleArrayMember()) {
9885 // Mark the end of the structure.
9886 uint64_t offs = toBits(size);
9887 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9888 std::make_pair(offs, nullptr));
9889 }
9890
9891 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
9892#ifndef NDEBUG
9893 assert(CurOffs <= CurLayObj->first);
9894 if (CurOffs < CurLayObj->first) {
9895 uint64_t padding = CurLayObj->first - CurOffs;
9896 // FIXME: There doesn't seem to be a way to indicate in the encoding that
9897 // packing/alignment of members is different that normal, in which case
9898 // the encoding will be out-of-sync with the real layout.
9899 // If the runtime switches to just consider the size of types without
9900 // taking into account alignment, we could make padding explicit in the
9901 // encoding (e.g. using arrays of chars). The encoding strings would be
9902 // longer then though.
9903 CurOffs += padding;
9904 }
9905#endif
9906
9907 NamedDecl *dcl = CurLayObj->second;
9908 if (!dcl)
9909 break; // reached end of structure.
9910
9911 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
9912 // We expand the bases without their virtual bases since those are going
9913 // in the initial structure. Note that this differs from gcc which
9914 // expands virtual bases each time one is encountered in the hierarchy,
9915 // making the encoding type bigger than it really is.
9916 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
9917 NotEncodedT);
9918 assert(!base->isEmpty());
9919#ifndef NDEBUG
9920 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
9921#endif
9922 } else {
9923 const auto *field = cast<FieldDecl>(dcl);
9924 if (FD) {
9925 S += '"';
9926 S += field->getNameAsString();
9927 S += '"';
9928 }
9929
9930 if (field->isBitField()) {
9931 EncodeBitField(this, S, field->getType(), field);
9932#ifndef NDEBUG
9933 CurOffs += field->getBitWidthValue();
9934#endif
9935 } else {
9936 QualType qt = field->getType();
9938 getObjCEncodingForTypeImpl(
9939 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
9940 FD, NotEncodedT);
9941#ifndef NDEBUG
9942 CurOffs += getTypeSize(field->getType());
9943#endif
9944 }
9945 }
9946 }
9947}
9948
9950 std::string& S) const {
9951 if (QT & Decl::OBJC_TQ_In)
9952 S += 'n';
9953 if (QT & Decl::OBJC_TQ_Inout)
9954 S += 'N';
9955 if (QT & Decl::OBJC_TQ_Out)
9956 S += 'o';
9957 if (QT & Decl::OBJC_TQ_Bycopy)
9958 S += 'O';
9959 if (QT & Decl::OBJC_TQ_Byref)
9960 S += 'R';
9961 if (QT & Decl::OBJC_TQ_Oneway)
9962 S += 'V';
9963}
9964
9966 if (!ObjCIdDecl) {
9969 ObjCIdDecl = buildImplicitTypedef(T, "id");
9970 }
9971 return ObjCIdDecl;
9972}
9973
9975 if (!ObjCSelDecl) {
9977 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
9978 }
9979 return ObjCSelDecl;
9980}
9981
9983 if (!ObjCClassDecl) {
9986 ObjCClassDecl = buildImplicitTypedef(T, "Class");
9987 }
9988 return ObjCClassDecl;
9989}
9990
9992 if (!ObjCProtocolClassDecl) {
9993 ObjCProtocolClassDecl
9996 &Idents.get("Protocol"),
9997 /*typeParamList=*/nullptr,
9998 /*PrevDecl=*/nullptr,
9999 SourceLocation(), true);
10000 }
10001
10002 return ObjCProtocolClassDecl;
10003}
10004
10006 if (!getLangOpts().PointerAuthObjcInterfaceSel)
10007 return PointerAuthQualifier();
10009 getLangOpts().PointerAuthObjcInterfaceSelKey,
10010 /*isAddressDiscriminated=*/true, SelPointerConstantDiscriminator,
10012 /*isIsaPointer=*/false,
10013 /*authenticatesNullValues=*/false);
10014}
10015
10016//===----------------------------------------------------------------------===//
10017// __builtin_va_list Construction Functions
10018//===----------------------------------------------------------------------===//
10019
10021 StringRef Name) {
10022 // typedef char* __builtin[_ms]_va_list;
10023 QualType T = Context->getPointerType(Context->CharTy);
10024 return Context->buildImplicitTypedef(T, Name);
10025}
10026
10028 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
10029}
10030
10032 // typedef char *__builtin_zos_va_list[2];
10033 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 2);
10034 QualType T = Context->getPointerType(Context->CharTy);
10035 QualType ArrayType = Context->getConstantArrayType(
10036 T, Size, nullptr, ArraySizeModifier::Normal, 0);
10037 return Context->buildImplicitTypedef(ArrayType, "__builtin_zos_va_list");
10038}
10039
10041 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
10042}
10043
10045 // typedef void* __builtin_va_list;
10046 QualType T = Context->getPointerType(Context->VoidTy);
10047 return Context->buildImplicitTypedef(T, "__builtin_va_list");
10048}
10049
10050static TypedefDecl *
10052 // struct __va_list
10053 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
10054 if (Context->getLangOpts().CPlusPlus) {
10055 // namespace std { struct __va_list {
10056 auto *NS = NamespaceDecl::Create(
10057 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
10058 /*Inline=*/false, SourceLocation(), SourceLocation(),
10059 &Context->Idents.get("std"),
10060 /*PrevDecl=*/nullptr, /*Nested=*/false);
10061 NS->setImplicit();
10063 }
10064
10065 VaListTagDecl->startDefinition();
10066
10067 const size_t NumFields = 5;
10068 QualType FieldTypes[NumFields];
10069 const char *FieldNames[NumFields];
10070
10071 // void *__stack;
10072 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
10073 FieldNames[0] = "__stack";
10074
10075 // void *__gr_top;
10076 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
10077 FieldNames[1] = "__gr_top";
10078
10079 // void *__vr_top;
10080 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10081 FieldNames[2] = "__vr_top";
10082
10083 // int __gr_offs;
10084 FieldTypes[3] = Context->IntTy;
10085 FieldNames[3] = "__gr_offs";
10086
10087 // int __vr_offs;
10088 FieldTypes[4] = Context->IntTy;
10089 FieldNames[4] = "__vr_offs";
10090
10091 // Create fields
10092 for (unsigned i = 0; i < NumFields; ++i) {
10093 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10097 &Context->Idents.get(FieldNames[i]),
10098 FieldTypes[i], /*TInfo=*/nullptr,
10099 /*BitWidth=*/nullptr,
10100 /*Mutable=*/false,
10101 ICIS_NoInit);
10102 Field->setAccess(AS_public);
10103 VaListTagDecl->addDecl(Field);
10104 }
10105 VaListTagDecl->completeDefinition();
10106 Context->VaListTagDecl = VaListTagDecl;
10107 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10108
10109 // } __builtin_va_list;
10110 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10111}
10112
10114 // typedef struct __va_list_tag {
10116
10117 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10118 VaListTagDecl->startDefinition();
10119
10120 const size_t NumFields = 5;
10121 QualType FieldTypes[NumFields];
10122 const char *FieldNames[NumFields];
10123
10124 // unsigned char gpr;
10125 FieldTypes[0] = Context->UnsignedCharTy;
10126 FieldNames[0] = "gpr";
10127
10128 // unsigned char fpr;
10129 FieldTypes[1] = Context->UnsignedCharTy;
10130 FieldNames[1] = "fpr";
10131
10132 // unsigned short reserved;
10133 FieldTypes[2] = Context->UnsignedShortTy;
10134 FieldNames[2] = "reserved";
10135
10136 // void* overflow_arg_area;
10137 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10138 FieldNames[3] = "overflow_arg_area";
10139
10140 // void* reg_save_area;
10141 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
10142 FieldNames[4] = "reg_save_area";
10143
10144 // Create fields
10145 for (unsigned i = 0; i < NumFields; ++i) {
10146 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
10149 &Context->Idents.get(FieldNames[i]),
10150 FieldTypes[i], /*TInfo=*/nullptr,
10151 /*BitWidth=*/nullptr,
10152 /*Mutable=*/false,
10153 ICIS_NoInit);
10154 Field->setAccess(AS_public);
10155 VaListTagDecl->addDecl(Field);
10156 }
10157 VaListTagDecl->completeDefinition();
10158 Context->VaListTagDecl = VaListTagDecl;
10159 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10160
10161 // } __va_list_tag;
10162 TypedefDecl *VaListTagTypedefDecl =
10163 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10164
10165 QualType VaListTagTypedefType =
10166 Context->getTypedefType(ElaboratedTypeKeyword::None,
10167 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10168
10169 // typedef __va_list_tag __builtin_va_list[1];
10170 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10171 QualType VaListTagArrayType = Context->getConstantArrayType(
10172 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10173 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10174}
10175
10176static TypedefDecl *
10178 // struct __va_list_tag {
10180 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10181 VaListTagDecl->startDefinition();
10182
10183 const size_t NumFields = 4;
10184 QualType FieldTypes[NumFields];
10185 const char *FieldNames[NumFields];
10186
10187 // unsigned gp_offset;
10188 FieldTypes[0] = Context->UnsignedIntTy;
10189 FieldNames[0] = "gp_offset";
10190
10191 // unsigned fp_offset;
10192 FieldTypes[1] = Context->UnsignedIntTy;
10193 FieldNames[1] = "fp_offset";
10194
10195 // void* overflow_arg_area;
10196 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10197 FieldNames[2] = "overflow_arg_area";
10198
10199 // void* reg_save_area;
10200 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10201 FieldNames[3] = "reg_save_area";
10202
10203 // Create fields
10204 for (unsigned i = 0; i < NumFields; ++i) {
10205 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10209 &Context->Idents.get(FieldNames[i]),
10210 FieldTypes[i], /*TInfo=*/nullptr,
10211 /*BitWidth=*/nullptr,
10212 /*Mutable=*/false,
10213 ICIS_NoInit);
10214 Field->setAccess(AS_public);
10215 VaListTagDecl->addDecl(Field);
10216 }
10217 VaListTagDecl->completeDefinition();
10218 Context->VaListTagDecl = VaListTagDecl;
10219 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10220
10221 // };
10222
10223 // typedef struct __va_list_tag __builtin_va_list[1];
10224 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10225 QualType VaListTagArrayType = Context->getConstantArrayType(
10226 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10227 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10228}
10229
10230static TypedefDecl *
10232 // struct __va_list
10233 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
10234 if (Context->getLangOpts().CPlusPlus) {
10235 // namespace std { struct __va_list {
10236 NamespaceDecl *NS;
10237 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
10238 Context->getTranslationUnitDecl(),
10239 /*Inline=*/false, SourceLocation(),
10240 SourceLocation(), &Context->Idents.get("std"),
10241 /*PrevDecl=*/nullptr, /*Nested=*/false);
10242 NS->setImplicit();
10243 VaListDecl->setDeclContext(NS);
10244 }
10245
10246 VaListDecl->startDefinition();
10247
10248 // void * __ap;
10249 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10250 VaListDecl,
10253 &Context->Idents.get("__ap"),
10254 Context->getPointerType(Context->VoidTy),
10255 /*TInfo=*/nullptr,
10256 /*BitWidth=*/nullptr,
10257 /*Mutable=*/false,
10258 ICIS_NoInit);
10259 Field->setAccess(AS_public);
10260 VaListDecl->addDecl(Field);
10261
10262 // };
10263 VaListDecl->completeDefinition();
10264 Context->VaListTagDecl = VaListDecl;
10265
10266 // typedef struct __va_list __builtin_va_list;
10267 CanQualType T = Context->getCanonicalTagType(VaListDecl);
10268 return Context->buildImplicitTypedef(T, "__builtin_va_list");
10269}
10270
10271static TypedefDecl *
10273 // struct __va_list_tag {
10275 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10276 VaListTagDecl->startDefinition();
10277
10278 const size_t NumFields = 4;
10279 QualType FieldTypes[NumFields];
10280 const char *FieldNames[NumFields];
10281
10282 // long __gpr;
10283 FieldTypes[0] = Context->LongTy;
10284 FieldNames[0] = "__gpr";
10285
10286 // long __fpr;
10287 FieldTypes[1] = Context->LongTy;
10288 FieldNames[1] = "__fpr";
10289
10290 // void *__overflow_arg_area;
10291 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10292 FieldNames[2] = "__overflow_arg_area";
10293
10294 // void *__reg_save_area;
10295 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10296 FieldNames[3] = "__reg_save_area";
10297
10298 // Create fields
10299 for (unsigned i = 0; i < NumFields; ++i) {
10300 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10304 &Context->Idents.get(FieldNames[i]),
10305 FieldTypes[i], /*TInfo=*/nullptr,
10306 /*BitWidth=*/nullptr,
10307 /*Mutable=*/false,
10308 ICIS_NoInit);
10309 Field->setAccess(AS_public);
10310 VaListTagDecl->addDecl(Field);
10311 }
10312 VaListTagDecl->completeDefinition();
10313 Context->VaListTagDecl = VaListTagDecl;
10314 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10315
10316 // };
10317
10318 // typedef __va_list_tag __builtin_va_list[1];
10319 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10320 QualType VaListTagArrayType = Context->getConstantArrayType(
10321 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10322
10323 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10324}
10325
10327 // typedef struct __va_list_tag {
10329 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10330 VaListTagDecl->startDefinition();
10331
10332 const size_t NumFields = 3;
10333 QualType FieldTypes[NumFields];
10334 const char *FieldNames[NumFields];
10335
10336 // void *CurrentSavedRegisterArea;
10337 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
10338 FieldNames[0] = "__current_saved_reg_area_pointer";
10339
10340 // void *SavedRegAreaEnd;
10341 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
10342 FieldNames[1] = "__saved_reg_area_end_pointer";
10343
10344 // void *OverflowArea;
10345 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10346 FieldNames[2] = "__overflow_area_pointer";
10347
10348 // Create fields
10349 for (unsigned i = 0; i < NumFields; ++i) {
10351 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
10352 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
10353 /*TInfo=*/nullptr,
10354 /*BitWidth=*/nullptr,
10355 /*Mutable=*/false, ICIS_NoInit);
10356 Field->setAccess(AS_public);
10357 VaListTagDecl->addDecl(Field);
10358 }
10359 VaListTagDecl->completeDefinition();
10360 Context->VaListTagDecl = VaListTagDecl;
10361 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10362
10363 // } __va_list_tag;
10364 TypedefDecl *VaListTagTypedefDecl =
10365 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10366
10367 QualType VaListTagTypedefType =
10368 Context->getTypedefType(ElaboratedTypeKeyword::None,
10369 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10370
10371 // typedef __va_list_tag __builtin_va_list[1];
10372 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10373 QualType VaListTagArrayType = Context->getConstantArrayType(
10374 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10375
10376 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10377}
10378
10379static TypedefDecl *
10381 // typedef struct __va_list_tag {
10382 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10383
10384 VaListTagDecl->startDefinition();
10385
10386 // int* __va_stk;
10387 // int* __va_reg;
10388 // int __va_ndx;
10389 constexpr size_t NumFields = 3;
10390 QualType FieldTypes[NumFields] = {Context->getPointerType(Context->IntTy),
10391 Context->getPointerType(Context->IntTy),
10392 Context->IntTy};
10393 const char *FieldNames[NumFields] = {"__va_stk", "__va_reg", "__va_ndx"};
10394
10395 // Create fields
10396 for (unsigned i = 0; i < NumFields; ++i) {
10399 &Context->Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
10400 /*BitWidth=*/nullptr,
10401 /*Mutable=*/false, ICIS_NoInit);
10402 Field->setAccess(AS_public);
10403 VaListTagDecl->addDecl(Field);
10404 }
10405 VaListTagDecl->completeDefinition();
10406 Context->VaListTagDecl = VaListTagDecl;
10407 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10408
10409 // } __va_list_tag;
10410 TypedefDecl *VaListTagTypedefDecl =
10411 Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10412
10413 return VaListTagTypedefDecl;
10414}
10415
10418 switch (Kind) {
10420 return CreateCharPtrBuiltinVaListDecl(Context);
10422 return CreateVoidPtrBuiltinVaListDecl(Context);
10424 return CreateAArch64ABIBuiltinVaListDecl(Context);
10426 return CreatePowerABIBuiltinVaListDecl(Context);
10428 return CreateX86_64ABIBuiltinVaListDecl(Context);
10430 return CreateAAPCSABIBuiltinVaListDecl(Context);
10432 return CreateSystemZBuiltinVaListDecl(Context);
10434 return CreateHexagonBuiltinVaListDecl(Context);
10436 return CreateXtensaABIBuiltinVaListDecl(Context);
10437 }
10438
10439 llvm_unreachable("Unhandled __builtin_va_list type kind");
10440}
10441
10443 if (!BuiltinVaListDecl) {
10444 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
10445 assert(BuiltinVaListDecl->isImplicit());
10446 }
10447
10448 return BuiltinVaListDecl;
10449}
10450
10452 // Force the creation of VaListTagDecl by building the __builtin_va_list
10453 // declaration.
10454 if (!VaListTagDecl)
10455 (void)getBuiltinVaListDecl();
10456
10457 return VaListTagDecl;
10458}
10459
10461 if (!BuiltinMSVaListDecl)
10462 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
10463
10464 return BuiltinMSVaListDecl;
10465}
10466
10468 if (!BuiltinZOSVaListDecl)
10469 BuiltinZOSVaListDecl = CreateZOSVaListDecl(this);
10470
10471 return BuiltinZOSVaListDecl;
10472}
10473
10475 // Allow redecl custom type checking builtin for HLSL.
10476 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
10477 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10478 return true;
10479 // Allow redecl custom type checking builtin for SPIR-V.
10480 if (getTargetInfo().getTriple().isSPIROrSPIRV() &&
10481 BuiltinInfo.isTSBuiltin(FD->getBuiltinID()) &&
10482 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10483 return true;
10484 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
10485}
10486
10488 assert(ObjCConstantStringType.isNull() &&
10489 "'NSConstantString' type already set!");
10490
10491 ObjCConstantStringType = getObjCInterfaceType(Decl);
10492}
10493
10494/// Retrieve the template name that corresponds to a non-empty
10495/// lookup.
10498 UnresolvedSetIterator End) const {
10499 unsigned size = End - Begin;
10500 assert(size > 1 && "set is not overloaded!");
10501
10502 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
10503 size * sizeof(FunctionTemplateDecl*));
10504 auto *OT = new (memory) OverloadedTemplateStorage(size);
10505
10506 NamedDecl **Storage = OT->getStorage();
10507 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
10508 NamedDecl *D = *I;
10509 assert(isa<FunctionTemplateDecl>(D) ||
10513 *Storage++ = D;
10514 }
10515
10516 return TemplateName(OT);
10517}
10518
10519/// Retrieve a template name representing an unqualified-id that has been
10520/// assumed to name a template for ADL purposes.
10522 auto *OT = new (*this) AssumedTemplateStorage(Name);
10523 return TemplateName(OT);
10524}
10525
10526/// Retrieve the template name that represents a qualified
10527/// template name such as \c std::vector.
10529 bool TemplateKeyword,
10530 TemplateName Template) const {
10531 assert(Template.getKind() == TemplateName::Template ||
10533
10534 if (Template.getAsTemplateDecl()->getKind() == Decl::TemplateTemplateParm) {
10535 assert(!Qualifier && "unexpected qualified template template parameter");
10536 assert(TemplateKeyword == false);
10537 return Template;
10538 }
10539
10540 // FIXME: Canonicalization?
10541 llvm::FoldingSetNodeID ID;
10542 QualifiedTemplateName::Profile(ID, Qualifier, TemplateKeyword, Template);
10543
10544 void *InsertPos = nullptr;
10546 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
10547 if (!QTN) {
10548 QTN = new (*this, alignof(QualifiedTemplateName))
10549 QualifiedTemplateName(Qualifier, TemplateKeyword, Template);
10550 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
10551 }
10552
10553 return TemplateName(QTN);
10554}
10555
10556/// Retrieve the template name that represents a dependent
10557/// template name such as \c MetaFun::template operator+.
10560 llvm::FoldingSetNodeID ID;
10561 S.Profile(ID);
10562
10563 void *InsertPos = nullptr;
10564 if (DependentTemplateName *QTN =
10565 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos))
10566 return TemplateName(QTN);
10567
10569 new (*this, alignof(DependentTemplateName)) DependentTemplateName(S);
10570 DependentTemplateNames.InsertNode(QTN, InsertPos);
10571 return TemplateName(QTN);
10572}
10573
10575 Decl *AssociatedDecl,
10576 unsigned Index,
10578 bool Final) const {
10579 llvm::FoldingSetNodeID ID;
10580 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
10581 Index, PackIndex, Final);
10582
10583 void *insertPos = nullptr;
10585 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
10586
10587 if (!subst) {
10588 subst = new (*this) SubstTemplateTemplateParmStorage(
10589 Replacement, AssociatedDecl, Index, PackIndex, Final);
10590 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
10591 }
10592
10593 return TemplateName(subst);
10594}
10595
10598 Decl *AssociatedDecl,
10599 unsigned Index, bool Final) const {
10600 auto &Self = const_cast<ASTContext &>(*this);
10601 llvm::FoldingSetNodeID ID;
10603 AssociatedDecl, Index, Final);
10604
10605 void *InsertPos = nullptr;
10607 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
10608
10609 if (!Subst) {
10610 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
10611 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
10612 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
10613 }
10614
10615 return TemplateName(Subst);
10616}
10617
10618/// Retrieve the template name that represents a template name
10619/// deduced from a specialization.
10622 DefaultArguments DefaultArgs) const {
10623 if (!DefaultArgs)
10624 return Underlying;
10625
10626 llvm::FoldingSetNodeID ID;
10627 DeducedTemplateStorage::Profile(ID, *this, Underlying, DefaultArgs);
10628
10629 void *InsertPos = nullptr;
10631 DeducedTemplates.FindNodeOrInsertPos(ID, InsertPos);
10632 if (!DTS) {
10633 void *Mem = Allocate(sizeof(DeducedTemplateStorage) +
10634 sizeof(TemplateArgument) * DefaultArgs.Args.size(),
10635 alignof(DeducedTemplateStorage));
10636 DTS = new (Mem) DeducedTemplateStorage(Underlying, DefaultArgs);
10637 DeducedTemplates.InsertNode(DTS, InsertPos);
10638 }
10639 return TemplateName(DTS);
10640}
10641
10642/// getFromTargetType - Given one of the integer types provided by
10643/// TargetInfo, produce the corresponding type. The unsigned @p Type
10644/// is actually a value of type @c TargetInfo::IntType.
10645CanQualType ASTContext::getFromTargetType(unsigned Type) const {
10646 switch (Type) {
10647 case TargetInfo::NoInt: return {};
10650 case TargetInfo::SignedShort: return ShortTy;
10652 case TargetInfo::SignedInt: return IntTy;
10654 case TargetInfo::SignedLong: return LongTy;
10658 }
10659
10660 llvm_unreachable("Unhandled TargetInfo::IntType value");
10661}
10662
10663//===----------------------------------------------------------------------===//
10664// Type Predicates.
10665//===----------------------------------------------------------------------===//
10666
10667/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
10668/// garbage collection attribute.
10669///
10671 if (getLangOpts().getGC() == LangOptions::NonGC)
10672 return Qualifiers::GCNone;
10673
10674 assert(getLangOpts().ObjC);
10675 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
10676
10677 // Default behaviour under objective-C's gc is for ObjC pointers
10678 // (or pointers to them) be treated as though they were declared
10679 // as __strong.
10680 if (GCAttrs == Qualifiers::GCNone) {
10682 return Qualifiers::Strong;
10683 else if (Ty->isPointerType())
10685 } else {
10686 // It's not valid to set GC attributes on anything that isn't a
10687 // pointer.
10688#ifndef NDEBUG
10690 while (const auto *AT = dyn_cast<ArrayType>(CT))
10691 CT = AT->getElementType();
10692 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
10693#endif
10694 }
10695 return GCAttrs;
10696}
10697
10698//===----------------------------------------------------------------------===//
10699// Type Compatibility Testing
10700//===----------------------------------------------------------------------===//
10701
10702/// areCompatVectorTypes - Return true if the two specified vector types are
10703/// compatible.
10704static bool areCompatVectorTypes(const VectorType *LHS,
10705 const VectorType *RHS) {
10706 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10707 return LHS->getElementType() == RHS->getElementType() &&
10708 LHS->getNumElements() == RHS->getNumElements();
10709}
10710
10711/// areCompatMatrixTypes - Return true if the two specified matrix types are
10712/// compatible.
10714 const ConstantMatrixType *RHS) {
10715 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10716 return LHS->getElementType() == RHS->getElementType() &&
10717 LHS->getNumRows() == RHS->getNumRows() &&
10718 LHS->getNumColumns() == RHS->getNumColumns();
10719}
10720
10722 QualType SecondVec) {
10723 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
10724 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
10725
10726 if (hasSameUnqualifiedType(FirstVec, SecondVec))
10727 return true;
10728
10729 // Treat Neon vector types and most AltiVec vector types as if they are the
10730 // equivalent GCC vector types.
10731 const auto *First = FirstVec->castAs<VectorType>();
10732 const auto *Second = SecondVec->castAs<VectorType>();
10733 if (First->getNumElements() == Second->getNumElements() &&
10734 hasSameType(First->getElementType(), Second->getElementType()) &&
10735 First->getVectorKind() != VectorKind::AltiVecPixel &&
10736 First->getVectorKind() != VectorKind::AltiVecBool &&
10739 First->getVectorKind() != VectorKind::SveFixedLengthData &&
10740 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10743 First->getVectorKind() != VectorKind::RVVFixedLengthData &&
10745 First->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10747 First->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10749 First->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10751 First->getVectorKind() != VectorKind::RVVFixedLengthMask_4 &&
10753 return true;
10754
10755 // In OpenCL, treat half and _Float16 vector types as compatible.
10756 if (getLangOpts().OpenCL &&
10757 First->getNumElements() == Second->getNumElements()) {
10758 QualType FirstElt = First->getElementType();
10759 QualType SecondElt = Second->getElementType();
10760
10761 if ((FirstElt->isFloat16Type() && SecondElt->isHalfType()) ||
10762 (FirstElt->isHalfType() && SecondElt->isFloat16Type())) {
10763 if (First->getVectorKind() != VectorKind::AltiVecPixel &&
10764 First->getVectorKind() != VectorKind::AltiVecBool &&
10767 return true;
10768 }
10769 }
10770 return false;
10771}
10772
10778
10781 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
10782 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
10783
10784 if (!LHSOBT && !RHSOBT)
10786
10787 if (LHSOBT && RHSOBT) {
10788 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
10791 }
10792
10793 QualType LHSUnderlying = LHSOBT ? LHSOBT->desugar() : LHS;
10794 QualType RHSUnderlying = RHSOBT ? RHSOBT->desugar() : RHS;
10795
10796 if (RHSOBT && !LHSOBT) {
10797 if (LHSUnderlying->isIntegerType() && RHSUnderlying->isIntegerType())
10799 }
10800
10802}
10803
10804/// getRVVTypeSize - Return RVV vector register size.
10805static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
10806 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
10807 auto VScale = Context.getTargetInfo().getVScaleRange(
10808 Context.getLangOpts(), TargetInfo::ArmStreamingKind::NotStreaming);
10809 if (!VScale)
10810 return 0;
10811
10812 ASTContext::BuiltinVectorTypeInfo Info = Context.getBuiltinVectorTypeInfo(Ty);
10813
10814 uint64_t EltSize = Context.getTypeSize(Info.ElementType);
10815 if (Info.ElementType == Context.BoolTy)
10816 EltSize = 1;
10817
10818 uint64_t MinElts = Info.EC.getKnownMinValue();
10819 return VScale->first * MinElts * EltSize;
10820}
10821
10823 QualType SecondType) {
10824 assert(
10825 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10826 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10827 "Expected RVV builtin type and vector type!");
10828
10829 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10830 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10831 if (const auto *VT = SecondType->getAs<VectorType>()) {
10832 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10834 return FirstType->isRVVVLSBuiltinType() &&
10835 Info.ElementType == BoolTy &&
10836 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)));
10837 }
10838 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1) {
10840 return FirstType->isRVVVLSBuiltinType() &&
10841 Info.ElementType == BoolTy &&
10842 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT) * 8));
10843 }
10844 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2) {
10846 return FirstType->isRVVVLSBuiltinType() &&
10847 Info.ElementType == BoolTy &&
10848 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 4);
10849 }
10850 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10852 return FirstType->isRVVVLSBuiltinType() &&
10853 Info.ElementType == BoolTy &&
10854 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 2);
10855 }
10856 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
10857 VT->getVectorKind() == VectorKind::Generic)
10858 return FirstType->isRVVVLSBuiltinType() &&
10859 getTypeSize(SecondType) == getRVVTypeSize(*this, BT) &&
10860 hasSameType(VT->getElementType(),
10861 getBuiltinVectorTypeInfo(BT).ElementType);
10862 }
10863 }
10864 return false;
10865 };
10866
10867 return IsValidCast(FirstType, SecondType) ||
10868 IsValidCast(SecondType, FirstType);
10869}
10870
10872 QualType SecondType) {
10873 assert(
10874 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10875 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10876 "Expected RVV builtin type and vector type!");
10877
10878 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10879 const auto *BT = FirstType->getAs<BuiltinType>();
10880 if (!BT)
10881 return false;
10882
10883 if (!BT->isRVVVLSBuiltinType())
10884 return false;
10885
10886 const auto *VecTy = SecondType->getAs<VectorType>();
10887 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
10889 getLangOpts().getLaxVectorConversions();
10890
10891 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
10892 if (getTypeSize(SecondType) != getRVVTypeSize(*this, BT))
10893 return false;
10894
10895 // If -flax-vector-conversions=all is specified, the types are
10896 // certainly compatible.
10898 return true;
10899
10900 // If -flax-vector-conversions=integer is specified, the types are
10901 // compatible if the elements are integer types.
10903 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10904 FirstType->getRVVEltType(*this)->isIntegerType();
10905 }
10906
10907 return false;
10908 };
10909
10910 return IsLaxCompatible(FirstType, SecondType) ||
10911 IsLaxCompatible(SecondType, FirstType);
10912}
10913
10915 while (true) {
10916 // __strong id
10917 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
10918 if (Attr->getAttrKind() == attr::ObjCOwnership)
10919 return true;
10920
10921 Ty = Attr->getModifiedType();
10922
10923 // X *__strong (...)
10924 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
10925 Ty = Paren->getInnerType();
10926
10927 // We do not want to look through typedefs, typeof(expr),
10928 // typeof(type), or any other way that the type is somehow
10929 // abstracted.
10930 } else {
10931 return false;
10932 }
10933 }
10934}
10935
10936//===----------------------------------------------------------------------===//
10937// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
10938//===----------------------------------------------------------------------===//
10939
10940/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
10941/// inheritance hierarchy of 'rProto'.
10942bool
10944 ObjCProtocolDecl *rProto) const {
10945 if (declaresSameEntity(lProto, rProto))
10946 return true;
10947 for (auto *PI : rProto->protocols())
10948 if (ProtocolCompatibleWithProtocol(lProto, PI))
10949 return true;
10950 return false;
10951}
10952
10953/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
10954/// Class<pr1, ...>.
10956 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
10957 for (auto *lhsProto : lhs->quals()) {
10958 bool match = false;
10959 for (auto *rhsProto : rhs->quals()) {
10960 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
10961 match = true;
10962 break;
10963 }
10964 }
10965 if (!match)
10966 return false;
10967 }
10968 return true;
10969}
10970
10971/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
10972/// ObjCQualifiedIDType.
10974 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
10975 bool compare) {
10976 // Allow id<P..> and an 'id' in all cases.
10977 if (lhs->isObjCIdType() || rhs->isObjCIdType())
10978 return true;
10979
10980 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
10981 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
10983 return false;
10984
10985 if (lhs->isObjCQualifiedIdType()) {
10986 if (rhs->qual_empty()) {
10987 // If the RHS is a unqualified interface pointer "NSString*",
10988 // make sure we check the class hierarchy.
10989 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10990 for (auto *I : lhs->quals()) {
10991 // when comparing an id<P> on lhs with a static type on rhs,
10992 // see if static class implements all of id's protocols, directly or
10993 // through its super class and categories.
10994 if (!rhsID->ClassImplementsProtocol(I, true))
10995 return false;
10996 }
10997 }
10998 // If there are no qualifiers and no interface, we have an 'id'.
10999 return true;
11000 }
11001 // Both the right and left sides have qualifiers.
11002 for (auto *lhsProto : lhs->quals()) {
11003 bool match = false;
11004
11005 // when comparing an id<P> on lhs with a static type on rhs,
11006 // see if static class implements all of id's protocols, directly or
11007 // through its super class and categories.
11008 for (auto *rhsProto : rhs->quals()) {
11009 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
11010 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
11011 match = true;
11012 break;
11013 }
11014 }
11015 // If the RHS is a qualified interface pointer "NSString<P>*",
11016 // make sure we check the class hierarchy.
11017 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
11018 for (auto *I : lhs->quals()) {
11019 // when comparing an id<P> on lhs with a static type on rhs,
11020 // see if static class implements all of id's protocols, directly or
11021 // through its super class and categories.
11022 if (rhsID->ClassImplementsProtocol(I, true)) {
11023 match = true;
11024 break;
11025 }
11026 }
11027 }
11028 if (!match)
11029 return false;
11030 }
11031
11032 return true;
11033 }
11034
11035 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
11036
11037 if (lhs->getInterfaceType()) {
11038 // If both the right and left sides have qualifiers.
11039 for (auto *lhsProto : lhs->quals()) {
11040 bool match = false;
11041
11042 // when comparing an id<P> on rhs with a static type on lhs,
11043 // see if static class implements all of id's protocols, directly or
11044 // through its super class and categories.
11045 // First, lhs protocols in the qualifier list must be found, direct
11046 // or indirect in rhs's qualifier list or it is a mismatch.
11047 for (auto *rhsProto : rhs->quals()) {
11048 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
11049 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
11050 match = true;
11051 break;
11052 }
11053 }
11054 if (!match)
11055 return false;
11056 }
11057
11058 // Static class's protocols, or its super class or category protocols
11059 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
11060 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
11061 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
11062 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
11063 // This is rather dubious but matches gcc's behavior. If lhs has
11064 // no type qualifier and its class has no static protocol(s)
11065 // assume that it is mismatch.
11066 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
11067 return false;
11068 for (auto *lhsProto : LHSInheritedProtocols) {
11069 bool match = false;
11070 for (auto *rhsProto : rhs->quals()) {
11071 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
11072 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
11073 match = true;
11074 break;
11075 }
11076 }
11077 if (!match)
11078 return false;
11079 }
11080 }
11081 return true;
11082 }
11083 return false;
11084}
11085
11086/// canAssignObjCInterfaces - Return true if the two interface types are
11087/// compatible for assignment from RHS to LHS. This handles validation of any
11088/// protocol qualifiers on the LHS or RHS.
11090 const ObjCObjectPointerType *RHSOPT) {
11091 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11092 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11093
11094 // If either type represents the built-in 'id' type, return true.
11095 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
11096 return true;
11097
11098 // Function object that propagates a successful result or handles
11099 // __kindof types.
11100 auto finish = [&](bool succeeded) -> bool {
11101 if (succeeded)
11102 return true;
11103
11104 if (!RHS->isKindOfType())
11105 return false;
11106
11107 // Strip off __kindof and protocol qualifiers, then check whether
11108 // we can assign the other way.
11110 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
11111 };
11112
11113 // Casts from or to id<P> are allowed when the other side has compatible
11114 // protocols.
11115 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
11116 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
11117 }
11118
11119 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
11120 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
11121 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
11122 }
11123
11124 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
11125 if (LHS->isObjCClass() && RHS->isObjCClass()) {
11126 return true;
11127 }
11128
11129 // If we have 2 user-defined types, fall into that path.
11130 if (LHS->getInterface() && RHS->getInterface()) {
11131 return finish(canAssignObjCInterfaces(LHS, RHS));
11132 }
11133
11134 return false;
11135}
11136
11137/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
11138/// for providing type-safety for objective-c pointers used to pass/return
11139/// arguments in block literals. When passed as arguments, passing 'A*' where
11140/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
11141/// not OK. For the return type, the opposite is not OK.
11143 const ObjCObjectPointerType *LHSOPT,
11144 const ObjCObjectPointerType *RHSOPT,
11145 bool BlockReturnType) {
11146
11147 // Function object that propagates a successful result or handles
11148 // __kindof types.
11149 auto finish = [&](bool succeeded) -> bool {
11150 if (succeeded)
11151 return true;
11152
11153 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
11154 if (!Expected->isKindOfType())
11155 return false;
11156
11157 // Strip off __kindof and protocol qualifiers, then check whether
11158 // we can assign the other way.
11160 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
11161 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
11162 BlockReturnType);
11163 };
11164
11165 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
11166 return true;
11167
11168 if (LHSOPT->isObjCBuiltinType()) {
11169 return finish(RHSOPT->isObjCBuiltinType() ||
11170 RHSOPT->isObjCQualifiedIdType());
11171 }
11172
11173 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
11174 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
11175 // Use for block parameters previous type checking for compatibility.
11176 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
11177 // Or corrected type checking as in non-compat mode.
11178 (!BlockReturnType &&
11179 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
11180 else
11182 (BlockReturnType ? LHSOPT : RHSOPT),
11183 (BlockReturnType ? RHSOPT : LHSOPT), false));
11184 }
11185
11186 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
11187 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
11188 if (LHS && RHS) { // We have 2 user-defined types.
11189 if (LHS != RHS) {
11190 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
11191 return finish(BlockReturnType);
11192 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
11193 return finish(!BlockReturnType);
11194 }
11195 else
11196 return true;
11197 }
11198 return false;
11199}
11200
11201/// Comparison routine for Objective-C protocols to be used with
11202/// llvm::array_pod_sort.
11204 ObjCProtocolDecl * const *rhs) {
11205 return (*lhs)->getName().compare((*rhs)->getName());
11206}
11207
11208/// getIntersectionOfProtocols - This routine finds the intersection of set
11209/// of protocols inherited from two distinct objective-c pointer objects with
11210/// the given common base.
11211/// It is used to build composite qualifier list of the composite type of
11212/// the conditional expression involving two objective-c pointer objects.
11213static
11215 const ObjCInterfaceDecl *CommonBase,
11216 const ObjCObjectPointerType *LHSOPT,
11217 const ObjCObjectPointerType *RHSOPT,
11218 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
11219
11220 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11221 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11222 assert(LHS->getInterface() && "LHS must have an interface base");
11223 assert(RHS->getInterface() && "RHS must have an interface base");
11224
11225 // Add all of the protocols for the LHS.
11227
11228 // Start with the protocol qualifiers.
11229 for (auto *proto : LHS->quals()) {
11230 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
11231 }
11232
11233 // Also add the protocols associated with the LHS interface.
11234 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
11235
11236 // Add all of the protocols for the RHS.
11238
11239 // Start with the protocol qualifiers.
11240 for (auto *proto : RHS->quals()) {
11241 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
11242 }
11243
11244 // Also add the protocols associated with the RHS interface.
11245 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
11246
11247 // Compute the intersection of the collected protocol sets.
11248 for (auto *proto : LHSProtocolSet) {
11249 if (RHSProtocolSet.count(proto))
11250 IntersectionSet.push_back(proto);
11251 }
11252
11253 // Compute the set of protocols that is implied by either the common type or
11254 // the protocols within the intersection.
11256 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
11257
11258 // Remove any implied protocols from the list of inherited protocols.
11259 if (!ImpliedProtocols.empty()) {
11260 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
11261 return ImpliedProtocols.contains(proto);
11262 });
11263 }
11264
11265 // Sort the remaining protocols by name.
11266 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
11268}
11269
11270/// Determine whether the first type is a subtype of the second.
11272 QualType rhs) {
11273 // Common case: two object pointers.
11274 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
11275 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
11276 if (lhsOPT && rhsOPT)
11277 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
11278
11279 // Two block pointers.
11280 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
11281 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
11282 if (lhsBlock && rhsBlock)
11283 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
11284
11285 // If either is an unqualified 'id' and the other is a block, it's
11286 // acceptable.
11287 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
11288 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
11289 return true;
11290
11291 return false;
11292}
11293
11294// Check that the given Objective-C type argument lists are equivalent.
11296 const ObjCInterfaceDecl *iface,
11297 ArrayRef<QualType> lhsArgs,
11298 ArrayRef<QualType> rhsArgs,
11299 bool stripKindOf) {
11300 if (lhsArgs.size() != rhsArgs.size())
11301 return false;
11302
11303 ObjCTypeParamList *typeParams = iface->getTypeParamList();
11304 if (!typeParams)
11305 return false;
11306
11307 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
11308 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
11309 continue;
11310
11311 switch (typeParams->begin()[i]->getVariance()) {
11313 if (!stripKindOf ||
11314 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
11315 rhsArgs[i].stripObjCKindOfType(ctx))) {
11316 return false;
11317 }
11318 break;
11319
11321 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
11322 return false;
11323 break;
11324
11326 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
11327 return false;
11328 break;
11329 }
11330 }
11331
11332 return true;
11333}
11334
11336 const ObjCObjectPointerType *Lptr,
11337 const ObjCObjectPointerType *Rptr) {
11338 const ObjCObjectType *LHS = Lptr->getObjectType();
11339 const ObjCObjectType *RHS = Rptr->getObjectType();
11340 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
11341 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
11342
11343 if (!LDecl || !RDecl)
11344 return {};
11345
11346 // When either LHS or RHS is a kindof type, we should return a kindof type.
11347 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
11348 // kindof(A).
11349 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
11350
11351 // Follow the left-hand side up the class hierarchy until we either hit a
11352 // root or find the RHS. Record the ancestors in case we don't find it.
11353 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
11354 LHSAncestors;
11355 while (true) {
11356 // Record this ancestor. We'll need this if the common type isn't in the
11357 // path from the LHS to the root.
11358 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
11359
11360 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
11361 // Get the type arguments.
11362 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
11363 bool anyChanges = false;
11364 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11365 // Both have type arguments, compare them.
11366 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11367 LHS->getTypeArgs(), RHS->getTypeArgs(),
11368 /*stripKindOf=*/true))
11369 return {};
11370 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11371 // If only one has type arguments, the result will not have type
11372 // arguments.
11373 LHSTypeArgs = {};
11374 anyChanges = true;
11375 }
11376
11377 // Compute the intersection of protocols.
11379 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
11380 Protocols);
11381 if (!Protocols.empty())
11382 anyChanges = true;
11383
11384 // If anything in the LHS will have changed, build a new result type.
11385 // If we need to return a kindof type but LHS is not a kindof type, we
11386 // build a new result type.
11387 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
11388 QualType Result = getObjCInterfaceType(LHS->getInterface());
11389 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
11390 anyKindOf || LHS->isKindOfType());
11392 }
11393
11394 return getObjCObjectPointerType(QualType(LHS, 0));
11395 }
11396
11397 // Find the superclass.
11398 QualType LHSSuperType = LHS->getSuperClassType();
11399 if (LHSSuperType.isNull())
11400 break;
11401
11402 LHS = LHSSuperType->castAs<ObjCObjectType>();
11403 }
11404
11405 // We didn't find anything by following the LHS to its root; now check
11406 // the RHS against the cached set of ancestors.
11407 while (true) {
11408 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
11409 if (KnownLHS != LHSAncestors.end()) {
11410 LHS = KnownLHS->second;
11411
11412 // Get the type arguments.
11413 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
11414 bool anyChanges = false;
11415 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11416 // Both have type arguments, compare them.
11417 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11418 LHS->getTypeArgs(), RHS->getTypeArgs(),
11419 /*stripKindOf=*/true))
11420 return {};
11421 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11422 // If only one has type arguments, the result will not have type
11423 // arguments.
11424 RHSTypeArgs = {};
11425 anyChanges = true;
11426 }
11427
11428 // Compute the intersection of protocols.
11430 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
11431 Protocols);
11432 if (!Protocols.empty())
11433 anyChanges = true;
11434
11435 // If we need to return a kindof type but RHS is not a kindof type, we
11436 // build a new result type.
11437 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
11438 QualType Result = getObjCInterfaceType(RHS->getInterface());
11439 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
11440 anyKindOf || RHS->isKindOfType());
11442 }
11443
11444 return getObjCObjectPointerType(QualType(RHS, 0));
11445 }
11446
11447 // Find the superclass of the RHS.
11448 QualType RHSSuperType = RHS->getSuperClassType();
11449 if (RHSSuperType.isNull())
11450 break;
11451
11452 RHS = RHSSuperType->castAs<ObjCObjectType>();
11453 }
11454
11455 return {};
11456}
11457
11459 const ObjCObjectType *RHS) {
11460 assert(LHS->getInterface() && "LHS is not an interface type");
11461 assert(RHS->getInterface() && "RHS is not an interface type");
11462
11463 // Verify that the base decls are compatible: the RHS must be a subclass of
11464 // the LHS.
11465 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
11466 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
11467 if (!IsSuperClass)
11468 return false;
11469
11470 // If the LHS has protocol qualifiers, determine whether all of them are
11471 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
11472 // LHS).
11473 if (LHS->getNumProtocols() > 0) {
11474 // OK if conversion of LHS to SuperClass results in narrowing of types
11475 // ; i.e., SuperClass may implement at least one of the protocols
11476 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
11477 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
11478 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
11479 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
11480 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
11481 // qualifiers.
11482 for (auto *RHSPI : RHS->quals())
11483 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
11484 // If there is no protocols associated with RHS, it is not a match.
11485 if (SuperClassInheritedProtocols.empty())
11486 return false;
11487
11488 for (const auto *LHSProto : LHS->quals()) {
11489 bool SuperImplementsProtocol = false;
11490 for (auto *SuperClassProto : SuperClassInheritedProtocols)
11491 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
11492 SuperImplementsProtocol = true;
11493 break;
11494 }
11495 if (!SuperImplementsProtocol)
11496 return false;
11497 }
11498 }
11499
11500 // If the LHS is specialized, we may need to check type arguments.
11501 if (LHS->isSpecialized()) {
11502 // Follow the superclass chain until we've matched the LHS class in the
11503 // hierarchy. This substitutes type arguments through.
11504 const ObjCObjectType *RHSSuper = RHS;
11505 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
11506 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
11507
11508 // If the RHS is specializd, compare type arguments.
11509 if (RHSSuper->isSpecialized() &&
11510 !sameObjCTypeArgs(*this, LHS->getInterface(),
11511 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
11512 /*stripKindOf=*/true)) {
11513 return false;
11514 }
11515 }
11516
11517 return true;
11518}
11519
11521 // get the "pointed to" types
11522 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
11523 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
11524
11525 if (!LHSOPT || !RHSOPT)
11526 return false;
11527
11528 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
11529 canAssignObjCInterfaces(RHSOPT, LHSOPT);
11530}
11531
11534 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
11535 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
11536}
11537
11538/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
11539/// both shall have the identically qualified version of a compatible type.
11540/// C99 6.2.7p1: Two types have compatible types if their types are the
11541/// same. See 6.7.[2,3,5] for additional rules.
11543 bool CompareUnqualified) {
11544 if (getLangOpts().CPlusPlus)
11545 return hasSameType(LHS, RHS);
11546
11547 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
11548}
11549
11551 return typesAreCompatible(LHS, RHS);
11552}
11553
11555 return !mergeTypes(LHS, RHS, true).isNull();
11556}
11557
11558/// mergeTransparentUnionType - if T is a transparent union type and a member
11559/// of T is compatible with SubType, return the merged type, else return
11560/// QualType()
11562 bool OfBlockPointer,
11563 bool Unqualified) {
11564 if (const RecordType *UT = T->getAsUnionType()) {
11565 RecordDecl *UD = UT->getDecl()->getMostRecentDecl();
11566 if (UD->hasAttr<TransparentUnionAttr>()) {
11567 for (const auto *I : UD->fields()) {
11568 QualType ET = I->getType().getUnqualifiedType();
11569 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
11570 if (!MT.isNull())
11571 return MT;
11572 }
11573 }
11574 }
11575
11576 return {};
11577}
11578
11579/// mergeFunctionParameterTypes - merge two types which appear as function
11580/// parameter types
11582 bool OfBlockPointer,
11583 bool Unqualified) {
11584 // GNU extension: two types are compatible if they appear as a function
11585 // argument, one of the types is a transparent union type and the other
11586 // type is compatible with a union member
11587 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
11588 Unqualified);
11589 if (!lmerge.isNull())
11590 return lmerge;
11591
11592 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
11593 Unqualified);
11594 if (!rmerge.isNull())
11595 return rmerge;
11596
11597 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
11598}
11599
11601 bool OfBlockPointer, bool Unqualified,
11602 bool AllowCXX,
11603 bool IsConditionalOperator) {
11604 const auto *lbase = lhs->castAs<FunctionType>();
11605 const auto *rbase = rhs->castAs<FunctionType>();
11606 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
11607 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
11608 bool allLTypes = true;
11609 bool allRTypes = true;
11610
11611 // Check return type
11612 QualType retType;
11613 if (OfBlockPointer) {
11614 QualType RHS = rbase->getReturnType();
11615 QualType LHS = lbase->getReturnType();
11616 bool UnqualifiedResult = Unqualified;
11617 if (!UnqualifiedResult)
11618 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
11619 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
11620 }
11621 else
11622 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
11623 Unqualified);
11624 if (retType.isNull())
11625 return {};
11626
11627 if (Unqualified)
11628 retType = retType.getUnqualifiedType();
11629
11630 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
11631 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
11632 if (Unqualified) {
11633 LRetType = LRetType.getUnqualifiedType();
11634 RRetType = RRetType.getUnqualifiedType();
11635 }
11636
11637 if (getCanonicalType(retType) != LRetType)
11638 allLTypes = false;
11639 if (getCanonicalType(retType) != RRetType)
11640 allRTypes = false;
11641
11642 // FIXME: double check this
11643 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
11644 // rbase->getRegParmAttr() != 0 &&
11645 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
11646 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
11647 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
11648
11649 // Compatible functions must have compatible calling conventions
11650 if (lbaseInfo.getCC() != rbaseInfo.getCC())
11651 return {};
11652
11653 // Regparm is part of the calling convention.
11654 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
11655 return {};
11656 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
11657 return {};
11658
11659 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
11660 return {};
11661 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
11662 return {};
11663 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
11664 return {};
11665
11666 // When merging declarations, it's common for supplemental information like
11667 // attributes to only be present in one of the declarations, and we generally
11668 // want type merging to preserve the union of information. So a merged
11669 // function type should be noreturn if it was noreturn in *either* operand
11670 // type.
11671 //
11672 // But for the conditional operator, this is backwards. The result of the
11673 // operator could be either operand, and its type should conservatively
11674 // reflect that. So a function type in a composite type is noreturn only
11675 // if it's noreturn in *both* operand types.
11676 //
11677 // Arguably, noreturn is a kind of subtype, and the conditional operator
11678 // ought to produce the most specific common supertype of its operand types.
11679 // That would differ from this rule in contravariant positions. However,
11680 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
11681 // as a practical matter, it would only affect C code that does abstraction of
11682 // higher-order functions (taking noreturn callbacks!), which is uncommon to
11683 // say the least. So we use the simpler rule.
11684 bool NoReturn = IsConditionalOperator
11685 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
11686 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
11687 if (lbaseInfo.getNoReturn() != NoReturn)
11688 allLTypes = false;
11689 if (rbaseInfo.getNoReturn() != NoReturn)
11690 allRTypes = false;
11691
11692 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
11693
11694 std::optional<FunctionEffectSet> MergedFX;
11695
11696 if (lproto && rproto) { // two C99 style function prototypes
11697 assert((AllowCXX ||
11698 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
11699 "C++ shouldn't be here");
11700 // Compatible functions must have the same number of parameters
11701 if (lproto->getNumParams() != rproto->getNumParams())
11702 return {};
11703
11704 // Variadic and non-variadic functions aren't compatible
11705 if (lproto->isVariadic() != rproto->isVariadic())
11706 return {};
11707
11708 if (lproto->getMethodQuals() != rproto->getMethodQuals())
11709 return {};
11710
11711 // Function protos with different 'cfi_salt' values aren't compatible.
11712 if (lproto->getExtraAttributeInfo().CFISalt !=
11713 rproto->getExtraAttributeInfo().CFISalt)
11714 return {};
11715
11716 // Function effects are handled similarly to noreturn, see above.
11717 FunctionEffectsRef LHSFX = lproto->getFunctionEffects();
11718 FunctionEffectsRef RHSFX = rproto->getFunctionEffects();
11719 if (LHSFX != RHSFX) {
11720 if (IsConditionalOperator)
11721 MergedFX = FunctionEffectSet::getIntersection(LHSFX, RHSFX);
11722 else {
11724 MergedFX = FunctionEffectSet::getUnion(LHSFX, RHSFX, Errs);
11725 // Here we're discarding a possible error due to conflicts in the effect
11726 // sets. But we're not in a context where we can report it. The
11727 // operation does however guarantee maintenance of invariants.
11728 }
11729 if (*MergedFX != LHSFX)
11730 allLTypes = false;
11731 if (*MergedFX != RHSFX)
11732 allRTypes = false;
11733 }
11734
11736 bool canUseLeft, canUseRight;
11737 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
11738 newParamInfos))
11739 return {};
11740
11741 if (!canUseLeft)
11742 allLTypes = false;
11743 if (!canUseRight)
11744 allRTypes = false;
11745
11746 // Check parameter type compatibility
11748 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
11749 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
11750 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
11752 lParamType, rParamType, OfBlockPointer, Unqualified);
11753 if (paramType.isNull())
11754 return {};
11755
11756 if (Unqualified)
11757 paramType = paramType.getUnqualifiedType();
11758
11759 types.push_back(paramType);
11760 if (Unqualified) {
11761 lParamType = lParamType.getUnqualifiedType();
11762 rParamType = rParamType.getUnqualifiedType();
11763 }
11764
11765 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
11766 allLTypes = false;
11767 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
11768 allRTypes = false;
11769 }
11770
11771 if (allLTypes) return lhs;
11772 if (allRTypes) return rhs;
11773
11774 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
11775 EPI.ExtInfo = einfo;
11776 EPI.ExtParameterInfos =
11777 newParamInfos.empty() ? nullptr : newParamInfos.data();
11778 if (MergedFX)
11779 EPI.FunctionEffects = *MergedFX;
11780 return getFunctionType(retType, types, EPI);
11781 }
11782
11783 if (lproto) allRTypes = false;
11784 if (rproto) allLTypes = false;
11785
11786 const FunctionProtoType *proto = lproto ? lproto : rproto;
11787 if (proto) {
11788 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
11789 if (proto->isVariadic())
11790 return {};
11791 // Check that the types are compatible with the types that
11792 // would result from default argument promotions (C99 6.7.5.3p15).
11793 // The only types actually affected are promotable integer
11794 // types and floats, which would be passed as a different
11795 // type depending on whether the prototype is visible.
11796 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
11797 QualType paramTy = proto->getParamType(i);
11798
11799 // Look at the converted type of enum types, since that is the type used
11800 // to pass enum values.
11801 if (const auto *ED = paramTy->getAsEnumDecl()) {
11802 paramTy = ED->getIntegerType();
11803 if (paramTy.isNull())
11804 return {};
11805 }
11806
11807 if (isPromotableIntegerType(paramTy) ||
11808 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
11809 return {};
11810 }
11811
11812 if (allLTypes) return lhs;
11813 if (allRTypes) return rhs;
11814
11816 EPI.ExtInfo = einfo;
11817 if (MergedFX)
11818 EPI.FunctionEffects = *MergedFX;
11819 return getFunctionType(retType, proto->getParamTypes(), EPI);
11820 }
11821
11822 if (allLTypes) return lhs;
11823 if (allRTypes) return rhs;
11824 return getFunctionNoProtoType(retType, einfo);
11825}
11826
11827/// Given that we have an enum type and a non-enum type, try to merge them.
11828static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
11829 QualType other, bool isBlockReturnType) {
11830 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
11831 // a signed integer type, or an unsigned integer type.
11832 // Compatibility is based on the underlying type, not the promotion
11833 // type.
11834 QualType underlyingType =
11835 ET->getDecl()->getDefinitionOrSelf()->getIntegerType();
11836 if (underlyingType.isNull())
11837 return {};
11838 if (Context.hasSameType(underlyingType, other))
11839 return other;
11840
11841 // In block return types, we're more permissive and accept any
11842 // integral type of the same size.
11843 if (isBlockReturnType && other->isIntegerType() &&
11844 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
11845 return other;
11846
11847 return {};
11848}
11849
11851 // C17 and earlier and C++ disallow two tag definitions within the same TU
11852 // from being compatible.
11853 if (LangOpts.CPlusPlus || !LangOpts.C23)
11854 return {};
11855
11856 // Nameless tags are comparable only within outer definitions. At the top
11857 // level they are not comparable.
11858 const TagDecl *LTagD = LHS->castAsTagDecl(), *RTagD = RHS->castAsTagDecl();
11859 if (!LTagD->getIdentifier() || !RTagD->getIdentifier())
11860 return {};
11861
11862 // C23, on the other hand, requires the members to be "the same enough", so
11863 // we use a structural equivalence check.
11866 getLangOpts(), *this, *this, NonEquivalentDecls,
11867 StructuralEquivalenceKind::Default, /*StrictTypeSpelling=*/false,
11868 /*Complain=*/false, /*ErrorOnTagTypeMismatch=*/true);
11869 return Ctx.IsEquivalent(LHS, RHS) ? LHS : QualType{};
11870}
11871
11873 QualType LHS, QualType RHS, bool OfBlockPointer, bool Unqualified,
11874 bool BlockReturnType, bool IsConditionalOperator) {
11875 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
11876 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
11877
11878 if (!LHSOBT && !RHSOBT)
11879 return std::nullopt;
11880
11881 if (LHSOBT) {
11882 if (RHSOBT) {
11883 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
11884 return QualType();
11885
11886 QualType MergedUnderlying = mergeTypes(
11887 LHSOBT->getUnderlyingType(), RHSOBT->getUnderlyingType(),
11888 OfBlockPointer, Unqualified, BlockReturnType, IsConditionalOperator);
11889
11890 if (MergedUnderlying.isNull())
11891 return QualType();
11892
11893 if (getCanonicalType(LHSOBT) == getCanonicalType(RHSOBT)) {
11894 if (LHSOBT->getUnderlyingType() == RHSOBT->getUnderlyingType())
11895 return getCommonSugaredType(LHS, RHS);
11897 LHSOBT->getBehaviorKind(),
11898 getCanonicalType(LHSOBT->getUnderlyingType()));
11899 }
11900
11901 // For different underlying types that successfully merge, wrap the
11902 // merged underlying type with the common overflow behavior
11903 return getOverflowBehaviorType(LHSOBT->getBehaviorKind(),
11904 MergedUnderlying);
11905 }
11906 return mergeTypes(LHSOBT->getUnderlyingType(), RHS, OfBlockPointer,
11907 Unqualified, BlockReturnType, IsConditionalOperator);
11908 }
11909
11910 return mergeTypes(LHS, RHSOBT->getUnderlyingType(), OfBlockPointer,
11911 Unqualified, BlockReturnType, IsConditionalOperator);
11912}
11913
11914QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
11915 bool Unqualified, bool BlockReturnType,
11916 bool IsConditionalOperator) {
11917 // For C++ we will not reach this code with reference types (see below),
11918 // for OpenMP variant call overloading we might.
11919 //
11920 // C++ [expr]: If an expression initially has the type "reference to T", the
11921 // type is adjusted to "T" prior to any further analysis, the expression
11922 // designates the object or function denoted by the reference, and the
11923 // expression is an lvalue unless the reference is an rvalue reference and
11924 // the expression is a function call (possibly inside parentheses).
11925 auto *LHSRefTy = LHS->getAs<ReferenceType>();
11926 auto *RHSRefTy = RHS->getAs<ReferenceType>();
11927 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
11928 LHS->getTypeClass() == RHS->getTypeClass())
11929 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
11930 OfBlockPointer, Unqualified, BlockReturnType);
11931 if (LHSRefTy || RHSRefTy)
11932 return {};
11933
11934 if (std::optional<QualType> MergedOBT =
11935 tryMergeOverflowBehaviorTypes(LHS, RHS, OfBlockPointer, Unqualified,
11936 BlockReturnType, IsConditionalOperator))
11937 return *MergedOBT;
11938
11939 if (Unqualified) {
11940 LHS = LHS.getUnqualifiedType();
11941 RHS = RHS.getUnqualifiedType();
11942 }
11943
11944 QualType LHSCan = getCanonicalType(LHS),
11945 RHSCan = getCanonicalType(RHS);
11946
11947 // If two types are identical, they are compatible.
11948 if (LHSCan == RHSCan)
11949 return LHS;
11950
11951 // If the qualifiers are different, the types aren't compatible... mostly.
11952 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11953 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11954 if (LQuals != RQuals) {
11955 // If any of these qualifiers are different, we have a type
11956 // mismatch.
11957 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11958 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
11959 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
11960 !LQuals.getPointerAuth().isEquivalent(RQuals.getPointerAuth()) ||
11961 LQuals.hasUnaligned() != RQuals.hasUnaligned())
11962 return {};
11963
11964 // Exactly one GC qualifier difference is allowed: __strong is
11965 // okay if the other type has no GC qualifier but is an Objective
11966 // C object pointer (i.e. implicitly strong by default). We fix
11967 // this by pretending that the unqualified type was actually
11968 // qualified __strong.
11969 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11970 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11971 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11972
11973 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11974 return {};
11975
11976 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
11978 }
11979 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
11981 }
11982 return {};
11983 }
11984
11985 // Okay, qualifiers are equal.
11986
11987 Type::TypeClass LHSClass = LHSCan->getTypeClass();
11988 Type::TypeClass RHSClass = RHSCan->getTypeClass();
11989
11990 // We want to consider the two function types to be the same for these
11991 // comparisons, just force one to the other.
11992 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
11993 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
11994
11995 // Same as above for arrays
11996 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
11997 LHSClass = Type::ConstantArray;
11998 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
11999 RHSClass = Type::ConstantArray;
12000
12001 // ObjCInterfaces are just specialized ObjCObjects.
12002 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
12003 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
12004
12005 // Canonicalize ExtVector -> Vector.
12006 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
12007 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
12008
12009 // If the canonical type classes don't match.
12010 if (LHSClass != RHSClass) {
12011 // Note that we only have special rules for turning block enum
12012 // returns into block int returns, not vice-versa.
12013 if (const auto *ETy = LHS->getAsCanonical<EnumType>()) {
12014 return mergeEnumWithInteger(*this, ETy, RHS, false);
12015 }
12016 if (const EnumType *ETy = RHS->getAsCanonical<EnumType>()) {
12017 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
12018 }
12019 // allow block pointer type to match an 'id' type.
12020 if (OfBlockPointer && !BlockReturnType) {
12021 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
12022 return LHS;
12023 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
12024 return RHS;
12025 }
12026 // Allow __auto_type to match anything; it merges to the type with more
12027 // information.
12028 if (const auto *AT = LHS->getAs<AutoType>()) {
12029 if (!AT->isDeduced() && AT->isGNUAutoType())
12030 return RHS;
12031 }
12032 if (const auto *AT = RHS->getAs<AutoType>()) {
12033 if (!AT->isDeduced() && AT->isGNUAutoType())
12034 return LHS;
12035 }
12036 return {};
12037 }
12038
12039 // The canonical type classes match.
12040 switch (LHSClass) {
12041#define TYPE(Class, Base)
12042#define ABSTRACT_TYPE(Class, Base)
12043#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
12044#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
12045#define DEPENDENT_TYPE(Class, Base) case Type::Class:
12046#include "clang/AST/TypeNodes.inc"
12047 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
12048
12049 case Type::Auto:
12050 case Type::DeducedTemplateSpecialization:
12051 case Type::LValueReference:
12052 case Type::RValueReference:
12053 case Type::MemberPointer:
12054 llvm_unreachable("C++ should never be in mergeTypes");
12055
12056 case Type::ObjCInterface:
12057 case Type::IncompleteArray:
12058 case Type::VariableArray:
12059 case Type::FunctionProto:
12060 case Type::ExtVector:
12061 case Type::OverflowBehavior:
12062 llvm_unreachable("Types are eliminated above");
12063
12064 case Type::Pointer:
12065 {
12066 // Merge two pointer types, while trying to preserve typedef info
12067 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
12068 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
12069 if (Unqualified) {
12070 LHSPointee = LHSPointee.getUnqualifiedType();
12071 RHSPointee = RHSPointee.getUnqualifiedType();
12072 }
12073 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
12074 Unqualified);
12075 if (ResultType.isNull())
12076 return {};
12077 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
12078 return LHS;
12079 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
12080 return RHS;
12081 return getPointerType(ResultType);
12082 }
12083 case Type::BlockPointer:
12084 {
12085 // Merge two block pointer types, while trying to preserve typedef info
12086 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
12087 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
12088 if (Unqualified) {
12089 LHSPointee = LHSPointee.getUnqualifiedType();
12090 RHSPointee = RHSPointee.getUnqualifiedType();
12091 }
12092 if (getLangOpts().OpenCL) {
12093 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
12094 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
12095 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
12096 // 6.12.5) thus the following check is asymmetric.
12097 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual, *this))
12098 return {};
12099 LHSPteeQual.removeAddressSpace();
12100 RHSPteeQual.removeAddressSpace();
12101 LHSPointee =
12102 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
12103 RHSPointee =
12104 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
12105 }
12106 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
12107 Unqualified);
12108 if (ResultType.isNull())
12109 return {};
12110 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
12111 return LHS;
12112 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
12113 return RHS;
12114 return getBlockPointerType(ResultType);
12115 }
12116 case Type::Atomic:
12117 {
12118 // Merge two pointer types, while trying to preserve typedef info
12119 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
12120 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
12121 if (Unqualified) {
12122 LHSValue = LHSValue.getUnqualifiedType();
12123 RHSValue = RHSValue.getUnqualifiedType();
12124 }
12125 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
12126 Unqualified);
12127 if (ResultType.isNull())
12128 return {};
12129 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
12130 return LHS;
12131 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
12132 return RHS;
12133 return getAtomicType(ResultType);
12134 }
12135 case Type::ConstantArray:
12136 {
12137 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
12138 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
12139 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
12140 return {};
12141
12142 QualType LHSElem = getAsArrayType(LHS)->getElementType();
12143 QualType RHSElem = getAsArrayType(RHS)->getElementType();
12144 if (Unqualified) {
12145 LHSElem = LHSElem.getUnqualifiedType();
12146 RHSElem = RHSElem.getUnqualifiedType();
12147 }
12148
12149 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
12150 if (ResultType.isNull())
12151 return {};
12152
12153 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
12154 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
12155
12156 // If either side is a variable array, and both are complete, check whether
12157 // the current dimension is definite.
12158 if (LVAT || RVAT) {
12159 auto SizeFetch = [this](const VariableArrayType* VAT,
12160 const ConstantArrayType* CAT)
12161 -> std::pair<bool,llvm::APInt> {
12162 if (VAT) {
12163 std::optional<llvm::APSInt> TheInt;
12164 Expr *E = VAT->getSizeExpr();
12165 if (E && (TheInt = E->getIntegerConstantExpr(*this)))
12166 return std::make_pair(true, *TheInt);
12167 return std::make_pair(false, llvm::APSInt());
12168 }
12169 if (CAT)
12170 return std::make_pair(true, CAT->getSize());
12171 return std::make_pair(false, llvm::APInt());
12172 };
12173
12174 bool HaveLSize, HaveRSize;
12175 llvm::APInt LSize, RSize;
12176 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
12177 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
12178 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
12179 return {}; // Definite, but unequal, array dimension
12180 }
12181
12182 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
12183 return LHS;
12184 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
12185 return RHS;
12186 if (LCAT)
12187 return getConstantArrayType(ResultType, LCAT->getSize(),
12188 LCAT->getSizeExpr(), ArraySizeModifier(), 0);
12189 if (RCAT)
12190 return getConstantArrayType(ResultType, RCAT->getSize(),
12191 RCAT->getSizeExpr(), ArraySizeModifier(), 0);
12192 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
12193 return LHS;
12194 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
12195 return RHS;
12196 if (LVAT) {
12197 // FIXME: This isn't correct! But tricky to implement because
12198 // the array's size has to be the size of LHS, but the type
12199 // has to be different.
12200 return LHS;
12201 }
12202 if (RVAT) {
12203 // FIXME: This isn't correct! But tricky to implement because
12204 // the array's size has to be the size of RHS, but the type
12205 // has to be different.
12206 return RHS;
12207 }
12208 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
12209 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
12210 return getIncompleteArrayType(ResultType, ArraySizeModifier(), 0);
12211 }
12212 case Type::FunctionNoProto:
12213 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified,
12214 /*AllowCXX=*/false, IsConditionalOperator);
12215 case Type::Record:
12216 case Type::Enum:
12217 return mergeTagDefinitions(LHS, RHS);
12218 case Type::Builtin:
12219 // Only exactly equal builtin types are compatible, which is tested above.
12220 return {};
12221 case Type::Complex:
12222 // Distinct complex types are incompatible.
12223 return {};
12224 case Type::Vector:
12225 // FIXME: The merged type should be an ExtVector!
12226 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
12227 RHSCan->castAs<VectorType>()))
12228 return LHS;
12229 return {};
12230 case Type::ConstantMatrix:
12232 RHSCan->castAs<ConstantMatrixType>()))
12233 return LHS;
12234 return {};
12235 case Type::ObjCObject: {
12236 // Check if the types are assignment compatible.
12237 // FIXME: This should be type compatibility, e.g. whether
12238 // "LHS x; RHS x;" at global scope is legal.
12240 RHS->castAs<ObjCObjectType>()))
12241 return LHS;
12242 return {};
12243 }
12244 case Type::ObjCObjectPointer:
12245 if (OfBlockPointer) {
12248 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
12249 return LHS;
12250 return {};
12251 }
12254 return LHS;
12255 return {};
12256 case Type::Pipe:
12257 assert(LHS != RHS &&
12258 "Equivalent pipe types should have already been handled!");
12259 return {};
12260 case Type::ArrayParameter:
12261 assert(LHS != RHS &&
12262 "Equivalent ArrayParameter types should have already been handled!");
12263 return {};
12264 case Type::BitInt: {
12265 // Merge two bit-precise int types, while trying to preserve typedef info.
12266 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
12267 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
12268 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
12269 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
12270
12271 // Like unsigned/int, shouldn't have a type if they don't match.
12272 if (LHSUnsigned != RHSUnsigned)
12273 return {};
12274
12275 if (LHSBits != RHSBits)
12276 return {};
12277 return LHS;
12278 }
12279 case Type::HLSLAttributedResource: {
12280 const HLSLAttributedResourceType *LHSTy =
12281 LHS->castAs<HLSLAttributedResourceType>();
12282 const HLSLAttributedResourceType *RHSTy =
12283 RHS->castAs<HLSLAttributedResourceType>();
12284 assert(LHSTy->getWrappedType() == RHSTy->getWrappedType() &&
12285 LHSTy->getWrappedType()->isHLSLResourceType() &&
12286 "HLSLAttributedResourceType should always wrap __hlsl_resource_t");
12287
12288 if (LHSTy->getAttrs() == RHSTy->getAttrs() &&
12289 LHSTy->getContainedType() == RHSTy->getContainedType())
12290 return LHS;
12291 return {};
12292 }
12293 case Type::HLSLInlineSpirv:
12294 const HLSLInlineSpirvType *LHSTy = LHS->castAs<HLSLInlineSpirvType>();
12295 const HLSLInlineSpirvType *RHSTy = RHS->castAs<HLSLInlineSpirvType>();
12296
12297 if (LHSTy->getOpcode() == RHSTy->getOpcode() &&
12298 LHSTy->getSize() == RHSTy->getSize() &&
12299 LHSTy->getAlignment() == RHSTy->getAlignment()) {
12300 for (size_t I = 0; I < LHSTy->getOperands().size(); I++)
12301 if (LHSTy->getOperands()[I] != RHSTy->getOperands()[I])
12302 return {};
12303
12304 return LHS;
12305 }
12306 return {};
12307 }
12308
12309 llvm_unreachable("Invalid Type::Class!");
12310}
12311
12313 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
12314 bool &CanUseFirst, bool &CanUseSecond,
12316 assert(NewParamInfos.empty() && "param info list not empty");
12317 CanUseFirst = CanUseSecond = true;
12318 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
12319 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
12320
12321 // Fast path: if the first type doesn't have ext parameter infos,
12322 // we match if and only if the second type also doesn't have them.
12323 if (!FirstHasInfo && !SecondHasInfo)
12324 return true;
12325
12326 bool NeedParamInfo = false;
12327 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
12328 : SecondFnType->getExtParameterInfos().size();
12329
12330 for (size_t I = 0; I < E; ++I) {
12331 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
12332 if (FirstHasInfo)
12333 FirstParam = FirstFnType->getExtParameterInfo(I);
12334 if (SecondHasInfo)
12335 SecondParam = SecondFnType->getExtParameterInfo(I);
12336
12337 // Cannot merge unless everything except the noescape flag matches.
12338 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
12339 return false;
12340
12341 bool FirstNoEscape = FirstParam.isNoEscape();
12342 bool SecondNoEscape = SecondParam.isNoEscape();
12343 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
12344 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
12345 if (NewParamInfos.back().getOpaqueValue())
12346 NeedParamInfo = true;
12347 if (FirstNoEscape != IsNoEscape)
12348 CanUseFirst = false;
12349 if (SecondNoEscape != IsNoEscape)
12350 CanUseSecond = false;
12351 }
12352
12353 if (!NeedParamInfo)
12354 NewParamInfos.clear();
12355
12356 return true;
12357}
12358
12360 if (auto It = ObjCLayouts.find(D); It != ObjCLayouts.end()) {
12361 It->second = nullptr;
12362 for (auto *SubClass : ObjCSubClasses.lookup(D))
12363 ResetObjCLayout(SubClass);
12364 }
12365}
12366
12367/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
12368/// 'RHS' attributes and returns the merged version; including for function
12369/// return types.
12371 QualType LHSCan = getCanonicalType(LHS),
12372 RHSCan = getCanonicalType(RHS);
12373 // If two types are identical, they are compatible.
12374 if (LHSCan == RHSCan)
12375 return LHS;
12376 if (RHSCan->isFunctionType()) {
12377 if (!LHSCan->isFunctionType())
12378 return {};
12379 QualType OldReturnType =
12380 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
12381 QualType NewReturnType =
12382 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
12383 QualType ResReturnType =
12384 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
12385 if (ResReturnType.isNull())
12386 return {};
12387 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
12388 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
12389 // In either case, use OldReturnType to build the new function type.
12390 const auto *F = LHS->castAs<FunctionType>();
12391 if (const auto *FPT = cast<FunctionProtoType>(F)) {
12392 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12393 EPI.ExtInfo = getFunctionExtInfo(LHS);
12394 QualType ResultType =
12395 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
12396 return ResultType;
12397 }
12398 }
12399 return {};
12400 }
12401
12402 // If the qualifiers are different, the types can still be merged.
12403 Qualifiers LQuals = LHSCan.getLocalQualifiers();
12404 Qualifiers RQuals = RHSCan.getLocalQualifiers();
12405 if (LQuals != RQuals) {
12406 // If any of these qualifiers are different, we have a type mismatch.
12407 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
12408 LQuals.getAddressSpace() != RQuals.getAddressSpace())
12409 return {};
12410
12411 // Exactly one GC qualifier difference is allowed: __strong is
12412 // okay if the other type has no GC qualifier but is an Objective
12413 // C object pointer (i.e. implicitly strong by default). We fix
12414 // this by pretending that the unqualified type was actually
12415 // qualified __strong.
12416 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
12417 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
12418 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
12419
12420 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
12421 return {};
12422
12423 if (GC_L == Qualifiers::Strong)
12424 return LHS;
12425 if (GC_R == Qualifiers::Strong)
12426 return RHS;
12427 return {};
12428 }
12429
12430 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
12431 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12432 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12433 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
12434 if (ResQT == LHSBaseQT)
12435 return LHS;
12436 if (ResQT == RHSBaseQT)
12437 return RHS;
12438 }
12439 return {};
12440}
12441
12442//===----------------------------------------------------------------------===//
12443// Integer Predicates
12444//===----------------------------------------------------------------------===//
12445
12447 if (const auto *ED = T->getAsEnumDecl())
12448 T = ED->getIntegerType();
12449 if (T->isBooleanType())
12450 return 1;
12451 if (const auto *EIT = T->getAs<BitIntType>())
12452 return EIT->getNumBits();
12453 // For builtin types, just use the standard type sizing method
12454 return (unsigned)getTypeSize(T);
12455}
12456
12458 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12459 T->isFixedPointType()) &&
12460 "Unexpected type");
12461
12462 // Turn <4 x signed int> -> <4 x unsigned int>
12463 if (const auto *VTy = T->getAs<VectorType>())
12464 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
12465 VTy->getNumElements(), VTy->getVectorKind());
12466
12467 // For _BitInt, return an unsigned _BitInt with same width.
12468 if (const auto *EITy = T->getAs<BitIntType>())
12469 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
12470
12471 // For the overflow behavior types, construct a new unsigned variant
12472 if (const auto *OBT = T->getAs<OverflowBehaviorType>())
12474 OBT->getBehaviorKind(),
12475 getCorrespondingUnsignedType(OBT->getUnderlyingType()));
12476
12477 // For enums, get the underlying integer type of the enum, and let the general
12478 // integer type signchanging code handle it.
12479 if (const auto *ED = T->getAsEnumDecl())
12480 T = ED->getIntegerType();
12481
12482 switch (T->castAs<BuiltinType>()->getKind()) {
12483 case BuiltinType::Char_U:
12484 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
12485 case BuiltinType::Char_S:
12486 case BuiltinType::SChar:
12487 case BuiltinType::Char8:
12488 return UnsignedCharTy;
12489 case BuiltinType::Short:
12490 return UnsignedShortTy;
12491 case BuiltinType::Int:
12492 return UnsignedIntTy;
12493 case BuiltinType::Long:
12494 return UnsignedLongTy;
12495 case BuiltinType::LongLong:
12496 return UnsignedLongLongTy;
12497 case BuiltinType::Int128:
12498 return UnsignedInt128Ty;
12499 // wchar_t is special. It is either signed or not, but when it's signed,
12500 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
12501 // version of its underlying type instead.
12502 case BuiltinType::WChar_S:
12503 return getUnsignedWCharType();
12504
12505 case BuiltinType::ShortAccum:
12506 return UnsignedShortAccumTy;
12507 case BuiltinType::Accum:
12508 return UnsignedAccumTy;
12509 case BuiltinType::LongAccum:
12510 return UnsignedLongAccumTy;
12511 case BuiltinType::SatShortAccum:
12513 case BuiltinType::SatAccum:
12514 return SatUnsignedAccumTy;
12515 case BuiltinType::SatLongAccum:
12517 case BuiltinType::ShortFract:
12518 return UnsignedShortFractTy;
12519 case BuiltinType::Fract:
12520 return UnsignedFractTy;
12521 case BuiltinType::LongFract:
12522 return UnsignedLongFractTy;
12523 case BuiltinType::SatShortFract:
12525 case BuiltinType::SatFract:
12526 return SatUnsignedFractTy;
12527 case BuiltinType::SatLongFract:
12529 default:
12530 assert((T->hasUnsignedIntegerRepresentation() ||
12531 T->isUnsignedFixedPointType()) &&
12532 "Unexpected signed integer or fixed point type");
12533 return T;
12534 }
12535}
12536
12538 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12539 T->isFixedPointType()) &&
12540 "Unexpected type");
12541
12542 // Turn <4 x unsigned int> -> <4 x signed int>
12543 if (const auto *VTy = T->getAs<VectorType>())
12544 return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
12545 VTy->getNumElements(), VTy->getVectorKind());
12546
12547 // For _BitInt, return a signed _BitInt with same width.
12548 if (const auto *EITy = T->getAs<BitIntType>())
12549 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
12550
12551 // For enums, get the underlying integer type of the enum, and let the general
12552 // integer type signchanging code handle it.
12553 if (const auto *ED = T->getAsEnumDecl())
12554 T = ED->getIntegerType();
12555
12556 switch (T->castAs<BuiltinType>()->getKind()) {
12557 case BuiltinType::Char_S:
12558 // Plain `char` is mapped to `signed char` even if it's already signed
12559 case BuiltinType::Char_U:
12560 case BuiltinType::UChar:
12561 case BuiltinType::Char8:
12562 return SignedCharTy;
12563 case BuiltinType::UShort:
12564 return ShortTy;
12565 case BuiltinType::UInt:
12566 return IntTy;
12567 case BuiltinType::ULong:
12568 return LongTy;
12569 case BuiltinType::ULongLong:
12570 return LongLongTy;
12571 case BuiltinType::UInt128:
12572 return Int128Ty;
12573 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
12574 // there's no matching "signed wchar_t". Therefore we return the signed
12575 // version of its underlying type instead.
12576 case BuiltinType::WChar_U:
12577 return getSignedWCharType();
12578
12579 case BuiltinType::UShortAccum:
12580 return ShortAccumTy;
12581 case BuiltinType::UAccum:
12582 return AccumTy;
12583 case BuiltinType::ULongAccum:
12584 return LongAccumTy;
12585 case BuiltinType::SatUShortAccum:
12586 return SatShortAccumTy;
12587 case BuiltinType::SatUAccum:
12588 return SatAccumTy;
12589 case BuiltinType::SatULongAccum:
12590 return SatLongAccumTy;
12591 case BuiltinType::UShortFract:
12592 return ShortFractTy;
12593 case BuiltinType::UFract:
12594 return FractTy;
12595 case BuiltinType::ULongFract:
12596 return LongFractTy;
12597 case BuiltinType::SatUShortFract:
12598 return SatShortFractTy;
12599 case BuiltinType::SatUFract:
12600 return SatFractTy;
12601 case BuiltinType::SatULongFract:
12602 return SatLongFractTy;
12603 default:
12604 assert(
12605 (T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
12606 "Unexpected signed integer or fixed point type");
12607 return T;
12608 }
12609}
12610
12612
12615
12616//===----------------------------------------------------------------------===//
12617// Builtin Type Computation
12618//===----------------------------------------------------------------------===//
12619
12620/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
12621/// pointer over the consumed characters. This returns the resultant type. If
12622/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
12623/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
12624/// a vector of "i*".
12625///
12626/// RequiresICE is filled in on return to indicate whether the value is required
12627/// to be an Integer Constant Expression.
12628static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
12630 bool &RequiresICE,
12631 bool AllowTypeModifiers) {
12632 // Modifiers.
12633 int HowLong = 0;
12634 bool Signed = false, Unsigned = false;
12635 bool IsChar = false, IsShort = false;
12636 RequiresICE = false;
12637
12638 // Read the prefixed modifiers first.
12639 bool Done = false;
12640 #ifndef NDEBUG
12641 bool IsSpecial = false;
12642 #endif
12643 while (!Done) {
12644 switch (*Str++) {
12645 default: Done = true; --Str; break;
12646 case 'I':
12647 RequiresICE = true;
12648 break;
12649 case 'S':
12650 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
12651 assert(!Signed && "Can't use 'S' modifier multiple times!");
12652 Signed = true;
12653 break;
12654 case 'U':
12655 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
12656 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
12657 Unsigned = true;
12658 break;
12659 case 'B':
12660 // This modifier represents int8 type (byte-width).
12661 assert(!IsSpecial &&
12662 "Can't use two 'N', 'W', 'Z', 'O', 'B', or 'T' modifiers!");
12663 assert(HowLong == 0 && "Can't use both 'L' and 'B' modifiers!");
12664#ifndef NDEBUG
12665 IsSpecial = true;
12666#endif
12667 IsChar = true;
12668 break;
12669 case 'T':
12670 // This modifier represents int16 type (short-width).
12671 assert(!IsSpecial &&
12672 "Can't use two 'N', 'W', 'Z', 'O', 'B', or 'T' modifiers!");
12673 assert(HowLong == 0 && "Can't use both 'L' and 'T' modifiers!");
12674#ifndef NDEBUG
12675 IsSpecial = true;
12676#endif
12677 IsShort = true;
12678 break;
12679 case 'L':
12680 assert(!IsSpecial &&
12681 "Can't use 'L' with 'W', 'N', 'Z', 'O', 'B', or 'T' modifiers");
12682 assert(HowLong <= 2 && "Can't have LLLL modifier");
12683 ++HowLong;
12684 break;
12685 case 'N':
12686 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
12687 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12688 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
12689 #ifndef NDEBUG
12690 IsSpecial = true;
12691 #endif
12692 if (Context.getTargetInfo().getLongWidth() == 32)
12693 ++HowLong;
12694 break;
12695 case 'W':
12696 // This modifier represents int64 type.
12697 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12698 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
12699 #ifndef NDEBUG
12700 IsSpecial = true;
12701 #endif
12702 switch (Context.getTargetInfo().getInt64Type()) {
12703 default:
12704 llvm_unreachable("Unexpected integer type");
12706 HowLong = 1;
12707 break;
12709 HowLong = 2;
12710 break;
12711 }
12712 break;
12713 case 'Z':
12714 // This modifier represents int32 type.
12715 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12716 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
12717 #ifndef NDEBUG
12718 IsSpecial = true;
12719 #endif
12720 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
12721 default:
12722 llvm_unreachable("Unexpected integer type");
12724 HowLong = 0;
12725 break;
12727 HowLong = 1;
12728 break;
12730 HowLong = 2;
12731 break;
12732 }
12733 break;
12734 case 'O':
12735 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12736 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
12737 #ifndef NDEBUG
12738 IsSpecial = true;
12739 #endif
12740 if (Context.getLangOpts().OpenCL)
12741 HowLong = 1;
12742 else
12743 HowLong = 2;
12744 break;
12745 }
12746 }
12747
12748 QualType Type;
12749
12750 // Read the base type.
12751 switch (*Str++) {
12752 default:
12753 llvm_unreachable("Unknown builtin type letter!");
12754 case 'x':
12755 assert(HowLong == 0 && !Signed && !Unsigned &&
12756 "Bad modifiers used with 'x'!");
12757 Type = Context.Float16Ty;
12758 break;
12759 case 'y':
12760 assert(HowLong == 0 && !Signed && !Unsigned &&
12761 "Bad modifiers used with 'y'!");
12762 Type = Context.BFloat16Ty;
12763 break;
12764 case 'v':
12765 assert(HowLong == 0 && !Signed && !Unsigned &&
12766 "Bad modifiers used with 'v'!");
12767 Type = Context.VoidTy;
12768 break;
12769 case 'h':
12770 assert(HowLong == 0 && !Signed && !Unsigned &&
12771 "Bad modifiers used with 'h'!");
12772 Type = Context.HalfTy;
12773 break;
12774 case 'f':
12775 assert(HowLong == 0 && !Signed && !Unsigned &&
12776 "Bad modifiers used with 'f'!");
12777 Type = Context.FloatTy;
12778 break;
12779 case 'd':
12780 assert(HowLong < 3 && !Signed && !Unsigned &&
12781 "Bad modifiers used with 'd'!");
12782 if (HowLong == 1)
12783 Type = Context.LongDoubleTy;
12784 else if (HowLong == 2)
12785 Type = Context.Float128Ty;
12786 else
12787 Type = Context.DoubleTy;
12788 break;
12789 case 's':
12790 assert(HowLong == 0 && "Bad modifiers used with 's'!");
12791 if (Unsigned)
12792 Type = Context.UnsignedShortTy;
12793 else
12794 Type = Context.ShortTy;
12795 break;
12796 case 'i':
12797 if (IsChar)
12798 Type = Unsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
12799 else if (IsShort)
12800 Type = Unsigned ? Context.UnsignedShortTy : Context.ShortTy;
12801 else if (HowLong == 3)
12802 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
12803 else if (HowLong == 2)
12804 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
12805 else if (HowLong == 1)
12806 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
12807 else
12808 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
12809 break;
12810 case 'c':
12811 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
12812 if (Signed)
12813 Type = Context.SignedCharTy;
12814 else if (Unsigned)
12815 Type = Context.UnsignedCharTy;
12816 else
12817 Type = Context.CharTy;
12818 break;
12819 case 'b': // boolean
12820 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
12821 Type = Context.BoolTy;
12822 break;
12823 case 'z': // size_t.
12824 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
12825 Type = Context.getSizeType();
12826 break;
12827 case 'w': // wchar_t.
12828 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
12829 Type = Context.getWideCharType();
12830 break;
12831 case 'F':
12832 Type = Context.getCFConstantStringType();
12833 break;
12834 case 'G':
12835 Type = Context.getObjCIdType();
12836 break;
12837 case 'H':
12838 Type = Context.getObjCSelType();
12839 break;
12840 case 'M':
12841 Type = Context.getObjCSuperType();
12842 break;
12843 case 'a':
12844 Type = Context.getBuiltinVaListType();
12845 assert(!Type.isNull() && "builtin va list type not initialized!");
12846 break;
12847 case 'A':
12848 // This is a "reference" to a va_list; however, what exactly
12849 // this means depends on how va_list is defined. There are two
12850 // different kinds of va_list: ones passed by value, and ones
12851 // passed by reference. An example of a by-value va_list is
12852 // x86, where va_list is a char*. An example of by-ref va_list
12853 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
12854 // we want this argument to be a char*&; for x86-64, we want
12855 // it to be a __va_list_tag*.
12856 Type = Context.getBuiltinVaListType();
12857 assert(!Type.isNull() && "builtin va list type not initialized!");
12858 if (Type->isArrayType())
12859 Type = Context.getArrayDecayedType(Type);
12860 else
12861 Type = Context.getLValueReferenceType(Type);
12862 break;
12863 case 'q': {
12864 char *End;
12865 unsigned NumElements = strtoul(Str, &End, 10);
12866 assert(End != Str && "Missing vector size");
12867 Str = End;
12868
12869 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12870 RequiresICE, false);
12871 assert(!RequiresICE && "Can't require vector ICE");
12872
12873 Type = Context.getScalableVectorType(ElementType, NumElements);
12874 break;
12875 }
12876 case 'Q': {
12877 switch (*Str++) {
12878 case 'a': {
12879 Type = Context.SveCountTy;
12880 break;
12881 }
12882 case 'b': {
12883 Type = Context.AMDGPUBufferRsrcTy;
12884 break;
12885 }
12886 case 'c': {
12887 Type = Context.AMDGPUFeaturePredicateTy;
12888 break;
12889 }
12890 case 't': {
12891 Type = Context.AMDGPUTextureTy;
12892 break;
12893 }
12894 case 'r': {
12895 Type = Context.HLSLResourceTy;
12896 break;
12897 }
12898 default:
12899 llvm_unreachable("Unexpected target builtin type");
12900 }
12901 break;
12902 }
12903 case 'V': {
12904 char *End;
12905 unsigned NumElements = strtoul(Str, &End, 10);
12906 assert(End != Str && "Missing vector size");
12907 Str = End;
12908
12909 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12910 RequiresICE, false);
12911 assert(!RequiresICE && "Can't require vector ICE");
12912
12913 // TODO: No way to make AltiVec vectors in builtins yet.
12914 Type = Context.getVectorType(ElementType, NumElements, VectorKind::Generic);
12915 break;
12916 }
12917 case 'E': {
12918 char *End;
12919
12920 unsigned NumElements = strtoul(Str, &End, 10);
12921 assert(End != Str && "Missing vector size");
12922
12923 Str = End;
12924
12925 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12926 false);
12927 Type = Context.getExtVectorType(ElementType, NumElements);
12928 break;
12929 }
12930 case 'X': {
12931 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12932 false);
12933 assert(!RequiresICE && "Can't require complex ICE");
12934 Type = Context.getComplexType(ElementType);
12935 break;
12936 }
12937 case 'Y':
12938 Type = Context.getPointerDiffType();
12939 break;
12940 case 'P':
12941 Type = Context.getFILEType();
12942 if (Type.isNull()) {
12944 return {};
12945 }
12946 break;
12947 case 'J':
12948 if (Signed)
12949 Type = Context.getsigjmp_bufType();
12950 else
12951 Type = Context.getjmp_bufType();
12952
12953 if (Type.isNull()) {
12955 return {};
12956 }
12957 break;
12958 case 'K':
12959 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
12960 Type = Context.getucontext_tType();
12961
12962 if (Type.isNull()) {
12964 return {};
12965 }
12966 break;
12967 case 'p':
12968 Type = Context.getProcessIDType();
12969 break;
12970 case 'm':
12971 Type = Context.MFloat8Ty;
12972 break;
12973 }
12974
12975 // If there are modifiers and if we're allowed to parse them, go for it.
12976 Done = !AllowTypeModifiers;
12977 while (!Done) {
12978 switch (char c = *Str++) {
12979 default: Done = true; --Str; break;
12980 case '*':
12981 case '&': {
12982 // Both pointers and references can have their pointee types
12983 // qualified with an address space.
12984 char *End;
12985 unsigned AddrSpace = strtoul(Str, &End, 10);
12986 if (End != Str) {
12987 // Note AddrSpace == 0 is not the same as an unspecified address space.
12988 Type = Context.getAddrSpaceQualType(
12989 Type,
12990 Context.getLangASForBuiltinAddressSpace(AddrSpace));
12991 Str = End;
12992 }
12993 if (c == '*')
12994 Type = Context.getPointerType(Type);
12995 else
12996 Type = Context.getLValueReferenceType(Type);
12997 break;
12998 }
12999 // FIXME: There's no way to have a built-in with an rvalue ref arg.
13000 case 'C':
13001 Type = Type.withConst();
13002 break;
13003 case 'D':
13004 Type = Context.getVolatileType(Type);
13005 break;
13006 case 'R':
13007 Type = Type.withRestrict();
13008 break;
13009 }
13010 }
13011
13012 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
13013 "Integer constant 'I' type must be an integer");
13014
13015 return Type;
13016}
13017
13018// On some targets such as PowerPC, some of the builtins are defined with custom
13019// type descriptors for target-dependent types. These descriptors are decoded in
13020// other functions, but it may be useful to be able to fall back to default
13021// descriptor decoding to define builtins mixing target-dependent and target-
13022// independent types. This function allows decoding one type descriptor with
13023// default decoding.
13024QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
13025 GetBuiltinTypeError &Error, bool &RequireICE,
13026 bool AllowTypeModifiers) const {
13027 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
13028}
13029
13030/// GetBuiltinType - Return the type for the specified builtin.
13033 unsigned *IntegerConstantArgs) const {
13034 const char *TypeStr = BuiltinInfo.getTypeString(Id);
13035 if (TypeStr[0] == '\0') {
13037 return {};
13038 }
13039
13040 SmallVector<QualType, 8> ArgTypes;
13041
13042 bool RequiresICE = false;
13043 Error = GE_None;
13044 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
13045 RequiresICE, true);
13046 if (Error != GE_None)
13047 return {};
13048
13049 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
13050
13051 while (TypeStr[0] && TypeStr[0] != '.') {
13052 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
13053 if (Error != GE_None)
13054 return {};
13055
13056 // If this argument is required to be an IntegerConstantExpression and the
13057 // caller cares, fill in the bitmask we return.
13058 if (RequiresICE && IntegerConstantArgs)
13059 *IntegerConstantArgs |= 1 << ArgTypes.size();
13060
13061 // Do array -> pointer decay. The builtin should use the decayed type.
13062 if (Ty->isArrayType())
13063 Ty = getArrayDecayedType(Ty);
13064
13065 ArgTypes.push_back(Ty);
13066 }
13067
13068 if (Id == Builtin::BI__GetExceptionInfo)
13069 return {};
13070
13071 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
13072 "'.' should only occur at end of builtin type list!");
13073
13074 bool Variadic = (TypeStr[0] == '.');
13075
13076 FunctionType::ExtInfo EI(Target->getDefaultCallingConv());
13077 if (BuiltinInfo.isNoReturn(Id))
13078 EI = EI.withNoReturn(true);
13079
13080 // We really shouldn't be making a no-proto type here.
13081 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
13082 return getFunctionNoProtoType(ResType, EI);
13083
13085 EPI.ExtInfo = EI;
13086 EPI.Variadic = Variadic;
13087 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
13088 EPI.ExceptionSpec.Type =
13090
13091 return getFunctionType(ResType, ArgTypes, EPI);
13092}
13093
13095 const FunctionDecl *FD) {
13096 if (!FD->isExternallyVisible())
13097 return GVA_Internal;
13098
13099 // Non-user-provided functions get emitted as weak definitions with every
13100 // use, no matter whether they've been explicitly instantiated etc.
13101 if (!FD->isUserProvided())
13102 return GVA_DiscardableODR;
13103
13105 switch (FD->getTemplateSpecializationKind()) {
13106 case TSK_Undeclared:
13109 break;
13110
13112 return GVA_StrongODR;
13113
13114 // C++11 [temp.explicit]p10:
13115 // [ Note: The intent is that an inline function that is the subject of
13116 // an explicit instantiation declaration will still be implicitly
13117 // instantiated when used so that the body can be considered for
13118 // inlining, but that no out-of-line copy of the inline function would be
13119 // generated in the translation unit. -- end note ]
13122
13125 break;
13126 }
13127
13128 if (!FD->isInlined())
13129 return External;
13130
13131 if ((!Context.getLangOpts().CPlusPlus &&
13132 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13133 !FD->hasAttr<DLLExportAttr>()) ||
13134 FD->hasAttr<GNUInlineAttr>()) {
13135 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
13136
13137 // GNU or C99 inline semantics. Determine whether this symbol should be
13138 // externally visible.
13139 if (auto *Def = FD->getDefinition();
13141 return External;
13142
13143 // C99 inline semantics, where the symbol is not externally visible.
13145 }
13146
13147 // Functions specified with extern and inline in -fms-compatibility mode
13148 // forcibly get emitted. While the body of the function cannot be later
13149 // replaced, the function definition cannot be discarded.
13150 if (FD->isMSExternInline())
13151 return GVA_StrongODR;
13152
13153 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13155 cast<CXXConstructorDecl>(FD)->isInheritingConstructor() &&
13156 !FD->hasAttr<DLLExportAttr>()) {
13157 // Both Clang and MSVC implement inherited constructors as forwarding
13158 // thunks that delegate to the base constructor. Keep non-dllexport
13159 // inheriting constructor thunks internal since they are not needed
13160 // outside the translation unit.
13161 //
13162 // dllexport inherited constructors are exempted so they are externally
13163 // visible, matching MSVC's export behavior. Inherited constructors
13164 // whose parameters prevent ABI-compatible forwarding (e.g. callee-
13165 // cleanup types) are excluded from export in Sema to avoid silent
13166 // runtime mismatches.
13167 return GVA_Internal;
13168 }
13169
13170 return GVA_DiscardableODR;
13171}
13172
13174 const Decl *D, GVALinkage L) {
13175 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
13176 // dllexport/dllimport on inline functions.
13177 if (D->hasAttr<DLLImportAttr>()) {
13178 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
13180 } else if (D->hasAttr<DLLExportAttr>()) {
13181 if (L == GVA_DiscardableODR)
13182 return GVA_StrongODR;
13183 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
13184 // Device-side functions with __global__ attribute must always be
13185 // visible externally so they can be launched from host.
13186 if (D->hasAttr<CUDAGlobalAttr>() &&
13187 (L == GVA_DiscardableODR || L == GVA_Internal))
13188 return GVA_StrongODR;
13189 // Single source offloading languages like CUDA/HIP need to be able to
13190 // access static device variables from host code of the same compilation
13191 // unit. This is done by externalizing the static variable with a shared
13192 // name between the host and device compilation which is the same for the
13193 // same compilation unit whereas different among different compilation
13194 // units.
13195 if (Context.shouldExternalize(D))
13196 return GVA_StrongExternal;
13197 }
13198 return L;
13199}
13200
13201/// Adjust the GVALinkage for a declaration based on what an external AST source
13202/// knows about whether there can be other definitions of this declaration.
13203static GVALinkage
13205 GVALinkage L) {
13206 ExternalASTSource *Source = Ctx.getExternalSource();
13207 if (!Source)
13208 return L;
13209
13210 switch (Source->hasExternalDefinitions(D)) {
13212 // Other translation units rely on us to provide the definition.
13213 if (L == GVA_DiscardableODR)
13214 return GVA_StrongODR;
13215 break;
13216
13219
13221 break;
13222 }
13223 return L;
13224}
13225
13231
13233 const VarDecl *VD) {
13234 // As an extension for interactive REPLs, make sure constant variables are
13235 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
13236 // marking them as internal.
13237 if (Context.getLangOpts().CPlusPlus &&
13238 Context.getLangOpts().IncrementalExtensions &&
13239 VD->getType().isConstQualified() &&
13240 !VD->getType().isVolatileQualified() && !VD->isInline() &&
13242 return GVA_DiscardableODR;
13243
13244 if (!VD->isExternallyVisible())
13245 return GVA_Internal;
13246
13247 if (VD->isStaticLocal()) {
13248 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
13249 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
13250 LexicalContext = LexicalContext->getLexicalParent();
13251
13252 // ObjC Blocks can create local variables that don't have a FunctionDecl
13253 // LexicalContext.
13254 if (!LexicalContext)
13255 return GVA_DiscardableODR;
13256
13257 // Otherwise, let the static local variable inherit its linkage from the
13258 // nearest enclosing function.
13259 auto StaticLocalLinkage =
13260 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
13261
13262 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
13263 // be emitted in any object with references to the symbol for the object it
13264 // contains, whether inline or out-of-line."
13265 // Similar behavior is observed with MSVC. An alternative ABI could use
13266 // StrongODR/AvailableExternally to match the function, but none are
13267 // known/supported currently.
13268 if (StaticLocalLinkage == GVA_StrongODR ||
13269 StaticLocalLinkage == GVA_AvailableExternally)
13270 return GVA_DiscardableODR;
13271 return StaticLocalLinkage;
13272 }
13273
13274 // MSVC treats in-class initialized static data members as definitions.
13275 // By giving them non-strong linkage, out-of-line definitions won't
13276 // cause link errors.
13277 if (Context.isMSStaticDataMemberInlineDefinition(VD))
13278 return GVA_DiscardableODR;
13279
13280 // Most non-template variables have strong linkage; inline variables are
13281 // linkonce_odr or (occasionally, for compatibility) weak_odr.
13282 GVALinkage StrongLinkage;
13283 switch (Context.getInlineVariableDefinitionKind(VD)) {
13285 StrongLinkage = GVA_StrongExternal;
13286 break;
13289 StrongLinkage = GVA_DiscardableODR;
13290 break;
13292 StrongLinkage = GVA_StrongODR;
13293 break;
13294 }
13295
13296 switch (VD->getTemplateSpecializationKind()) {
13297 case TSK_Undeclared:
13298 return StrongLinkage;
13299
13301 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13302 VD->isStaticDataMember()
13304 : StrongLinkage;
13305
13307 return GVA_StrongODR;
13308
13311
13313 return GVA_DiscardableODR;
13314 }
13315
13316 llvm_unreachable("Invalid Linkage!");
13317}
13318
13324
13326 if (const auto *VD = dyn_cast<VarDecl>(D)) {
13327 if (!VD->isFileVarDecl())
13328 return false;
13329 // Global named register variables (GNU extension) are never emitted.
13330 if (VD->getStorageClass() == SC_Register)
13331 return false;
13332 if (VD->getDescribedVarTemplate() ||
13334 return false;
13335 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13336 // We never need to emit an uninstantiated function template.
13337 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13338 return false;
13339 } else if (isa<PragmaCommentDecl>(D))
13340 return true;
13342 return true;
13343 else if (isa<OMPRequiresDecl>(D))
13344 return true;
13345 else if (isa<OMPThreadPrivateDecl>(D))
13346 return !D->getDeclContext()->isDependentContext();
13347 else if (isa<OMPAllocateDecl>(D))
13348 return !D->getDeclContext()->isDependentContext();
13350 return !D->getDeclContext()->isDependentContext();
13351 else if (isa<ImportDecl>(D))
13352 return true;
13353 else
13354 return false;
13355
13356 // If this is a member of a class template, we do not need to emit it.
13358 return false;
13359
13360 // Weak references don't produce any output by themselves.
13361 if (D->hasAttr<WeakRefAttr>())
13362 return false;
13363
13364 // SYCL device compilation requires that functions defined with the
13365 // sycl_kernel_entry_point or sycl_external attributes be emitted. All
13366 // other entities are emitted only if they are used by a function
13367 // defined with one of those attributes.
13368 if (LangOpts.SYCLIsDevice)
13369 return isa<FunctionDecl>(D) && (D->hasAttr<SYCLKernelEntryPointAttr>() ||
13370 D->hasAttr<SYCLExternalAttr>());
13371
13372 // Aliases and used decls are required.
13373 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
13374 return true;
13375
13376 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13377 // Forward declarations aren't required.
13378 if (!FD->doesThisDeclarationHaveABody())
13379 return FD->doesDeclarationForceExternallyVisibleDefinition();
13380
13381 // Constructors and destructors are required.
13382 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
13383 return true;
13384
13385 // The key function for a class is required. This rule only comes
13386 // into play when inline functions can be key functions, though.
13387 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13388 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13389 const CXXRecordDecl *RD = MD->getParent();
13390 if (MD->isOutOfLine() && RD->isDynamicClass()) {
13391 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
13392 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
13393 return true;
13394 }
13395 }
13396 }
13397
13399
13400 // static, static inline, always_inline, and extern inline functions can
13401 // always be deferred. Normal inline functions can be deferred in C99/C++.
13402 // Implicit template instantiations can also be deferred in C++.
13404 }
13405
13406 const auto *VD = cast<VarDecl>(D);
13407 assert(VD->isFileVarDecl() && "Expected file scoped var");
13408
13409 // If the decl is marked as `declare target to`, it should be emitted for the
13410 // host and for the device.
13411 if (LangOpts.OpenMP &&
13412 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
13413 return true;
13414
13415 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
13417 return false;
13418
13419 if (VD->shouldEmitInExternalSource())
13420 return false;
13421
13422 // Variables that can be needed in other TUs are required.
13425 return true;
13426
13427 // We never need to emit a variable that is available in another TU.
13429 return false;
13430
13431 // Variables that have destruction with side-effects are required.
13432 if (VD->needsDestruction(*this))
13433 return true;
13434
13435 // Variables that have initialization with side-effects are required.
13436 if (VD->hasInitWithSideEffects())
13437 return true;
13438
13439 // Likewise, variables with tuple-like bindings are required if their
13440 // bindings have side-effects.
13441 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) {
13442 for (const auto *BD : DD->flat_bindings())
13443 if (const auto *BindingVD = BD->getHoldingVar())
13444 if (DeclMustBeEmitted(BindingVD))
13445 return true;
13446 }
13447
13448 return false;
13449}
13450
13452 const FunctionDecl *FD,
13453 llvm::function_ref<void(FunctionDecl *)> Pred) const {
13454 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
13455 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
13456 FD = FD->getMostRecentDecl();
13457 // FIXME: The order of traversal here matters and depends on the order of
13458 // lookup results, which happens to be (mostly) oldest-to-newest, but we
13459 // shouldn't rely on that.
13460 for (auto *CurDecl :
13462 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
13463 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
13464 SeenDecls.insert(CurFD).second) {
13465 Pred(CurFD);
13466 }
13467 }
13468}
13469
13471 bool IsCXXMethod) const {
13472 // Pass through to the C++ ABI object
13473 if (IsCXXMethod)
13474 return ABI->getDefaultMethodCallConv(IsVariadic);
13475
13476 switch (LangOpts.getDefaultCallingConv()) {
13478 break;
13480 return CC_C;
13482 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
13483 return CC_X86FastCall;
13484 break;
13486 if (!IsVariadic)
13487 return CC_X86StdCall;
13488 break;
13490 // __vectorcall cannot be applied to variadic functions.
13491 if (!IsVariadic)
13492 return CC_X86VectorCall;
13493 break;
13495 // __regcall cannot be applied to variadic functions.
13496 if (!IsVariadic)
13497 return CC_X86RegCall;
13498 break;
13500 if (!IsVariadic)
13501 return CC_M68kRTD;
13502 break;
13503 }
13504 return Target->getDefaultCallingConv();
13505}
13506
13508 // Pass through to the C++ ABI object
13509 return ABI->isNearlyEmpty(RD);
13510}
13511
13513 if (!VTContext) {
13514 auto ABI = Target->getCXXABI();
13515 if (ABI.isMicrosoft())
13516 VTContext.reset(new MicrosoftVTableContext(*this));
13517 else {
13518 VTContext.reset(new ItaniumVTableContext(*this));
13519 }
13520 }
13521 return VTContext.get();
13522}
13523
13525 if (!T)
13526 T = Target;
13527 switch (T->getCXXABI().getKind()) {
13528 case TargetCXXABI::AppleARM64:
13529 case TargetCXXABI::Fuchsia:
13530 case TargetCXXABI::GenericAArch64:
13531 case TargetCXXABI::GenericItanium:
13532 case TargetCXXABI::GenericARM:
13533 case TargetCXXABI::GenericMIPS:
13534 case TargetCXXABI::iOS:
13535 case TargetCXXABI::WebAssembly:
13536 case TargetCXXABI::WatchOS:
13537 case TargetCXXABI::XL:
13539 case TargetCXXABI::Microsoft:
13541 }
13542 llvm_unreachable("Unsupported ABI");
13543}
13544
13546 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
13547 "Device mangle context does not support Microsoft mangling.");
13548 switch (T.getCXXABI().getKind()) {
13549 case TargetCXXABI::AppleARM64:
13550 case TargetCXXABI::Fuchsia:
13551 case TargetCXXABI::GenericAArch64:
13552 case TargetCXXABI::GenericItanium:
13553 case TargetCXXABI::GenericARM:
13554 case TargetCXXABI::GenericMIPS:
13555 case TargetCXXABI::iOS:
13556 case TargetCXXABI::WebAssembly:
13557 case TargetCXXABI::WatchOS:
13558 case TargetCXXABI::XL:
13560 *this, getDiagnostics(),
13561 [](ASTContext &, const NamedDecl *ND) -> UnsignedOrNone {
13562 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
13563 return RD->getDeviceLambdaManglingNumber();
13564 return std::nullopt;
13565 },
13566 /*IsAux=*/true);
13567 case TargetCXXABI::Microsoft:
13569 /*IsAux=*/true);
13570 }
13571 llvm_unreachable("Unsupported ABI");
13572}
13573
13575 // If the host and device have different C++ ABIs, mark it as the device
13576 // mangle context so that the mangling needs to retrieve the additional
13577 // device lambda mangling number instead of the regular host one.
13578 if (getAuxTargetInfo() && getTargetInfo().getCXXABI().isMicrosoft() &&
13579 getAuxTargetInfo()->getCXXABI().isItaniumFamily()) {
13581 }
13582
13584}
13585
13586CXXABI::~CXXABI() = default;
13587
13589 return ASTRecordLayouts.getMemorySize() +
13590 llvm::capacity_in_bytes(ObjCLayouts) +
13591 llvm::capacity_in_bytes(KeyFunctions) +
13592 llvm::capacity_in_bytes(ObjCImpls) +
13593 llvm::capacity_in_bytes(BlockVarCopyInits) +
13594 llvm::capacity_in_bytes(DeclAttrs) +
13595 llvm::capacity_in_bytes(TemplateOrInstantiation) +
13596 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
13597 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
13598 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
13599 llvm::capacity_in_bytes(OverriddenMethods) +
13600 llvm::capacity_in_bytes(Types) +
13601 llvm::capacity_in_bytes(VariableArrayTypes);
13602}
13603
13604/// getIntTypeForBitwidth -
13605/// sets integer QualTy according to specified details:
13606/// bitwidth, signed/unsigned.
13607/// Returns empty type if there is no appropriate target types.
13609 unsigned Signed) const {
13611 CanQualType QualTy = getFromTargetType(Ty);
13612 if (!QualTy && DestWidth == 128)
13613 return Signed ? Int128Ty : UnsignedInt128Ty;
13614 return QualTy;
13615}
13616
13618 unsigned Signed) const {
13619 return getFromTargetType(
13620 getTargetInfo().getLeastIntTypeByWidth(DestWidth, Signed));
13621}
13622
13623/// getRealTypeForBitwidth -
13624/// sets floating point QualTy according to specified bitwidth.
13625/// Returns empty type if there is no appropriate target types.
13627 FloatModeKind ExplicitType) const {
13628 FloatModeKind Ty =
13629 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
13630 switch (Ty) {
13632 return HalfTy;
13634 return FloatTy;
13636 return DoubleTy;
13638 return LongDoubleTy;
13640 return Float128Ty;
13642 return Ibm128Ty;
13644 return {};
13645 }
13646
13647 llvm_unreachable("Unhandled TargetInfo::RealType value");
13648}
13649
13650void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
13651 if (Number <= 1)
13652 return;
13653
13654 MangleNumbers[ND] = Number;
13655
13656 if (Listener)
13657 Listener->AddedManglingNumber(ND, Number);
13658}
13659
13661 bool ForAuxTarget) const {
13662 auto I = MangleNumbers.find(ND);
13663 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
13664 // CUDA/HIP host compilation encodes host and device mangling numbers
13665 // as lower and upper half of 32 bit integer.
13666 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
13667 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
13668 } else {
13669 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
13670 "number for aux target");
13671 }
13672 return Res > 1 ? Res : 1;
13673}
13674
13675void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
13676 if (Number <= 1)
13677 return;
13678
13679 StaticLocalNumbers[VD] = Number;
13680
13681 if (Listener)
13682 Listener->AddedStaticLocalNumbers(VD, Number);
13683}
13684
13686 auto I = StaticLocalNumbers.find(VD);
13687 return I != StaticLocalNumbers.end() ? I->second : 1;
13688}
13689
13691 bool IsDestroying) {
13692 if (!IsDestroying) {
13693 assert(!DestroyingOperatorDeletes.contains(FD->getCanonicalDecl()));
13694 return;
13695 }
13696 DestroyingOperatorDeletes.insert(FD->getCanonicalDecl());
13697}
13698
13700 return DestroyingOperatorDeletes.contains(FD->getCanonicalDecl());
13701}
13702
13704 bool IsTypeAware) {
13705 if (!IsTypeAware) {
13706 assert(!TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl()));
13707 return;
13708 }
13709 TypeAwareOperatorNewAndDeletes.insert(FD->getCanonicalDecl());
13710}
13711
13713 return TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl());
13714}
13715
13717 FunctionDecl *OperatorDelete,
13718 OperatorDeleteKind K) const {
13719 switch (K) {
13721 OperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] = OperatorDelete;
13722 break;
13724 GlobalOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13725 OperatorDelete;
13726 break;
13728 ArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13729 OperatorDelete;
13730 break;
13732 GlobalArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13733 OperatorDelete;
13734 break;
13735 }
13736}
13737
13739 OperatorDeleteKind K) const {
13740 switch (K) {
13742 return OperatorDeletesForVirtualDtor.contains(Dtor->getCanonicalDecl());
13744 return GlobalOperatorDeletesForVirtualDtor.contains(
13745 Dtor->getCanonicalDecl());
13747 return ArrayOperatorDeletesForVirtualDtor.contains(
13748 Dtor->getCanonicalDecl());
13750 return GlobalArrayOperatorDeletesForVirtualDtor.contains(
13751 Dtor->getCanonicalDecl());
13752 }
13753 return false;
13754}
13755
13758 OperatorDeleteKind K) const {
13759 const CXXDestructorDecl *Canon = Dtor->getCanonicalDecl();
13760 switch (K) {
13762 if (OperatorDeletesForVirtualDtor.contains(Canon))
13763 return OperatorDeletesForVirtualDtor[Canon];
13764 return nullptr;
13766 if (GlobalOperatorDeletesForVirtualDtor.contains(Canon))
13767 return GlobalOperatorDeletesForVirtualDtor[Canon];
13768 return nullptr;
13770 if (ArrayOperatorDeletesForVirtualDtor.contains(Canon))
13771 return ArrayOperatorDeletesForVirtualDtor[Canon];
13772 return nullptr;
13774 if (GlobalArrayOperatorDeletesForVirtualDtor.contains(Canon))
13775 return GlobalArrayOperatorDeletesForVirtualDtor[Canon];
13776 return nullptr;
13777 }
13778 return nullptr;
13779}
13780
13782 const CXXRecordDecl *RD) {
13783 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13784 return false;
13785
13786 return MaybeRequireVectorDeletingDtor.count(RD);
13787}
13788
13790 const CXXRecordDecl *RD) {
13791 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13792 return;
13793
13794 MaybeRequireVectorDeletingDtor.insert(RD);
13795}
13796
13799 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13800 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
13801 if (!MCtx)
13803 return *MCtx;
13804}
13805
13808 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13809 std::unique_ptr<MangleNumberingContext> &MCtx =
13810 ExtraMangleNumberingContexts[D];
13811 if (!MCtx)
13813 return *MCtx;
13814}
13815
13816std::unique_ptr<MangleNumberingContext>
13818 return ABI->createMangleNumberingContext();
13819}
13820
13821const CXXConstructorDecl *
13823 return ABI->getCopyConstructorForExceptionObject(
13825}
13826
13828 CXXConstructorDecl *CD) {
13829 return ABI->addCopyConstructorForExceptionObject(
13832}
13833
13835 TypedefNameDecl *DD) {
13836 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
13837}
13838
13841 return ABI->getTypedefNameForUnnamedTagDecl(TD);
13842}
13843
13845 DeclaratorDecl *DD) {
13846 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
13847}
13848
13850 return ABI->getDeclaratorForUnnamedTagDecl(TD);
13851}
13852
13854 ParamIndices[D] = index;
13855}
13856
13858 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
13859 assert(I != ParamIndices.end() &&
13860 "ParmIndices lacks entry set by ParmVarDecl");
13861 return I->second;
13862}
13863
13865 unsigned Length) const {
13866 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
13867 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
13868 EltTy = EltTy.withConst();
13869
13870 EltTy = adjustStringLiteralBaseType(EltTy);
13871
13872 // Get an array type for the string, according to C99 6.4.5. This includes
13873 // the null terminator character.
13874 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
13875 ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
13876}
13877
13880 StringLiteral *&Result = StringLiteralCache[Key];
13881 if (!Result)
13883 *this, Key, StringLiteralKind::Ordinary,
13884 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
13885 SourceLocation());
13886 return Result;
13887}
13888
13889MSGuidDecl *
13891 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
13892
13893 llvm::FoldingSetNodeID ID;
13894 MSGuidDecl::Profile(ID, Parts);
13895
13896 void *InsertPos;
13897 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
13898 return Existing;
13899
13900 QualType GUIDType = getMSGuidType().withConst();
13901 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
13902 MSGuidDecls.InsertNode(New, InsertPos);
13903 return New;
13904}
13905
13908 const APValue &APVal) const {
13909 llvm::FoldingSetNodeID ID;
13911
13912 void *InsertPos;
13913 if (UnnamedGlobalConstantDecl *Existing =
13914 UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos))
13915 return Existing;
13916
13918 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
13919 UnnamedGlobalConstantDecls.InsertNode(New, InsertPos);
13920 return New;
13921}
13922
13925 assert(T->isRecordType() && "template param object of unexpected type");
13926
13927 // C++ [temp.param]p8:
13928 // [...] a static storage duration object of type 'const T' [...]
13929 T.addConst();
13930
13931 llvm::FoldingSetNodeID ID;
13933
13934 void *InsertPos;
13935 if (TemplateParamObjectDecl *Existing =
13936 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
13937 return Existing;
13938
13939 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
13940 TemplateParamObjectDecls.InsertNode(New, InsertPos);
13941 return New;
13942}
13943
13945 const llvm::Triple &T = getTargetInfo().getTriple();
13946 if (!T.isOSDarwin())
13947 return false;
13948
13949 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
13950 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
13951 return false;
13952
13953 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
13954 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
13955 uint64_t Size = sizeChars.getQuantity();
13956 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
13957 unsigned Align = alignChars.getQuantity();
13958 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
13959 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
13960}
13961
13962bool
13964 const ObjCMethodDecl *MethodImpl) {
13965 // No point trying to match an unavailable/deprecated mothod.
13966 if (MethodDecl->hasAttr<UnavailableAttr>()
13967 || MethodDecl->hasAttr<DeprecatedAttr>())
13968 return false;
13969 if (MethodDecl->getObjCDeclQualifier() !=
13970 MethodImpl->getObjCDeclQualifier())
13971 return false;
13972 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
13973 return false;
13974
13975 if (MethodDecl->param_size() != MethodImpl->param_size())
13976 return false;
13977
13978 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
13979 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
13980 EF = MethodDecl->param_end();
13981 IM != EM && IF != EF; ++IM, ++IF) {
13982 const ParmVarDecl *DeclVar = (*IF);
13983 const ParmVarDecl *ImplVar = (*IM);
13984 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
13985 return false;
13986 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
13987 return false;
13988 }
13989
13990 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
13991}
13992
13994 LangAS AS;
13996 AS = LangAS::Default;
13997 else
13998 AS = QT->getPointeeType().getAddressSpace();
13999
14001}
14002
14005}
14006
14007bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
14008 if (X == Y)
14009 return true;
14010 if (!X || !Y)
14011 return false;
14012 llvm::FoldingSetNodeID IDX, IDY;
14013 X->Profile(IDX, *this, /*Canonical=*/true);
14014 Y->Profile(IDY, *this, /*Canonical=*/true);
14015 return IDX == IDY;
14016}
14017
14018// The getCommon* helpers return, for given 'same' X and Y entities given as
14019// inputs, another entity which is also the 'same' as the inputs, but which
14020// is closer to the canonical form of the inputs, each according to a given
14021// criteria.
14022// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
14023// the regular ones.
14024
14026 if (!declaresSameEntity(X, Y))
14027 return nullptr;
14028 for (const Decl *DX : X->redecls()) {
14029 // If we reach Y before reaching the first decl, that means X is older.
14030 if (DX == Y)
14031 return X;
14032 // If we reach the first decl, then Y is older.
14033 if (DX->isFirstDecl())
14034 return Y;
14035 }
14036 llvm_unreachable("Corrupt redecls chain");
14037}
14038
14039template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
14040static T *getCommonDecl(T *X, T *Y) {
14041 return cast_or_null<T>(
14042 getCommonDecl(const_cast<Decl *>(cast_or_null<Decl>(X)),
14043 const_cast<Decl *>(cast_or_null<Decl>(Y))));
14044}
14045
14046template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
14047static T *getCommonDeclChecked(T *X, T *Y) {
14048 return cast<T>(getCommonDecl(const_cast<Decl *>(cast<Decl>(X)),
14049 const_cast<Decl *>(cast<Decl>(Y))));
14050}
14051
14053 TemplateName Y,
14054 bool IgnoreDeduced = false) {
14055 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
14056 return X;
14057 // FIXME: There are cases here where we could find a common template name
14058 // with more sugar. For example one could be a SubstTemplateTemplate*
14059 // replacing the other.
14060 TemplateName CX = Ctx.getCanonicalTemplateName(X, IgnoreDeduced);
14061 if (CX.getAsVoidPointer() !=
14063 return TemplateName();
14064 return CX;
14065}
14066
14069 bool IgnoreDeduced) {
14070 TemplateName R = getCommonTemplateName(Ctx, X, Y, IgnoreDeduced);
14071 assert(R.getAsVoidPointer() != nullptr);
14072 return R;
14073}
14074
14076 ArrayRef<QualType> Ys, bool Unqualified = false) {
14077 assert(Xs.size() == Ys.size());
14078 SmallVector<QualType, 8> Rs(Xs.size());
14079 for (size_t I = 0; I < Rs.size(); ++I)
14080 Rs[I] = Ctx.getCommonSugaredType(Xs[I], Ys[I], Unqualified);
14081 return Rs;
14082}
14083
14084template <class T>
14085static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
14086 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
14087 : SourceLocation();
14088}
14089
14091 const TemplateArgument &X,
14092 const TemplateArgument &Y) {
14093 if (X.getKind() != Y.getKind())
14094 return TemplateArgument();
14095
14096 switch (X.getKind()) {
14098 if (!Ctx.hasSameType(X.getAsType(), Y.getAsType()))
14099 return TemplateArgument();
14100 return TemplateArgument(
14101 Ctx.getCommonSugaredType(X.getAsType(), Y.getAsType()));
14103 if (!Ctx.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
14104 return TemplateArgument();
14105 return TemplateArgument(
14106 Ctx.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
14107 /*Unqualified=*/true);
14109 if (!Ctx.hasSameType(X.getAsExpr()->getType(), Y.getAsExpr()->getType()))
14110 return TemplateArgument();
14111 // FIXME: Try to keep the common sugar.
14112 return X;
14114 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
14115 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
14116 if (!CTN.getAsVoidPointer())
14117 return TemplateArgument();
14118 return TemplateArgument(CTN);
14119 }
14121 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
14123 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
14124 if (!CTN.getAsVoidPointer())
14125 return TemplateName();
14126 auto NExpX = X.getNumTemplateExpansions();
14127 assert(NExpX == Y.getNumTemplateExpansions());
14128 return TemplateArgument(CTN, NExpX);
14129 }
14130 default:
14131 // FIXME: Handle the other argument kinds.
14132 return X;
14133 }
14134}
14135
14140 if (Xs.size() != Ys.size())
14141 return true;
14142 R.resize(Xs.size());
14143 for (size_t I = 0; I < R.size(); ++I) {
14144 R[I] = getCommonTemplateArgument(Ctx, Xs[I], Ys[I]);
14145 if (R[I].isNull())
14146 return true;
14147 }
14148 return false;
14149}
14150
14155 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
14156 assert(!Different);
14157 (void)Different;
14158 return R;
14159}
14160
14161template <class T>
14163 bool IsSame) {
14164 ElaboratedTypeKeyword KX = X->getKeyword(), KY = Y->getKeyword();
14165 if (KX == KY)
14166 return KX;
14168 assert(!IsSame || KX == getCanonicalElaboratedTypeKeyword(KY));
14169 return KX;
14170}
14171
14172/// Returns a NestedNameSpecifier which has only the common sugar
14173/// present in both NNS1 and NNS2.
14176 NestedNameSpecifier NNS2, bool IsSame) {
14177 // If they are identical, all sugar is common.
14178 if (NNS1 == NNS2)
14179 return NNS1;
14180
14181 // IsSame implies both Qualifiers are equivalent.
14182 NestedNameSpecifier Canon = NNS1.getCanonical();
14183 if (Canon != NNS2.getCanonical()) {
14184 assert(!IsSame && "Should be the same NestedNameSpecifier");
14185 // If they are not the same, there is nothing to unify.
14186 return std::nullopt;
14187 }
14188
14189 NestedNameSpecifier R = std::nullopt;
14190 NestedNameSpecifier::Kind Kind = NNS1.getKind();
14191 assert(Kind == NNS2.getKind());
14192 switch (Kind) {
14194 auto [Namespace1, Prefix1] = NNS1.getAsNamespaceAndPrefix();
14195 auto [Namespace2, Prefix2] = NNS2.getAsNamespaceAndPrefix();
14196 auto Kind = Namespace1->getKind();
14197 if (Kind != Namespace2->getKind() ||
14198 (Kind == Decl::NamespaceAlias &&
14199 !declaresSameEntity(Namespace1, Namespace2))) {
14201 Ctx,
14202 ::getCommonDeclChecked(Namespace1->getNamespace(),
14203 Namespace2->getNamespace()),
14204 /*Prefix=*/std::nullopt);
14205 break;
14206 }
14207 // The prefixes for namespaces are not significant, its declaration
14208 // identifies it uniquely.
14209 NestedNameSpecifier Prefix = ::getCommonNNS(Ctx, Prefix1, Prefix2,
14210 /*IsSame=*/false);
14211 R = NestedNameSpecifier(Ctx, ::getCommonDeclChecked(Namespace1, Namespace2),
14212 Prefix);
14213 break;
14214 }
14216 const Type *T1 = NNS1.getAsType(), *T2 = NNS2.getAsType();
14217 const Type *T = Ctx.getCommonSugaredType(QualType(T1, 0), QualType(T2, 0),
14218 /*Unqualified=*/true)
14219 .getTypePtr();
14221 break;
14222 }
14224 // FIXME: Can __super even be used with data members?
14225 // If it's only usable in functions, we will never see it here,
14226 // unless we save the qualifiers used in function types.
14227 // In that case, it might be possible NNS2 is a type,
14228 // in which case we should degrade the result to
14229 // a CXXRecordType.
14231 NNS2.getAsMicrosoftSuper()));
14232 break;
14233 }
14236 // These are singletons.
14237 llvm_unreachable("singletons did not compare equal");
14238 }
14239 assert(R.getCanonical() == Canon);
14240 return R;
14241}
14242
14243template <class T>
14245 const T *Y, bool IsSame) {
14246 return ::getCommonNNS(Ctx, X->getQualifier(), Y->getQualifier(), IsSame);
14247}
14248
14249template <class T>
14250static QualType getCommonElementType(const ASTContext &Ctx, const T *X,
14251 const T *Y) {
14252 return Ctx.getCommonSugaredType(X->getElementType(), Y->getElementType());
14253}
14254
14256 QualType X, QualType Y,
14257 Qualifiers &QX,
14258 Qualifiers &QY) {
14259 QualType R = Ctx.getCommonSugaredType(X, Y,
14260 /*Unqualified=*/true);
14261 // Qualifiers common to both element types.
14262 Qualifiers RQ = R.getQualifiers();
14263 // For each side, move to the top level any qualifiers which are not common to
14264 // both element types. The caller must assume top level qualifiers might
14265 // be different, even if they are the same type, and can be treated as sugar.
14266 QX += X.getQualifiers() - RQ;
14267 QY += Y.getQualifiers() - RQ;
14268 return R;
14269}
14270
14271template <class T>
14273 Qualifiers &QX, const T *Y,
14274 Qualifiers &QY) {
14275 return getCommonTypeWithQualifierLifting(Ctx, X->getElementType(),
14276 Y->getElementType(), QX, QY);
14277}
14278
14279template <class T>
14280static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X,
14281 const T *Y) {
14282 return Ctx.getCommonSugaredType(X->getPointeeType(), Y->getPointeeType());
14283}
14284
14285template <class T>
14286static auto *getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y) {
14287 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
14288 return X->getSizeExpr();
14289}
14290
14291static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
14292 assert(X->getSizeModifier() == Y->getSizeModifier());
14293 return X->getSizeModifier();
14294}
14295
14297 const ArrayType *Y) {
14298 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
14299 return X->getIndexTypeCVRQualifiers();
14300}
14301
14302// Merges two type lists such that the resulting vector will contain
14303// each type (in a canonical sense) only once, in the order they appear
14304// from X to Y. If they occur in both X and Y, the result will contain
14305// the common sugared type between them.
14306static void mergeTypeLists(const ASTContext &Ctx,
14309 llvm::DenseMap<QualType, unsigned> Found;
14310 for (auto Ts : {X, Y}) {
14311 for (QualType T : Ts) {
14312 auto Res = Found.try_emplace(Ctx.getCanonicalType(T), Out.size());
14313 if (!Res.second) {
14314 QualType &U = Out[Res.first->second];
14315 U = Ctx.getCommonSugaredType(U, T);
14316 } else {
14317 Out.emplace_back(T);
14318 }
14319 }
14320 }
14321}
14322
14323FunctionProtoType::ExceptionSpecInfo
14326 SmallVectorImpl<QualType> &ExceptionTypeStorage,
14327 bool AcceptDependent) const {
14328 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
14329
14330 // If either of them can throw anything, that is the result.
14331 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
14332 if (EST1 == I)
14333 return ESI1;
14334 if (EST2 == I)
14335 return ESI2;
14336 }
14337
14338 // If either of them is non-throwing, the result is the other.
14339 for (auto I :
14341 if (EST1 == I)
14342 return ESI2;
14343 if (EST2 == I)
14344 return ESI1;
14345 }
14346
14347 // If we're left with value-dependent computed noexcept expressions, we're
14348 // stuck. Before C++17, we can just drop the exception specification entirely,
14349 // since it's not actually part of the canonical type. And this should never
14350 // happen in C++17, because it would mean we were computing the composite
14351 // pointer type of dependent types, which should never happen.
14352 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
14353 assert(AcceptDependent &&
14354 "computing composite pointer type of dependent types");
14356 }
14357
14358 // Switch over the possibilities so that people adding new values know to
14359 // update this function.
14360 switch (EST1) {
14361 case EST_None:
14362 case EST_DynamicNone:
14363 case EST_MSAny:
14364 case EST_BasicNoexcept:
14366 case EST_NoexceptFalse:
14367 case EST_NoexceptTrue:
14368 case EST_NoThrow:
14369 llvm_unreachable("These ESTs should be handled above");
14370
14371 case EST_Dynamic: {
14372 // This is the fun case: both exception specifications are dynamic. Form
14373 // the union of the two lists.
14374 assert(EST2 == EST_Dynamic && "other cases should already be handled");
14375 mergeTypeLists(*this, ExceptionTypeStorage, ESI1.Exceptions,
14376 ESI2.Exceptions);
14378 Result.Exceptions = ExceptionTypeStorage;
14379 return Result;
14380 }
14381
14382 case EST_Unevaluated:
14383 case EST_Uninstantiated:
14384 case EST_Unparsed:
14385 llvm_unreachable("shouldn't see unresolved exception specifications here");
14386 }
14387
14388 llvm_unreachable("invalid ExceptionSpecificationType");
14389}
14390
14392 Qualifiers &QX, const Type *Y,
14393 Qualifiers &QY) {
14394 Type::TypeClass TC = X->getTypeClass();
14395 assert(TC == Y->getTypeClass());
14396 switch (TC) {
14397#define UNEXPECTED_TYPE(Class, Kind) \
14398 case Type::Class: \
14399 llvm_unreachable("Unexpected " Kind ": " #Class);
14400
14401#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
14402#define TYPE(Class, Base)
14403#include "clang/AST/TypeNodes.inc"
14404
14405#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
14407 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
14408 SUGAR_FREE_TYPE(DependentBitInt)
14410 SUGAR_FREE_TYPE(ObjCInterface)
14411 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
14412 SUGAR_FREE_TYPE(SubstBuiltinTemplatePack)
14413 SUGAR_FREE_TYPE(UnresolvedUsing)
14414 SUGAR_FREE_TYPE(HLSLAttributedResource)
14415 SUGAR_FREE_TYPE(HLSLInlineSpirv)
14416#undef SUGAR_FREE_TYPE
14417#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
14418 NON_UNIQUE_TYPE(TypeOfExpr)
14419 NON_UNIQUE_TYPE(VariableArray)
14420#undef NON_UNIQUE_TYPE
14421
14422 UNEXPECTED_TYPE(TypeOf, "sugar")
14423
14424#undef UNEXPECTED_TYPE
14425
14426 case Type::Auto: {
14427 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14428 assert(AX->getDeducedKind() == AY->getDeducedKind());
14429 assert(AX->getDeducedKind() != DeducedKind::Deduced);
14430 assert(AX->getKeyword() == AY->getKeyword());
14431 TemplateDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(),
14432 AY->getTypeConstraintConcept());
14434 if (CD &&
14435 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
14436 AY->getTypeConstraintArguments())) {
14437 CD = nullptr; // The arguments differ, so make it unconstrained.
14438 As.clear();
14439 }
14440 return Ctx.getAutoType(AX->getDeducedKind(), QualType(), AX->getKeyword(),
14441 CD, As);
14442 }
14443 case Type::IncompleteArray: {
14444 const auto *AX = cast<IncompleteArrayType>(X),
14446 return Ctx.getIncompleteArrayType(
14447 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14449 }
14450 case Type::DependentSizedArray: {
14451 const auto *AX = cast<DependentSizedArrayType>(X),
14453 return Ctx.getDependentSizedArrayType(
14454 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14455 getCommonSizeExpr(Ctx, AX, AY), getCommonSizeModifier(AX, AY),
14457 }
14458 case Type::ConstantArray: {
14459 const auto *AX = cast<ConstantArrayType>(X),
14460 *AY = cast<ConstantArrayType>(Y);
14461 assert(AX->getSize() == AY->getSize());
14462 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14463 ? AX->getSizeExpr()
14464 : nullptr;
14465 return Ctx.getConstantArrayType(
14466 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14468 }
14469 case Type::ArrayParameter: {
14470 const auto *AX = cast<ArrayParameterType>(X),
14471 *AY = cast<ArrayParameterType>(Y);
14472 assert(AX->getSize() == AY->getSize());
14473 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14474 ? AX->getSizeExpr()
14475 : nullptr;
14476 auto ArrayTy = Ctx.getConstantArrayType(
14477 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14479 return Ctx.getArrayParameterType(ArrayTy);
14480 }
14481 case Type::Atomic: {
14482 const auto *AX = cast<AtomicType>(X), *AY = cast<AtomicType>(Y);
14483 return Ctx.getAtomicType(
14484 Ctx.getCommonSugaredType(AX->getValueType(), AY->getValueType()));
14485 }
14486 case Type::Complex: {
14487 const auto *CX = cast<ComplexType>(X), *CY = cast<ComplexType>(Y);
14488 return Ctx.getComplexType(getCommonArrayElementType(Ctx, CX, QX, CY, QY));
14489 }
14490 case Type::Pointer: {
14491 const auto *PX = cast<PointerType>(X), *PY = cast<PointerType>(Y);
14492 return Ctx.getPointerType(getCommonPointeeType(Ctx, PX, PY));
14493 }
14494 case Type::BlockPointer: {
14495 const auto *PX = cast<BlockPointerType>(X), *PY = cast<BlockPointerType>(Y);
14496 return Ctx.getBlockPointerType(getCommonPointeeType(Ctx, PX, PY));
14497 }
14498 case Type::ObjCObjectPointer: {
14499 const auto *PX = cast<ObjCObjectPointerType>(X),
14501 return Ctx.getObjCObjectPointerType(getCommonPointeeType(Ctx, PX, PY));
14502 }
14503 case Type::MemberPointer: {
14504 const auto *PX = cast<MemberPointerType>(X),
14505 *PY = cast<MemberPointerType>(Y);
14506 assert(declaresSameEntity(PX->getMostRecentCXXRecordDecl(),
14507 PY->getMostRecentCXXRecordDecl()));
14508 return Ctx.getMemberPointerType(
14509 getCommonPointeeType(Ctx, PX, PY),
14510 getCommonQualifier(Ctx, PX, PY, /*IsSame=*/true),
14511 PX->getMostRecentCXXRecordDecl());
14512 }
14513 case Type::LValueReference: {
14514 const auto *PX = cast<LValueReferenceType>(X),
14516 // FIXME: Preserve PointeeTypeAsWritten.
14517 return Ctx.getLValueReferenceType(getCommonPointeeType(Ctx, PX, PY),
14518 PX->isSpelledAsLValue() ||
14519 PY->isSpelledAsLValue());
14520 }
14521 case Type::RValueReference: {
14522 const auto *PX = cast<RValueReferenceType>(X),
14524 // FIXME: Preserve PointeeTypeAsWritten.
14525 return Ctx.getRValueReferenceType(getCommonPointeeType(Ctx, PX, PY));
14526 }
14527 case Type::DependentAddressSpace: {
14528 const auto *PX = cast<DependentAddressSpaceType>(X),
14530 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
14531 return Ctx.getDependentAddressSpaceType(getCommonPointeeType(Ctx, PX, PY),
14532 PX->getAddrSpaceExpr(),
14533 getCommonAttrLoc(PX, PY));
14534 }
14535 case Type::FunctionNoProto: {
14536 const auto *FX = cast<FunctionNoProtoType>(X),
14538 assert(FX->getExtInfo() == FY->getExtInfo());
14539 return Ctx.getFunctionNoProtoType(
14540 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType()),
14541 FX->getExtInfo());
14542 }
14543 case Type::FunctionProto: {
14544 const auto *FX = cast<FunctionProtoType>(X),
14545 *FY = cast<FunctionProtoType>(Y);
14546 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
14547 EPIY = FY->getExtProtoInfo();
14548 assert(EPIX.ExtInfo == EPIY.ExtInfo);
14549 assert(!EPIX.ExtParameterInfos == !EPIY.ExtParameterInfos);
14550 assert(!EPIX.ExtParameterInfos ||
14551 llvm::equal(
14552 llvm::ArrayRef(EPIX.ExtParameterInfos, FX->getNumParams()),
14553 llvm::ArrayRef(EPIY.ExtParameterInfos, FY->getNumParams())));
14554 assert(EPIX.RefQualifier == EPIY.RefQualifier);
14555 assert(EPIX.TypeQuals == EPIY.TypeQuals);
14556 assert(EPIX.Variadic == EPIY.Variadic);
14557
14558 // FIXME: Can we handle an empty EllipsisLoc?
14559 // Use emtpy EllipsisLoc if X and Y differ.
14560
14561 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
14562
14563 QualType R =
14564 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType());
14565 auto P = getCommonTypes(Ctx, FX->param_types(), FY->param_types(),
14566 /*Unqualified=*/true);
14567
14568 SmallVector<QualType, 8> Exceptions;
14570 EPIX.ExceptionSpec, EPIY.ExceptionSpec, Exceptions, true);
14571 return Ctx.getFunctionType(R, P, EPIX);
14572 }
14573 case Type::ObjCObject: {
14574 const auto *OX = cast<ObjCObjectType>(X), *OY = cast<ObjCObjectType>(Y);
14575 assert(
14576 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
14577 OY->getProtocols().begin(), OY->getProtocols().end(),
14578 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
14579 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
14580 }) &&
14581 "protocol lists must be the same");
14582 auto TAs = getCommonTypes(Ctx, OX->getTypeArgsAsWritten(),
14583 OY->getTypeArgsAsWritten());
14584 return Ctx.getObjCObjectType(
14585 Ctx.getCommonSugaredType(OX->getBaseType(), OY->getBaseType()), TAs,
14586 OX->getProtocols(),
14587 OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
14588 }
14589 case Type::ConstantMatrix: {
14590 const auto *MX = cast<ConstantMatrixType>(X),
14591 *MY = cast<ConstantMatrixType>(Y);
14592 assert(MX->getNumRows() == MY->getNumRows());
14593 assert(MX->getNumColumns() == MY->getNumColumns());
14594 return Ctx.getConstantMatrixType(getCommonElementType(Ctx, MX, MY),
14595 MX->getNumRows(), MX->getNumColumns());
14596 }
14597 case Type::DependentSizedMatrix: {
14598 const auto *MX = cast<DependentSizedMatrixType>(X),
14600 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
14601 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
14602 return Ctx.getDependentSizedMatrixType(
14603 getCommonElementType(Ctx, MX, MY), MX->getRowExpr(),
14604 MX->getColumnExpr(), getCommonAttrLoc(MX, MY));
14605 }
14606 case Type::Vector: {
14607 const auto *VX = cast<VectorType>(X), *VY = cast<VectorType>(Y);
14608 assert(VX->getNumElements() == VY->getNumElements());
14609 assert(VX->getVectorKind() == VY->getVectorKind());
14610 return Ctx.getVectorType(getCommonElementType(Ctx, VX, VY),
14611 VX->getNumElements(), VX->getVectorKind());
14612 }
14613 case Type::ExtVector: {
14614 const auto *VX = cast<ExtVectorType>(X), *VY = cast<ExtVectorType>(Y);
14615 assert(VX->getNumElements() == VY->getNumElements());
14616 return Ctx.getExtVectorType(getCommonElementType(Ctx, VX, VY),
14617 VX->getNumElements());
14618 }
14619 case Type::DependentSizedExtVector: {
14620 const auto *VX = cast<DependentSizedExtVectorType>(X),
14623 getCommonSizeExpr(Ctx, VX, VY),
14624 getCommonAttrLoc(VX, VY));
14625 }
14626 case Type::DependentVector: {
14627 const auto *VX = cast<DependentVectorType>(X),
14629 assert(VX->getVectorKind() == VY->getVectorKind());
14630 return Ctx.getDependentVectorType(
14631 getCommonElementType(Ctx, VX, VY), getCommonSizeExpr(Ctx, VX, VY),
14632 getCommonAttrLoc(VX, VY), VX->getVectorKind());
14633 }
14634 case Type::Enum:
14635 case Type::Record:
14636 case Type::InjectedClassName: {
14637 const auto *TX = cast<TagType>(X), *TY = cast<TagType>(Y);
14638 return Ctx.getTagType(::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14639 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false),
14640 ::getCommonDeclChecked(TX->getDecl(), TY->getDecl()),
14641 /*OwnedTag=*/false);
14642 }
14643 case Type::TemplateSpecialization: {
14644 const auto *TX = cast<TemplateSpecializationType>(X),
14646 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
14647 TY->template_arguments());
14649 getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14650 ::getCommonTemplateNameChecked(Ctx, TX->getTemplateName(),
14651 TY->getTemplateName(),
14652 /*IgnoreDeduced=*/true),
14653 As, /*CanonicalArgs=*/{}, X->getCanonicalTypeInternal());
14654 }
14655 case Type::Decltype: {
14656 const auto *DX = cast<DecltypeType>(X);
14657 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Y);
14658 assert(DX->isDependentType());
14659 assert(DY->isDependentType());
14660 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
14661 // As Decltype is not uniqued, building a common type would be wasteful.
14662 return QualType(DX, 0);
14663 }
14664 case Type::PackIndexing: {
14665 const auto *DX = cast<PackIndexingType>(X);
14666 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Y);
14667 assert(DX->isDependentType());
14668 assert(DY->isDependentType());
14669 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
14670 return QualType(DX, 0);
14671 }
14672 case Type::DependentName: {
14673 const auto *NX = cast<DependentNameType>(X),
14674 *NY = cast<DependentNameType>(Y);
14675 assert(NX->getIdentifier() == NY->getIdentifier());
14676 return Ctx.getDependentNameType(
14677 getCommonTypeKeyword(NX, NY, /*IsSame=*/true),
14678 getCommonQualifier(Ctx, NX, NY, /*IsSame=*/true), NX->getIdentifier());
14679 }
14680 case Type::OverflowBehavior: {
14681 const auto *NX = cast<OverflowBehaviorType>(X),
14683 assert(NX->getBehaviorKind() == NY->getBehaviorKind());
14684 return Ctx.getOverflowBehaviorType(
14685 NX->getBehaviorKind(),
14686 getCommonTypeWithQualifierLifting(Ctx, NX->getUnderlyingType(),
14687 NY->getUnderlyingType(), QX, QY));
14688 }
14689 case Type::UnaryTransform: {
14690 const auto *TX = cast<UnaryTransformType>(X),
14691 *TY = cast<UnaryTransformType>(Y);
14692 assert(TX->getUTTKind() == TY->getUTTKind());
14693 return Ctx.getUnaryTransformType(
14694 Ctx.getCommonSugaredType(TX->getBaseType(), TY->getBaseType()),
14695 Ctx.getCommonSugaredType(TX->getUnderlyingType(),
14696 TY->getUnderlyingType()),
14697 TX->getUTTKind());
14698 }
14699 case Type::PackExpansion: {
14700 const auto *PX = cast<PackExpansionType>(X),
14701 *PY = cast<PackExpansionType>(Y);
14702 assert(PX->getNumExpansions() == PY->getNumExpansions());
14703 return Ctx.getPackExpansionType(
14704 Ctx.getCommonSugaredType(PX->getPattern(), PY->getPattern()),
14705 PX->getNumExpansions(), false);
14706 }
14707 case Type::Pipe: {
14708 const auto *PX = cast<PipeType>(X), *PY = cast<PipeType>(Y);
14709 assert(PX->isReadOnly() == PY->isReadOnly());
14710 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
14712 return (Ctx.*MP)(getCommonElementType(Ctx, PX, PY));
14713 }
14714 case Type::TemplateTypeParm: {
14715 const auto *TX = cast<TemplateTypeParmType>(X),
14717 assert(TX->getDepth() == TY->getDepth());
14718 assert(TX->getIndex() == TY->getIndex());
14719 assert(TX->isParameterPack() == TY->isParameterPack());
14720 return Ctx.getTemplateTypeParmType(
14721 TX->getDepth(), TX->getIndex(), TX->isParameterPack(),
14722 getCommonDecl(TX->getDecl(), TY->getDecl()));
14723 }
14724 }
14725 llvm_unreachable("Unknown Type Class");
14726}
14727
14729 const Type *Y,
14730 SplitQualType Underlying) {
14731 Type::TypeClass TC = X->getTypeClass();
14732 if (TC != Y->getTypeClass())
14733 return QualType();
14734 switch (TC) {
14735#define UNEXPECTED_TYPE(Class, Kind) \
14736 case Type::Class: \
14737 llvm_unreachable("Unexpected " Kind ": " #Class);
14738#define TYPE(Class, Base)
14739#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
14740#include "clang/AST/TypeNodes.inc"
14741
14742#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
14745 CANONICAL_TYPE(BlockPointer)
14748 CANONICAL_TYPE(ConstantArray)
14749 CANONICAL_TYPE(ArrayParameter)
14750 CANONICAL_TYPE(ConstantMatrix)
14752 CANONICAL_TYPE(ExtVector)
14753 CANONICAL_TYPE(FunctionNoProto)
14754 CANONICAL_TYPE(FunctionProto)
14755 CANONICAL_TYPE(IncompleteArray)
14756 CANONICAL_TYPE(HLSLAttributedResource)
14757 CANONICAL_TYPE(HLSLInlineSpirv)
14758 CANONICAL_TYPE(LValueReference)
14759 CANONICAL_TYPE(ObjCInterface)
14760 CANONICAL_TYPE(ObjCObject)
14761 CANONICAL_TYPE(ObjCObjectPointer)
14762 CANONICAL_TYPE(OverflowBehavior)
14766 CANONICAL_TYPE(RValueReference)
14767 CANONICAL_TYPE(VariableArray)
14769#undef CANONICAL_TYPE
14770
14771#undef UNEXPECTED_TYPE
14772
14773 case Type::Adjusted: {
14774 const auto *AX = cast<AdjustedType>(X), *AY = cast<AdjustedType>(Y);
14775 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
14776 if (!Ctx.hasSameType(OX, OY))
14777 return QualType();
14778 // FIXME: It's inefficient to have to unify the original types.
14779 return Ctx.getAdjustedType(Ctx.getCommonSugaredType(OX, OY),
14780 Ctx.getQualifiedType(Underlying));
14781 }
14782 case Type::Decayed: {
14783 const auto *DX = cast<DecayedType>(X), *DY = cast<DecayedType>(Y);
14784 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
14785 if (!Ctx.hasSameType(OX, OY))
14786 return QualType();
14787 // FIXME: It's inefficient to have to unify the original types.
14788 return Ctx.getDecayedType(Ctx.getCommonSugaredType(OX, OY),
14789 Ctx.getQualifiedType(Underlying));
14790 }
14791 case Type::Attributed: {
14792 const auto *AX = cast<AttributedType>(X), *AY = cast<AttributedType>(Y);
14793 AttributedType::Kind Kind = AX->getAttrKind();
14794 if (Kind != AY->getAttrKind())
14795 return QualType();
14796 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
14797 if (!Ctx.hasSameType(MX, MY))
14798 return QualType();
14799 // FIXME: It's inefficient to have to unify the modified types.
14800 return Ctx.getAttributedType(Kind, Ctx.getCommonSugaredType(MX, MY),
14801 Ctx.getQualifiedType(Underlying),
14802 AX->getAttr());
14803 }
14804 case Type::BTFTagAttributed: {
14805 const auto *BX = cast<BTFTagAttributedType>(X);
14806 const BTFTypeTagAttr *AX = BX->getAttr();
14807 // The attribute is not uniqued, so just compare the tag.
14808 if (AX->getBTFTypeTag() !=
14809 cast<BTFTagAttributedType>(Y)->getAttr()->getBTFTypeTag())
14810 return QualType();
14811 return Ctx.getBTFTagAttributedType(AX, Ctx.getQualifiedType(Underlying));
14812 }
14813 case Type::Auto: {
14814 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14815 assert(AX->getDeducedKind() == DeducedKind::Deduced);
14816 assert(AY->getDeducedKind() == DeducedKind::Deduced);
14817
14818 AutoTypeKeyword KW = AX->getKeyword();
14819 if (KW != AY->getKeyword())
14820 return QualType();
14821
14822 TemplateDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(),
14823 AY->getTypeConstraintConcept());
14825 if (CD &&
14826 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
14827 AY->getTypeConstraintArguments())) {
14828 CD = nullptr; // The arguments differ, so make it unconstrained.
14829 As.clear();
14830 }
14831
14832 // Both auto types can't be dependent, otherwise they wouldn't have been
14833 // sugar. This implies they can't contain unexpanded packs either.
14835 Ctx.getQualifiedType(Underlying), AX->getKeyword(),
14836 CD, As);
14837 }
14838 case Type::PackIndexing:
14839 case Type::Decltype:
14840 return QualType();
14841 case Type::DeducedTemplateSpecialization:
14842 // FIXME: Try to merge these.
14843 return QualType();
14844 case Type::MacroQualified: {
14845 const auto *MX = cast<MacroQualifiedType>(X),
14846 *MY = cast<MacroQualifiedType>(Y);
14847 const IdentifierInfo *IX = MX->getMacroIdentifier();
14848 if (IX != MY->getMacroIdentifier())
14849 return QualType();
14850 return Ctx.getMacroQualifiedType(Ctx.getQualifiedType(Underlying), IX);
14851 }
14852 case Type::SubstTemplateTypeParm: {
14853 const auto *SX = cast<SubstTemplateTypeParmType>(X),
14855 Decl *CD =
14856 ::getCommonDecl(SX->getAssociatedDecl(), SY->getAssociatedDecl());
14857 if (!CD)
14858 return QualType();
14859 unsigned Index = SX->getIndex();
14860 if (Index != SY->getIndex())
14861 return QualType();
14862 auto PackIndex = SX->getPackIndex();
14863 if (PackIndex != SY->getPackIndex())
14864 return QualType();
14865 return Ctx.getSubstTemplateTypeParmType(Ctx.getQualifiedType(Underlying),
14866 CD, Index, PackIndex,
14867 SX->getFinal() && SY->getFinal());
14868 }
14869 case Type::ObjCTypeParam:
14870 // FIXME: Try to merge these.
14871 return QualType();
14872 case Type::Paren:
14873 return Ctx.getParenType(Ctx.getQualifiedType(Underlying));
14874
14875 case Type::TemplateSpecialization: {
14876 const auto *TX = cast<TemplateSpecializationType>(X),
14878 TemplateName CTN =
14879 ::getCommonTemplateName(Ctx, TX->getTemplateName(),
14880 TY->getTemplateName(), /*IgnoreDeduced=*/true);
14881 if (!CTN.getAsVoidPointer())
14882 return QualType();
14884 if (getCommonTemplateArguments(Ctx, As, TX->template_arguments(),
14885 TY->template_arguments()))
14886 return QualType();
14888 getCommonTypeKeyword(TX, TY, /*IsSame=*/false), CTN, As,
14889 /*CanonicalArgs=*/{}, Ctx.getQualifiedType(Underlying));
14890 }
14891 case Type::Typedef: {
14892 const auto *TX = cast<TypedefType>(X), *TY = cast<TypedefType>(Y);
14893 const TypedefNameDecl *CD = ::getCommonDecl(TX->getDecl(), TY->getDecl());
14894 if (!CD)
14895 return QualType();
14896 return Ctx.getTypedefType(
14897 ::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14898 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false), CD,
14899 Ctx.getQualifiedType(Underlying));
14900 }
14901 case Type::TypeOf: {
14902 // The common sugar between two typeof expressions, where one is
14903 // potentially a typeof_unqual and the other is not, we unify to the
14904 // qualified type as that retains the most information along with the type.
14905 // We only return a typeof_unqual type when both types are unqual types.
14910 return Ctx.getTypeOfType(Ctx.getQualifiedType(Underlying), Kind);
14911 }
14912 case Type::TypeOfExpr:
14913 return QualType();
14914
14915 case Type::UnaryTransform: {
14916 const auto *UX = cast<UnaryTransformType>(X),
14917 *UY = cast<UnaryTransformType>(Y);
14918 UnaryTransformType::UTTKind KX = UX->getUTTKind();
14919 if (KX != UY->getUTTKind())
14920 return QualType();
14921 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
14922 if (!Ctx.hasSameType(BX, BY))
14923 return QualType();
14924 // FIXME: It's inefficient to have to unify the base types.
14925 return Ctx.getUnaryTransformType(Ctx.getCommonSugaredType(BX, BY),
14926 Ctx.getQualifiedType(Underlying), KX);
14927 }
14928 case Type::Using: {
14929 const auto *UX = cast<UsingType>(X), *UY = cast<UsingType>(Y);
14930 const UsingShadowDecl *CD = ::getCommonDecl(UX->getDecl(), UY->getDecl());
14931 if (!CD)
14932 return QualType();
14933 return Ctx.getUsingType(::getCommonTypeKeyword(UX, UY, /*IsSame=*/false),
14934 ::getCommonQualifier(Ctx, UX, UY, /*IsSame=*/false),
14935 CD, Ctx.getQualifiedType(Underlying));
14936 }
14937 case Type::MemberPointer: {
14938 const auto *PX = cast<MemberPointerType>(X),
14939 *PY = cast<MemberPointerType>(Y);
14940 CXXRecordDecl *Cls = PX->getMostRecentCXXRecordDecl();
14941 assert(Cls == PY->getMostRecentCXXRecordDecl());
14942 return Ctx.getMemberPointerType(
14943 ::getCommonPointeeType(Ctx, PX, PY),
14944 ::getCommonQualifier(Ctx, PX, PY, /*IsSame=*/false), Cls);
14945 }
14946 case Type::CountAttributed: {
14947 const auto *DX = cast<CountAttributedType>(X),
14949 if (DX->isCountInBytes() != DY->isCountInBytes())
14950 return QualType();
14951 if (DX->isOrNull() != DY->isOrNull())
14952 return QualType();
14953 Expr *CEX = DX->getCountExpr();
14954 Expr *CEY = DY->getCountExpr();
14955 ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
14956 if (Ctx.hasSameExpr(CEX, CEY))
14957 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14958 DX->isCountInBytes(), DX->isOrNull(),
14959 CDX);
14960 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
14961 return QualType();
14962 // Two declarations with the same integer constant may still differ in their
14963 // expression pointers, so we need to evaluate them.
14964 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
14965 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
14966 if (VX != VY)
14967 return QualType();
14968 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14969 DX->isCountInBytes(), DX->isOrNull(),
14970 CDX);
14971 }
14972
14973 case Type::LateParsedAttr:
14974 return QualType();
14975
14976 case Type::PredefinedSugar:
14977 assert(cast<PredefinedSugarType>(X)->getKind() !=
14979 return QualType();
14980 }
14981 llvm_unreachable("Unhandled Type Class");
14982}
14983
14984static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
14986 while (true) {
14987 QTotal.addConsistentQualifiers(T.Quals);
14988 QualType NT = T.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
14989 if (NT == QualType(T.Ty, 0))
14990 break;
14991 R.push_back(T);
14992 T = NT.split();
14993 }
14994 return R;
14995}
14996
14998 bool Unqualified) const {
14999 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
15000 if (X == Y)
15001 return X;
15002 if (!Unqualified) {
15003 if (X.isCanonical())
15004 return X;
15005 if (Y.isCanonical())
15006 return Y;
15007 }
15008
15009 SplitQualType SX = X.split(), SY = Y.split();
15010 Qualifiers QX, QY;
15011 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
15012 // until we reach their underlying "canonical nodes". Note these are not
15013 // necessarily canonical types, as they may still have sugared properties.
15014 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
15015 auto Xs = ::unwrapSugar(SX, QX), Ys = ::unwrapSugar(SY, QY);
15016
15017 // If this is an ArrayType, the element qualifiers are interchangeable with
15018 // the top level qualifiers.
15019 // * In case the canonical nodes are the same, the elements types are already
15020 // the same.
15021 // * Otherwise, the element types will be made the same, and any different
15022 // element qualifiers will be moved up to the top level qualifiers, per
15023 // 'getCommonArrayElementType'.
15024 // In both cases, this means there may be top level qualifiers which differ
15025 // between X and Y. If so, these differing qualifiers are redundant with the
15026 // element qualifiers, and can be removed without changing the canonical type.
15027 // The desired behaviour is the same as for the 'Unqualified' case here:
15028 // treat the redundant qualifiers as sugar, remove the ones which are not
15029 // common to both sides.
15030 bool KeepCommonQualifiers =
15032
15033 if (SX.Ty != SY.Ty) {
15034 // The canonical nodes differ. Build a common canonical node out of the two,
15035 // unifying their sugar. This may recurse back here.
15036 SX.Ty =
15037 ::getCommonNonSugarTypeNode(*this, SX.Ty, QX, SY.Ty, QY).getTypePtr();
15038 } else {
15039 // The canonical nodes were identical: We may have desugared too much.
15040 // Add any common sugar back in.
15041 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
15042 QX -= SX.Quals;
15043 QY -= SY.Quals;
15044 SX = Xs.pop_back_val();
15045 SY = Ys.pop_back_val();
15046 }
15047 }
15048 if (KeepCommonQualifiers)
15050 else
15051 assert(QX == QY);
15052
15053 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
15054 // related. Walk up these nodes, unifying them and adding the result.
15055 while (!Xs.empty() && !Ys.empty()) {
15056 auto Underlying = SplitQualType(
15057 SX.Ty, Qualifiers::removeCommonQualifiers(SX.Quals, SY.Quals));
15058 SX = Xs.pop_back_val();
15059 SY = Ys.pop_back_val();
15060 SX.Ty = ::getCommonSugarTypeNode(*this, SX.Ty, SY.Ty, Underlying)
15062 // Stop at the first pair which is unrelated.
15063 if (!SX.Ty) {
15064 SX.Ty = Underlying.Ty;
15065 break;
15066 }
15067 QX -= Underlying.Quals;
15068 };
15069
15070 // Add back the missing accumulated qualifiers, which were stripped off
15071 // with the sugar nodes we could not unify.
15072 QualType R = getQualifiedType(SX.Ty, QX);
15073 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
15074 return R;
15075}
15076
15078 assert(Ty->isFixedPointType());
15079
15081 return Ty;
15082
15083 switch (Ty->castAs<BuiltinType>()->getKind()) {
15084 default:
15085 llvm_unreachable("Not a saturated fixed point type!");
15086 case BuiltinType::SatShortAccum:
15087 return ShortAccumTy;
15088 case BuiltinType::SatAccum:
15089 return AccumTy;
15090 case BuiltinType::SatLongAccum:
15091 return LongAccumTy;
15092 case BuiltinType::SatUShortAccum:
15093 return UnsignedShortAccumTy;
15094 case BuiltinType::SatUAccum:
15095 return UnsignedAccumTy;
15096 case BuiltinType::SatULongAccum:
15097 return UnsignedLongAccumTy;
15098 case BuiltinType::SatShortFract:
15099 return ShortFractTy;
15100 case BuiltinType::SatFract:
15101 return FractTy;
15102 case BuiltinType::SatLongFract:
15103 return LongFractTy;
15104 case BuiltinType::SatUShortFract:
15105 return UnsignedShortFractTy;
15106 case BuiltinType::SatUFract:
15107 return UnsignedFractTy;
15108 case BuiltinType::SatULongFract:
15109 return UnsignedLongFractTy;
15110 }
15111}
15112
15114 assert(Ty->isFixedPointType());
15115
15116 if (Ty->isSaturatedFixedPointType()) return Ty;
15117
15118 switch (Ty->castAs<BuiltinType>()->getKind()) {
15119 default:
15120 llvm_unreachable("Not a fixed point type!");
15121 case BuiltinType::ShortAccum:
15122 return SatShortAccumTy;
15123 case BuiltinType::Accum:
15124 return SatAccumTy;
15125 case BuiltinType::LongAccum:
15126 return SatLongAccumTy;
15127 case BuiltinType::UShortAccum:
15129 case BuiltinType::UAccum:
15130 return SatUnsignedAccumTy;
15131 case BuiltinType::ULongAccum:
15133 case BuiltinType::ShortFract:
15134 return SatShortFractTy;
15135 case BuiltinType::Fract:
15136 return SatFractTy;
15137 case BuiltinType::LongFract:
15138 return SatLongFractTy;
15139 case BuiltinType::UShortFract:
15141 case BuiltinType::UFract:
15142 return SatUnsignedFractTy;
15143 case BuiltinType::ULongFract:
15145 }
15146}
15147
15149 if (LangOpts.OpenCL)
15151
15152 if (LangOpts.CUDA)
15154
15155 return getLangASFromTargetAS(AS);
15156}
15157
15158// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
15159// doesn't include ASTContext.h
15160template
15162 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
15164 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
15165 const clang::ASTContext &Ctx, Decl *Value);
15166
15168 assert(Ty->isFixedPointType());
15169
15170 const TargetInfo &Target = getTargetInfo();
15171 switch (Ty->castAs<BuiltinType>()->getKind()) {
15172 default:
15173 llvm_unreachable("Not a fixed point type!");
15174 case BuiltinType::ShortAccum:
15175 case BuiltinType::SatShortAccum:
15176 return Target.getShortAccumScale();
15177 case BuiltinType::Accum:
15178 case BuiltinType::SatAccum:
15179 return Target.getAccumScale();
15180 case BuiltinType::LongAccum:
15181 case BuiltinType::SatLongAccum:
15182 return Target.getLongAccumScale();
15183 case BuiltinType::UShortAccum:
15184 case BuiltinType::SatUShortAccum:
15185 return Target.getUnsignedShortAccumScale();
15186 case BuiltinType::UAccum:
15187 case BuiltinType::SatUAccum:
15188 return Target.getUnsignedAccumScale();
15189 case BuiltinType::ULongAccum:
15190 case BuiltinType::SatULongAccum:
15191 return Target.getUnsignedLongAccumScale();
15192 case BuiltinType::ShortFract:
15193 case BuiltinType::SatShortFract:
15194 return Target.getShortFractScale();
15195 case BuiltinType::Fract:
15196 case BuiltinType::SatFract:
15197 return Target.getFractScale();
15198 case BuiltinType::LongFract:
15199 case BuiltinType::SatLongFract:
15200 return Target.getLongFractScale();
15201 case BuiltinType::UShortFract:
15202 case BuiltinType::SatUShortFract:
15203 return Target.getUnsignedShortFractScale();
15204 case BuiltinType::UFract:
15205 case BuiltinType::SatUFract:
15206 return Target.getUnsignedFractScale();
15207 case BuiltinType::ULongFract:
15208 case BuiltinType::SatULongFract:
15209 return Target.getUnsignedLongFractScale();
15210 }
15211}
15212
15214 assert(Ty->isFixedPointType());
15215
15216 const TargetInfo &Target = getTargetInfo();
15217 switch (Ty->castAs<BuiltinType>()->getKind()) {
15218 default:
15219 llvm_unreachable("Not a fixed point type!");
15220 case BuiltinType::ShortAccum:
15221 case BuiltinType::SatShortAccum:
15222 return Target.getShortAccumIBits();
15223 case BuiltinType::Accum:
15224 case BuiltinType::SatAccum:
15225 return Target.getAccumIBits();
15226 case BuiltinType::LongAccum:
15227 case BuiltinType::SatLongAccum:
15228 return Target.getLongAccumIBits();
15229 case BuiltinType::UShortAccum:
15230 case BuiltinType::SatUShortAccum:
15231 return Target.getUnsignedShortAccumIBits();
15232 case BuiltinType::UAccum:
15233 case BuiltinType::SatUAccum:
15234 return Target.getUnsignedAccumIBits();
15235 case BuiltinType::ULongAccum:
15236 case BuiltinType::SatULongAccum:
15237 return Target.getUnsignedLongAccumIBits();
15238 case BuiltinType::ShortFract:
15239 case BuiltinType::SatShortFract:
15240 case BuiltinType::Fract:
15241 case BuiltinType::SatFract:
15242 case BuiltinType::LongFract:
15243 case BuiltinType::SatLongFract:
15244 case BuiltinType::UShortFract:
15245 case BuiltinType::SatUShortFract:
15246 case BuiltinType::UFract:
15247 case BuiltinType::SatUFract:
15248 case BuiltinType::ULongFract:
15249 case BuiltinType::SatULongFract:
15250 return 0;
15251 }
15252}
15253
15254llvm::FixedPointSemantics
15256 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
15257 "Can only get the fixed point semantics for a "
15258 "fixed point or integer type.");
15259 if (Ty->isIntegerType())
15260 return llvm::FixedPointSemantics::GetIntegerSemantics(
15261 getIntWidth(Ty), Ty->isSignedIntegerType());
15262
15263 bool isSigned = Ty->isSignedFixedPointType();
15264 return llvm::FixedPointSemantics(
15265 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
15267 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
15268}
15269
15270llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
15271 assert(Ty->isFixedPointType());
15272 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
15273}
15274
15275llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
15276 assert(Ty->isFixedPointType());
15277 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
15278}
15279
15281 assert(Ty->isUnsignedFixedPointType() &&
15282 "Expected unsigned fixed point type");
15283
15284 switch (Ty->castAs<BuiltinType>()->getKind()) {
15285 case BuiltinType::UShortAccum:
15286 return ShortAccumTy;
15287 case BuiltinType::UAccum:
15288 return AccumTy;
15289 case BuiltinType::ULongAccum:
15290 return LongAccumTy;
15291 case BuiltinType::SatUShortAccum:
15292 return SatShortAccumTy;
15293 case BuiltinType::SatUAccum:
15294 return SatAccumTy;
15295 case BuiltinType::SatULongAccum:
15296 return SatLongAccumTy;
15297 case BuiltinType::UShortFract:
15298 return ShortFractTy;
15299 case BuiltinType::UFract:
15300 return FractTy;
15301 case BuiltinType::ULongFract:
15302 return LongFractTy;
15303 case BuiltinType::SatUShortFract:
15304 return SatShortFractTy;
15305 case BuiltinType::SatUFract:
15306 return SatFractTy;
15307 case BuiltinType::SatULongFract:
15308 return SatLongFractTy;
15309 default:
15310 llvm_unreachable("Unexpected unsigned fixed point type");
15311 }
15312}
15313
15314// Given a list of FMV features, return a concatenated list of the
15315// corresponding backend features (which may contain duplicates).
15316static std::vector<std::string> getFMVBackendFeaturesFor(
15317 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) {
15318 std::vector<std::string> BackendFeats;
15319 llvm::AArch64::ExtensionSet FeatureBits;
15320 for (StringRef F : FMVFeatStrings)
15321 if (auto FMVExt = llvm::AArch64::parseFMVExtension(F))
15322 if (FMVExt->ID)
15323 FeatureBits.enable(*FMVExt->ID);
15324 FeatureBits.toLLVMFeatureList(BackendFeats);
15325 return BackendFeats;
15326}
15327
15328ParsedTargetAttr
15329ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
15330 assert(TD != nullptr);
15331 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TD->getFeaturesStr());
15332
15333 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
15334 return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
15335 });
15336 return ParsedAttr;
15337}
15338
15339void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15340 const FunctionDecl *FD) const {
15341 if (FD)
15342 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
15343 else
15344 Target->initFeatureMap(FeatureMap, getDiagnostics(),
15345 Target->getTargetOpts().CPU,
15346 Target->getTargetOpts().Features);
15347}
15348
15349// Fills in the supplied string map with the set of target features for the
15350// passed in function.
15351void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15352 GlobalDecl GD) const {
15353 StringRef TargetCPU = Target->getTargetOpts().CPU;
15354 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
15355 if (const auto *TD = FD->getAttr<TargetAttr>()) {
15357
15358 // Make a copy of the features as passed on the command line into the
15359 // beginning of the additional features from the function to override.
15360 // AArch64 handles command line option features in parseTargetAttr().
15361 if (!Target->getTriple().isAArch64())
15362 ParsedAttr.Features.insert(
15363 ParsedAttr.Features.begin(),
15364 Target->getTargetOpts().FeaturesAsWritten.begin(),
15365 Target->getTargetOpts().FeaturesAsWritten.end());
15366
15367 if (ParsedAttr.CPU != "" && Target->isValidCPUName(ParsedAttr.CPU))
15368 TargetCPU = ParsedAttr.CPU;
15369
15370 // Now populate the feature map, first with the TargetCPU which is either
15371 // the default or a new one from the target attribute string. Then we'll use
15372 // the passed in features (FeaturesAsWritten) along with the new ones from
15373 // the attribute.
15374 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
15375 ParsedAttr.Features);
15376 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
15378 Target->getCPUSpecificCPUDispatchFeatures(
15379 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
15380 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
15381 Features.insert(Features.begin(),
15382 Target->getTargetOpts().FeaturesAsWritten.begin(),
15383 Target->getTargetOpts().FeaturesAsWritten.end());
15384 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15385 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
15386 if (Target->getTriple().isAArch64()) {
15388 TC->getFeatures(Feats, GD.getMultiVersionIndex());
15389 std::vector<std::string> Features = getFMVBackendFeaturesFor(Feats);
15390 Features.insert(Features.begin(),
15391 Target->getTargetOpts().FeaturesAsWritten.begin(),
15392 Target->getTargetOpts().FeaturesAsWritten.end());
15393 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15394 } else if (Target->getTriple().isRISCV()) {
15395 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15396 std::vector<std::string> Features;
15397 if (VersionStr != "default") {
15398 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(VersionStr);
15399 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
15400 ParsedAttr.Features.end());
15401 }
15402 Features.insert(Features.begin(),
15403 Target->getTargetOpts().FeaturesAsWritten.begin(),
15404 Target->getTargetOpts().FeaturesAsWritten.end());
15405 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15406 } else if (Target->getTriple().isOSAIX()) {
15407 std::vector<std::string> Features;
15408 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15409 if (VersionStr.starts_with("cpu="))
15410 TargetCPU = VersionStr.drop_front(sizeof("cpu=") - 1);
15411 else
15412 assert(VersionStr == "default");
15413 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15414 } else {
15415 std::vector<std::string> Features;
15416 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15417 if (VersionStr.starts_with("arch="))
15418 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
15419 else if (VersionStr != "default")
15420 Features.push_back((StringRef{"+"} + VersionStr).str());
15421 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15422 }
15423 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
15424 std::vector<std::string> Features;
15425 if (Target->getTriple().isRISCV()) {
15426 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TV->getName());
15427 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
15428 ParsedAttr.Features.end());
15429 } else {
15430 assert(Target->getTriple().isAArch64());
15432 TV->getFeatures(Feats);
15433 Features = getFMVBackendFeaturesFor(Feats);
15434 }
15435 Features.insert(Features.begin(),
15436 Target->getTargetOpts().FeaturesAsWritten.begin(),
15437 Target->getTargetOpts().FeaturesAsWritten.end());
15438 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15439 } else {
15440 FeatureMap = Target->getTargetOpts().FeatureMap;
15441 }
15442}
15443
15445 CanQualType KernelNameType,
15446 const FunctionDecl *FD) {
15447 // Host and device compilation may use different ABIs and different ABIs
15448 // may allocate name mangling discriminators differently. A discriminator
15449 // override is used to ensure consistent discriminator allocation across
15450 // host and device compilation.
15451 auto DeviceDiscriminatorOverrider =
15452 [](ASTContext &Ctx, const NamedDecl *ND) -> UnsignedOrNone {
15453 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
15454 if (RD->isLambda())
15455 return RD->getDeviceLambdaManglingNumber();
15456 return std::nullopt;
15457 };
15458 std::unique_ptr<MangleContext> MC{ItaniumMangleContext::create(
15459 Context, Context.getDiagnostics(), DeviceDiscriminatorOverrider)};
15460
15461 // Construct a mangled name for the SYCL kernel caller offload entry point.
15462 // FIXME: The Itanium typeinfo mangling (_ZTS<type>) is currently used to
15463 // name the SYCL kernel caller offload entry point function. This mangling
15464 // does not suffice to clearly identify symbols that correspond to SYCL
15465 // kernel caller functions, nor is this mangling natural for targets that
15466 // use a non-Itanium ABI.
15467 std::string Buffer;
15468 Buffer.reserve(128);
15469 llvm::raw_string_ostream Out(Buffer);
15470 MC->mangleCanonicalTypeName(KernelNameType, Out);
15471 std::string KernelName = Out.str();
15472
15473 return {KernelNameType, FD, KernelName};
15474}
15475
15477 // If the function declaration to register is invalid or dependent, the
15478 // registration attempt is ignored.
15479 if (FD->isInvalidDecl() || FD->isTemplated())
15480 return;
15481
15482 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
15483 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
15484
15485 // Be tolerant of multiple registration attempts so long as each attempt
15486 // is for the same entity. Callers are obligated to detect and diagnose
15487 // conflicting kernel names prior to calling this function.
15488 CanQualType KernelNameType = getCanonicalType(SKEPAttr->getKernelName());
15489 auto IT = SYCLKernels.find(KernelNameType);
15490 assert((IT == SYCLKernels.end() ||
15491 declaresSameEntity(FD, IT->second.getKernelEntryPointDecl())) &&
15492 "SYCL kernel name conflict");
15493 (void)IT;
15494 SYCLKernels.insert(std::make_pair(
15495 KernelNameType, BuildSYCLKernelInfo(*this, KernelNameType, FD)));
15496}
15497
15499 CanQualType KernelNameType = getCanonicalType(T);
15500 return SYCLKernels.at(KernelNameType);
15501}
15502
15504 CanQualType KernelNameType = getCanonicalType(T);
15505 auto IT = SYCLKernels.find(KernelNameType);
15506 if (IT != SYCLKernels.end())
15507 return &IT->second;
15508 return nullptr;
15509}
15510
15512 OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
15513 return *OMPTraitInfoVector.back();
15514}
15515
15518 const ASTContext::SectionInfo &Section) {
15519 if (Section.Decl)
15520 return DB << Section.Decl;
15521 return DB << "a prior #pragma section";
15522}
15523
15524bool ASTContext::mayExternalize(const Decl *D) const {
15525 bool IsInternalVar =
15526 isa<VarDecl>(D) &&
15528 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
15529 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
15530 (D->hasAttr<CUDAConstantAttr>() &&
15531 !D->getAttr<CUDAConstantAttr>()->isImplicit());
15532 // CUDA/HIP: managed variables need to be externalized since it is
15533 // a declaration in IR, therefore cannot have internal linkage. Kernels in
15534 // anonymous name space needs to be externalized to avoid duplicate symbols.
15535 return (IsInternalVar &&
15536 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
15537 (D->hasAttr<CUDAGlobalAttr>() &&
15539 GVA_Internal);
15540}
15541
15543 return mayExternalize(D) &&
15544 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
15546}
15547
15548StringRef ASTContext::getCUIDHash() const {
15549 if (!CUIDHash.empty())
15550 return CUIDHash;
15551 if (LangOpts.CUID.empty())
15552 return StringRef();
15553 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
15554 return CUIDHash;
15555}
15556
15557const CXXRecordDecl *
15559 assert(ThisClass);
15560 assert(ThisClass->isPolymorphic());
15561 const CXXRecordDecl *PrimaryBase = ThisClass;
15562 while (1) {
15563 assert(PrimaryBase);
15564 assert(PrimaryBase->isPolymorphic());
15565 auto &Layout = getASTRecordLayout(PrimaryBase);
15566 auto Base = Layout.getPrimaryBase();
15567 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
15568 break;
15569 PrimaryBase = Base;
15570 }
15571 return PrimaryBase;
15572}
15573
15575 StringRef MangledName) {
15576 auto *Method = cast<CXXMethodDecl>(VirtualMethodDecl.getDecl());
15577 assert(Method->isVirtual());
15578 bool DefaultIncludesPointerAuth =
15579 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics;
15580
15581 if (!DefaultIncludesPointerAuth)
15582 return true;
15583
15584 auto Existing = ThunksToBeAbbreviated.find(VirtualMethodDecl);
15585 if (Existing != ThunksToBeAbbreviated.end())
15586 return Existing->second.contains(MangledName.str());
15587
15588 std::unique_ptr<MangleContext> Mangler(createMangleContext());
15589 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks;
15590 auto VtableContext = getVTableContext();
15591 if (const auto *ThunkInfos = VtableContext->getThunkInfo(VirtualMethodDecl)) {
15592 auto *Destructor = dyn_cast<CXXDestructorDecl>(Method);
15593 for (const auto &Thunk : *ThunkInfos) {
15594 SmallString<256> ElidedName;
15595 llvm::raw_svector_ostream ElidedNameStream(ElidedName);
15596 if (Destructor)
15597 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15598 Thunk, /* elideOverrideInfo */ true,
15599 ElidedNameStream);
15600 else
15601 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ true,
15602 ElidedNameStream);
15603 SmallString<256> MangledName;
15604 llvm::raw_svector_ostream mangledNameStream(MangledName);
15605 if (Destructor)
15606 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15607 Thunk, /* elideOverrideInfo */ false,
15608 mangledNameStream);
15609 else
15610 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ false,
15611 mangledNameStream);
15612
15613 Thunks[ElidedName].push_back(std::string(MangledName));
15614 }
15615 }
15616 llvm::StringSet<> SimplifiedThunkNames;
15617 for (auto &ThunkList : Thunks) {
15618 llvm::sort(ThunkList.second);
15619 SimplifiedThunkNames.insert(ThunkList.second[0]);
15620 }
15621 bool Result = SimplifiedThunkNames.contains(MangledName);
15622 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames);
15623 return Result;
15624}
15625
15627 // Check for trivially-destructible here because non-trivially-destructible
15628 // types will always cause the type and any types derived from it to be
15629 // considered non-trivially-copyable. The same cannot be said for
15630 // trivially-copyable because deleting special members of a type derived from
15631 // a non-trivially-copyable type can cause the derived type to be considered
15632 // trivially copyable.
15633 if (getLangOpts().PointerFieldProtectionTagged)
15634 return !isa<CXXRecordDecl>(RD) ||
15635 cast<CXXRecordDecl>(RD)->hasTrivialDestructor();
15636 return true;
15637}
15638
15639static void findPFPFields(const ASTContext &Ctx, QualType Ty, CharUnits Offset,
15640 std::vector<PFPField> &Fields, bool IncludeVBases) {
15641 if (auto *AT = Ctx.getAsConstantArrayType(Ty)) {
15642 if (auto *ElemDecl = AT->getElementType()->getAsCXXRecordDecl()) {
15643 const ASTRecordLayout &ElemRL = Ctx.getASTRecordLayout(ElemDecl);
15644 for (unsigned i = 0; i != AT->getSize(); ++i)
15645 findPFPFields(Ctx, AT->getElementType(), Offset + i * ElemRL.getSize(),
15646 Fields, true);
15647 }
15648 }
15649 auto *Decl = Ty->getAsCXXRecordDecl();
15650 // isPFPType() is inherited from bases and members (including via arrays), so
15651 // we can early exit if it is false. Unions are excluded per the API
15652 // documentation.
15653 if (!Decl || !Decl->isPFPType() || Decl->isUnion())
15654 return;
15655 const ASTRecordLayout &RL = Ctx.getASTRecordLayout(Decl);
15656 for (FieldDecl *Field : Decl->fields()) {
15657 CharUnits FieldOffset =
15658 Offset +
15659 Ctx.toCharUnitsFromBits(RL.getFieldOffset(Field->getFieldIndex()));
15660 if (Ctx.isPFPField(Field))
15661 Fields.push_back({FieldOffset, Field});
15662 findPFPFields(Ctx, Field->getType(), FieldOffset, Fields,
15663 /*IncludeVBases=*/true);
15664 }
15665 // Pass false for IncludeVBases below because vbases are only included in
15666 // layout for top-level types, i.e. not bases or vbases.
15667 for (CXXBaseSpecifier &Base : Decl->bases()) {
15668 if (Base.isVirtual())
15669 continue;
15670 CharUnits BaseOffset =
15671 Offset + RL.getBaseClassOffset(Base.getType()->getAsCXXRecordDecl());
15672 findPFPFields(Ctx, Base.getType(), BaseOffset, Fields,
15673 /*IncludeVBases=*/false);
15674 }
15675 if (IncludeVBases) {
15676 for (CXXBaseSpecifier &Base : Decl->vbases()) {
15677 CharUnits BaseOffset =
15678 Offset + RL.getVBaseClassOffset(Base.getType()->getAsCXXRecordDecl());
15679 findPFPFields(Ctx, Base.getType(), BaseOffset, Fields,
15680 /*IncludeVBases=*/false);
15681 }
15682 }
15683}
15684
15685std::vector<PFPField> ASTContext::findPFPFields(QualType Ty) const {
15686 std::vector<PFPField> PFPFields;
15687 ::findPFPFields(*this, Ty, CharUnits::Zero(), PFPFields, true);
15688 return PFPFields;
15689}
15690
15692 return !findPFPFields(Ty).empty();
15693}
15694
15695bool ASTContext::isPFPField(const FieldDecl *FD) const {
15696 if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getParent()))
15697 return RD->isPFPType() && FD->getType()->isPointerType() &&
15698 !FD->hasAttr<NoFieldProtectionAttr>();
15699 return false;
15700}
15701
15703 auto *FD = dyn_cast<FieldDecl>(VD);
15704 if (!FD)
15705 FD = cast<FieldDecl>(cast<IndirectFieldDecl>(VD)->chain().back());
15706 if (isPFPField(FD))
15708}
15709
15711 if (E->getNumComponents() == 0)
15712 return;
15713 OffsetOfNode Comp = E->getComponent(E->getNumComponents() - 1);
15714 if (Comp.getKind() != OffsetOfNode::Field)
15715 return;
15716 if (FieldDecl *FD = Comp.getField(); isPFPField(FD))
15718}
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 getCanonicalTemplateArguments(const ASTContext &C, ArrayRef< TemplateArgument > Args, bool &AnyNonCanonArgs)
static char getObjCEncodingForPrimitiveType(const ASTContext *C, const BuiltinType *BT)
static bool isSameQualifier(const NestedNameSpecifier X, const NestedNameSpecifier Y)
static bool unionHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD, bool CheckIfTriviallyCopyable)
static TypedefDecl * CreateHexagonBuiltinVaListDecl(const ASTContext *Context)
#define CANONICAL_TYPE(Class)
static ElaboratedTypeKeyword getCommonTypeKeyword(const T *X, const T *Y, bool IsSame)
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 QualType getCommonArrayElementType(const ASTContext &Ctx, const T *X, Qualifiers &QX, const T *Y, Qualifiers &QY)
#define SUGAR_FREE_TYPE(Class)
static SYCLKernelInfo BuildSYCLKernelInfo(ASTContext &Context, CanQualType KernelNameType, const FunctionDecl *FD)
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 SmallVector< SourceLocation, 2 > getLocsForCommentSearch(ASTContext::RawCommentLookupKey Key, SourceManager &SourceMgr)
static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B)
static TemplateName getCommonTemplateName(const ASTContext &Ctx, TemplateName X, TemplateName Y, bool IgnoreDeduced=false)
static int CmpProtocolNames(ObjCProtocolDecl *const *LHS, ObjCProtocolDecl *const *RHS)
CmpProtocolNames - Comparison predicate for sorting protocols alphabetically.
static auto * getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y)
static TypedefDecl * CreatePowerABIBuiltinVaListDecl(const ASTContext *Context)
static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y)
static TemplateArgument getCommonTemplateArgument(const ASTContext &Ctx, const TemplateArgument &X, const TemplateArgument &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 NestedNameSpecifier getCommonNNS(const ASTContext &Ctx, NestedNameSpecifier NNS1, NestedNameSpecifier NNS2, bool IsSame)
Returns a NestedNameSpecifier which has only the common sugar present in both NNS1 and NNS2.
static TypedefDecl * CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context)
static int64_t getSubobjectOffset(const FieldDecl *Field, const ASTContext &Context, const clang::ASTRecordLayout &)
static QualType getCommonSugarTypeNode(const ASTContext &Ctx, const Type *X, const Type *Y, SplitQualType Underlying)
static TypedefDecl * CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context)
static QualType getCommonNonSugarTypeNode(const ASTContext &Ctx, const Type *X, Qualifiers &QX, const Type *Y, Qualifiers &QY)
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)
static ElaboratedTypeKeyword getCanonicalElaboratedTypeKeyword(ElaboratedTypeKeyword Keyword)
static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X, const T *Y)
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
@ FloatRank
@ LongDoubleRank
@ Float16Rank
@ Ibm128Rank
@ Float128Rank
@ BFloat16Rank
@ HalfRank
@ DoubleRank
static TypedefDecl * CreateCharPtrBuiltinVaListDecl(const ASTContext *Context)
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 bool getCommonTemplateArguments(const ASTContext &Ctx, SmallVectorImpl< TemplateArgument > &R, ArrayRef< TemplateArgument > Xs, ArrayRef< TemplateArgument > Ys)
static TypedefDecl * CreateXtensaABIBuiltinVaListDecl(const ASTContext *Context)
static QualType getCommonElementType(const ASTContext &Ctx, const T *X, const T *Y)
static void mergeTypeLists(const ASTContext &Ctx, SmallVectorImpl< QualType > &Out, ArrayRef< QualType > X, ArrayRef< QualType > Y)
static bool matchesPostDecrInWhile(const UnaryOperator *UO, ASTContext &Ctx)
For the purposes of overflow pattern exclusion, does this match the while(i–) pattern?
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 uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty)
getRVVTypeSize - Return RVV vector register size.
static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal)
static TemplateName getCommonTemplateNameChecked(const ASTContext &Ctx, TemplateName X, TemplateName Y, bool IgnoreDeduced)
static int compareObjCProtocolsByName(ObjCProtocolDecl *const *lhs, ObjCProtocolDecl *const *rhs)
Comparison routine for Objective-C protocols to be used with llvm::array_pod_sort.
static std::string charUnitsToString(const CharUnits &CU)
static const TagDecl * getNonInjectedClassName(const TagDecl *TD)
static TypedefDecl * CreateZOSVaListDecl(const ASTContext *Context)
static bool hasAnyPackExpansions(ArrayRef< TemplateArgument > Args)
static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED)
static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod, SmallVectorImpl< const NamedDecl * > &Redeclared)
static QualType getCommonTypeWithQualifierLifting(const ASTContext &Ctx, QualType X, QualType Y, Qualifiers &QX, Qualifiers &QY)
static auto getCommonTypes(const ASTContext &Ctx, ArrayRef< QualType > Xs, ArrayRef< QualType > Ys, bool Unqualified=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)
static NestedNameSpecifier getCommonQualifier(const ASTContext &Ctx, const T *X, const T *Y, bool IsSame)
#define UNEXPECTED_TYPE(Class, Kind)
static TypedefDecl * CreateVaListDecl(const ASTContext *Context, TargetInfo::BuiltinVaListKind Kind)
static bool primaryBaseHaseAddressDiscriminatedVTableAuthentication(const ASTContext &Context, const CXXRecordDecl *Class)
static std::vector< std::string > getFMVBackendFeaturesFor(const llvm::SmallVectorImpl< StringRef > &FMVFeatStrings)
Defines the clang::ASTContext interface.
#define V(N, I)
#define BuiltinTemplate(BTName)
Definition ASTContext.h:475
Provides definitions for the various language-specific address spaces.
static bool isUnsigned(SValBuilder &SVB, NonLoc Value)
Defines enum values for all the target-independent builtin functions.
static bool CanThrow(Expr *E, ASTContext &Ctx)
Definition CFG.cpp:2852
Defines the clang::CommentOptions interface.
static Decl::Kind getKind(const Decl *D)
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.
FormatToken * Next
The next token in the unwrapped line.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
static const Decl * getCanonicalDecl(const Decl *D)
#define X(type, name)
Definition Value.h:97
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
Defines the clang::MacroInfo and clang::MacroDirective classes.
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:95
Defines the clang::Module class, which describes a module in the source code.
static StringRef getTriple(const Command &Job)
Defines types useful for describing an Objective-C runtime.
#define SM(sm)
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
static QualType getUnderlyingType(const SubRegion *R)
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.
C Language Family Type Representation.
QualType getReadPipeType(QualType T) const
Return a read_only pipe type for the specified type.
llvm::PointerUnion< const Decl *, const MacroInfo * > RawCommentLookupKey
Key used to look up the raw comment attached to a declaration or macro.
RawComment * getRawCommentNoCacheImpl(RawCommentLookupKey Key, const SourceLocation RepresentativeLoc, const std::map< unsigned, RawComment * > &CommentsInFile) const
QualType getWritePipeType(QualType T) const
Return a write_only pipe type for the specified type.
@ GE_Missing_stdio
Missing a type from <stdio.h>
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
bool isMemberPointerToDerivedMember() const
Definition APValue.cpp:1110
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1103
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition APValue.cpp:1117
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
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.
CanQualType AccumTy
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
TranslationUnitDecl * getTranslationUnitDecl() const
const ConstantArrayType * getAsConstantArrayType(QualType T) const
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.
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.
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
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.
unsigned getManglingNumber(const NamedDecl *ND, bool ForAuxTarget=false) const
CanQualType LongTy
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
@ Weak
Weak definition of inline variable.
@ WeakUnknown
Weak for now, might become strong later in this TU.
bool dtorHasOperatorDelete(const CXXDestructorDecl *Dtor, OperatorDeleteKind K) const
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
CanQualType SatUnsignedFractTy
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 areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
TypedefDecl * getObjCSelDecl() const
Retrieve the typedef corresponding to the predefined 'SEL' type in Objective-C.
CanQualType UnsignedShortAccumTy
TypedefDecl * getObjCInstanceTypeDecl()
Retrieve the typedef declaration corresponding to the Objective-C "instancetype" type.
bool isPFPField(const FieldDecl *Field) 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 isTypeAwareOperatorNewOrDelete(const FunctionDecl *FD) const
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 getCanonicalTemplateSpecializationType(ElaboratedTypeKeyword Keyword, TemplateName T, ArrayRef< TemplateArgument > CanonicalArgs) const
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.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
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:812
comments::FullComment * cloneFullComment(comments::FullComment *FC, const Decl *D) 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.
const TemplateArgument * getDefaultTemplateArgumentOrNone(const NamedDecl *P) const
Return the default argument of a template parameter, if one exists.
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.
std::unique_ptr< MangleNumberingContext > createMangleNumberingContext() const
CanQualType SatAccumTy
ArrayRef< CXXDefaultArgExpr * > getCtorClosureDefaultArgs(const CXXConstructorDecl *CD)
QualType getUnsignedPointerDiffType() const
Return the unique unsigned counterpart of "ptrdiff_t" integer type.
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.
RawComment * getRawCommentNoCache(RawCommentLookupKey Key) const
Return the documentation comment attached to a given declaration or macro, without looking into cache...
QualType getRealTypeForBitwidth(unsigned DestWidth, FloatModeKind ExplicitType) const
getRealTypeForBitwidth - sets floating point QualTy according to specified bitwidth.
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
CanQualType ShortAccumTy
ASTMutationListener * getASTMutationListener() const
Retrieve a pointer to the AST mutation listener associated with this AST context, if any.
unsigned NumImplicitCopyAssignmentOperatorsDeclared
The number of implicitly-declared copy assignment operators for which declarations were built.
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,...
unsigned char getFixedPointIBits(QualType Ty) const
QualType getSubstBuiltinTemplatePack(const TemplateArgument &ArgPack)
QualType getCorrespondingSignedFixedPointType(QualType Ty) const
IntrusiveRefCntPtr< ExternalASTSource > ExternalSource
Definition ASTContext.h:813
CanQualType FloatTy
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,...
unsigned NumImplicitDestructorsDeclared
The number of implicitly-declared destructors for which declarations were built.
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 propertyTypesAreCompatible(QualType, QualType)
void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, UsingShadowDecl *Pattern)
CanQualType DoubleTy
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
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.
TemplateName getDependentTemplateName(const DependentTemplateStorage &Name) const
Retrieve the template name that represents a dependent template name such as MetaFun::template operat...
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.
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
CanQualType OMPArrayShapingTy
ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents, SelectorTable &sels, Builtin::Context &builtins, TranslationUnitKind TUKind)
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
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)
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...
void setRelocationInfoForCXXRecord(const CXXRecordDecl *, CXXRecordDeclRelocationInfo)
QualType getSubstTemplateTypeParmType(QualType Replacement, Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex, bool Final) const
Retrieve a substitution-result type.
RecordDecl * buildImplicitRecord(StringRef Name, RecordDecl::TagKind TK=RecordDecl::TagKind::Struct) const
Create a new implicit TU-level CXXRecordDecl or RecordDecl declaration.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
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...
CanQualType UnsignedLongFractTy
QualType mergeTagDefinitions(QualType, QualType)
void setClassMaybeNeedsVectorDeletingDestructor(const CXXRecordDecl *RD)
overridden_method_range overridden_methods(const CXXMethodDecl *Method) const
void setIsTypeAwareOperatorNewOrDelete(const FunctionDecl *FD, bool IsTypeAware)
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
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
bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT, ObjCInterfaceDecl *IDecl)
QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in QT's qualified-id protocol list adopt...
FunctionProtoType::ExceptionSpecInfo mergeExceptionSpecs(FunctionProtoType::ExceptionSpecInfo ESI1, FunctionProtoType::ExceptionSpecInfo ESI2, SmallVectorImpl< QualType > &ExceptionTypeStorage, bool AcceptDependent) const
llvm::PointerUnion< const Decl *, const MacroInfo * > RawCommentLookupKey
Key used to look up the raw comment attached to a declaration or macro.
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...
bool BlockRequiresCopying(QualType Ty, const VarDecl *D)
Returns true iff we need copy/dispose helpers for the given type.
CanQualType NullPtrTy
QualType getUsingType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UsingShadowDecl *D, QualType UnderlyingType=QualType()) const
std::optional< QualType > tryMergeOverflowBehaviorTypes(QualType LHS, QualType RHS, bool OfBlockPointer, bool Unqualified, bool BlockReturnType, bool IsConditionalOperator)
Attempts to merge two types that may be OverflowBehaviorTypes.
CanQualType WideCharTy
CanQualType OMPIteratorTy
IdentifierTable & Idents
Definition ASTContext.h:808
Builtin::Context & BuiltinInfo
Definition ASTContext.h:810
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:965
QualType getFunctionTypeWithoutPtrSizes(QualType T)
Get a function type and produce the equivalent function type where pointer size address spaces in the...
uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID, const ObjCIvarDecl *Ivar) const
Get the offset of an ObjCIvarDecl in bits.
SelectorTable & Selectors
Definition ASTContext.h:809
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...
unsigned getMinGlobalAlignOfVar(uint64_t Size, const VarDecl *VD) const
Return the minimum alignment as specified by the target.
RawCommentList Comments
All comments in this translation unit.
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 getLateParsedAttrType(QualType Wrapped, LateParsedTypeAttribute *LateParsedAttr) const
Return a placeholder type for a late-parsed type attribute.
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
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod) const
Retrieves the default calling convention for the current context.
bool canBindObjCObjectType(QualType To, QualType From)
TemplateTemplateParmDecl * insertCanonicalTemplateTemplateParmDeclInternal(TemplateTemplateParmDecl *CanonTTP) const
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...
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier NNS, const IdentifierInfo *Name) const
Qualifiers::GC getObjCGCAttrKind(QualType Ty) const
Return one of the GCNone, Weak or Strong Objective-C garbage collection attributes.
CanQualType Ibm128Ty
bool hasUniqueObjectRepresentations(QualType Ty, bool CheckIfTriviallyCopyable=true) const
Return true if the specified type has unique object representations according to (C++17 [meta....
CanQualType getCanonicalSizeType() const
bool typesAreBlockPointerCompatible(QualType, QualType)
CanQualType SatUnsignedAccumTy
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 getAutoType(DeducedKind DK, QualType DeducedAsType, AutoTypeKeyword Keyword, TemplateDecl *TypeConstraintConcept=nullptr, ArrayRef< TemplateArgument > TypeConstraintArgs={}) const
C++11 deduced auto type.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
llvm::SetVector< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
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
CanQualType ObjCBuiltinIdTy
overridden_cxx_method_iterator overridden_methods_end(const CXXMethodDecl *Method) const
VTableContextBase * getVTableContext()
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>,...
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
PointerAuthQualifier getObjCMemberSelTypePtrAuth()
QualType AutoDeductTy
CanQualType BoolTy
void attachCommentsToJustParsedDecls(ArrayRef< Decl * > Decls, const Preprocessor *PP)
Searches existing comments for doc comments that should be attached to Decls.
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
std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const
Emit the encoded type for the function Decl into S.
TypeSourceInfo * getTemplateSpecializationTypeInfo(ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc, TemplateName T, SourceLocation TLoc, const TemplateArgumentListInfo &SpecifiedArgs, ArrayRef< TemplateArgument > CanonicalArgs, QualType Canon=QualType()) const
CanQualType UnsignedFractTy
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
void addOverriddenMethod(const CXXMethodDecl *Method, const CXXMethodDecl *Overridden)
Note that the given C++ Method overrides the given Overridden method.
TemplateTemplateParmDecl * findCanonicalTemplateTemplateParmDeclInternal(TemplateTemplateParmDecl *TTP) const
const TargetInfo * getAuxTargetInfo() const
Definition ASTContext.h:928
CanQualType Float128Ty
CanQualType ObjCBuiltinClassTy
unsigned NumImplicitDefaultConstructorsDeclared
The number of implicitly-declared default constructors for which declarations were built.
CanQualType UnresolvedTemplateTy
OMPTraitInfo & getNewOMPTraitInfo()
Return a new OMPTraitInfo object owned by this context.
friend class CXXRecordDecl
Definition ASTContext.h:586
CanQualType UnsignedLongTy
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...
const TranslationUnitKind TUKind
Definition ASTContext.h:811
CanQualType UnsignedLongAccumTy
QualType AutoRRefDeductTy
RawComment * getRawCommentNoCacheImpl(RawCommentLookupKey Key, const SourceLocation RepresentativeLoc, const std::map< unsigned, RawComment * > &CommentsInFile) const
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
CanQualType ShortFractTy
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 arePFPFieldsTriviallyCopyable(const RecordDecl *RD) const
Returns whether this record's PFP fields (if any) are trivially copyable (i.e.
bool isSameEntity(const NamedDecl *X, const NamedDecl *Y) const
Determine whether the two declarations refer to the same entity.
QualType getSubstTemplateTypeParmPackType(Decl *AssociatedDecl, unsigned Index, bool Final, const TemplateArgument &ArgPack)
CanQualType BoundMemberTy
CanQualType SatUnsignedShortFractTy
CanQualType CharTy
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.
BlockVarCopyInit getBlockVarCopyInit(const VarDecl *VD) const
Get the copy initialization expression of the VarDecl VD, or nullptr if none exists.
QualType getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size, uint32_t Alignment, ArrayRef< SpirvOperand > Operands)
unsigned NumImplicitMoveConstructorsDeclared
The number of implicitly-declared move constructors for which declarations were built.
bool isInSameModule(const Module *M1, const Module *M2) const
If the two module M1 and M2 are in the same module.
unsigned NumImplicitCopyConstructorsDeclared
The number of implicitly-declared copy constructors for which declarations were built.
QualType getLeastIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
CanQualType IntTy
CanQualType PseudoObjectTy
QualType getWebAssemblyExternrefType() const
Return a WebAssembly externref type.
void setTraversalScope(const std::vector< Decl * > &)
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.
friend class NestedNameSpecifier
Definition ASTContext.h:224
void PrintStats() const
MangleContext * cudaNVInitDeviceMC()
unsigned getAlignOfGlobalVar(QualType T, const VarDecl *VD) const
Return the alignment in bits that should be given to a global variable with type T.
bool areCompatibleOverflowBehaviorTypes(QualType LHS, QualType RHS)
Return true if two OverflowBehaviorTypes are compatible for assignment.
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.
unsigned NumImplicitDestructors
The number of implicitly-declared destructors.
CanQualType Float16Ty
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
bool isAlignmentRequired(const Type *T) const
Determine if the alignment the type has was required using an alignment attribute.
TagDecl * MSGuidTagDecl
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
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
ASTMutationListener * Listener
Definition ASTContext.h:814
CanQualType ObjCBuiltinBoolTy
TypeInfoChars getTypeInfoInChars(const Type *T) const
QualType getPredefinedSugarType(PredefinedSugarType::Kind KD) 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.
interp::Context & getInterpContext() const
Returns the clang bytecode interpreter context.
CanQualType OverloadTy
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.
TemplateTemplateParmDecl * getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const
Canonicalize the given TemplateTemplateParmDecl.
CanQualType OCLClkEventTy
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.
bool hasPFPFields(QualType Ty) const
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:861
void ResetObjCLayout(const ObjCInterfaceDecl *D)
ArrayRef< Module * > getModulesWithMergedDefinition(const NamedDecl *Def)
Get the additional modules in which the definition Def has been merged.
void setCtorClosureDefaultArgs(const CXXConstructorDecl *CD, ArrayRef< CXXDefaultArgExpr * > Args)
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
CanQualType SatUnsignedShortAccumTy
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false, bool IsConditionalOperator=false)
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.
QualType getPackIndexingType(QualType Pattern, Expr *IndexExpr, bool FullySubstituted=false, ArrayRef< QualType > Expansions={}, UnsignedOrNone Index=std::nullopt) const
static bool isObjCNSObjectType(QualType Ty)
Return true if this is an NSObject object with its NSObject attribute set.
GVALinkage GetGVALinkageForVariable(const VarDecl *VD) const
llvm::PointerUnion< VarTemplateDecl *, MemberSpecializationInfo * > TemplateOrSpecializationInfo
A type synonym for the TemplateOrInstantiation mapping.
Definition ASTContext.h:578
UsingShadowDecl * getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst)
QualType getVariableArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a non-unique reference to the type for a variable array of the specified element type.
QualType getObjCIdType() const
Represents the Objective-CC id type.
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...
QualType getCorrespondingUnsaturatedType(QualType Ty) const
comments::FullComment * getCommentForDecl(const Decl *D, const Preprocessor *PP) const
Return parsed documentation comment attached to a given declaration.
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.
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.
QualType getTypeDeclType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypeDecl *Decl) const
bool isDestroyingOperatorDelete(const FunctionDecl *FD) const
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CanQualType UnsignedInt128Ty
CanQualType BuiltinFnTy
ObjCInterfaceDecl * getObjCProtocolDecl() const
Retrieve the Objective-C class declaration corresponding to the predefined Protocol class.
unsigned NumImplicitDefaultConstructors
The number of implicitly-declared default constructors.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
llvm::iterator_range< overridden_cxx_method_iterator > overridden_method_range
unsigned NumImplicitMoveAssignmentOperatorsDeclared
The number of implicitly-declared move assignment operators for which declarations were built.
void setManglingNumber(const NamedDecl *ND, unsigned Number)
CanQualType OCLSamplerTy
TypedefDecl * getBuiltinVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_va_list type.
CanQualType getCanonicalTypeDeclType(const TypeDecl *TD) const
CanQualType VoidTy
QualType getPackExpansionType(QualType Pattern, UnsignedOrNone NumExpansions, bool ExpectPackInType=true) const
Form a pack expansion type with the given pattern.
CanQualType UnsignedCharTy
CanQualType UnsignedShortFractTy
BuiltinTemplateDecl * buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, const IdentifierInfo *II) const
void * Allocate(size_t Size, unsigned Align=8) const
Definition ASTContext.h:882
ArrayRef< ExplicitInstantiationDecl * > getExplicitInstantiationDecls(const NamedDecl *Spec) const
Get all ExplicitInstantiationDecls for a given specialization.
bool canBuiltinBeRedeclared(const FunctionDecl *) const
Return whether a declaration to a builtin is allowed to be overloaded/redeclared.
CanQualType UnsignedIntTy
unsigned NumImplicitMoveConstructors
The number of implicitly-declared move constructors.
QualType getTypedefType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType UnderlyingType=QualType(), std::optional< bool > TypeMatchesDeclOrNone=std::nullopt) const
Return the unique reference to the type for the specified typedef-name decl.
QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl, ArrayRef< ObjCProtocolDecl * > protocols) const
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.
QualType getTemplateSpecializationType(ElaboratedTypeKeyword Keyword, TemplateName T, ArrayRef< TemplateArgument > SpecifiedArgs, ArrayRef< TemplateArgument > CanonicalArgs, QualType Underlying=QualType()) const
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
TemplateName getQualifiedTemplateName(NestedNameSpecifier Qualifier, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
bool isSameAssociatedConstraint(const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const
Determine whether two 'requires' expressions are similar enough that they may be used in re-declarati...
QualType getExceptionObjectType(QualType T) const
CanQualType UnknownAnyTy
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
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
CanQualType OCLReserveIDTy
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
FunctionDecl * getOperatorDeleteForVDtor(const CXXDestructorDecl *Dtor, OperatorDeleteKind K) const
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 isRepresentableIntegerValue(llvm::APSInt &Value, QualType T)
Determine whether the given integral value is representable within the given type T.
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.
llvm::DenseMap< RawCommentLookupKey, const RawComment * > RawComments
Mapping from declaration or macro to directly attached comment.
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
QualType getMemberPointerType(QualType T, NestedNameSpecifier Qualifier, const CXXRecordDecl *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
const CXXConstructorDecl * getCopyConstructorForExceptionObject(CXXRecordDecl *RD)
QualType getDependentAddressSpaceType(QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttrLoc) const
QualType getTagType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TagDecl *TD, bool OwnsTag) const
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
CanQualType getMSGuidType() const
Retrieve the implicitly-predeclared 'struct _GUID' type.
const VariableArrayType * getAsVariableArrayType(QualType T) const
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.
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
StringLiteral * getPredefinedStringLiteralFromCache(StringRef Key) const
Return a string representing the human readable name for the specified function declaration or file n...
CanQualType getCanonicalUnresolvedUsingType(const UnresolvedUsingTypenameDecl *D) const
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 classMaybeNeedsVectorDeletingDestructor(const CXXRecordDecl *RD)
QualType getTemplateTypeParmType(int Depth, int Index, bool ParameterPack, TemplateTypeParmDecl *ParmDecl=nullptr) const
Retrieve the template type parameter type for a template parameter or parameter pack with the given d...
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
CanQualType FractTy
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)
void deduplicateMergedDefinitionsFor(NamedDecl *ND)
Clean up the merged definition list.
DiagnosticsEngine & getDiagnostics() const
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
CanQualType LongAccumTy
CanQualType Char32Ty
void recordOffsetOfEvaluation(const OffsetOfExpr *E)
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
UnnamedGlobalConstantDecl * getUnnamedGlobalConstantDecl(QualType Ty, const APValue &Value) const
Return a declaration for a uniquified anonymous global constant corresponding to a given APValue.
CanQualType SatFractTy
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
QualType getUnresolvedUsingType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UnresolvedUsingTypenameDecl *D) const
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
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:927
void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl)
CanQualType OCLQueueTy
CanQualType LongFractTy
OBTAssignResult checkOBTAssignmentCompatibility(QualType LHS, QualType RHS)
Check overflow behavior type compatibility for assignments.
CanQualType SatShortAccumTy
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CanQualType BFloat16Ty
unsigned NumImplicitCopyConstructors
The number of implicitly-declared copy constructors.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
void addExplicitInstantiationDecl(const NamedDecl *Spec, ExplicitInstantiationDecl *EID)
Add an ExplicitInstantiationDecl for a given specialization.
QualType getOverflowBehaviorType(const OverflowBehaviorAttr *Attr, QualType Wrapped) const
CanQualType IncompleteMatrixIdxTy
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.
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 ...
QualType getSignedSizeType() const
Return the unique signed counterpart of the integer type corresponding to size_t.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const
Return number of constant array elements.
CanQualType SatUnsignedLongAccumTy
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
CanQualType LongLongTy
CanQualType getCanonicalTagType(const TagDecl *TD) const
bool isSameTemplateArgument(const TemplateArgument &Arg1, const TemplateArgument &Arg2) const
Determine whether the given template arguments Arg1 and Arg2 are equivalent.
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.
uint64_t getArrayInitLoopExprElementCount(const ArrayInitLoopExpr *AILE) const
Return number of elements initialized in an ArrayInitLoopExpr.
unsigned getTargetAddressSpace(LangAS AS) const
std::vector< PFPField > findPFPFields(QualType Ty) const
Returns a list of PFP fields for the given type, including subfields in bases or other fields,...
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...
QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a non-unique reference to the type for a dependently-sized array of the specified element type...
void addTranslationUnitDecl()
CanQualType WCharTy
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.
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.
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.
std::optional< CXXRecordDeclRelocationInfo > getRelocationInfoForCXXRecord(const CXXRecordDecl *) const
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
InlineVariableDefinitionKind getInlineVariableDefinitionKind(const VarDecl *VD) const
Determine whether a definition of this inline variable should be treated as a weak or strong definiti...
const RawComment * getRawCommentForAnyRedecl(RawCommentLookupKey Key, const Decl **OriginalDecl=nullptr) const
Return the documentation comment attached to a given declaration or macro.
TemplateName getSubstTemplateTemplateParm(TemplateName replacement, Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex, bool Final) const
CanQualType getUIntMaxType() const
Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in <stdint.h>.
friend class DeclContext
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...
void addOperatorDeleteForVDtor(const CXXDestructorDecl *Dtor, FunctionDecl *OperatorDelete, OperatorDeleteKind K) const
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.
@ GE_Missing_type
Missing a type.
QualType adjustStringLiteralBaseType(QualType StrLTy) const
uint16_t getPointerAuthTypeDiscriminator(QualType T)
Return the "other" type-specific discriminator for the given type.
llvm::SetVector< const FieldDecl * > PFPFieldsWithEvaluatedOffset
bool canonicalizeTemplateArguments(MutableArrayRef< TemplateArgument > Args) const
Canonicalize the given template argument list.
QualType getTypeOfExprType(Expr *E, TypeOfKind Kind) const
C23 feature and GCC extension.
CanQualType Char8Ty
bool isUnaryOverflowPatternExcluded(const UnaryOperator *UO)
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
CanQualType UnsignedAccumTy
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.
const CXXRecordDecl * baseForVTableAuthentication(const CXXRecordDecl *ThisClass) const
Resolve the root record to be used to derive the vtable pointer authentication policy for the specifi...
void cacheRawComment(RawCommentLookupKey Original, const RawComment &Comment) const
Attaches Comment to Original (a declaration or macro), and to its redeclaration chain when Original i...
QualType getVariableArrayDecayedType(QualType Ty) const
Returns a vla type where known sizes are replaced with [*].
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...
QualType getCommonSugaredType(QualType X, QualType Y, bool Unqualified=false) const
CanQualType OCLEventTy
void AddDeallocation(void(*Callback)(void *), void *Data) const
Add a deallocation callback that will be invoked when the ASTContext is destroyed.
AttrVec & getDeclAttrs(const Decl *D)
Retrieve the attributes for the given declaration.
QualType getDeducedTemplateSpecializationType(DeducedKind DK, QualType DeducedAsType, ElaboratedTypeKeyword Keyword, TemplateName Template) const
C++17 deduced class template specialization type.
CXXMethodVector::const_iterator overridden_cxx_method_iterator
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
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
void setIsDestroyingOperatorDelete(const FunctionDecl *FD, bool IsDestroying)
TypedefDecl * getBuiltinZOSVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_zos_va_list type.
void recordMemberDataPointerEvaluation(const ValueDecl *VD)
uint64_t getCharWidth() const
Return the size of the character type, in bits.
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.
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
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/...
CharUnits getAlignment() const
getAlignment - Get the record alignment in characters.
const CXXRecordDecl * getBaseSharingVBPtr() const
CharUnits getSize() const
getSize - Get the record size in characters.
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
CharUnits getDataSize() const
getDataSize() - Get the record data size, which is the record size without tail padding,...
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getNonVirtualSize() const
getNonVirtualSize - Get the non-virtual size (in chars) of an object, which is the size of the object...
CharUnits getUnadjustedAlignment() const
getUnadjustedAlignment - Get the record alignment in characters, before alignment adjustment.
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition TypeBase.h:3588
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3609
Represents a loop initializing the elements of an array.
Definition Expr.h:5980
llvm::APInt getArraySize() const
Definition Expr.h:6002
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:6000
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition TypeBase.h:3991
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3821
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3835
Qualifiers getIndexTypeQualifiers() const
Definition TypeBase.h:3839
QualType getElementType() const
Definition TypeBase.h:3833
unsigned getIndexTypeCVRQualifiers() const
Definition TypeBase.h:3843
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:6940
Expr * getPtr() const
Definition Expr.h:6971
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8293
Attr - This represents one attribute.
Definition Attr.h:46
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8341
void Profile(llvm::FoldingSetNodeID &ID) const
Definition TypeBase.h:8358
unsigned getNumBits() const
Definition TypeBase.h:8353
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4716
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6684
Pointer to a block type.
Definition TypeBase.h:3641
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3658
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 TypeBase.h:3229
Kind getKind() const
Definition TypeBase.h:3277
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition Builtins.h:236
Implements C++ ABI-specific semantic analysis functions.
Definition CXXABI.h:29
virtual ~CXXABI()
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents a C++ constructor within a class.
Definition DeclCXX.h:2633
Represents a C++ destructor within a class.
Definition DeclCXX.h:2898
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2145
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2254
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr)
Definition DeclCXX.cpp:133
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:548
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1219
bool isDynamicClass() const
Definition DeclCXX.h:574
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1191
SplitQualType split() const
static CanQual< Type > CreateUnsafe(QualType Other)
QualType withConst() const
Retrieves a version of this type with const applied.
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
Qualifiers getQualifiers() const
Retrieve all qualifiers.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
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
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3340
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3355
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 TypeBase.h:3859
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition TypeBase.h:3955
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3915
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition TypeBase.h:3974
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3935
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4486
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4505
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4551
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4502
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition TypeBase.h:3501
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3537
Represents a pointer type decayed from an array or function type.
Definition TypeBase.h:3624
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1466
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
bool isFileContext() const
Definition DeclBase.h:2197
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2142
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void addDecl(Decl *D)
Add the declaration D into this context.
Decl::Kind getDeclKind() const
Definition DeclBase.h:2119
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1276
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
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:344
bool isModuleLocal() const
Whether this declaration was a local declaration to a C++20 named module.
T * getAttr() const
Definition DeclBase.h:581
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
void addAttr(Attr *A)
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition DeclBase.cpp:564
bool isUnconditionallyVisible() const
Determine whether this declaration is definitely visible to name lookup, independent of whether the o...
Definition DeclBase.h:871
static Decl * castFromDeclContext(const DeclContext *)
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp:308
bool isCanonicalDecl() const
Whether this particular Decl is a canonical one.
Definition DeclBase.h:1001
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:854
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
ObjCDeclQualifier
ObjCDeclQualifier - 'Qualifiers' written next to the return and parameter types in method declaration...
Definition DeclBase.h:198
bool isInvalidDecl() const
Definition DeclBase.h:596
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:567
void setImplicit(bool I=true)
Definition DeclBase.h:602
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition DeclBase.h:1066
DeclContext * getDeclContext()
Definition DeclBase.h:456
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition DeclBase.cpp:385
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:935
bool hasAttr() const
Definition DeclBase.h:585
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:995
Kind getKind() const
Definition DeclBase.h:450
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.
The name of a declaration.
static int compare(DeclarationName LHS, DeclarationName RHS)
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:780
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
TemplateName getUnderlying() const
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) const
DefaultArguments getDefaultArguments() const
Represents an extended address space qualifier where the input address space value is dependent.
Definition TypeBase.h:4160
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4182
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:8386
Represents an array type in C++ whose size is a value-dependent expression.
Definition TypeBase.h:4110
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4139
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4200
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4225
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4572
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4592
Represents a dependent template name that cannot be resolved prior to template instantiation.
void Profile(llvm::FoldingSetNodeID &ID) const
IdentifierOrOverloadedOperator getName() const
NestedNameSpecifier getQualifier() const
Return the nested name specifier that qualifies this name.
bool hasTemplateKeyword() const
Was this template name was preceeded by the template keyword?
Internal representation of canonical, dependent typeof(expr) types.
Definition TypeBase.h:6351
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:6356
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4326
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4351
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:234
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
A dynamically typed AST node container.
Represents an enum.
Definition Decl.h:4055
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4273
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4287
EnumDecl * getDefinitionOrSelf() const
Definition Decl.h:4171
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4228
Represents an explicit instantiation of a template entity in source code.
This represents one expression.
Definition Expr.h:112
bool isIntegerConstantExpr(const ASTContext &Ctx) const
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3106
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:447
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4241
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:837
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition Expr.h:223
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3081
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:4080
QualType getType() const
Definition Expr.h:144
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:437
We can encode up to four bits in the low bits of a type pointer, but there are many more type qualifi...
Definition TypeBase.h:1733
void Profile(llvm::FoldingSetNodeID &ID) const
Definition TypeBase.h:1780
ExtVectorType - Extended vector type.
Definition TypeBase.h:4366
Declaration context for names declared as extern "C" in C++.
Definition Decl.h:247
static ExternCContextDecl * Create(const ASTContext &C, TranslationUnitDecl *TU)
Definition Decl.cpp:5548
Abstract interface for external sources of AST nodes.
virtual void CompleteRedeclChain(const Decl *D)
Gives the external AST source an opportunity to complete the redeclaration chain for a declaration.
Represents a member of a struct/union/class.
Definition Decl.h:3204
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3307
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4752
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3289
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3440
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:4700
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:2029
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2729
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3742
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2961
bool isMSExternInline() const
The combination of the extern and inline keywords under MSVC forces the function to be required.
Definition Decl.cpp:3871
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3727
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition Decl.h:2318
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4397
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition Decl.h:2446
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:4058
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5374
static FunctionEffectSet getIntersection(FunctionEffectsRef LHS, FunctionEffectsRef RHS)
Definition Type.cpp:5858
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition Type.cpp:5896
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5206
ArrayRef< EffectConditionExpr > conditions() const
Definition TypeBase.h:5240
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:4984
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:5000
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5406
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5910
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5713
unsigned getNumParams() const
Definition TypeBase.h:5684
QualType getParamType(unsigned i) const
Definition TypeBase.h:5686
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition Type.cpp:4086
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5719
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5810
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5695
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5691
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition TypeBase.h:5879
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition TypeBase.h:5875
Declaration of a template function.
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4713
CallingConv getCC() const
Definition TypeBase.h:4772
unsigned getRegParm() const
Definition TypeBase.h:4765
bool getNoCallerSavedRegs() const
Definition TypeBase.h:4761
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4784
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition TypeBase.h:4628
ExtParameterInfo withIsNoEscape(bool NoEscape) const
Definition TypeBase.h:4668
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4602
ExtInfo getExtInfo() const
Definition TypeBase.h:4958
QualType getReturnType() const
Definition TypeBase.h:4942
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:57
unsigned getMultiVersionIndex() const
Definition GlobalDecl.h:125
CXXDtorType getDtorType() const
Definition GlobalDecl.h:113
const Decl * getDecl() const
Definition GlobalDecl.h:106
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.
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition Decl.h:5097
Represents a C array with an unspecified size.
Definition TypeBase.h:4008
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4025
static ItaniumMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3716
@ 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.
@ PostDecrInWhile
while (count–)
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
std::optional< TargetCXXABI::Kind > CXXABI
C++ ABI to compile with, if specified by the frontend through -fc++-abi=.
clang::ObjCRuntime ObjCRuntime
CoreFoundationABI CFRuntime
bool isOverflowPatternExcluded(OverflowPatternExclusionKind Kind) const
Represents a placeholder type for late-parsed type attributes.
Definition TypeBase.h:3560
A global _GUID constant.
Definition DeclCXX.h:4424
static void Profile(llvm::FoldingSetNodeID &ID, Parts P)
Definition DeclCXX.h:4461
MSGuidDeclParts Parts
Definition DeclCXX.h:4426
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition TypeBase.h:6285
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
Definition Mangle.h:56
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
static bool isValidElementType(QualType T, const LangOptions &LangOpts)
Valid elements types are the following:
Definition TypeBase.h:4457
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4450
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3752
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3795
Provides information a specialization of a member of a class template, which may be a member function...
static MicrosoftMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
Describes a module or submodule.
Definition Module.h:340
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition Module.h:423
This represents a decl that may have a name.
Definition Decl.h:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition Decl.cpp:1095
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
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:317
bool isExternallyVisible() const
Definition Decl.h:433
Represent a C++ namespace.
Definition Decl.h:592
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl, bool Nested)
Definition DeclCXX.cpp:3374
A C++ nested-name-specifier augmented with source location information.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NestedNameSpecifier getCanonical() const
Retrieves the "canonical" nested name specifier for a given nested name specifier.
CXXRecordDecl * getAsMicrosoftSuper() const
NamespaceAndPrefix getAsNamespaceAndPrefix() const
Kind
The kind of specifier that completes this nested name specifier.
@ MicrosoftSuper
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace-like entity, stored as a NamespaceBaseDecl*.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, int D, int P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
ObjCCategoryDecl - Represents a category declaration.
Definition DeclObjC.h:2329
ObjCCategoryImplDecl - An object of this class encapsulates a category @implementation declaration.
Definition DeclObjC.h:2545
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition DeclObjC.h:2597
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
ObjCTypeParamList * getTypeParamList() const
Retrieve the type parameters of this class.
Definition DeclObjC.cpp:319
static ObjCInterfaceDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation atLoc, const IdentifierInfo *Id, ObjCTypeParamList *typeParamList, ObjCInterfaceDecl *PrevDecl, SourceLocation ClassLoc=SourceLocation(), bool isInternal=false)
bool hasDefinition() const
Determine whether this class has been defined.
Definition DeclObjC.h:1528
ivar_range ivars() const
Definition DeclObjC.h:1451
bool ClassImplementsProtocol(ObjCProtocolDecl *lProto, bool lookupCategory, bool RHSIsQualifiedID=false)
ClassImplementsProtocol - Checks that 'lProto' protocol has been implemented in IDecl class,...
StringRef getObjCRuntimeNameAsString() const
Produce a name to be used for class's metadata.
ObjCImplementationDecl * getImplementation() const
ObjCInterfaceDecl * getSuperClass() const
Definition DeclObjC.cpp:349
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:1810
known_extensions_range known_extensions() const
Definition DeclObjC.h:1762
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:8051
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition Type.cpp:988
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1952
ObjCIvarDecl * getNextIvar()
Definition DeclObjC.h:1987
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 TypeBase.h:8107
bool isObjCQualifiedClassType() const
True if this is equivalent to 'Class.
Definition TypeBase.h:8188
const ObjCObjectPointerType * stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const
Strip off the Objective-C "kindof" type and (with it) any protocol qualifiers.
Definition Type.cpp:995
bool isObjCQualifiedIdType() const
True if this is equivalent to 'id.
Definition TypeBase.h:8182
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8264
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8144
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:8165
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8119
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:8159
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:1889
qual_range quals() const
Definition TypeBase.h:8226
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition TypeBase.h:8171
Represents one property declaration in an Objective-C interface.
Definition DeclObjC.h:731
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
Definition DeclObjC.h:838
static ObjCPropertyDecl * findPropertyDecl(const DeclContext *DC, const IdentifierInfo *propertyID, ObjCPropertyQueryKind queryKind)
Lookup a property by name in the specified DeclContext.
Definition DeclObjC.cpp:176
bool isOptional() const
Definition DeclObjC.h:916
SetterKind getSetterKind() const
getSetterKind - Return the method used for doing assignment in the property setter.
Definition DeclObjC.h:873
Selector getSetterName() const
Definition DeclObjC.h:893
QualType getType() const
Definition DeclObjC.h:804
Selector getGetterName() const
Definition DeclObjC.h:885
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition DeclObjC.h:815
ObjCPropertyImplDecl - Represents implementation declaration of a property in a class or category imp...
Definition DeclObjC.h:2805
ObjCIvarDecl * getPropertyIvarDecl() const
Definition DeclObjC.h:2879
Represents an Objective-C protocol declaration.
Definition DeclObjC.h:2084
protocol_range protocols() const
Definition DeclObjC.h:2161
bool isGNUFamily() const
Is this runtime basically of the GNU family of runtimes?
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:662
OffsetOfExpr - [C99 7.17] - This represents an expression of the form offsetof(record-type,...
Definition Expr.h:2533
const OffsetOfNode & getComponent(unsigned Idx) const
Definition Expr.h:2580
unsigned getNumComponents() const
Definition Expr.h:2588
Helper class for OffsetOfExpr.
Definition Expr.h:2427
@ Field
A field.
Definition Expr.h:2434
A structure for storing the information associated with an overloaded template name.
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition ExprCXX.h:4362
Sugar for parentheses used when specifying types.
Definition TypeBase.h:3367
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3381
void clear()
Clear parent maps.
DynTypedNodeList getParents(const NodeT &Node)
Returns the parents of the given node (within the traversal scope).
Represents a parameter to a function.
Definition Decl.h:1819
ObjCDeclQualifier getObjCDeclQualifier() const
Definition Decl.h:1883
QualType getOriginalType() const
Definition Decl.cpp:2945
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8324
Pointer-authentication qualifiers.
Definition TypeBase.h:153
static PointerAuthQualifier Create(unsigned Key, bool IsAddressDiscriminated, unsigned ExtraDiscriminator, PointerAuthenticationMode AuthenticationMode, bool IsIsaPointer, bool AuthenticatesNullValues)
Definition TypeBase.h:240
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:302
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3393
QualType getPointeeType() const
Definition TypeBase.h:3403
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3408
PredefinedSugarKind Kind
Definition TypeBase.h:8400
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
A (possibly-)qualified type.
Definition TypeBase.h:938
bool hasAddressDiscriminatedPointerAuth() const
Definition TypeBase.h:1473
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8573
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2970
Qualifiers::GC getObjCGCAttr() const
Returns gc attribute of this type.
Definition TypeBase.h:8620
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8578
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition TypeBase.h:1312
QualType withConst() const
Definition TypeBase.h:1175
bool hasLocalQualifiers() const
Determine whether this particular QualType instance has any qualifiers, without looking through any t...
Definition TypeBase.h:1065
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8489
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8615
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8529
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1454
QualType getCanonicalType() const
Definition TypeBase.h:8541
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8583
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition TypeBase.h:8510
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8562
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1561
bool isCanonical() const
Definition TypeBase.h:8546
const Type * getTypePtrOrNull() const
Definition TypeBase.h:8493
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1348
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:3113
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8521
Represents a template name as written in source code.
void Profile(llvm::FoldingSetNodeID &ID)
A qualifier set is used to build a set of qualifiers.
Definition TypeBase.h:8429
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8436
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
unsigned getCVRQualifiers() const
Definition TypeBase.h:489
void removeCVRQualifiers(unsigned mask)
Definition TypeBase.h:496
GC getObjCGCAttr() const
Definition TypeBase.h:520
void addAddressSpace(LangAS space)
Definition TypeBase.h:598
static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R)
Returns the common set of qualifiers while removing them from the given sets.
Definition TypeBase.h:385
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:362
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:355
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:351
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:365
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:368
void removeObjCLifetime()
Definition TypeBase.h:552
bool hasNonFastQualifiers() const
Return true if the set contains any qualifiers which require an ExtQuals node to be allocated.
Definition TypeBase.h:639
void addConsistentQualifiers(Qualifiers qs)
Add the qualifiers from the given set to this set, given that they don't conflict.
Definition TypeBase.h:690
void removeFastQualifiers(unsigned mask)
Definition TypeBase.h:625
bool hasUnaligned() const
Definition TypeBase.h:512
bool hasAddressSpace() const
Definition TypeBase.h:571
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 TypeBase.h:709
unsigned getFastQualifiers() const
Definition TypeBase.h:620
void removeAddressSpace()
Definition TypeBase.h:597
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:604
bool hasObjCGCAttr() const
Definition TypeBase.h:519
uint64_t getAsOpaqueValue() const
Definition TypeBase.h:456
bool hasObjCLifetime() const
Definition TypeBase.h:545
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:546
bool empty() const
Definition TypeBase.h:648
void addObjCGCAttr(GC type)
Definition TypeBase.h:525
LangAS getAddressSpace() const
Definition TypeBase.h:572
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3734
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:4369
bool isLambda() const
Determine whether this record is a class describing a lambda function object.
Definition Decl.cpp:5246
bool hasFlexibleArrayMember() const
Definition Decl.h:4402
field_range fields() const
Definition Decl.h:4572
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition Decl.cpp:5232
RecordDecl * getMostRecentDecl()
Definition Decl.h:4395
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition Decl.cpp:5291
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4553
bool field_empty() const
Definition Decl.h:4580
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3672
QualType getPointeeType() const
Definition TypeBase.h:3690
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3698
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.
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.
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1805
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, ArrayRef< SourceLocation > Locs)
This is the "fully general" constructor that allows representation of strings formed from one or more...
Definition Expr.cpp:1194
A structure for storing an already-substituted template template parameter pack.
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.
A structure for storing the information associated with a substituted template template parameter.
void Profile(llvm::FoldingSetNodeID &ID)
TemplateTemplateParmDecl * getParameter() const
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3761
TagTypeKind TagKind
Definition Decl.h:3766
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition Decl.h:3998
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4906
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4899
bool isUnion() const
Definition Decl.h:3972
TagKind getTagKind() const
Definition Decl.h:3961
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Kind
The basic C++ ABI kind.
static Kind getKind(StringRef Name)
Exposes information about the current target.
Definition TargetInfo.h:227
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
unsigned getMaxAtomicInlineWidth() const
Return the maximum width lock-free atomic operation which can be inlined given the supported features...
Definition TargetInfo.h:862
virtual LangAS getCUDABuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
virtual LangAS getOpenCLBuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
unsigned getDefaultAlignForAttributeAligned() const
Return the default alignment for attribute((aligned)) on this target, to be used if no alignment valu...
Definition TargetInfo.h:755
BuiltinVaListKind
The different kinds of __builtin_va_list types defined by the target implementation.
Definition TargetInfo.h:337
@ AArch64ABIBuiltinVaList
__builtin_va_list as defined by the AArch64 ABI http://infocenter.arm.com/help/topic/com....
Definition TargetInfo.h:346
@ PowerABIBuiltinVaList
__builtin_va_list as defined by the Power ABI: https://www.power.org /resources/downloads/Power-Arch-...
Definition TargetInfo.h:351
@ AAPCSABIBuiltinVaList
__builtin_va_list as defined by ARM AAPCS ABI http://infocenter.arm.com
Definition TargetInfo.h:360
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition TargetInfo.h:339
@ VoidPtrBuiltinVaList
typedef void* __builtin_va_list;
Definition TargetInfo.h:342
@ X86_64ABIBuiltinVaList
__builtin_va_list as defined by the x86-64 ABI: http://refspecs.linuxbase.org/elf/x86_64-abi-0....
Definition TargetInfo.h:355
virtual uint64_t getNullPointerValue(LangAS AddrSpace) const
Get integer value for null pointer.
Definition TargetInfo.h:509
static bool isTypeSigned(IntType T)
Returns true if the type is signed; false otherwise.
IntType getPtrDiffType(LangAS AddrSpace) const
Definition TargetInfo.h:411
IntType getSizeType() const
Definition TargetInfo.h:392
FloatModeKind getRealTypeByWidth(unsigned BitWidth, FloatModeKind ExplicitType) const
Return floating point type with specified width.
virtual IntType getIntTypeByWidth(unsigned BitWidth, bool IsSigned) const
Return integer type with specified width.
unsigned getMaxAlignedAttribute() const
Get the maximum alignment in bits for a static variable with aligned attribute.
Definition TargetInfo.h:982
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:763
unsigned getTargetAddressSpace(LangAS AS) const
IntType getSignedSizeType() const
Definition TargetInfo.h:393
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
bool useAddressSpaceMapMangling() const
Specify if mangling based on address space map should be used or not for language specific address sp...
A convenient class for passing around template argument information.
ArrayRef< TemplateArgumentLoc > arguments() const
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Location wrapper for a TemplateArgument.
Represents a template argument.
ArrayRef< TemplateArgument > getPackAsArray() const
Return the array of arguments in this template argument pack.
QualType getStructuralValueType() const
Get the type of a StructuralValue.
QualType getParamTypeForDecl() const
Expr * getAsExpr() const
Retrieve the template argument as an expression.
UnsignedOrNone 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.
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
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.
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.
bool getIsDefaulted() const
If returns 'true', this TemplateArgument corresponds to a default template parameter.
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
ArrayRef< TemplateArgument > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
@ Template
The template argument is a template name that was provided for a template template parameter.
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
@ Pack
The template argument is actually a parameter pack.
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
@ Type
The template argument is a type.
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
ArgKind getKind() const
Return the kind of stored template argument.
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
The base class of all kinds of template declarations (e.g., class, function, etc.).
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
DeducedTemplateStorage * getAsDeducedTemplateName() const
Retrieve the deduced template info, if any.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
std::optional< TemplateName > desugar(bool IgnoreDeduced) const
OverloadedTemplateStorage * getAsOverloadedTemplate() const
Retrieve the underlying, overloaded function template declarations that this template name refers to,...
AssumedTemplateStorage * getAsAssumedTemplateName() const
Retrieve information on a name that has been assumed to be a template-name in order to permit a call ...
NameKind getKind() const
void * getAsVoidPointer() const
Retrieve the template name as a void pointer.
@ UsingTemplate
A template name that refers to a template declaration found through a specific using shadow declarati...
@ OverloadedTemplate
A set of overloaded template declarations.
@ Template
A single template declaration.
@ DependentTemplate
A dependent template name that has not been resolved to a template (or set of templates).
@ SubstTemplateTemplateParm
A template template parameter that has been substituted for some other template name.
@ SubstTemplateTemplateParmPack
A template template parameter pack that has been substituted for a template template argument pack,...
@ DeducedTemplate
A template name that refers to another TemplateName with deduced default arguments.
@ QualifiedTemplate
A qualified template name, where the qualification is kept to describe the source code as written.
@ AssumedTemplate
An unqualified-id that has been assumed to name a function template that will be found by ADL.
UsingShadowDecl * getAsUsingShadowDecl() const
Retrieve the using shadow declaration through which the underlying template declaration is introduced...
SubstTemplateTemplateParmPackStorage * getAsSubstTemplateTemplateParmPack() const
Retrieve the substituted template template parameter pack, if known.
SubstTemplateTemplateParmStorage * getAsSubstTemplateTemplateParm() const
Retrieve the substituted template template parameter, if known.
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.
NamedDecl * getParam(unsigned Idx)
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.
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
ArrayRef< NamedDecl * > asArray()
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
TemplateNameKind templateParameterKind() const
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.
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, int D, int P, bool ParameterPack, IdentifierInfo *Id, TemplateNameKind ParameterKind, bool Typename, TemplateParameterList *Params)
unsigned getDepth() const
Get the nesting depth of the template parameter.
Declaration of a template type parameter.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, int D, int P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, UnsignedOrNone NumExpanded=std::nullopt)
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition ASTConcept.h:227
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition ASTConcept.h:244
TemplateDecl * getNamedConcept() const
Definition ASTConcept.h:254
ConceptReference * getConceptReference() const
Definition ASTConcept.h:248
Represents a declaration of a type.
Definition Decl.h:3557
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:95
void initialize(ASTContext &Context, SourceLocation Loc) const
Initializes this to state that every location in this type is the given location.
Definition TypeLoc.h:211
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition TypeBase.h:6317
A container of type source information.
Definition TypeBase.h:8460
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
The base class of the type hierarchy.
Definition TypeBase.h:1876
bool isBlockPointerType() const
Definition TypeBase.h:8746
bool isVoidType() const
Definition TypeBase.h:9092
bool isObjCBuiltinType() const
Definition TypeBase.h:8956
QualType getRVVEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an RVV builtin type.
Definition Type.cpp:2775
bool isIncompleteArrayType() const
Definition TypeBase.h:8833
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2270
bool isFloat16Type() const
Definition TypeBase.h:9101
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isConstantArrayType() const
Definition TypeBase.h:8829
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2521
bool isArrayType() const
Definition TypeBase.h:8825
bool isCharType() const
Definition Type.cpp:2197
bool isPointerType() const
Definition TypeBase.h:8726
TagDecl * castAsTagDecl() const
Definition Type.h:69
bool isArrayParameterType() const
Definition TypeBase.h:8841
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9136
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9386
bool isSignedFixedPointType() const
Return true if this is a fixed point type that is signed according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9180
bool isEnumeralType() const
Definition TypeBase.h:8857
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8926
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9214
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2964
bool isBitIntType() const
Definition TypeBase.h:9001
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8849
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2847
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9152
bool isHalfType() const
Definition TypeBase.h:9096
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9168
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2466
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3184
@ PtrdiffT
The "ptrdiff_t" type.
Definition TypeBase.h:2341
@ SizeT
The "size_t" type.
Definition TypeBase.h:2335
@ SignedSizeT
The signed integer type corresponding to "size_t".
Definition TypeBase.h:2338
bool isObjCIdType() const
Definition TypeBase.h:8938
bool isOverflowBehaviorType() const
Definition TypeBase.h:8897
bool isUnsaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9176
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9372
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2531
bool isFunctionType() const
Definition TypeBase.h:8722
bool isObjCObjectPointerType() const
Definition TypeBase.h:8905
bool isUnsignedFixedPointType() const
Return true if this is a fixed point type that is unsigned according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9194
bool isVectorType() const
Definition TypeBase.h:8865
bool isObjCClassType() const
Definition TypeBase.h:8944
bool isRVVVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'riscv_rvv_vector_bits' type attribute,...
Definition Type.cpp:2757
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2692
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2986
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:2336
bool isAnyPointerType() const
Definition TypeBase.h:8734
TypeClass getTypeClass() const
Definition TypeBase.h:2446
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2472
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9319
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:690
bool isNullPtrType() const
Definition TypeBase.h:9129
bool isRecordType() const
Definition TypeBase.h:8853
bool isObjCRetainableType() const
Definition Type.cpp:5435
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5156
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3711
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5766
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3606
QualType getUnderlyingType() const
Definition Decl.h:3661
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType Underlying)
Definition TypeBase.h:6261
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2250
Opcode getOpcode() const
Definition Expr.h:2286
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition DeclCXX.h:4481
static void Profile(llvm::FoldingSetNodeID &ID, QualType Ty, const APValue &APVal)
Definition DeclCXX.h:4509
The iterator over UnresolvedSets.
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition TypeBase.h:6122
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UnresolvedUsingTypenameDecl *D)
Definition TypeBase.h:6159
Represents a dependent using declaration which was marked with typename.
Definition DeclCXX.h:4058
UnresolvedUsingTypenameDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this declaration.
Definition DeclCXX.h:4123
Represents a C++ using-enum-declaration.
Definition DeclCXX.h:3813
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3420
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3484
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition DeclCXX.cpp:3487
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UsingShadowDecl *D, QualType UnderlyingType)
Definition TypeBase.h:6199
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
void setType(QualType newType)
Definition Decl.h:724
QualType getType() const
Definition Decl.h:723
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5581
void clear()
Definition Value.cpp:217
Represents a variable declaration or definition.
Definition Decl.h:932
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2773
bool hasInit() const
Definition Decl.cpp:2379
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:2442
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1306
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1214
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1575
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1318
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2356
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:2742
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4065
Expr * getSizeExpr() const
Definition TypeBase.h:4079
Represents a GCC generic vector type.
Definition TypeBase.h:4274
unsigned getNumElements() const
Definition TypeBase.h:4289
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4298
VectorKind getVectorKind() const
Definition TypeBase.h:4294
QualType getElementType() const
Definition TypeBase.h:4288
A full comment attached to a declaration, contains block content.
Definition Comment.h:1097
ArrayRef< BlockContentComment * > getBlocks() const
Definition Comment.h:1135
const DeclInfo * getDeclInfo() const LLVM_READONLY
Definition Comment.h:1129
const Decl * getDecl() const LLVM_READONLY
Definition Comment.h:1125
Holds all information required to evaluate constexpr code in a module.
Definition Context.h:47
Defines the Linkage enumeration and various utility functions.
Defines the clang::TargetInfo interface.
Definition SPIR.cpp:47
mlir::Type getBaseType(mlir::Value varPtr)
const AstTypeMatcher< TagType > tagType
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
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus17
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 TypeBase.h:1835
OpenCLTypeKind
OpenCL type kinds.
Definition TargetInfo.h:213
@ OCLTK_ReserveID
Definition TargetInfo.h:220
@ OCLTK_Sampler
Definition TargetInfo.h:221
@ OCLTK_Pipe
Definition TargetInfo.h:218
@ OCLTK_ClkEvent
Definition TargetInfo.h:215
@ OCLTK_Event
Definition TargetInfo.h:216
@ OCLTK_Default
Definition TargetInfo.h:214
@ OCLTK_Queue
Definition TargetInfo.h:219
FunctionType::ExtInfo getFunctionExtInfo(const Type &t)
Definition TypeBase.h:8624
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
NullabilityKind
Describes the nullability of a particular type.
Definition Specifiers.h:349
@ Nullable
Values of this type can be null.
Definition Specifiers.h:353
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
Definition Specifiers.h:358
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:351
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:273
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
std::pair< FileID, unsigned > FileIDAndOffset
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 TypeBase.h:919
@ AS_public
Definition Specifiers.h:125
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ SC_Register
Definition Specifiers.h:258
@ SC_Static
Definition Specifiers.h:253
CXXABI * CreateItaniumCXXABI(ASTContext &Ctx)
Creates an instance of a C++ ABI class.
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.
Definition Linkage.h:58
@ Result
The result type of a method or function.
Definition TypeBase.h:906
@ TypeAlignment
Definition TypeBase.h:77
ArraySizeModifier
Capture whether this is a normal array (e.g.
Definition TypeBase.h:3818
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
@ Template
We are parsing a template declaration.
Definition Parser.h:81
@ Interface
The "__interface" keyword.
Definition TypeBase.h:6035
@ Struct
The "struct" keyword.
Definition TypeBase.h:6032
@ Class
The "class" keyword.
Definition TypeBase.h:6041
constexpr uint16_t SelPointerConstantDiscriminator
Constant discriminator to be used with objective-c sel pointers.
bool isDiscardableGVALinkage(GVALinkage L)
Definition Linkage.h:80
BuiltinTemplateKind
Kinds of BuiltinTemplateDecl.
Definition Builtins.h:491
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:562
LangAS
Defines the address space values used by the address space qualifier of QualType.
TranslationUnitKind
Describes the kind of translation unit being processed.
DeducedKind
Definition TypeBase.h:1808
@ Deduced
The normal deduced case.
Definition TypeBase.h:1815
@ Undeduced
Not deduced yet. This is for example an 'auto' which was just parsed.
Definition TypeBase.h:1810
const Decl & adjustDeclToTemplate(const Decl &D)
If we have a 'templated' declaration for a template, adjust 'D' to refer to the actual template.
FloatModeKind
Definition TargetInfo.h:75
bool isPtrSizeAddressSpace(LangAS AS)
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:133
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:145
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:140
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1305
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ConceptReference *C)
Insertion operator for diagnostics.
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:189
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:207
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:203
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:199
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:195
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:192
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:279
@ CC_M68kRTD
Definition Specifiers.h:300
@ CC_X86RegCall
Definition Specifiers.h:288
@ CC_X86VectorCall
Definition Specifiers.h:284
@ CC_X86StdCall
Definition Specifiers.h:281
@ CC_X86FastCall
Definition Specifiers.h:282
@ Invariant
The parameter is invariant: must match exactly.
Definition DeclObjC.h:555
@ Contravariant
The parameter is contravariant, e.g., X<T> is a subtype of X when the type parameter is covariant and...
Definition DeclObjC.h:563
@ Covariant
The parameter is covariant, e.g., X<T> is a subtype of X when the type parameter is covariant and T i...
Definition DeclObjC.h:559
@ AltiVecBool
is AltiVec 'vector bool ...'
Definition TypeBase.h:4244
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4253
@ AltiVecPixel
is AltiVec 'vector Pixel'
Definition TypeBase.h:4241
@ Generic
not a target-specific vector type
Definition TypeBase.h:4235
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
Definition TypeBase.h:4259
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
Definition TypeBase.h:4262
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4256
U cast(CodeGen::Address addr)
Definition Address.h:327
LangAS getLangASFromTargetAS(unsigned TargetAS)
AlignRequirementKind
Definition ASTContext.h:174
@ None
The alignment was not explicit in code.
Definition ASTContext.h:176
@ RequiredByEnum
The alignment comes from an alignment attribute on a enum type.
Definition ASTContext.h:185
@ RequiredByTypedef
The alignment comes from an alignment attribute on a typedef.
Definition ASTContext.h:179
@ RequiredByRecord
The alignment comes from an alignment attribute on a record type.
Definition ASTContext.h:182
@ PackIndex
Index of a pack indexing expression or specifier.
Definition Sema.h:851
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:6005
@ Interface
The "__interface" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6010
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6026
@ Struct
The "struct" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6007
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6016
@ Union
The "union" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6013
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6019
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:6023
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_DependentNoexcept
noexcept(expression), value-dependent
@ 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)
unsigned long uint64_t
unsigned NumTemplateArgs
The number of template arguments in TemplateArgs.
const Expr * ConstraintExpr
Definition Decl.h:88
UnsignedOrNone ArgPackSubstIndex
Definition Decl.h:89
Copy initialization expr of a __block variable and a boolean flag that indicates whether the expressi...
Definition Expr.h:6730
Expr * getCopyExpr() const
Definition Expr.h:6737
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
ArrayRef< TemplateArgument > Args
Holds information about the various types of exception specification.
Definition TypeBase.h:5463
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5465
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition TypeBase.h:5468
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition TypeBase.h:5471
Extra information about a function prototype.
Definition TypeBase.h:5491
bool requiresFunctionProtoTypeArmAttributes() const
Definition TypeBase.h:5537
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5496
bool requiresFunctionProtoTypeExtraAttributeInfo() const
Definition TypeBase.h:5541
bool requiresFunctionProtoTypeExtraBitfields() const
Definition TypeBase.h:5530
const IdentifierInfo * getIdentifier() const
Returns the identifier to which this template name refers.
OverloadedOperatorKind getOperator() const
Return the overloaded operator to which this template name refers.
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition Type.cpp:3389
A late-parsed attribute that will be applied as a type attribute.
Definition Parser.h:233
A lazy value (of type T) that is within an AST node of type Owner, where the value might change in la...
Contains information gathered from parsing the contents of TargetAttr.
Definition TargetInfo.h:60
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition TypeBase.h:871
const Type * Ty
The locally-unqualified type.
Definition TypeBase.h:873
Qualifiers Quals
The local qualifiers.
Definition TypeBase.h:876
llvm::DenseSet< std::tuple< Decl *, Decl *, int > > NonEquivalentDeclSet
Store declaration pairs already found to be non-equivalent.
bool IsEquivalent(Decl *D1, Decl *D2)
Determine whether the two declarations are structurally equivalent.
A this pointer adjustment.
Definition Thunk.h:92
IntType
===-— Target Data Type Query Methods ----------------------------—===//
Definition TargetInfo.h:147
AlignRequirementKind AlignRequirement
Definition ASTContext.h:205
bool isAlignRequired()
Definition ASTContext.h:197
AlignRequirementKind AlignRequirement
Definition ASTContext.h:191
Information about the declaration, useful to clients of FullComment.
Definition Comment.h:974
const TemplateParameterList * TemplateParameters
Template parameters that can be referenced by \tparam if CommentDecl is a template (IsTemplateDecl or...
Definition Comment.h:1000
const Decl * CommentDecl
Declaration the comment is actually attached to (in the source).
Definition Comment.h:977