clang 23.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)) {
752 QualType T = getUnconstrainedType(getCanonicalType(NTTP->getType()));
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 DependentBitIntTypes(this_()), SubstTemplateTemplateParmPacks(this_()),
941 DeducedTemplates(this_()), ArrayParameterTypes(this_()),
942 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
943 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
944 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
945 LangOpts.XRayNeverInstrumentFiles,
946 LangOpts.XRayAttrListFiles, SM)),
947 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
948 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
949 BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this),
950 Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
951 CompCategories(this_()), LastSDM(nullptr, 0) {
953}
954
956 // Release the DenseMaps associated with DeclContext objects.
957 // FIXME: Is this the ideal solution?
958 ReleaseDeclContextMaps();
959
960 // Call all of the deallocation functions on all of their targets.
961 for (auto &Pair : Deallocations)
962 (Pair.first)(Pair.second);
963 Deallocations.clear();
964
965 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
966 // because they can contain DenseMaps.
967 for (llvm::DenseMap<const ObjCInterfaceDecl *,
969 I = ObjCLayouts.begin(),
970 E = ObjCLayouts.end();
971 I != E;)
972 // Increment in loop to prevent using deallocated memory.
973 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
974 R->Destroy(*this);
975 ObjCLayouts.clear();
976
977 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
978 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
979 // Increment in loop to prevent using deallocated memory.
980 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
981 R->Destroy(*this);
982 }
983 ASTRecordLayouts.clear();
984
985 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
986 AEnd = DeclAttrs.end();
987 A != AEnd; ++A)
988 A->second->~AttrVec();
989 DeclAttrs.clear();
990
991 for (const auto &Value : ModuleInitializers)
992 Value.second->~PerModuleInitializers();
993 ModuleInitializers.clear();
994
995 TUDecl = nullptr;
996 XRayFilter.reset();
997 NoSanitizeL.reset();
998}
999
1001
1002void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
1003 TraversalScope = TopLevelDecls;
1005}
1006
1007void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
1008 Deallocations.push_back({Callback, Data});
1009}
1010
1011void
1015
1017 llvm::errs() << "\n*** AST Context Stats:\n";
1018 llvm::errs() << " " << Types.size() << " types total.\n";
1019
1020 unsigned counts[] = {
1021#define TYPE(Name, Parent) 0,
1022#define ABSTRACT_TYPE(Name, Parent)
1023#include "clang/AST/TypeNodes.inc"
1024 0 // Extra
1025 };
1026
1027 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1028 Type *T = Types[i];
1029 counts[(unsigned)T->getTypeClass()]++;
1030 }
1031
1032 unsigned Idx = 0;
1033 unsigned TotalBytes = 0;
1034#define TYPE(Name, Parent) \
1035 if (counts[Idx]) \
1036 llvm::errs() << " " << counts[Idx] << " " << #Name \
1037 << " types, " << sizeof(Name##Type) << " each " \
1038 << "(" << counts[Idx] * sizeof(Name##Type) \
1039 << " bytes)\n"; \
1040 TotalBytes += counts[Idx] * sizeof(Name##Type); \
1041 ++Idx;
1042#define ABSTRACT_TYPE(Name, Parent)
1043#include "clang/AST/TypeNodes.inc"
1044
1045 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1046
1047 // Implicit special member functions.
1048 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1050 << " implicit default constructors created\n";
1051 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1053 << " implicit copy constructors created\n";
1054 if (getLangOpts().CPlusPlus)
1055 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1057 << " implicit move constructors created\n";
1058 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1060 << " implicit copy assignment operators created\n";
1061 if (getLangOpts().CPlusPlus)
1062 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1064 << " implicit move assignment operators created\n";
1065 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1067 << " implicit destructors created\n";
1068
1069 if (ExternalSource) {
1070 llvm::errs() << "\n";
1071 ExternalSource->PrintStats();
1072 }
1073
1074 BumpAlloc.PrintStats();
1075}
1076
1078 bool NotifyListeners) {
1079 if (NotifyListeners)
1080 if (auto *Listener = getASTMutationListener();
1082 Listener->RedefinedHiddenDefinition(ND, M);
1083
1084 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1085}
1086
1088 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1089 if (It == MergedDefModules.end())
1090 return;
1091
1092 auto &Merged = It->second;
1093 llvm::DenseSet<Module*> Found;
1094 for (Module *&M : Merged)
1095 if (!Found.insert(M).second)
1096 M = nullptr;
1097 llvm::erase(Merged, nullptr);
1098}
1099
1102 auto MergedIt =
1103 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1104 if (MergedIt == MergedDefModules.end())
1105 return {};
1106 return MergedIt->second;
1107}
1108
1109void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1110 if (LazyInitializers.empty())
1111 return;
1112
1113 auto *Source = Ctx.getExternalSource();
1114 assert(Source && "lazy initializers but no external source");
1115
1116 auto LazyInits = std::move(LazyInitializers);
1117 LazyInitializers.clear();
1118
1119 for (auto ID : LazyInits)
1120 Initializers.push_back(Source->GetExternalDecl(ID));
1121
1122 assert(LazyInitializers.empty() &&
1123 "GetExternalDecl for lazy module initializer added more inits");
1124}
1125
1127 // One special case: if we add a module initializer that imports another
1128 // module, and that module's only initializer is an ImportDecl, simplify.
1129 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1130 auto It = ModuleInitializers.find(ID->getImportedModule());
1131
1132 // Maybe the ImportDecl does nothing at all. (Common case.)
1133 if (It == ModuleInitializers.end())
1134 return;
1135
1136 // Maybe the ImportDecl only imports another ImportDecl.
1137 auto &Imported = *It->second;
1138 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1139 Imported.resolve(*this);
1140 auto *OnlyDecl = Imported.Initializers.front();
1141 if (isa<ImportDecl>(OnlyDecl))
1142 D = OnlyDecl;
1143 }
1144 }
1145
1146 auto *&Inits = ModuleInitializers[M];
1147 if (!Inits)
1148 Inits = new (*this) PerModuleInitializers;
1149 Inits->Initializers.push_back(D);
1150}
1151
1154 auto *&Inits = ModuleInitializers[M];
1155 if (!Inits)
1156 Inits = new (*this) PerModuleInitializers;
1157 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1158 IDs.begin(), IDs.end());
1159}
1160
1162 auto It = ModuleInitializers.find(M);
1163 if (It == ModuleInitializers.end())
1164 return {};
1165
1166 auto *Inits = It->second;
1167 Inits->resolve(*this);
1168 return Inits->Initializers;
1169}
1170
1172 assert(M->isNamedModule());
1173 assert(!CurrentCXXNamedModule &&
1174 "We should set named module for ASTContext for only once");
1175 CurrentCXXNamedModule = M;
1176}
1177
1178bool ASTContext::isInSameModule(const Module *M1, const Module *M2) const {
1179 if (!M1 != !M2)
1180 return false;
1181
1182 /// Get the representative module for M. The representative module is the
1183 /// first module unit for a specific primary module name. So that the module
1184 /// units have the same representative module belongs to the same module.
1185 ///
1186 /// The process is helpful to reduce the expensive string operations.
1187 auto GetRepresentativeModule = [this](const Module *M) {
1188 auto Iter = SameModuleLookupSet.find(M);
1189 if (Iter != SameModuleLookupSet.end())
1190 return Iter->second;
1191
1192 const Module *RepresentativeModule =
1193 PrimaryModuleNameMap.try_emplace(M->getPrimaryModuleInterfaceName(), M)
1194 .first->second;
1195 SameModuleLookupSet[M] = RepresentativeModule;
1196 return RepresentativeModule;
1197 };
1198
1199 assert(M1 && "Shouldn't call `isInSameModule` if both M1 and M2 are none.");
1200 return GetRepresentativeModule(M1) == GetRepresentativeModule(M2);
1201}
1202
1204 if (!ExternCContext)
1205 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1206
1207 return ExternCContext;
1208}
1209
1220
1221#define BuiltinTemplate(BTName) \
1222 BuiltinTemplateDecl *ASTContext::get##BTName##Decl() const { \
1223 if (!Decl##BTName) \
1224 Decl##BTName = \
1225 buildBuiltinTemplateDecl(BTK##BTName, get##BTName##Name()); \
1226 return Decl##BTName; \
1227 }
1228#include "clang/Basic/BuiltinTemplates.inc"
1229
1231 RecordDecl::TagKind TK) const {
1232 SourceLocation Loc;
1233 RecordDecl *NewDecl;
1234 if (getLangOpts().CPlusPlus)
1235 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1236 Loc, &Idents.get(Name));
1237 else
1238 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1239 &Idents.get(Name));
1240 NewDecl->setImplicit();
1241 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1242 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1243 return NewDecl;
1244}
1245
1247 StringRef Name) const {
1250 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1251 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1252 NewDecl->setImplicit();
1253 return NewDecl;
1254}
1255
1257 if (!Int128Decl)
1258 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1259 return Int128Decl;
1260}
1261
1263 if (!UInt128Decl)
1264 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1265 return UInt128Decl;
1266}
1267
1268void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1269 auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K);
1271 Types.push_back(Ty);
1272}
1273
1275 const TargetInfo *AuxTarget) {
1276 assert((!this->Target || this->Target == &Target) &&
1277 "Incorrect target reinitialization");
1278 assert(VoidTy.isNull() && "Context reinitialized?");
1279
1280 this->Target = &Target;
1281 this->AuxTarget = AuxTarget;
1282
1283 ABI.reset(createCXXABI(Target));
1284 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1285
1286 // C99 6.2.5p19.
1287 InitBuiltinType(VoidTy, BuiltinType::Void);
1288
1289 // C99 6.2.5p2.
1290 InitBuiltinType(BoolTy, BuiltinType::Bool);
1291 // C99 6.2.5p3.
1292 if (LangOpts.CharIsSigned)
1293 InitBuiltinType(CharTy, BuiltinType::Char_S);
1294 else
1295 InitBuiltinType(CharTy, BuiltinType::Char_U);
1296 // C99 6.2.5p4.
1297 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1298 InitBuiltinType(ShortTy, BuiltinType::Short);
1299 InitBuiltinType(IntTy, BuiltinType::Int);
1300 InitBuiltinType(LongTy, BuiltinType::Long);
1301 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1302
1303 // C99 6.2.5p6.
1304 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1305 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1306 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1307 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1308 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1309
1310 // C99 6.2.5p10.
1311 InitBuiltinType(FloatTy, BuiltinType::Float);
1312 InitBuiltinType(DoubleTy, BuiltinType::Double);
1313 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1314
1315 // GNU extension, __float128 for IEEE quadruple precision
1316 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1317
1318 // __ibm128 for IBM extended precision
1319 InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128);
1320
1321 // C11 extension ISO/IEC TS 18661-3
1322 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1323
1324 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1325 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1326 InitBuiltinType(AccumTy, BuiltinType::Accum);
1327 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1328 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1329 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1330 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1331 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1332 InitBuiltinType(FractTy, BuiltinType::Fract);
1333 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1334 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1335 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1336 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1337 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1338 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1339 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1340 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1341 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1342 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1343 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1344 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1345 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1346 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1347 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1348 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
1349
1350 // GNU extension, 128-bit integers.
1351 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1352 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1353
1354 // C++ 3.9.1p5
1355 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1356 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1357 else // -fshort-wchar makes wchar_t be unsigned.
1358 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1359 if (LangOpts.CPlusPlus && LangOpts.WChar)
1361 else {
1362 // C99 (or C++ using -fno-wchar).
1363 WideCharTy = getFromTargetType(Target.getWCharType());
1364 }
1365
1366 WIntTy = getFromTargetType(Target.getWIntType());
1367
1368 // C++20 (proposed)
1369 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1370
1371 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1372 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1373 else // C99
1374 Char16Ty = getFromTargetType(Target.getChar16Type());
1375
1376 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1377 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1378 else // C99
1379 Char32Ty = getFromTargetType(Target.getChar32Type());
1380
1381 // Placeholder type for type-dependent expressions whose type is
1382 // completely unknown. No code should ever check a type against
1383 // DependentTy and users should never see it; however, it is here to
1384 // help diagnose failures to properly check for type-dependent
1385 // expressions.
1386 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1387
1388 // Placeholder type for functions.
1389 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1390
1391 // Placeholder type for bound members.
1392 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1393
1394 // Placeholder type for unresolved templates.
1395 InitBuiltinType(UnresolvedTemplateTy, BuiltinType::UnresolvedTemplate);
1396
1397 // Placeholder type for pseudo-objects.
1398 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1399
1400 // "any" type; useful for debugger-like clients.
1401 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1402
1403 // Placeholder type for unbridged ARC casts.
1404 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1405
1406 // Placeholder type for builtin functions.
1407 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1408
1409 // Placeholder type for OMP array sections.
1410 if (LangOpts.OpenMP) {
1411 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1412 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1413 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1414 }
1415 // Placeholder type for OpenACC array sections, if we are ALSO in OMP mode,
1416 // don't bother, as we're just using the same type as OMP.
1417 if (LangOpts.OpenACC && !LangOpts.OpenMP) {
1418 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1419 }
1420 if (LangOpts.MatrixTypes)
1421 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1422
1423 // Builtin types for 'id', 'Class', and 'SEL'.
1424 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1425 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1426 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1427
1428 if (LangOpts.OpenCL) {
1429#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1430 InitBuiltinType(SingletonId, BuiltinType::Id);
1431#include "clang/Basic/OpenCLImageTypes.def"
1432
1433 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1434 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1435 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1436 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1437 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1438
1439#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1440 InitBuiltinType(Id##Ty, BuiltinType::Id);
1441#include "clang/Basic/OpenCLExtensionTypes.def"
1442 }
1443
1444 if (LangOpts.HLSL) {
1445#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1446 InitBuiltinType(SingletonId, BuiltinType::Id);
1447#include "clang/Basic/HLSLIntangibleTypes.def"
1448 }
1449
1450 if (Target.hasAArch64ACLETypes() ||
1451 (AuxTarget && AuxTarget->hasAArch64ACLETypes())) {
1452#define SVE_TYPE(Name, Id, SingletonId) \
1453 InitBuiltinType(SingletonId, BuiltinType::Id);
1454#include "clang/Basic/AArch64ACLETypes.def"
1455 }
1456
1457 if (Target.getTriple().isPPC64()) {
1458#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1459 InitBuiltinType(Id##Ty, BuiltinType::Id);
1460#include "clang/Basic/PPCTypes.def"
1461#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1462 InitBuiltinType(Id##Ty, BuiltinType::Id);
1463#include "clang/Basic/PPCTypes.def"
1464 }
1465
1466 if (Target.hasRISCVVTypes()) {
1467#define RVV_TYPE(Name, Id, SingletonId) \
1468 InitBuiltinType(SingletonId, BuiltinType::Id);
1469#include "clang/Basic/RISCVVTypes.def"
1470 }
1471
1472 if (Target.getTriple().isWasm() && Target.hasFeature("reference-types")) {
1473#define WASM_TYPE(Name, Id, SingletonId) \
1474 InitBuiltinType(SingletonId, BuiltinType::Id);
1475#include "clang/Basic/WebAssemblyReferenceTypes.def"
1476 }
1477
1478 if (Target.getTriple().isAMDGPU() ||
1479 (Target.getTriple().isSPIRV() &&
1480 Target.getTriple().getVendor() == llvm::Triple::AMD) ||
1481 (AuxTarget &&
1482 (AuxTarget->getTriple().isAMDGPU() ||
1483 ((AuxTarget->getTriple().isSPIRV() &&
1484 AuxTarget->getTriple().getVendor() == llvm::Triple::AMD))))) {
1485#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
1486 InitBuiltinType(SingletonId, BuiltinType::Id);
1487#include "clang/Basic/AMDGPUTypes.def"
1488 }
1489
1490 // Builtin type for __objc_yes and __objc_no
1491 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1493
1494 ObjCConstantStringType = QualType();
1495
1496 ObjCSuperType = QualType();
1497
1498 // void * type
1499 if (LangOpts.OpenCLGenericAddressSpace) {
1500 auto Q = VoidTy.getQualifiers();
1501 Q.setAddressSpace(LangAS::opencl_generic);
1503 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1504 } else {
1506 }
1507
1508 // nullptr type (C++0x 2.14.7)
1509 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1510
1511 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1512 InitBuiltinType(HalfTy, BuiltinType::Half);
1513
1514 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1515
1516 // Builtin type used to help define __builtin_va_list.
1517 VaListTagDecl = nullptr;
1518
1519 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1520 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1523 }
1524}
1525
1527 return SourceMgr.getDiagnostics();
1528}
1529
1531 AttrVec *&Result = DeclAttrs[D];
1532 if (!Result) {
1533 void *Mem = Allocate(sizeof(AttrVec));
1534 Result = new (Mem) AttrVec;
1535 }
1536
1537 return *Result;
1538}
1539
1540/// Erase the attributes corresponding to the given declaration.
1542 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1543 if (Pos != DeclAttrs.end()) {
1544 Pos->second->~AttrVec();
1545 DeclAttrs.erase(Pos);
1546 }
1547}
1548
1551 auto It =
1552 ExplicitInstantiations.find(cast<NamedDecl>(Spec->getCanonicalDecl()));
1553 if (It != ExplicitInstantiations.end())
1554 return It->second;
1555 return {};
1556}
1557
1560 ExplicitInstantiations[cast<NamedDecl>(Spec->getCanonicalDecl())].push_back(
1561 EID);
1562}
1563
1564// FIXME: Remove ?
1567 assert(Var->isStaticDataMember() && "Not a static data member");
1569 .dyn_cast<MemberSpecializationInfo *>();
1570}
1571
1574 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1575 TemplateOrInstantiation.find(Var);
1576 if (Pos == TemplateOrInstantiation.end())
1577 return {};
1578
1579 return Pos->second;
1580}
1581
1582void
1585 SourceLocation PointOfInstantiation) {
1586 assert(Inst->isStaticDataMember() && "Not a static data member");
1587 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1589 Tmpl, TSK, PointOfInstantiation));
1590}
1591
1592void
1595 assert(!TemplateOrInstantiation[Inst] &&
1596 "Already noted what the variable was instantiated from");
1597 TemplateOrInstantiation[Inst] = TSI;
1598}
1599
1600NamedDecl *
1602 return InstantiatedFromUsingDecl.lookup(UUD);
1603}
1604
1605void
1607 assert((isa<UsingDecl>(Pattern) ||
1610 "pattern decl is not a using decl");
1611 assert((isa<UsingDecl>(Inst) ||
1614 "instantiation did not produce a using decl");
1615 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1616 InstantiatedFromUsingDecl[Inst] = Pattern;
1617}
1618
1621 return InstantiatedFromUsingEnumDecl.lookup(UUD);
1622}
1623
1625 UsingEnumDecl *Pattern) {
1626 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1627 InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1628}
1629
1632 return InstantiatedFromUsingShadowDecl.lookup(Inst);
1633}
1634
1635void
1637 UsingShadowDecl *Pattern) {
1638 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1639 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1640}
1641
1642FieldDecl *
1644 return InstantiatedFromUnnamedFieldDecl.lookup(Field);
1645}
1646
1648 FieldDecl *Tmpl) {
1649 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1650 "Instantiated field decl is not unnamed");
1651 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1652 "Template field decl is not unnamed");
1653 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1654 "Already noted what unnamed field was instantiated from");
1655
1656 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1657}
1658
1663
1668
1669unsigned
1671 auto Range = overridden_methods(Method);
1672 return Range.end() - Range.begin();
1673}
1674
1677 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1678 OverriddenMethods.find(Method->getCanonicalDecl());
1679 if (Pos == OverriddenMethods.end())
1680 return overridden_method_range(nullptr, nullptr);
1681 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1682}
1683
1685 const CXXMethodDecl *Overridden) {
1686 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1687 OverriddenMethods[Method].push_back(Overridden);
1688}
1689
1691 const NamedDecl *D,
1692 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1693 assert(D);
1694
1695 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1696 Overridden.append(overridden_methods_begin(CXXMethod),
1697 overridden_methods_end(CXXMethod));
1698 return;
1699 }
1700
1701 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1702 if (!Method)
1703 return;
1704
1706 Method->getOverriddenMethods(OverDecls);
1707 Overridden.append(OverDecls.begin(), OverDecls.end());
1708}
1709
1710std::optional<ASTContext::CXXRecordDeclRelocationInfo>
1712 assert(RD);
1713 CXXRecordDecl *D = RD->getDefinition();
1714 auto it = RelocatableClasses.find(D);
1715 if (it != RelocatableClasses.end())
1716 return it->getSecond();
1717 return std::nullopt;
1718}
1719
1722 assert(RD);
1723 CXXRecordDecl *D = RD->getDefinition();
1724 assert(RelocatableClasses.find(D) == RelocatableClasses.end());
1725 RelocatableClasses.insert({D, Info});
1726}
1727
1729 const ASTContext &Context, const CXXRecordDecl *Class) {
1730 if (!Class->isPolymorphic())
1731 return false;
1732 const CXXRecordDecl *BaseType = Context.baseForVTableAuthentication(Class);
1733 using AuthAttr = VTablePointerAuthenticationAttr;
1734 const AuthAttr *ExplicitAuth = BaseType->getAttr<AuthAttr>();
1735 if (!ExplicitAuth)
1736 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1737 AuthAttr::AddressDiscriminationMode AddressDiscrimination =
1738 ExplicitAuth->getAddressDiscrimination();
1739 if (AddressDiscrimination == AuthAttr::DefaultAddressDiscrimination)
1740 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1741 return AddressDiscrimination == AuthAttr::AddressDiscrimination;
1742}
1743
1744ASTContext::PointerAuthContent
1745ASTContext::findPointerAuthContent(QualType T) const {
1746 assert(isPointerAuthenticationAvailable());
1747
1748 T = T.getCanonicalType();
1749 if (T->isDependentType())
1750 return PointerAuthContent::None;
1751
1753 return PointerAuthContent::AddressDiscriminatedData;
1754 const RecordDecl *RD = T->getAsRecordDecl();
1755 if (!RD)
1756 return PointerAuthContent::None;
1757
1758 if (RD->isInvalidDecl())
1759 return PointerAuthContent::None;
1760
1761 if (auto Existing = RecordContainsAddressDiscriminatedPointerAuth.find(RD);
1762 Existing != RecordContainsAddressDiscriminatedPointerAuth.end())
1763 return Existing->second;
1764
1765 PointerAuthContent Result = PointerAuthContent::None;
1766
1767 auto SaveResultAndReturn = [&]() -> PointerAuthContent {
1768 auto [ResultIter, DidAdd] =
1769 RecordContainsAddressDiscriminatedPointerAuth.try_emplace(RD, Result);
1770 (void)ResultIter;
1771 (void)DidAdd;
1772 assert(DidAdd);
1773 return Result;
1774 };
1775 auto ShouldContinueAfterUpdate = [&](PointerAuthContent NewResult) {
1776 static_assert(PointerAuthContent::None <
1777 PointerAuthContent::AddressDiscriminatedVTable);
1778 static_assert(PointerAuthContent::AddressDiscriminatedVTable <
1779 PointerAuthContent::AddressDiscriminatedData);
1780 if (NewResult > Result)
1781 Result = NewResult;
1782 return Result != PointerAuthContent::AddressDiscriminatedData;
1783 };
1784 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1786 !ShouldContinueAfterUpdate(
1787 PointerAuthContent::AddressDiscriminatedVTable))
1788 return SaveResultAndReturn();
1789 for (auto Base : CXXRD->bases()) {
1790 if (!ShouldContinueAfterUpdate(findPointerAuthContent(Base.getType())))
1791 return SaveResultAndReturn();
1792 }
1793 }
1794 for (auto *FieldDecl : RD->fields()) {
1795 if (!ShouldContinueAfterUpdate(
1796 findPointerAuthContent(FieldDecl->getType())))
1797 return SaveResultAndReturn();
1798 }
1799 return SaveResultAndReturn();
1800}
1801
1803 assert(!Import->getNextLocalImport() &&
1804 "Import declaration already in the chain");
1805 assert(!Import->isFromASTFile() && "Non-local import declaration");
1806 if (!FirstLocalImport) {
1807 FirstLocalImport = Import;
1808 LastLocalImport = Import;
1809 return;
1810 }
1811
1812 LastLocalImport->setNextLocalImport(Import);
1813 LastLocalImport = Import;
1814}
1815
1816//===----------------------------------------------------------------------===//
1817// Type Sizing and Analysis
1818//===----------------------------------------------------------------------===//
1819
1820/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1821/// scalar floating point type.
1822const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1823 switch (T->castAs<BuiltinType>()->getKind()) {
1824 default:
1825 llvm_unreachable("Not a floating point type!");
1826 case BuiltinType::BFloat16:
1827 return Target->getBFloat16Format();
1828 case BuiltinType::Float16:
1829 return Target->getHalfFormat();
1830 case BuiltinType::Half:
1831 return Target->getHalfFormat();
1832 case BuiltinType::Float: return Target->getFloatFormat();
1833 case BuiltinType::Double: return Target->getDoubleFormat();
1834 case BuiltinType::Ibm128:
1835 return Target->getIbm128Format();
1836 case BuiltinType::LongDouble:
1837 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1838 return AuxTarget->getLongDoubleFormat();
1839 return Target->getLongDoubleFormat();
1840 case BuiltinType::Float128:
1841 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1842 return AuxTarget->getFloat128Format();
1843 return Target->getFloat128Format();
1844 }
1845}
1846
1847CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1848 unsigned Align = Target->getCharWidth();
1849
1850 const unsigned AlignFromAttr = D->getMaxAlignment();
1851 if (AlignFromAttr)
1852 Align = AlignFromAttr;
1853
1854 // __attribute__((aligned)) can increase or decrease alignment
1855 // *except* on a struct or struct member, where it only increases
1856 // alignment unless 'packed' is also specified.
1857 //
1858 // It is an error for alignas to decrease alignment, so we can
1859 // ignore that possibility; Sema should diagnose it.
1860 bool UseAlignAttrOnly;
1861 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D))
1862 UseAlignAttrOnly =
1863 FD->hasAttr<PackedAttr>() || FD->getParent()->hasAttr<PackedAttr>();
1864 else
1865 UseAlignAttrOnly = AlignFromAttr != 0;
1866 // If we're using the align attribute only, just ignore everything
1867 // else about the declaration and its type.
1868 if (UseAlignAttrOnly) {
1869 // do nothing
1870 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1871 QualType T = VD->getType();
1872 if (const auto *RT = T->getAs<ReferenceType>()) {
1873 if (ForAlignof)
1874 T = RT->getPointeeType();
1875 else
1876 T = getPointerType(RT->getPointeeType());
1877 }
1878 QualType BaseT = getBaseElementType(T);
1879 if (T->isFunctionType())
1880 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1881 else if (!BaseT->isIncompleteType()) {
1882 // Adjust alignments of declarations with array type by the
1883 // large-array alignment on the target.
1884 if (const ArrayType *arrayType = getAsArrayType(T)) {
1885 unsigned MinWidth = Target->getLargeArrayMinWidth();
1886 if (!ForAlignof && MinWidth) {
1888 Align = std::max(Align, Target->getLargeArrayAlign());
1891 Align = std::max(Align, Target->getLargeArrayAlign());
1892 }
1893 }
1894 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1895 if (BaseT.getQualifiers().hasUnaligned())
1896 Align = Target->getCharWidth();
1897 }
1898
1899 // Ensure minimum alignment for global variables.
1900 if (const auto *VD = dyn_cast<VarDecl>(D))
1901 if (VD->hasGlobalStorage() && !ForAlignof) {
1902 uint64_t TypeSize =
1903 !BaseT->isIncompleteType() ? getTypeSize(T.getTypePtr()) : 0;
1904 Align = std::max(Align, getMinGlobalAlignOfVar(TypeSize, VD));
1905 }
1906
1907 // Fields can be subject to extra alignment constraints, like if
1908 // the field is packed, the struct is packed, or the struct has a
1909 // a max-field-alignment constraint (#pragma pack). So calculate
1910 // the actual alignment of the field within the struct, and then
1911 // (as we're expected to) constrain that by the alignment of the type.
1912 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1913 const RecordDecl *Parent = Field->getParent();
1914 // We can only produce a sensible answer if the record is valid.
1915 if (!Parent->isInvalidDecl()) {
1916 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1917
1918 // Start with the record's overall alignment.
1919 unsigned FieldAlign = toBits(Layout.getAlignment());
1920
1921 // Use the GCD of that and the offset within the record.
1922 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1923 if (Offset > 0) {
1924 // Alignment is always a power of 2, so the GCD will be a power of 2,
1925 // which means we get to do this crazy thing instead of Euclid's.
1926 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1927 if (LowBitOfOffset < FieldAlign)
1928 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1929 }
1930
1931 Align = std::min(Align, FieldAlign);
1932 }
1933 }
1934 }
1935
1936 // Some targets have hard limitation on the maximum requestable alignment in
1937 // aligned attribute for static variables.
1938 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1939 const auto *VD = dyn_cast<VarDecl>(D);
1940 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1941 Align = std::min(Align, MaxAlignedAttr);
1942
1943 return toCharUnitsFromBits(Align);
1944}
1945
1947 return toCharUnitsFromBits(Target->getExnObjectAlignment());
1948}
1949
1950// getTypeInfoDataSizeInChars - Return the size of a type, in
1951// chars. If the type is a record, its data size is returned. This is
1952// the size of the memcpy that's performed when assigning this type
1953// using a trivial copy/move assignment operator.
1956
1957 // In C++, objects can sometimes be allocated into the tail padding
1958 // of a base-class subobject. We decide whether that's possible
1959 // during class layout, so here we can just trust the layout results.
1960 if (getLangOpts().CPlusPlus) {
1961 if (const auto *RD = T->getAsCXXRecordDecl(); RD && !RD->isInvalidDecl()) {
1962 const ASTRecordLayout &layout = getASTRecordLayout(RD);
1963 Info.Width = layout.getDataSize();
1964 }
1965 }
1966
1967 return Info;
1968}
1969
1970/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1971/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1974 const ConstantArrayType *CAT) {
1975 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1976 uint64_t Size = CAT->getZExtSize();
1977 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1978 (uint64_t)(-1)/Size) &&
1979 "Overflow in array type char size evaluation");
1980 uint64_t Width = EltInfo.Width.getQuantity() * Size;
1981 unsigned Align = EltInfo.Align.getQuantity();
1982 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1983 Context.getTargetInfo().getPointerWidth(LangAS::Default) == 64)
1984 Width = llvm::alignTo(Width, Align);
1987 EltInfo.AlignRequirement);
1988}
1989
1991 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1992 return getConstantArrayInfoInChars(*this, CAT);
1993 TypeInfo Info = getTypeInfo(T);
1996}
1997
1999 return getTypeInfoInChars(T.getTypePtr());
2000}
2001
2003 // HLSL doesn't promote all small integer types to int, it
2004 // just uses the rank-based promotion rules for all types.
2005 if (getLangOpts().HLSL)
2006 return false;
2007
2008 if (const auto *BT = T->getAs<BuiltinType>())
2009 switch (BT->getKind()) {
2010 case BuiltinType::Bool:
2011 case BuiltinType::Char_S:
2012 case BuiltinType::Char_U:
2013 case BuiltinType::SChar:
2014 case BuiltinType::UChar:
2015 case BuiltinType::Short:
2016 case BuiltinType::UShort:
2017 case BuiltinType::WChar_S:
2018 case BuiltinType::WChar_U:
2019 case BuiltinType::Char8:
2020 case BuiltinType::Char16:
2021 case BuiltinType::Char32:
2022 return true;
2023 default:
2024 return false;
2025 }
2026
2027 // Enumerated types are promotable to their compatible integer types
2028 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
2029 if (const auto *ED = T->getAsEnumDecl()) {
2030 if (T->isDependentType() || ED->getPromotionType().isNull() ||
2031 ED->isScoped())
2032 return false;
2033
2034 return true;
2035 }
2036
2037 // OverflowBehaviorTypes are promotable if their underlying type is promotable
2038 if (const auto *OBT = T->getAs<OverflowBehaviorType>()) {
2039 return isPromotableIntegerType(OBT->getUnderlyingType());
2040 }
2041
2042 return false;
2043}
2044
2048
2050 return isAlignmentRequired(T.getTypePtr());
2051}
2052
2054 bool NeedsPreferredAlignment) const {
2055 // An alignment on a typedef overrides anything else.
2056 if (const auto *TT = T->getAs<TypedefType>())
2057 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2058 return Align;
2059
2060 // If we have an (array of) complete type, we're done.
2061 T = getBaseElementType(T);
2062 if (!T->isIncompleteType())
2063 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
2064
2065 // If we had an array type, its element type might be a typedef
2066 // type with an alignment attribute.
2067 if (const auto *TT = T->getAs<TypedefType>())
2068 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2069 return Align;
2070
2071 // Otherwise, see if the declaration of the type had an attribute.
2072 if (const auto *TD = T->getAsTagDecl())
2073 return TD->getMaxAlignment();
2074
2075 return 0;
2076}
2077
2079 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
2080 if (I != MemoizedTypeInfo.end())
2081 return I->second;
2082
2083 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
2084 TypeInfo TI = getTypeInfoImpl(T);
2085 MemoizedTypeInfo[T] = TI;
2086 return TI;
2087}
2088
2089/// getTypeInfoImpl - Return the size of the specified type, in bits. This
2090/// method does not work on incomplete types.
2091///
2092/// FIXME: Pointers into different addr spaces could have different sizes and
2093/// alignment requirements: getPointerInfo should take an AddrSpace, this
2094/// should take a QualType, &c.
2095TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
2096 uint64_t Width = 0;
2097 unsigned Align = 8;
2100 switch (T->getTypeClass()) {
2101#define TYPE(Class, Base)
2102#define ABSTRACT_TYPE(Class, Base)
2103#define NON_CANONICAL_TYPE(Class, Base)
2104#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2105#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
2106 case Type::Class: \
2107 assert(!T->isDependentType() && "should not see dependent types here"); \
2108 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
2109#include "clang/AST/TypeNodes.inc"
2110 llvm_unreachable("Should not see dependent types");
2111
2112 case Type::FunctionNoProto:
2113 case Type::FunctionProto:
2114 // GCC extension: alignof(function) = 32 bits
2115 Width = 0;
2116 Align = 32;
2117 break;
2118
2119 case Type::IncompleteArray:
2120 case Type::VariableArray:
2121 case Type::ConstantArray:
2122 case Type::ArrayParameter: {
2123 // Model non-constant sized arrays as size zero, but track the alignment.
2124 uint64_t Size = 0;
2125 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
2126 Size = CAT->getZExtSize();
2127
2128 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
2129 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
2130 "Overflow in array type bit size evaluation");
2131 Width = EltInfo.Width * Size;
2132 Align = EltInfo.Align;
2133 AlignRequirement = EltInfo.AlignRequirement;
2134 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
2135 getTargetInfo().getPointerWidth(LangAS::Default) == 64)
2136 Width = llvm::alignTo(Width, Align);
2137 break;
2138 }
2139
2140 case Type::ExtVector:
2141 case Type::Vector: {
2142 const auto *VT = cast<VectorType>(T);
2143 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
2144 Width = VT->isPackedVectorBoolType(*this)
2145 ? VT->getNumElements()
2146 : EltInfo.Width * VT->getNumElements();
2147 // Enforce at least byte size and alignment.
2148 Width = std::max<unsigned>(8, Width);
2149 Align = std::max<unsigned>(
2150 8, Target->vectorsAreElementAligned() ? EltInfo.Width : Width);
2151
2152 // If the alignment is not a power of 2, round up to the next power of 2.
2153 // This happens for non-power-of-2 length vectors.
2154 if (Align & (Align-1)) {
2155 Align = llvm::bit_ceil(Align);
2156 Width = llvm::alignTo(Width, Align);
2157 }
2158 // Adjust the alignment based on the target max.
2159 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
2160 if (TargetVectorAlign && TargetVectorAlign < Align)
2161 Align = TargetVectorAlign;
2162 if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
2163 // Adjust the alignment for fixed-length SVE vectors. This is important
2164 // for non-power-of-2 vector lengths.
2165 Align = 128;
2166 else if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
2167 // Adjust the alignment for fixed-length SVE predicates.
2168 Align = 16;
2169 else if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
2170 VT->getVectorKind() == VectorKind::RVVFixedLengthMask ||
2171 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
2172 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
2173 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4)
2174 // Adjust the alignment for fixed-length RVV vectors.
2175 Align = std::min<unsigned>(64, Width);
2176 break;
2177 }
2178
2179 case Type::ConstantMatrix: {
2180 const auto *MT = cast<ConstantMatrixType>(T);
2181 TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
2182 // The internal layout of a matrix value is implementation defined.
2183 // Initially be ABI compatible with arrays with respect to alignment and
2184 // size.
2185 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
2186 Align = ElementInfo.Align;
2187 break;
2188 }
2189
2190 case Type::Builtin:
2191 switch (cast<BuiltinType>(T)->getKind()) {
2192 default: llvm_unreachable("Unknown builtin type!");
2193 case BuiltinType::Void:
2194 // GCC extension: alignof(void) = 8 bits.
2195 Width = 0;
2196 Align = 8;
2197 break;
2198 case BuiltinType::Bool:
2199 Width = Target->getBoolWidth();
2200 Align = Target->getBoolAlign();
2201 break;
2202 case BuiltinType::Char_S:
2203 case BuiltinType::Char_U:
2204 case BuiltinType::UChar:
2205 case BuiltinType::SChar:
2206 case BuiltinType::Char8:
2207 Width = Target->getCharWidth();
2208 Align = Target->getCharAlign();
2209 break;
2210 case BuiltinType::WChar_S:
2211 case BuiltinType::WChar_U:
2212 Width = Target->getWCharWidth();
2213 Align = Target->getWCharAlign();
2214 break;
2215 case BuiltinType::Char16:
2216 Width = Target->getChar16Width();
2217 Align = Target->getChar16Align();
2218 break;
2219 case BuiltinType::Char32:
2220 Width = Target->getChar32Width();
2221 Align = Target->getChar32Align();
2222 break;
2223 case BuiltinType::UShort:
2224 case BuiltinType::Short:
2225 Width = Target->getShortWidth();
2226 Align = Target->getShortAlign();
2227 break;
2228 case BuiltinType::UInt:
2229 case BuiltinType::Int:
2230 Width = Target->getIntWidth();
2231 Align = Target->getIntAlign();
2232 break;
2233 case BuiltinType::ULong:
2234 case BuiltinType::Long:
2235 Width = Target->getLongWidth();
2236 Align = Target->getLongAlign();
2237 break;
2238 case BuiltinType::ULongLong:
2239 case BuiltinType::LongLong:
2240 Width = Target->getLongLongWidth();
2241 Align = Target->getLongLongAlign();
2242 break;
2243 case BuiltinType::Int128:
2244 case BuiltinType::UInt128:
2245 Width = 128;
2246 Align = Target->getInt128Align();
2247 break;
2248 case BuiltinType::ShortAccum:
2249 case BuiltinType::UShortAccum:
2250 case BuiltinType::SatShortAccum:
2251 case BuiltinType::SatUShortAccum:
2252 Width = Target->getShortAccumWidth();
2253 Align = Target->getShortAccumAlign();
2254 break;
2255 case BuiltinType::Accum:
2256 case BuiltinType::UAccum:
2257 case BuiltinType::SatAccum:
2258 case BuiltinType::SatUAccum:
2259 Width = Target->getAccumWidth();
2260 Align = Target->getAccumAlign();
2261 break;
2262 case BuiltinType::LongAccum:
2263 case BuiltinType::ULongAccum:
2264 case BuiltinType::SatLongAccum:
2265 case BuiltinType::SatULongAccum:
2266 Width = Target->getLongAccumWidth();
2267 Align = Target->getLongAccumAlign();
2268 break;
2269 case BuiltinType::ShortFract:
2270 case BuiltinType::UShortFract:
2271 case BuiltinType::SatShortFract:
2272 case BuiltinType::SatUShortFract:
2273 Width = Target->getShortFractWidth();
2274 Align = Target->getShortFractAlign();
2275 break;
2276 case BuiltinType::Fract:
2277 case BuiltinType::UFract:
2278 case BuiltinType::SatFract:
2279 case BuiltinType::SatUFract:
2280 Width = Target->getFractWidth();
2281 Align = Target->getFractAlign();
2282 break;
2283 case BuiltinType::LongFract:
2284 case BuiltinType::ULongFract:
2285 case BuiltinType::SatLongFract:
2286 case BuiltinType::SatULongFract:
2287 Width = Target->getLongFractWidth();
2288 Align = Target->getLongFractAlign();
2289 break;
2290 case BuiltinType::BFloat16:
2291 if (Target->hasBFloat16Type()) {
2292 Width = Target->getBFloat16Width();
2293 Align = Target->getBFloat16Align();
2294 } else if ((getLangOpts().SYCLIsDevice ||
2295 (getLangOpts().OpenMP &&
2296 getLangOpts().OpenMPIsTargetDevice)) &&
2297 AuxTarget->hasBFloat16Type()) {
2298 Width = AuxTarget->getBFloat16Width();
2299 Align = AuxTarget->getBFloat16Align();
2300 }
2301 break;
2302 case BuiltinType::Float16:
2303 case BuiltinType::Half:
2304 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2305 !getLangOpts().OpenMPIsTargetDevice) {
2306 Width = Target->getHalfWidth();
2307 Align = Target->getHalfAlign();
2308 } else {
2309 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2310 "Expected OpenMP device compilation.");
2311 Width = AuxTarget->getHalfWidth();
2312 Align = AuxTarget->getHalfAlign();
2313 }
2314 break;
2315 case BuiltinType::Float:
2316 Width = Target->getFloatWidth();
2317 Align = Target->getFloatAlign();
2318 break;
2319 case BuiltinType::Double:
2320 Width = Target->getDoubleWidth();
2321 Align = Target->getDoubleAlign();
2322 break;
2323 case BuiltinType::Ibm128:
2324 Width = Target->getIbm128Width();
2325 Align = Target->getIbm128Align();
2326 break;
2327 case BuiltinType::LongDouble:
2328 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2329 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2330 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2331 Width = AuxTarget->getLongDoubleWidth();
2332 Align = AuxTarget->getLongDoubleAlign();
2333 } else {
2334 Width = Target->getLongDoubleWidth();
2335 Align = Target->getLongDoubleAlign();
2336 }
2337 break;
2338 case BuiltinType::Float128:
2339 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2340 !getLangOpts().OpenMPIsTargetDevice) {
2341 Width = Target->getFloat128Width();
2342 Align = Target->getFloat128Align();
2343 } else {
2344 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2345 "Expected OpenMP device compilation.");
2346 Width = AuxTarget->getFloat128Width();
2347 Align = AuxTarget->getFloat128Align();
2348 }
2349 break;
2350 case BuiltinType::NullPtr:
2351 // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
2352 Width = Target->getPointerWidth(LangAS::Default);
2353 Align = Target->getPointerAlign(LangAS::Default);
2354 break;
2355 case BuiltinType::ObjCId:
2356 case BuiltinType::ObjCClass:
2357 case BuiltinType::ObjCSel:
2358 Width = Target->getPointerWidth(LangAS::Default);
2359 Align = Target->getPointerAlign(LangAS::Default);
2360 break;
2361 case BuiltinType::OCLSampler:
2362 case BuiltinType::OCLEvent:
2363 case BuiltinType::OCLClkEvent:
2364 case BuiltinType::OCLQueue:
2365 case BuiltinType::OCLReserveID:
2366#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2367 case BuiltinType::Id:
2368#include "clang/Basic/OpenCLImageTypes.def"
2369#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2370 case BuiltinType::Id:
2371#include "clang/Basic/OpenCLExtensionTypes.def"
2372 AS = Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
2373 Width = Target->getPointerWidth(AS);
2374 Align = Target->getPointerAlign(AS);
2375 break;
2376 // The SVE types are effectively target-specific. The length of an
2377 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2378 // of 128 bits. There is one predicate bit for each vector byte, so the
2379 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2380 //
2381 // Because the length is only known at runtime, we use a dummy value
2382 // of 0 for the static length. The alignment values are those defined
2383 // by the Procedure Call Standard for the Arm Architecture.
2384#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
2385 case BuiltinType::Id: \
2386 Width = 0; \
2387 Align = 128; \
2388 break;
2389#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
2390 case BuiltinType::Id: \
2391 Width = 0; \
2392 Align = 16; \
2393 break;
2394#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
2395 case BuiltinType::Id: \
2396 Width = 0; \
2397 Align = 16; \
2398 break;
2399#define SVE_SCALAR_TYPE(Name, MangledName, Id, SingletonId, Bits) \
2400 case BuiltinType::Id: \
2401 Width = Bits; \
2402 Align = Bits; \
2403 break;
2404#include "clang/Basic/AArch64ACLETypes.def"
2405#define PPC_VECTOR_TYPE(Name, Id, Size) \
2406 case BuiltinType::Id: \
2407 Width = Size; \
2408 Align = Size; \
2409 break;
2410#include "clang/Basic/PPCTypes.def"
2411#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
2412 IsFP, IsBF) \
2413 case BuiltinType::Id: \
2414 Width = 0; \
2415 Align = ElBits; \
2416 break;
2417#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2418 case BuiltinType::Id: \
2419 Width = 0; \
2420 Align = 8; \
2421 break;
2422#include "clang/Basic/RISCVVTypes.def"
2423#define WASM_TYPE(Name, Id, SingletonId) \
2424 case BuiltinType::Id: \
2425 Width = 0; \
2426 Align = 8; \
2427 break;
2428#include "clang/Basic/WebAssemblyReferenceTypes.def"
2429#define AMDGPU_TYPE(NAME, ID, SINGLETONID, WIDTH, ALIGN) \
2430 case BuiltinType::ID: \
2431 Width = WIDTH; \
2432 Align = ALIGN; \
2433 break;
2434#include "clang/Basic/AMDGPUTypes.def"
2435#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2436#include "clang/Basic/HLSLIntangibleTypes.def"
2437 Width = Target->getPointerWidth(LangAS::Default);
2438 Align = Target->getPointerAlign(LangAS::Default);
2439 break;
2440 }
2441 break;
2442 case Type::ObjCObjectPointer:
2443 Width = Target->getPointerWidth(LangAS::Default);
2444 Align = Target->getPointerAlign(LangAS::Default);
2445 break;
2446 case Type::BlockPointer:
2447 AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
2448 Width = Target->getPointerWidth(AS);
2449 Align = Target->getPointerAlign(AS);
2450 break;
2451 case Type::LValueReference:
2452 case Type::RValueReference:
2453 // alignof and sizeof should never enter this code path here, so we go
2454 // the pointer route.
2455 AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
2456 Width = Target->getPointerWidth(AS);
2457 Align = Target->getPointerAlign(AS);
2458 break;
2459 case Type::Pointer:
2460 AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
2461 Width = Target->getPointerWidth(AS);
2462 Align = Target->getPointerAlign(AS);
2463 break;
2464 case Type::MemberPointer: {
2465 const auto *MPT = cast<MemberPointerType>(T);
2466 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2467 Width = MPI.Width;
2468 Align = MPI.Align;
2469 break;
2470 }
2471 case Type::Complex: {
2472 // Complex types have the same alignment as their elements, but twice the
2473 // size.
2474 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2475 Width = EltInfo.Width * 2;
2476 Align = EltInfo.Align;
2477 break;
2478 }
2479 case Type::ObjCObject:
2480 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2481 case Type::Adjusted:
2482 case Type::Decayed:
2483 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2484 case Type::ObjCInterface: {
2485 const auto *ObjCI = cast<ObjCInterfaceType>(T);
2486 if (ObjCI->getDecl()->isInvalidDecl()) {
2487 Width = 8;
2488 Align = 8;
2489 break;
2490 }
2491 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2492 Width = toBits(Layout.getSize());
2493 Align = toBits(Layout.getAlignment());
2494 break;
2495 }
2496 case Type::BitInt: {
2497 const auto *EIT = cast<BitIntType>(T);
2498 Align = Target->getBitIntAlign(EIT->getNumBits());
2499 Width = Target->getBitIntWidth(EIT->getNumBits());
2500 break;
2501 }
2502 case Type::Record:
2503 case Type::Enum: {
2504 const auto *TT = cast<TagType>(T);
2505 const TagDecl *TD = TT->getDecl()->getDefinitionOrSelf();
2506
2507 if (TD->isInvalidDecl()) {
2508 Width = 8;
2509 Align = 8;
2510 break;
2511 }
2512
2513 if (isa<EnumType>(TT)) {
2514 const EnumDecl *ED = cast<EnumDecl>(TD);
2515 TypeInfo Info =
2517 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2518 Info.Align = AttrAlign;
2520 }
2521 return Info;
2522 }
2523
2524 const auto *RD = cast<RecordDecl>(TD);
2525 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2526 Width = toBits(Layout.getSize());
2527 Align = toBits(Layout.getAlignment());
2528 AlignRequirement = RD->hasAttr<AlignedAttr>()
2530 : AlignRequirementKind::None;
2531 break;
2532 }
2533
2534 case Type::SubstTemplateTypeParm:
2536 getReplacementType().getTypePtr());
2537
2538 case Type::Auto:
2539 case Type::DeducedTemplateSpecialization: {
2540 const auto *A = cast<DeducedType>(T);
2541 assert(!A->getDeducedType().isNull() &&
2542 "cannot request the size of an undeduced or dependent auto type");
2543 return getTypeInfo(A->getDeducedType().getTypePtr());
2544 }
2545
2546 case Type::Paren:
2547 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2548
2549 case Type::MacroQualified:
2550 return getTypeInfo(
2551 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2552
2553 case Type::ObjCTypeParam:
2554 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2555
2556 case Type::Using:
2557 return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr());
2558
2559 case Type::Typedef: {
2560 const auto *TT = cast<TypedefType>(T);
2561 TypeInfo Info = getTypeInfo(TT->desugar().getTypePtr());
2562 // If the typedef has an aligned attribute on it, it overrides any computed
2563 // alignment we have. This violates the GCC documentation (which says that
2564 // attribute(aligned) can only round up) but matches its implementation.
2565 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2566 Align = AttrAlign;
2567 AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2568 } else {
2569 Align = Info.Align;
2570 AlignRequirement = Info.AlignRequirement;
2571 }
2572 Width = Info.Width;
2573 break;
2574 }
2575
2576 case Type::Attributed:
2577 return getTypeInfo(
2578 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2579
2580 case Type::CountAttributed:
2581 return getTypeInfo(cast<CountAttributedType>(T)->desugar().getTypePtr());
2582
2583 case Type::BTFTagAttributed:
2584 return getTypeInfo(
2585 cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr());
2586
2587 case Type::OverflowBehavior:
2588 return getTypeInfo(
2590
2591 case Type::HLSLAttributedResource:
2592 return getTypeInfo(
2593 cast<HLSLAttributedResourceType>(T)->getWrappedType().getTypePtr());
2594
2595 case Type::HLSLInlineSpirv: {
2596 const auto *ST = cast<HLSLInlineSpirvType>(T);
2597 // Size is specified in bytes, convert to bits
2598 Width = ST->getSize() * 8;
2599 Align = ST->getAlignment();
2600 if (Width == 0 && Align == 0) {
2601 // We are defaulting to laying out opaque SPIR-V types as 32-bit ints.
2602 Width = 32;
2603 Align = 32;
2604 }
2605 break;
2606 }
2607
2608 case Type::Atomic: {
2609 // Start with the base type information.
2610 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2611 Width = Info.Width;
2612 Align = Info.Align;
2613
2614 if (!Width) {
2615 // An otherwise zero-sized type should still generate an
2616 // atomic operation.
2617 Width = Target->getCharWidth();
2618 assert(Align);
2619 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2620 // If the size of the type doesn't exceed the platform's max
2621 // atomic promotion width, make the size and alignment more
2622 // favorable to atomic operations:
2623
2624 // Round the size up to a power of 2.
2625 Width = llvm::bit_ceil(Width);
2626
2627 // Set the alignment equal to the size.
2628 Align = static_cast<unsigned>(Width);
2629 }
2630 }
2631 break;
2632
2633 case Type::PredefinedSugar:
2634 return getTypeInfo(cast<PredefinedSugarType>(T)->desugar().getTypePtr());
2635
2636 case Type::Pipe:
2637 Width = Target->getPointerWidth(LangAS::opencl_global);
2638 Align = Target->getPointerAlign(LangAS::opencl_global);
2639 break;
2640 }
2641
2642 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2643 return TypeInfo(Width, Align, AlignRequirement);
2644}
2645
2647 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2648 if (I != MemoizedUnadjustedAlign.end())
2649 return I->second;
2650
2651 unsigned UnadjustedAlign;
2652 if (const auto *RT = T->getAsCanonical<RecordType>()) {
2653 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
2654 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2655 } else if (const auto *ObjCI = T->getAsCanonical<ObjCInterfaceType>()) {
2656 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2657 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2658 } else {
2659 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2660 }
2661
2662 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2663 return UnadjustedAlign;
2664}
2665
2667 unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign(
2668 getTargetInfo().getTriple(), Target->getTargetOpts().FeatureMap);
2669 return SimdAlign;
2670}
2671
2672/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2674 return CharUnits::fromQuantity(BitSize / getCharWidth());
2675}
2676
2677/// toBits - Convert a size in characters to a size in characters.
2678int64_t ASTContext::toBits(CharUnits CharSize) const {
2679 return CharSize.getQuantity() * getCharWidth();
2680}
2681
2682/// getTypeSizeInChars - Return the size of the specified type, in characters.
2683/// This method does not work on incomplete types.
2690
2691/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2692/// characters. This method does not work on incomplete types.
2699
2700/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2701/// type, in characters, before alignment adjustments. This method does
2702/// not work on incomplete types.
2709
2710/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2711/// type for the current target in bits. This can be different than the ABI
2712/// alignment in cases where it is beneficial for performance or backwards
2713/// compatibility preserving to overalign a data type. (Note: despite the name,
2714/// the preferred alignment is ABI-impacting, and not an optimization.)
2715unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
2716 TypeInfo TI = getTypeInfo(T);
2717 unsigned ABIAlign = TI.Align;
2718
2719 T = T->getBaseElementTypeUnsafe();
2720
2721 // The preferred alignment of member pointers is that of a pointer.
2722 if (T->isMemberPointerType())
2723 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2724
2725 if (!Target->allowsLargerPreferedTypeAlignment())
2726 return ABIAlign;
2727
2728 if (const auto *RD = T->getAsRecordDecl()) {
2729 // When used as part of a typedef, or together with a 'packed' attribute,
2730 // the 'aligned' attribute can be used to decrease alignment. Note that the
2731 // 'packed' case is already taken into consideration when computing the
2732 // alignment, we only need to handle the typedef case here.
2734 RD->isInvalidDecl())
2735 return ABIAlign;
2736
2737 unsigned PreferredAlign = static_cast<unsigned>(
2738 toBits(getASTRecordLayout(RD).PreferredAlignment));
2739 assert(PreferredAlign >= ABIAlign &&
2740 "PreferredAlign should be at least as large as ABIAlign.");
2741 return PreferredAlign;
2742 }
2743
2744 // Double (and, for targets supporting AIX `power` alignment, long double) and
2745 // long long should be naturally aligned (despite requiring less alignment) if
2746 // possible.
2747 if (const auto *CT = T->getAs<ComplexType>())
2748 T = CT->getElementType().getTypePtr();
2749 if (const auto *ED = T->getAsEnumDecl())
2750 T = ED->getIntegerType().getTypePtr();
2751 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2752 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2753 T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2754 (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2755 Target->defaultsToAIXPowerAlignment()))
2756 // Don't increase the alignment if an alignment attribute was specified on a
2757 // typedef declaration.
2758 if (!TI.isAlignRequired())
2759 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2760
2761 return ABIAlign;
2762}
2763
2764/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2765/// for __attribute__((aligned)) on this target, to be used if no alignment
2766/// value is specified.
2770
2771/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2772/// to a global variable of the specified type.
2774 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2775 return std::max(getPreferredTypeAlign(T),
2776 getMinGlobalAlignOfVar(TypeSize, VD));
2777}
2778
2779/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2780/// should be given to a global variable of the specified type.
2785
2787 const VarDecl *VD) const {
2788 // Make the default handling as that of a non-weak definition in the
2789 // current translation unit.
2790 bool HasNonWeakDef = !VD || (VD->hasDefinition() && !VD->isWeak());
2791 return getTargetInfo().getMinGlobalAlign(Size, HasNonWeakDef);
2792}
2793
2795 CharUnits Offset = CharUnits::Zero();
2796 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2797 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2798 Offset += Layout->getBaseClassOffset(Base);
2799 Layout = &getASTRecordLayout(Base);
2800 }
2801 return Offset;
2802}
2803
2805 const ValueDecl *MPD = MP.getMemberPointerDecl();
2808 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2810 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2811 const CXXRecordDecl *Base = RD;
2812 const CXXRecordDecl *Derived = Path[I];
2813 if (DerivedMember)
2814 std::swap(Base, Derived);
2816 RD = Path[I];
2817 }
2818 if (DerivedMember)
2820 return ThisAdjustment;
2821}
2822
2823/// DeepCollectObjCIvars -
2824/// This routine first collects all declared, but not synthesized, ivars in
2825/// super class and then collects all ivars, including those synthesized for
2826/// current class. This routine is used for implementation of current class
2827/// when all ivars, declared and synthesized are known.
2829 bool leafClass,
2831 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2832 DeepCollectObjCIvars(SuperClass, false, Ivars);
2833 if (!leafClass) {
2834 llvm::append_range(Ivars, OI->ivars());
2835 } else {
2836 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2837 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2838 Iv= Iv->getNextIvar())
2839 Ivars.push_back(Iv);
2840 }
2841}
2842
2843/// CollectInheritedProtocols - Collect all protocols in current class and
2844/// those inherited by it.
2847 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2848 // We can use protocol_iterator here instead of
2849 // all_referenced_protocol_iterator since we are walking all categories.
2850 for (auto *Proto : OI->all_referenced_protocols()) {
2851 CollectInheritedProtocols(Proto, Protocols);
2852 }
2853
2854 // Categories of this Interface.
2855 for (const auto *Cat : OI->visible_categories())
2856 CollectInheritedProtocols(Cat, Protocols);
2857
2858 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2859 while (SD) {
2860 CollectInheritedProtocols(SD, Protocols);
2861 SD = SD->getSuperClass();
2862 }
2863 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2864 for (auto *Proto : OC->protocols()) {
2865 CollectInheritedProtocols(Proto, Protocols);
2866 }
2867 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2868 // Insert the protocol.
2869 if (!Protocols.insert(
2870 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2871 return;
2872
2873 for (auto *Proto : OP->protocols())
2874 CollectInheritedProtocols(Proto, Protocols);
2875 }
2876}
2877
2879 const RecordDecl *RD,
2880 bool CheckIfTriviallyCopyable) {
2881 assert(RD->isUnion() && "Must be union type");
2882 CharUnits UnionSize =
2883 Context.getTypeSizeInChars(Context.getCanonicalTagType(RD));
2884
2885 for (const auto *Field : RD->fields()) {
2886 if (!Context.hasUniqueObjectRepresentations(Field->getType(),
2887 CheckIfTriviallyCopyable))
2888 return false;
2889 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2890 if (FieldSize != UnionSize)
2891 return false;
2892 }
2893 return !RD->field_empty();
2894}
2895
2896static int64_t getSubobjectOffset(const FieldDecl *Field,
2897 const ASTContext &Context,
2898 const clang::ASTRecordLayout & /*Layout*/) {
2899 return Context.getFieldOffset(Field);
2900}
2901
2902static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2903 const ASTContext &Context,
2904 const clang::ASTRecordLayout &Layout) {
2905 return Context.toBits(Layout.getBaseClassOffset(RD));
2906}
2907
2908static std::optional<int64_t>
2910 const RecordDecl *RD,
2911 bool CheckIfTriviallyCopyable);
2912
2913static std::optional<int64_t>
2914getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context,
2915 bool CheckIfTriviallyCopyable) {
2916 if (const auto *RD = Field->getType()->getAsRecordDecl();
2917 RD && !RD->isUnion())
2918 return structHasUniqueObjectRepresentations(Context, RD,
2919 CheckIfTriviallyCopyable);
2920
2921 // A _BitInt type may not be unique if it has padding bits
2922 // but if it is a bitfield the padding bits are not used.
2923 bool IsBitIntType = Field->getType()->isBitIntType();
2924 if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2925 !Context.hasUniqueObjectRepresentations(Field->getType(),
2926 CheckIfTriviallyCopyable))
2927 return std::nullopt;
2928
2929 int64_t FieldSizeInBits =
2930 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2931 if (Field->isBitField()) {
2932 // If we have explicit padding bits, they don't contribute bits
2933 // to the actual object representation, so return 0.
2934 if (Field->isUnnamedBitField())
2935 return 0;
2936
2937 int64_t BitfieldSize = Field->getBitWidthValue();
2938 if (IsBitIntType) {
2939 if ((unsigned)BitfieldSize >
2940 cast<BitIntType>(Field->getType())->getNumBits())
2941 return std::nullopt;
2942 } else if (BitfieldSize > FieldSizeInBits) {
2943 return std::nullopt;
2944 }
2945 FieldSizeInBits = BitfieldSize;
2946 } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations(
2947 Field->getType(), CheckIfTriviallyCopyable)) {
2948 return std::nullopt;
2949 }
2950 return FieldSizeInBits;
2951}
2952
2953static std::optional<int64_t>
2955 bool CheckIfTriviallyCopyable) {
2956 return structHasUniqueObjectRepresentations(Context, RD,
2957 CheckIfTriviallyCopyable);
2958}
2959
2960template <typename RangeT>
2962 const RangeT &Subobjects, int64_t CurOffsetInBits,
2963 const ASTContext &Context, const clang::ASTRecordLayout &Layout,
2964 bool CheckIfTriviallyCopyable) {
2965 for (const auto *Subobject : Subobjects) {
2966 std::optional<int64_t> SizeInBits =
2967 getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable);
2968 if (!SizeInBits)
2969 return std::nullopt;
2970 if (*SizeInBits != 0) {
2971 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2972 if (Offset != CurOffsetInBits)
2973 return std::nullopt;
2974 CurOffsetInBits += *SizeInBits;
2975 }
2976 }
2977 return CurOffsetInBits;
2978}
2979
2980static std::optional<int64_t>
2982 const RecordDecl *RD,
2983 bool CheckIfTriviallyCopyable) {
2984 assert(!RD->isUnion() && "Must be struct/class type");
2985 const auto &Layout = Context.getASTRecordLayout(RD);
2986
2987 int64_t CurOffsetInBits = 0;
2988 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2989 if (ClassDecl->isDynamicClass())
2990 return std::nullopt;
2991
2993 for (const auto &Base : ClassDecl->bases()) {
2994 // Empty types can be inherited from, and non-empty types can potentially
2995 // have tail padding, so just make sure there isn't an error.
2996 Bases.emplace_back(Base.getType()->getAsCXXRecordDecl());
2997 }
2998
2999 llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
3000 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
3001 });
3002
3003 std::optional<int64_t> OffsetAfterBases =
3005 Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable);
3006 if (!OffsetAfterBases)
3007 return std::nullopt;
3008 CurOffsetInBits = *OffsetAfterBases;
3009 }
3010
3011 std::optional<int64_t> OffsetAfterFields =
3013 RD->fields(), CurOffsetInBits, Context, Layout,
3014 CheckIfTriviallyCopyable);
3015 if (!OffsetAfterFields)
3016 return std::nullopt;
3017 CurOffsetInBits = *OffsetAfterFields;
3018
3019 return CurOffsetInBits;
3020}
3021
3023 QualType Ty, bool CheckIfTriviallyCopyable) const {
3024 // C++17 [meta.unary.prop]:
3025 // The predicate condition for a template specialization
3026 // has_unique_object_representations<T> shall be satisfied if and only if:
3027 // (9.1) - T is trivially copyable, and
3028 // (9.2) - any two objects of type T with the same value have the same
3029 // object representation, where:
3030 // - two objects of array or non-union class type are considered to have
3031 // the same value if their respective sequences of direct subobjects
3032 // have the same values, and
3033 // - two objects of union type are considered to have the same value if
3034 // they have the same active member and the corresponding members have
3035 // the same value.
3036 // The set of scalar types for which this condition holds is
3037 // implementation-defined. [ Note: If a type has padding bits, the condition
3038 // does not hold; otherwise, the condition holds true for unsigned integral
3039 // types. -- end note ]
3040 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
3041
3042 // Arrays are unique only if their element type is unique.
3043 if (Ty->isArrayType())
3045 CheckIfTriviallyCopyable);
3046
3047 assert((Ty->isVoidType() || !Ty->isIncompleteType()) &&
3048 "hasUniqueObjectRepresentations should not be called with an "
3049 "incomplete type");
3050
3051 // (9.1) - T is trivially copyable...
3052 if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(*this))
3053 return false;
3054
3055 // All integrals and enums are unique.
3056 if (Ty->isIntegralOrEnumerationType()) {
3057 // Address discriminated integer types are not unique.
3059 return false;
3060 // Except _BitInt types that have padding bits.
3061 if (const auto *BIT = Ty->getAs<BitIntType>())
3062 return getTypeSize(BIT) == BIT->getNumBits();
3063
3064 return true;
3065 }
3066
3067 // All other pointers are unique.
3068 if (Ty->isPointerType())
3070
3071 if (const auto *MPT = Ty->getAs<MemberPointerType>())
3072 return !ABI->getMemberPointerInfo(MPT).HasPadding;
3073
3074 if (const auto *Record = Ty->getAsRecordDecl()) {
3075 if (Record->isInvalidDecl())
3076 return false;
3077
3078 if (Record->isUnion())
3080 CheckIfTriviallyCopyable);
3081
3082 std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(
3083 *this, Record, CheckIfTriviallyCopyable);
3084
3085 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(Ty));
3086 }
3087
3088 // FIXME: More cases to handle here (list by rsmith):
3089 // vectors (careful about, eg, vector of 3 foo)
3090 // _Complex int and friends
3091 // _Atomic T
3092 // Obj-C block pointers
3093 // Obj-C object pointers
3094 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
3095 // clk_event_t, queue_t, reserve_id_t)
3096 // There're also Obj-C class types and the Obj-C selector type, but I think it
3097 // makes sense for those to return false here.
3098
3099 return false;
3100}
3101
3103 unsigned count = 0;
3104 // Count ivars declared in class extension.
3105 for (const auto *Ext : OI->known_extensions())
3106 count += Ext->ivar_size();
3107
3108 // Count ivar defined in this class's implementation. This
3109 // includes synthesized ivars.
3110 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
3111 count += ImplDecl->ivar_size();
3112
3113 return count;
3114}
3115
3117 if (!E)
3118 return false;
3119
3120 // nullptr_t is always treated as null.
3121 if (E->getType()->isNullPtrType()) return true;
3122
3123 if (E->getType()->isAnyPointerType() &&
3126 return true;
3127
3128 // Unfortunately, __null has type 'int'.
3129 if (isa<GNUNullExpr>(E)) return true;
3130
3131 return false;
3132}
3133
3134/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
3135/// exists.
3137 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3138 I = ObjCImpls.find(D);
3139 if (I != ObjCImpls.end())
3140 return cast<ObjCImplementationDecl>(I->second);
3141 return nullptr;
3142}
3143
3144/// Get the implementation of ObjCCategoryDecl, or nullptr if none
3145/// exists.
3147 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3148 I = ObjCImpls.find(D);
3149 if (I != ObjCImpls.end())
3150 return cast<ObjCCategoryImplDecl>(I->second);
3151 return nullptr;
3152}
3153
3154/// Set the implementation of ObjCInterfaceDecl.
3156 ObjCImplementationDecl *ImplD) {
3157 assert(IFaceD && ImplD && "Passed null params");
3158 ObjCImpls[IFaceD] = ImplD;
3159}
3160
3161/// Set the implementation of ObjCCategoryDecl.
3163 ObjCCategoryImplDecl *ImplD) {
3164 assert(CatD && ImplD && "Passed null params");
3165 ObjCImpls[CatD] = ImplD;
3166}
3167
3168const ObjCMethodDecl *
3170 return ObjCMethodRedecls.lookup(MD);
3171}
3172
3174 const ObjCMethodDecl *Redecl) {
3175 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
3176 ObjCMethodRedecls[MD] = Redecl;
3177}
3178
3180 const NamedDecl *ND) const {
3181 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
3182 return ID;
3183 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
3184 return CD->getClassInterface();
3185 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
3186 return IMD->getClassInterface();
3187
3188 return nullptr;
3189}
3190
3191/// Get the copy initialization expression of VarDecl, or nullptr if
3192/// none exists.
3194 assert(VD && "Passed null params");
3195 assert(VD->hasAttr<BlocksAttr>() &&
3196 "getBlockVarCopyInits - not __block var");
3197 auto I = BlockVarCopyInits.find(VD);
3198 if (I != BlockVarCopyInits.end())
3199 return I->second;
3200 return {nullptr, false};
3201}
3202
3203/// Set the copy initialization expression of a block var decl.
3205 bool CanThrow) {
3206 assert(VD && CopyExpr && "Passed null params");
3207 assert(VD->hasAttr<BlocksAttr>() &&
3208 "setBlockVarCopyInits - not __block var");
3209 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
3210}
3211
3213 unsigned DataSize) const {
3214 if (!DataSize)
3215 DataSize = TypeLoc::getFullDataSizeForType(T);
3216 else
3217 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
3218 "incorrect data size provided to CreateTypeSourceInfo!");
3219
3220 auto *TInfo =
3221 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
3222 new (TInfo) TypeSourceInfo(T, DataSize);
3223 return TInfo;
3224}
3225
3227 SourceLocation L) const {
3229 TSI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
3230 return TSI;
3231}
3232
3233const ASTRecordLayout &
3235 return getObjCLayout(D);
3236}
3237
3240 bool &AnyNonCanonArgs) {
3241 SmallVector<TemplateArgument, 16> CanonArgs(Args);
3242 AnyNonCanonArgs |= C.canonicalizeTemplateArguments(CanonArgs);
3243 return CanonArgs;
3244}
3245
3248 bool AnyNonCanonArgs = false;
3249 for (auto &Arg : Args) {
3250 TemplateArgument OrigArg = Arg;
3252 AnyNonCanonArgs |= !Arg.structurallyEquals(OrigArg);
3253 }
3254 return AnyNonCanonArgs;
3255}
3256
3257//===----------------------------------------------------------------------===//
3258// Type creation/memoization methods
3259//===----------------------------------------------------------------------===//
3260
3262ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3263 unsigned fastQuals = quals.getFastQualifiers();
3264 quals.removeFastQualifiers();
3265
3266 // Check if we've already instantiated this type.
3267 llvm::FoldingSetNodeID ID;
3268 ExtQuals::Profile(ID, baseType, quals);
3269 void *insertPos = nullptr;
3270 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
3271 assert(eq->getQualifiers() == quals);
3272 return QualType(eq, fastQuals);
3273 }
3274
3275 // If the base type is not canonical, make the appropriate canonical type.
3276 QualType canon;
3277 if (!baseType->isCanonicalUnqualified()) {
3278 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3279 canonSplit.Quals.addConsistentQualifiers(quals);
3280 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
3281
3282 // Re-find the insert position.
3283 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
3284 }
3285
3286 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3287 ExtQualNodes.InsertNode(eq, insertPos);
3288 return QualType(eq, fastQuals);
3289}
3290
3292 LangAS AddressSpace) const {
3293 QualType CanT = getCanonicalType(T);
3294 if (CanT.getAddressSpace() == AddressSpace)
3295 return T;
3296
3297 // If we are composing extended qualifiers together, merge together
3298 // into one ExtQuals node.
3299 QualifierCollector Quals;
3300 const Type *TypeNode = Quals.strip(T);
3301
3302 // If this type already has an address space specified, it cannot get
3303 // another one.
3304 assert(!Quals.hasAddressSpace() &&
3305 "Type cannot be in multiple addr spaces!");
3306 Quals.addAddressSpace(AddressSpace);
3307
3308 return getExtQualType(TypeNode, Quals);
3309}
3310
3312 // If the type is not qualified with an address space, just return it
3313 // immediately.
3314 if (!T.hasAddressSpace())
3315 return T;
3316
3317 QualifierCollector Quals;
3318 const Type *TypeNode;
3319 // For arrays, strip the qualifier off the element type, then reconstruct the
3320 // array type
3321 if (T.getTypePtr()->isArrayType()) {
3322 T = getUnqualifiedArrayType(T, Quals);
3323 TypeNode = T.getTypePtr();
3324 } else {
3325 // If we are composing extended qualifiers together, merge together
3326 // into one ExtQuals node.
3327 while (T.hasAddressSpace()) {
3328 TypeNode = Quals.strip(T);
3329
3330 // If the type no longer has an address space after stripping qualifiers,
3331 // jump out.
3332 if (!QualType(TypeNode, 0).hasAddressSpace())
3333 break;
3334
3335 // There might be sugar in the way. Strip it and try again.
3336 T = T.getSingleStepDesugaredType(*this);
3337 }
3338 }
3339
3340 Quals.removeAddressSpace();
3341
3342 // Removal of the address space can mean there are no longer any
3343 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3344 // or required.
3345 if (Quals.hasNonFastQualifiers())
3346 return getExtQualType(TypeNode, Quals);
3347 else
3348 return QualType(TypeNode, Quals.getFastQualifiers());
3349}
3350
3351uint16_t
3353 assert(RD->isPolymorphic() &&
3354 "Attempted to get vtable pointer discriminator on a monomorphic type");
3355 std::unique_ptr<MangleContext> MC(createMangleContext());
3356 SmallString<256> Str;
3357 llvm::raw_svector_ostream Out(Str);
3358 MC->mangleCXXVTable(RD, Out);
3359 return llvm::getPointerAuthStableSipHash(Str);
3360}
3361
3362/// Encode a function type for use in the discriminator of a function pointer
3363/// type. We can't use the itanium scheme for this since C has quite permissive
3364/// rules for type compatibility that we need to be compatible with.
3365///
3366/// Formally, this function associates every function pointer type T with an
3367/// encoded string E(T). Let the equivalence relation T1 ~ T2 be defined as
3368/// E(T1) == E(T2). E(T) is part of the ABI of values of type T. C type
3369/// compatibility requires equivalent treatment under the ABI, so
3370/// CCompatible(T1, T2) must imply E(T1) == E(T2), that is, CCompatible must be
3371/// a subset of ~. Crucially, however, it must be a proper subset because
3372/// CCompatible is not an equivalence relation: for example, int[] is compatible
3373/// with both int[1] and int[2], but the latter are not compatible with each
3374/// other. Therefore this encoding function must be careful to only distinguish
3375/// types if there is no third type with which they are both required to be
3376/// compatible.
3378 raw_ostream &OS, QualType QT) {
3379 // FIXME: Consider address space qualifiers.
3380 const Type *T = QT.getCanonicalType().getTypePtr();
3381
3382 // FIXME: Consider using the C++ type mangling when we encounter a construct
3383 // that is incompatible with C.
3384
3385 switch (T->getTypeClass()) {
3386 case Type::Atomic:
3388 Ctx, OS, cast<AtomicType>(T)->getValueType());
3389
3390 case Type::LValueReference:
3391 OS << "R";
3394 return;
3395 case Type::RValueReference:
3396 OS << "O";
3399 return;
3400
3401 case Type::Pointer:
3402 // C11 6.7.6.1p2:
3403 // For two pointer types to be compatible, both shall be identically
3404 // qualified and both shall be pointers to compatible types.
3405 // FIXME: we should also consider pointee types.
3406 OS << "P";
3407 return;
3408
3409 case Type::ObjCObjectPointer:
3410 case Type::BlockPointer:
3411 OS << "P";
3412 return;
3413
3414 case Type::Complex:
3415 OS << "C";
3417 Ctx, OS, cast<ComplexType>(T)->getElementType());
3418
3419 case Type::VariableArray:
3420 case Type::ConstantArray:
3421 case Type::IncompleteArray:
3422 case Type::ArrayParameter:
3423 // C11 6.7.6.2p6:
3424 // For two array types to be compatible, both shall have compatible
3425 // element types, and if both size specifiers are present, and are integer
3426 // constant expressions, then both size specifiers shall have the same
3427 // constant value [...]
3428 //
3429 // So since ElemType[N] has to be compatible ElemType[], we can't encode the
3430 // width of the array.
3431 OS << "A";
3433 Ctx, OS, cast<ArrayType>(T)->getElementType());
3434
3435 case Type::ObjCInterface:
3436 case Type::ObjCObject:
3437 OS << "<objc_object>";
3438 return;
3439
3440 case Type::Enum: {
3441 // C11 6.7.2.2p4:
3442 // Each enumerated type shall be compatible with char, a signed integer
3443 // type, or an unsigned integer type.
3444 //
3445 // So we have to treat enum types as integers.
3446 QualType UnderlyingType = T->castAsEnumDecl()->getIntegerType();
3448 Ctx, OS, UnderlyingType.isNull() ? Ctx.IntTy : UnderlyingType);
3449 }
3450
3451 case Type::FunctionNoProto:
3452 case Type::FunctionProto: {
3453 // C11 6.7.6.3p15:
3454 // For two function types to be compatible, both shall specify compatible
3455 // return types. Moreover, the parameter type lists, if both are present,
3456 // shall agree in the number of parameters and in the use of the ellipsis
3457 // terminator; corresponding parameters shall have compatible types.
3458 //
3459 // That paragraph goes on to describe how unprototyped functions are to be
3460 // handled, which we ignore here. Unprototyped function pointers are hashed
3461 // as though they were prototyped nullary functions since thats probably
3462 // what the user meant. This behavior is non-conforming.
3463 // FIXME: If we add a "custom discriminator" function type attribute we
3464 // should encode functions as their discriminators.
3465 OS << "F";
3466 const auto *FuncType = cast<FunctionType>(T);
3467 encodeTypeForFunctionPointerAuth(Ctx, OS, FuncType->getReturnType());
3468 if (const auto *FPT = dyn_cast<FunctionProtoType>(FuncType)) {
3469 for (QualType Param : FPT->param_types()) {
3470 Param = Ctx.getSignatureParameterType(Param);
3471 encodeTypeForFunctionPointerAuth(Ctx, OS, Param);
3472 }
3473 if (FPT->isVariadic())
3474 OS << "z";
3475 }
3476 OS << "E";
3477 return;
3478 }
3479
3480 case Type::MemberPointer: {
3481 OS << "M";
3482 const auto *MPT = T->castAs<MemberPointerType>();
3484 Ctx, OS, QualType(MPT->getQualifier().getAsType(), 0));
3485 encodeTypeForFunctionPointerAuth(Ctx, OS, MPT->getPointeeType());
3486 return;
3487 }
3488 case Type::ExtVector:
3489 case Type::Vector:
3490 OS << "Dv" << Ctx.getTypeSizeInChars(T).getQuantity();
3491 break;
3492
3493 // Don't bother discriminating based on these types.
3494 case Type::Pipe:
3495 case Type::BitInt:
3496 case Type::ConstantMatrix:
3497 OS << "?";
3498 return;
3499
3500 case Type::Builtin: {
3501 const auto *BTy = T->castAs<BuiltinType>();
3502 switch (BTy->getKind()) {
3503#define SIGNED_TYPE(Id, SingletonId) \
3504 case BuiltinType::Id: \
3505 OS << "i"; \
3506 return;
3507#define UNSIGNED_TYPE(Id, SingletonId) \
3508 case BuiltinType::Id: \
3509 OS << "i"; \
3510 return;
3511#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
3512#define BUILTIN_TYPE(Id, SingletonId)
3513#include "clang/AST/BuiltinTypes.def"
3514 llvm_unreachable("placeholder types should not appear here.");
3515
3516 case BuiltinType::Half:
3517 OS << "Dh";
3518 return;
3519 case BuiltinType::Float:
3520 OS << "f";
3521 return;
3522 case BuiltinType::Double:
3523 OS << "d";
3524 return;
3525 case BuiltinType::LongDouble:
3526 OS << "e";
3527 return;
3528 case BuiltinType::Float16:
3529 OS << "DF16_";
3530 return;
3531 case BuiltinType::Float128:
3532 OS << "g";
3533 return;
3534
3535 case BuiltinType::Void:
3536 OS << "v";
3537 return;
3538
3539 case BuiltinType::ObjCId:
3540 case BuiltinType::ObjCClass:
3541 case BuiltinType::ObjCSel:
3542 case BuiltinType::NullPtr:
3543 OS << "P";
3544 return;
3545
3546 // Don't bother discriminating based on OpenCL types.
3547 case BuiltinType::OCLSampler:
3548 case BuiltinType::OCLEvent:
3549 case BuiltinType::OCLClkEvent:
3550 case BuiltinType::OCLQueue:
3551 case BuiltinType::OCLReserveID:
3552 case BuiltinType::BFloat16:
3553 case BuiltinType::VectorQuad:
3554 case BuiltinType::VectorPair:
3555 case BuiltinType::DMR1024:
3556 case BuiltinType::DMR2048:
3557 OS << "?";
3558 return;
3559
3560 // Don't bother discriminating based on these seldom-used types.
3561 case BuiltinType::Ibm128:
3562 return;
3563#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3564 case BuiltinType::Id: \
3565 return;
3566#include "clang/Basic/OpenCLImageTypes.def"
3567#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3568 case BuiltinType::Id: \
3569 return;
3570#include "clang/Basic/OpenCLExtensionTypes.def"
3571#define SVE_TYPE(Name, Id, SingletonId) \
3572 case BuiltinType::Id: \
3573 return;
3574#include "clang/Basic/AArch64ACLETypes.def"
3575#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3576 case BuiltinType::Id: \
3577 return;
3578#include "clang/Basic/HLSLIntangibleTypes.def"
3579 case BuiltinType::Dependent:
3580 llvm_unreachable("should never get here");
3581#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
3582#include "clang/Basic/AMDGPUTypes.def"
3583 case BuiltinType::WasmExternRef:
3584#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3585#include "clang/Basic/RISCVVTypes.def"
3586 llvm_unreachable("not yet implemented");
3587 }
3588 llvm_unreachable("should never get here");
3589 }
3590 case Type::Record: {
3591 const RecordDecl *RD = T->castAsCanonical<RecordType>()->getDecl();
3592 const IdentifierInfo *II = RD->getIdentifier();
3593
3594 // In C++, an immediate typedef of an anonymous struct or union
3595 // is considered to name it for ODR purposes, but C's specification
3596 // of type compatibility does not have a similar rule. Using the typedef
3597 // name in function type discriminators anyway, as we do here,
3598 // therefore technically violates the C standard: two function pointer
3599 // types defined in terms of two typedef'd anonymous structs with
3600 // different names are formally still compatible, but we are assigning
3601 // them different discriminators and therefore incompatible ABIs.
3602 //
3603 // This is a relatively minor violation that significantly improves
3604 // discrimination in some cases and has not caused problems in
3605 // practice. Regardless, it is now part of the ABI in places where
3606 // function type discrimination is used, and it can no longer be
3607 // changed except on new platforms.
3608
3609 if (!II)
3610 if (const TypedefNameDecl *Typedef = RD->getTypedefNameForAnonDecl())
3611 II = Typedef->getDeclName().getAsIdentifierInfo();
3612
3613 if (!II) {
3614 OS << "<anonymous_record>";
3615 return;
3616 }
3617 OS << II->getLength() << II->getName();
3618 return;
3619 }
3620 case Type::HLSLAttributedResource:
3621 case Type::HLSLInlineSpirv:
3622 llvm_unreachable("should never get here");
3623 break;
3624 case Type::OverflowBehavior:
3625 llvm_unreachable("should never get here");
3626 break;
3627 case Type::DeducedTemplateSpecialization:
3628 case Type::Auto:
3629#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3630#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3631#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3632#define ABSTRACT_TYPE(Class, Base)
3633#define TYPE(Class, Base)
3634#include "clang/AST/TypeNodes.inc"
3635 llvm_unreachable("unexpected non-canonical or dependent type!");
3636 return;
3637 }
3638}
3639
3641 assert(!T->isDependentType() &&
3642 "cannot compute type discriminator of a dependent type");
3643 SmallString<256> Str;
3644 llvm::raw_svector_ostream Out(Str);
3645
3646 if (T->isFunctionPointerType() || T->isFunctionReferenceType())
3647 T = T->getPointeeType();
3648
3649 if (T->isFunctionType()) {
3650 encodeTypeForFunctionPointerAuth(*this, Out, T);
3651 } else {
3652 T = T.getUnqualifiedType();
3653 // Calls to member function pointers don't need to worry about
3654 // language interop or the laxness of the C type compatibility rules.
3655 // We just mangle the member pointer type directly, which is
3656 // implicitly much stricter about type matching. However, we do
3657 // strip any top-level exception specification before this mangling.
3658 // C++23 requires calls to work when the function type is convertible
3659 // to the pointer type by a function pointer conversion, which can
3660 // change the exception specification. This does not technically
3661 // require the exception specification to not affect representation,
3662 // because the function pointer conversion is still always a direct
3663 // value conversion and therefore an opportunity to resign the
3664 // pointer. (This is in contrast to e.g. qualification conversions,
3665 // which can be applied in nested pointer positions, effectively
3666 // requiring qualified and unqualified representations to match.)
3667 // However, it is pragmatic to ignore exception specifications
3668 // because it allows a certain amount of `noexcept` mismatching
3669 // to not become a visible ODR problem. This also leaves some
3670 // room for the committee to add laxness to function pointer
3671 // conversions in future standards.
3672 if (auto *MPT = T->getAs<MemberPointerType>())
3673 if (MPT->isMemberFunctionPointer()) {
3674 QualType PointeeType = MPT->getPointeeType();
3675 if (PointeeType->castAs<FunctionProtoType>()->getExceptionSpecType() !=
3676 EST_None) {
3678 T = getMemberPointerType(FT, MPT->getQualifier(),
3679 MPT->getMostRecentCXXRecordDecl());
3680 }
3681 }
3682 std::unique_ptr<MangleContext> MC(createMangleContext());
3683 MC->mangleCanonicalTypeName(T, Out);
3684 }
3685
3686 return llvm::getPointerAuthStableSipHash(Str);
3687}
3688
3690 Qualifiers::GC GCAttr) const {
3691 QualType CanT = getCanonicalType(T);
3692 if (CanT.getObjCGCAttr() == GCAttr)
3693 return T;
3694
3695 if (const auto *ptr = T->getAs<PointerType>()) {
3696 QualType Pointee = ptr->getPointeeType();
3697 if (Pointee->isAnyPointerType()) {
3698 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
3699 return getPointerType(ResultType);
3700 }
3701 }
3702
3703 // If we are composing extended qualifiers together, merge together
3704 // into one ExtQuals node.
3705 QualifierCollector Quals;
3706 const Type *TypeNode = Quals.strip(T);
3707
3708 // If this type already has an ObjCGC specified, it cannot get
3709 // another one.
3710 assert(!Quals.hasObjCGCAttr() &&
3711 "Type cannot have multiple ObjCGCs!");
3712 Quals.addObjCGCAttr(GCAttr);
3713
3714 return getExtQualType(TypeNode, Quals);
3715}
3716
3718 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3719 QualType Pointee = Ptr->getPointeeType();
3720 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3721 return getPointerType(removeAddrSpaceQualType(Pointee));
3722 }
3723 }
3724 return T;
3725}
3726
3728 QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull,
3729 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3730 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3731
3732 llvm::FoldingSetNodeID ID;
3733 CountAttributedType::Profile(ID, WrappedTy, CountExpr, CountInBytes, OrNull);
3734
3735 void *InsertPos = nullptr;
3736 CountAttributedType *CATy =
3737 CountAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
3738 if (CATy)
3739 return QualType(CATy, 0);
3740
3741 QualType CanonTy = getCanonicalType(WrappedTy);
3742 size_t Size = CountAttributedType::totalSizeToAlloc<TypeCoupledDeclRefInfo>(
3743 DependentDecls.size());
3745 new (CATy) CountAttributedType(WrappedTy, CanonTy, CountExpr, CountInBytes,
3746 OrNull, DependentDecls);
3747 Types.push_back(CATy);
3748 CountAttributedTypes.InsertNode(CATy, InsertPos);
3749
3750 return QualType(CATy, 0);
3751}
3752
3755 llvm::function_ref<QualType(QualType)> Adjust) const {
3756 switch (Orig->getTypeClass()) {
3757 case Type::Attributed: {
3758 const auto *AT = cast<AttributedType>(Orig);
3759 return getAttributedType(AT->getAttrKind(),
3760 adjustType(AT->getModifiedType(), Adjust),
3761 adjustType(AT->getEquivalentType(), Adjust),
3762 AT->getAttr());
3763 }
3764
3765 case Type::BTFTagAttributed: {
3766 const auto *BTFT = dyn_cast<BTFTagAttributedType>(Orig);
3767 return getBTFTagAttributedType(BTFT->getAttr(),
3768 adjustType(BTFT->getWrappedType(), Adjust));
3769 }
3770
3771 case Type::OverflowBehavior: {
3772 const auto *OB = dyn_cast<OverflowBehaviorType>(Orig);
3773 return getOverflowBehaviorType(OB->getBehaviorKind(),
3774 adjustType(OB->getUnderlyingType(), Adjust));
3775 }
3776
3777 case Type::Paren:
3778 return getParenType(
3779 adjustType(cast<ParenType>(Orig)->getInnerType(), Adjust));
3780
3781 case Type::Adjusted: {
3782 const auto *AT = cast<AdjustedType>(Orig);
3783 return getAdjustedType(AT->getOriginalType(),
3784 adjustType(AT->getAdjustedType(), Adjust));
3785 }
3786
3787 case Type::MacroQualified: {
3788 const auto *MQT = cast<MacroQualifiedType>(Orig);
3789 return getMacroQualifiedType(adjustType(MQT->getUnderlyingType(), Adjust),
3790 MQT->getMacroIdentifier());
3791 }
3792
3793 default:
3794 return Adjust(Orig);
3795 }
3796}
3797
3799 FunctionType::ExtInfo Info) {
3800 if (T->getExtInfo() == Info)
3801 return T;
3802
3804 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3805 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3806 } else {
3807 const auto *FPT = cast<FunctionProtoType>(T);
3808 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3809 EPI.ExtInfo = Info;
3810 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3811 }
3812
3813 return cast<FunctionType>(Result.getTypePtr());
3814}
3815
3817 QualType ResultType) {
3818 return adjustType(FunctionType, [&](QualType Orig) {
3819 if (const auto *FNPT = Orig->getAs<FunctionNoProtoType>())
3820 return getFunctionNoProtoType(ResultType, FNPT->getExtInfo());
3821
3822 const auto *FPT = Orig->castAs<FunctionProtoType>();
3823 return getFunctionType(ResultType, FPT->getParamTypes(),
3824 FPT->getExtProtoInfo());
3825 });
3826}
3827
3829 QualType ResultType) {
3830 FD = FD->getMostRecentDecl();
3831 while (true) {
3832 FD->setType(adjustFunctionResultType(FD->getType(), ResultType));
3833 if (FunctionDecl *Next = FD->getPreviousDecl())
3834 FD = Next;
3835 else
3836 break;
3837 }
3839 L->DeducedReturnType(FD, ResultType);
3840}
3841
3842/// Get a function type and produce the equivalent function type with the
3843/// specified exception specification. Type sugar that can be present on a
3844/// declaration of a function with an exception specification is permitted
3845/// and preserved. Other type sugar (for instance, typedefs) is not.
3847 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3848 return adjustType(Orig, [&](QualType Ty) {
3849 const auto *Proto = Ty->castAs<FunctionProtoType>();
3850 return getFunctionType(Proto->getReturnType(), Proto->getParamTypes(),
3851 Proto->getExtProtoInfo().withExceptionSpec(ESI));
3852 });
3853}
3854
3862
3864 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3865 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3866 SmallVector<QualType, 16> Args(Proto->param_types().size());
3867 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3868 Args[i] = removePtrSizeAddrSpace(Proto->param_types()[i]);
3869 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3870 }
3871
3872 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3873 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3874 return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3875 }
3876
3877 return T;
3878}
3879
3885
3887 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3888 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3889 EPI.ExtParameterInfos = nullptr;
3890 return getFunctionType(Proto->getReturnType(), Proto->param_types(), EPI);
3891 }
3892 return T;
3893}
3894
3900
3903 bool AsWritten) {
3904 // Update the type.
3905 QualType Updated =
3907 FD->setType(Updated);
3908
3909 if (!AsWritten)
3910 return;
3911
3912 // Update the type in the type source information too.
3913 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3914 // If the type and the type-as-written differ, we may need to update
3915 // the type-as-written too.
3916 if (TSInfo->getType() != FD->getType())
3917 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3918
3919 // FIXME: When we get proper type location information for exceptions,
3920 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3921 // up the TypeSourceInfo;
3922 assert(TypeLoc::getFullDataSizeForType(Updated) ==
3923 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3924 "TypeLoc size mismatch from updating exception specification");
3925 TSInfo->overrideType(Updated);
3926 }
3927}
3928
3929/// getComplexType - Return the uniqued reference to the type for a complex
3930/// number with the specified element type.
3932 // Unique pointers, to guarantee there is only one pointer of a particular
3933 // structure.
3934 llvm::FoldingSetNodeID ID;
3935 ComplexType::Profile(ID, T);
3936
3937 void *InsertPos = nullptr;
3938 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3939 return QualType(CT, 0);
3940
3941 // If the pointee type isn't canonical, this won't be a canonical type either,
3942 // so fill in the canonical type field.
3943 QualType Canonical;
3944 if (!T.isCanonical()) {
3945 Canonical = getComplexType(getCanonicalType(T));
3946
3947 // Get the new insert position for the node we care about.
3948 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3949 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3950 }
3951 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
3952 Types.push_back(New);
3953 ComplexTypes.InsertNode(New, InsertPos);
3954 return QualType(New, 0);
3955}
3956
3957/// getPointerType - Return the uniqued reference to the type for a pointer to
3958/// the specified type.
3960 // Unique pointers, to guarantee there is only one pointer of a particular
3961 // structure.
3962 llvm::FoldingSetNodeID ID;
3963 PointerType::Profile(ID, T);
3964
3965 void *InsertPos = nullptr;
3966 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3967 return QualType(PT, 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 = getPointerType(getCanonicalType(T));
3974
3975 // Get the new insert position for the node we care about.
3976 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3977 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3978 }
3979 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
3980 Types.push_back(New);
3981 PointerTypes.InsertNode(New, InsertPos);
3982 return QualType(New, 0);
3983}
3984
3986 llvm::FoldingSetNodeID ID;
3987 AdjustedType::Profile(ID, Orig, New);
3988 void *InsertPos = nullptr;
3989 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3990 if (AT)
3991 return QualType(AT, 0);
3992
3993 QualType Canonical = getCanonicalType(New);
3994
3995 // Get the new insert position for the node we care about.
3996 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3997 assert(!AT && "Shouldn't be in the map!");
3998
3999 AT = new (*this, alignof(AdjustedType))
4000 AdjustedType(Type::Adjusted, Orig, New, Canonical);
4001 Types.push_back(AT);
4002 AdjustedTypes.InsertNode(AT, InsertPos);
4003 return QualType(AT, 0);
4004}
4005
4007 llvm::FoldingSetNodeID ID;
4008 AdjustedType::Profile(ID, Orig, Decayed);
4009 void *InsertPos = nullptr;
4010 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
4011 if (AT)
4012 return QualType(AT, 0);
4013
4014 QualType Canonical = getCanonicalType(Decayed);
4015
4016 // Get the new insert position for the node we care about.
4017 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
4018 assert(!AT && "Shouldn't be in the map!");
4019
4020 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
4021 Types.push_back(AT);
4022 AdjustedTypes.InsertNode(AT, InsertPos);
4023 return QualType(AT, 0);
4024}
4025
4027 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
4028
4029 QualType Decayed;
4030
4031 // C99 6.7.5.3p7:
4032 // A declaration of a parameter as "array of type" shall be
4033 // adjusted to "qualified pointer to type", where the type
4034 // qualifiers (if any) are those specified within the [ and ] of
4035 // the array type derivation.
4036 if (T->isArrayType())
4037 Decayed = getArrayDecayedType(T);
4038
4039 // C99 6.7.5.3p8:
4040 // A declaration of a parameter as "function returning type"
4041 // shall be adjusted to "pointer to function returning type", as
4042 // in 6.3.2.1.
4043 if (T->isFunctionType())
4044 Decayed = getPointerType(T);
4045
4046 return getDecayedType(T, Decayed);
4047}
4048
4050 if (Ty->isArrayParameterType())
4051 return Ty;
4052 assert(Ty->isConstantArrayType() && "Ty must be an array type.");
4053 QualType DTy = Ty.getDesugaredType(*this);
4054 const auto *ATy = cast<ConstantArrayType>(DTy);
4055 llvm::FoldingSetNodeID ID;
4056 ATy->Profile(ID, *this, ATy->getElementType(), ATy->getZExtSize(),
4057 ATy->getSizeExpr(), ATy->getSizeModifier(),
4058 ATy->getIndexTypeQualifiers().getAsOpaqueValue());
4059 void *InsertPos = nullptr;
4060 ArrayParameterType *AT =
4061 ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
4062 if (AT)
4063 return QualType(AT, 0);
4064
4065 QualType Canonical;
4066 if (!DTy.isCanonical()) {
4067 Canonical = getArrayParameterType(getCanonicalType(Ty));
4068
4069 // Get the new insert position for the node we care about.
4070 AT = ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
4071 assert(!AT && "Shouldn't be in the map!");
4072 }
4073
4074 AT = new (*this, alignof(ArrayParameterType))
4075 ArrayParameterType(ATy, Canonical);
4076 Types.push_back(AT);
4077 ArrayParameterTypes.InsertNode(AT, InsertPos);
4078 return QualType(AT, 0);
4079}
4080
4081/// getBlockPointerType - Return the uniqued reference to the type for
4082/// a pointer to the specified block.
4084 assert(T->isFunctionType() && "block of function types only");
4085 // Unique pointers, to guarantee there is only one block of a particular
4086 // structure.
4087 llvm::FoldingSetNodeID ID;
4089
4090 void *InsertPos = nullptr;
4091 if (BlockPointerType *PT =
4092 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4093 return QualType(PT, 0);
4094
4095 // If the block pointee type isn't canonical, this won't be a canonical
4096 // type either so fill in the canonical type field.
4097 QualType Canonical;
4098 if (!T.isCanonical()) {
4099 Canonical = getBlockPointerType(getCanonicalType(T));
4100
4101 // Get the new insert position for the node we care about.
4102 BlockPointerType *NewIP =
4103 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4104 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4105 }
4106 auto *New =
4107 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
4108 Types.push_back(New);
4109 BlockPointerTypes.InsertNode(New, InsertPos);
4110 return QualType(New, 0);
4111}
4112
4113/// getLValueReferenceType - Return the uniqued reference to the type for an
4114/// lvalue reference to the specified type.
4116ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
4117 assert((!T->isPlaceholderType() ||
4118 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4119 "Unresolved placeholder type");
4120
4121 // Unique pointers, to guarantee there is only one pointer of a particular
4122 // structure.
4123 llvm::FoldingSetNodeID ID;
4124 ReferenceType::Profile(ID, T, SpelledAsLValue);
4125
4126 void *InsertPos = nullptr;
4127 if (LValueReferenceType *RT =
4128 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4129 return QualType(RT, 0);
4130
4131 const auto *InnerRef = T->getAs<ReferenceType>();
4132
4133 // If the referencee type isn't canonical, this won't be a canonical type
4134 // either, so fill in the canonical type field.
4135 QualType Canonical;
4136 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
4137 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4138 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
4139
4140 // Get the new insert position for the node we care about.
4141 LValueReferenceType *NewIP =
4142 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4143 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4144 }
4145
4146 auto *New = new (*this, alignof(LValueReferenceType))
4147 LValueReferenceType(T, Canonical, SpelledAsLValue);
4148 Types.push_back(New);
4149 LValueReferenceTypes.InsertNode(New, InsertPos);
4150
4151 return QualType(New, 0);
4152}
4153
4154/// getRValueReferenceType - Return the uniqued reference to the type for an
4155/// rvalue reference to the specified type.
4157 assert((!T->isPlaceholderType() ||
4158 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4159 "Unresolved placeholder type");
4160
4161 // Unique pointers, to guarantee there is only one pointer of a particular
4162 // structure.
4163 llvm::FoldingSetNodeID ID;
4164 ReferenceType::Profile(ID, T, false);
4165
4166 void *InsertPos = nullptr;
4167 if (RValueReferenceType *RT =
4168 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4169 return QualType(RT, 0);
4170
4171 const auto *InnerRef = T->getAs<ReferenceType>();
4172
4173 // If the referencee type isn't canonical, this won't be a canonical type
4174 // either, so fill in the canonical type field.
4175 QualType Canonical;
4176 if (InnerRef || !T.isCanonical()) {
4177 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4178 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
4179
4180 // Get the new insert position for the node we care about.
4181 RValueReferenceType *NewIP =
4182 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4183 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4184 }
4185
4186 auto *New = new (*this, alignof(RValueReferenceType))
4187 RValueReferenceType(T, Canonical);
4188 Types.push_back(New);
4189 RValueReferenceTypes.InsertNode(New, InsertPos);
4190 return QualType(New, 0);
4191}
4192
4194 NestedNameSpecifier Qualifier,
4195 const CXXRecordDecl *Cls) const {
4196 if (!Qualifier) {
4197 assert(Cls && "At least one of Qualifier or Cls must be provided");
4198 Qualifier = NestedNameSpecifier(getCanonicalTagType(Cls).getTypePtr());
4199 } else if (!Cls) {
4200 Cls = Qualifier.getAsRecordDecl();
4201 }
4202 // Unique pointers, to guarantee there is only one pointer of a particular
4203 // structure.
4204 llvm::FoldingSetNodeID ID;
4205 MemberPointerType::Profile(ID, T, Qualifier, Cls);
4206
4207 void *InsertPos = nullptr;
4208 if (MemberPointerType *PT =
4209 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4210 return QualType(PT, 0);
4211
4212 NestedNameSpecifier CanonicalQualifier = [&] {
4213 if (!Cls)
4214 return Qualifier.getCanonical();
4215 NestedNameSpecifier R(getCanonicalTagType(Cls).getTypePtr());
4216 assert(R.isCanonical());
4217 return R;
4218 }();
4219 // If the pointee or class type isn't canonical, this won't be a canonical
4220 // type either, so fill in the canonical type field.
4221 QualType Canonical;
4222 if (!T.isCanonical() || Qualifier != CanonicalQualifier) {
4223 Canonical =
4224 getMemberPointerType(getCanonicalType(T), CanonicalQualifier, Cls);
4225 assert(!cast<MemberPointerType>(Canonical)->isSugared());
4226 // Get the new insert position for the node we care about.
4227 [[maybe_unused]] MemberPointerType *NewIP =
4228 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4229 assert(!NewIP && "Shouldn't be in the map!");
4230 }
4231 auto *New = new (*this, alignof(MemberPointerType))
4232 MemberPointerType(T, Qualifier, Canonical);
4233 Types.push_back(New);
4234 MemberPointerTypes.InsertNode(New, InsertPos);
4235 return QualType(New, 0);
4236}
4237
4238/// getConstantArrayType - Return the unique reference to the type for an
4239/// array of the specified element type.
4241 const llvm::APInt &ArySizeIn,
4242 const Expr *SizeExpr,
4244 unsigned IndexTypeQuals) const {
4245 assert((EltTy->isDependentType() ||
4246 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
4247 "Constant array of VLAs is illegal!");
4248
4249 // We only need the size as part of the type if it's instantiation-dependent.
4250 if (SizeExpr && !SizeExpr->isInstantiationDependent())
4251 SizeExpr = nullptr;
4252
4253 // Convert the array size into a canonical width matching the pointer size for
4254 // the target.
4255 llvm::APInt ArySize(ArySizeIn);
4256 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
4257
4258 llvm::FoldingSetNodeID ID;
4259 ConstantArrayType::Profile(ID, *this, EltTy, ArySize.getZExtValue(), SizeExpr,
4260 ASM, IndexTypeQuals);
4261
4262 void *InsertPos = nullptr;
4263 if (ConstantArrayType *ATP =
4264 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
4265 return QualType(ATP, 0);
4266
4267 // If the element type isn't canonical or has qualifiers, or the array bound
4268 // is instantiation-dependent, this won't be a canonical type either, so fill
4269 // in the canonical type field.
4270 QualType Canon;
4271 // FIXME: Check below should look for qualifiers behind sugar.
4272 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
4273 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4274 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
4275 ASM, IndexTypeQuals);
4276 Canon = getQualifiedType(Canon, canonSplit.Quals);
4277
4278 // Get the new insert position for the node we care about.
4279 ConstantArrayType *NewIP =
4280 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
4281 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4282 }
4283
4284 auto *New = ConstantArrayType::Create(*this, EltTy, Canon, ArySize, SizeExpr,
4285 ASM, IndexTypeQuals);
4286 ConstantArrayTypes.InsertNode(New, InsertPos);
4287 Types.push_back(New);
4288 return QualType(New, 0);
4289}
4290
4291/// getVariableArrayDecayedType - Turns the given type, which may be
4292/// variably-modified, into the corresponding type with all the known
4293/// sizes replaced with [*].
4295 // Vastly most common case.
4296 if (!type->isVariablyModifiedType()) return type;
4297
4298 QualType result;
4299
4300 SplitQualType split = type.getSplitDesugaredType();
4301 const Type *ty = split.Ty;
4302 switch (ty->getTypeClass()) {
4303#define TYPE(Class, Base)
4304#define ABSTRACT_TYPE(Class, Base)
4305#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4306#include "clang/AST/TypeNodes.inc"
4307 llvm_unreachable("didn't desugar past all non-canonical types?");
4308
4309 // These types should never be variably-modified.
4310 case Type::Builtin:
4311 case Type::Complex:
4312 case Type::Vector:
4313 case Type::DependentVector:
4314 case Type::ExtVector:
4315 case Type::DependentSizedExtVector:
4316 case Type::ConstantMatrix:
4317 case Type::DependentSizedMatrix:
4318 case Type::DependentAddressSpace:
4319 case Type::ObjCObject:
4320 case Type::ObjCInterface:
4321 case Type::ObjCObjectPointer:
4322 case Type::Record:
4323 case Type::Enum:
4324 case Type::UnresolvedUsing:
4325 case Type::TypeOfExpr:
4326 case Type::TypeOf:
4327 case Type::Decltype:
4328 case Type::UnaryTransform:
4329 case Type::DependentName:
4330 case Type::InjectedClassName:
4331 case Type::TemplateSpecialization:
4332 case Type::TemplateTypeParm:
4333 case Type::SubstTemplateTypeParmPack:
4334 case Type::SubstBuiltinTemplatePack:
4335 case Type::Auto:
4336 case Type::DeducedTemplateSpecialization:
4337 case Type::PackExpansion:
4338 case Type::PackIndexing:
4339 case Type::BitInt:
4340 case Type::DependentBitInt:
4341 case Type::ArrayParameter:
4342 case Type::HLSLAttributedResource:
4343 case Type::HLSLInlineSpirv:
4344 case Type::OverflowBehavior:
4345 llvm_unreachable("type should never be variably-modified");
4346
4347 // These types can be variably-modified but should never need to
4348 // further decay.
4349 case Type::FunctionNoProto:
4350 case Type::FunctionProto:
4351 case Type::BlockPointer:
4352 case Type::MemberPointer:
4353 case Type::Pipe:
4354 return type;
4355
4356 // These types can be variably-modified. All these modifications
4357 // preserve structure except as noted by comments.
4358 // TODO: if we ever care about optimizing VLAs, there are no-op
4359 // optimizations available here.
4360 case Type::Pointer:
4363 break;
4364
4365 case Type::LValueReference: {
4366 const auto *lv = cast<LValueReferenceType>(ty);
4367 result = getLValueReferenceType(
4368 getVariableArrayDecayedType(lv->getPointeeType()),
4369 lv->isSpelledAsLValue());
4370 break;
4371 }
4372
4373 case Type::RValueReference: {
4374 const auto *lv = cast<RValueReferenceType>(ty);
4375 result = getRValueReferenceType(
4376 getVariableArrayDecayedType(lv->getPointeeType()));
4377 break;
4378 }
4379
4380 case Type::Atomic: {
4381 const auto *at = cast<AtomicType>(ty);
4382 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
4383 break;
4384 }
4385
4386 case Type::ConstantArray: {
4387 const auto *cat = cast<ConstantArrayType>(ty);
4388 result = getConstantArrayType(
4389 getVariableArrayDecayedType(cat->getElementType()),
4390 cat->getSize(),
4391 cat->getSizeExpr(),
4392 cat->getSizeModifier(),
4393 cat->getIndexTypeCVRQualifiers());
4394 break;
4395 }
4396
4397 case Type::DependentSizedArray: {
4398 const auto *dat = cast<DependentSizedArrayType>(ty);
4400 getVariableArrayDecayedType(dat->getElementType()), dat->getSizeExpr(),
4401 dat->getSizeModifier(), dat->getIndexTypeCVRQualifiers());
4402 break;
4403 }
4404
4405 // Turn incomplete types into [*] types.
4406 case Type::IncompleteArray: {
4407 const auto *iat = cast<IncompleteArrayType>(ty);
4408 result =
4410 /*size*/ nullptr, ArraySizeModifier::Normal,
4411 iat->getIndexTypeCVRQualifiers());
4412 break;
4413 }
4414
4415 // Turn VLA types into [*] types.
4416 case Type::VariableArray: {
4417 const auto *vat = cast<VariableArrayType>(ty);
4418 result =
4420 /*size*/ nullptr, ArraySizeModifier::Star,
4421 vat->getIndexTypeCVRQualifiers());
4422 break;
4423 }
4424 }
4425
4426 // Apply the top-level qualifiers from the original.
4427 return getQualifiedType(result, split.Quals);
4428}
4429
4430/// getVariableArrayType - Returns a non-unique reference to the type for a
4431/// variable array of the specified element type.
4434 unsigned IndexTypeQuals) const {
4435 // Since we don't unique expressions, it isn't possible to unique VLA's
4436 // that have an expression provided for their size.
4437 QualType Canon;
4438
4439 // Be sure to pull qualifiers off the element type.
4440 // FIXME: Check below should look for qualifiers behind sugar.
4441 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
4442 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4443 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
4444 IndexTypeQuals);
4445 Canon = getQualifiedType(Canon, canonSplit.Quals);
4446 }
4447
4448 auto *New = new (*this, alignof(VariableArrayType))
4449 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals);
4450
4451 VariableArrayTypes.push_back(New);
4452 Types.push_back(New);
4453 return QualType(New, 0);
4454}
4455
4456/// getDependentSizedArrayType - Returns a non-unique reference to
4457/// the type for a dependently-sized array of the specified element
4458/// type.
4462 unsigned elementTypeQuals) const {
4463 assert((!numElements || numElements->isTypeDependent() ||
4464 numElements->isValueDependent()) &&
4465 "Size must be type- or value-dependent!");
4466
4467 SplitQualType canonElementType = getCanonicalType(elementType).split();
4468
4469 void *insertPos = nullptr;
4470 llvm::FoldingSetNodeID ID;
4472 ID, *this, numElements ? QualType(canonElementType.Ty, 0) : elementType,
4473 ASM, elementTypeQuals, numElements);
4474
4475 // Look for an existing type with these properties.
4476 DependentSizedArrayType *canonTy =
4477 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4478
4479 // Dependently-sized array types that do not have a specified number
4480 // of elements will have their sizes deduced from a dependent
4481 // initializer.
4482 if (!numElements) {
4483 if (canonTy)
4484 return QualType(canonTy, 0);
4485
4486 auto *newType = new (*this, alignof(DependentSizedArrayType))
4487 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
4488 elementTypeQuals);
4489 DependentSizedArrayTypes.InsertNode(newType, insertPos);
4490 Types.push_back(newType);
4491 return QualType(newType, 0);
4492 }
4493
4494 // If we don't have one, build one.
4495 if (!canonTy) {
4496 canonTy = new (*this, alignof(DependentSizedArrayType))
4497 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
4498 numElements, ASM, elementTypeQuals);
4499 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
4500 Types.push_back(canonTy);
4501 }
4502
4503 // Apply qualifiers from the element type to the array.
4504 QualType canon = getQualifiedType(QualType(canonTy,0),
4505 canonElementType.Quals);
4506
4507 // If we didn't need extra canonicalization for the element type or the size
4508 // expression, then just use that as our result.
4509 if (QualType(canonElementType.Ty, 0) == elementType &&
4510 canonTy->getSizeExpr() == numElements)
4511 return canon;
4512
4513 // Otherwise, we need to build a type which follows the spelling
4514 // of the element type.
4515 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
4516 DependentSizedArrayType(elementType, canon, numElements, ASM,
4517 elementTypeQuals);
4518 Types.push_back(sugaredType);
4519 return QualType(sugaredType, 0);
4520}
4521
4524 unsigned elementTypeQuals) const {
4525 llvm::FoldingSetNodeID ID;
4526 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
4527
4528 void *insertPos = nullptr;
4529 if (IncompleteArrayType *iat =
4530 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
4531 return QualType(iat, 0);
4532
4533 // If the element type isn't canonical, this won't be a canonical type
4534 // either, so fill in the canonical type field. We also have to pull
4535 // qualifiers off the element type.
4536 QualType canon;
4537
4538 // FIXME: Check below should look for qualifiers behind sugar.
4539 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
4540 SplitQualType canonSplit = getCanonicalType(elementType).split();
4541 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
4542 ASM, elementTypeQuals);
4543 canon = getQualifiedType(canon, canonSplit.Quals);
4544
4545 // Get the new insert position for the node we care about.
4546 IncompleteArrayType *existing =
4547 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4548 assert(!existing && "Shouldn't be in the map!"); (void) existing;
4549 }
4550
4551 auto *newType = new (*this, alignof(IncompleteArrayType))
4552 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
4553
4554 IncompleteArrayTypes.InsertNode(newType, insertPos);
4555 Types.push_back(newType);
4556 return QualType(newType, 0);
4557}
4558
4561#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
4562 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
4563 NUMVECTORS};
4564
4565#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
4566 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
4567
4568 switch (Ty->getKind()) {
4569 default:
4570 llvm_unreachable("Unsupported builtin vector type");
4571
4572#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4573 ElBits, NF, IsSigned) \
4574 case BuiltinType::Id: \
4575 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4576 llvm::ElementCount::getScalable(NumEls), NF};
4577#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4578 ElBits, NF) \
4579 case BuiltinType::Id: \
4580 return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy), \
4581 llvm::ElementCount::getScalable(NumEls), NF};
4582#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4583 ElBits, NF) \
4584 case BuiltinType::Id: \
4585 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4586#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4587 ElBits, NF) \
4588 case BuiltinType::Id: \
4589 return {MFloat8Ty, llvm::ElementCount::getScalable(NumEls), NF};
4590#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4591 case BuiltinType::Id: \
4592 return {BoolTy, llvm::ElementCount::getScalable(NumEls), NF};
4593#include "clang/Basic/AArch64ACLETypes.def"
4594
4595#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4596 IsSigned) \
4597 case BuiltinType::Id: \
4598 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4599 llvm::ElementCount::getScalable(NumEls), NF};
4600#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4601 case BuiltinType::Id: \
4602 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4603 llvm::ElementCount::getScalable(NumEls), NF};
4604#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4605 case BuiltinType::Id: \
4606 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4607#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4608 case BuiltinType::Id: \
4609 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4610#include "clang/Basic/RISCVVTypes.def"
4611 }
4612}
4613
4614/// getExternrefType - Return a WebAssembly externref type, which represents an
4615/// opaque reference to a host value.
4617 if (Target->getTriple().isWasm() && Target->hasFeature("reference-types")) {
4618#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4619 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4620 return SingletonId;
4621#include "clang/Basic/WebAssemblyReferenceTypes.def"
4622 }
4623 llvm_unreachable(
4624 "shouldn't try to generate type externref outside WebAssembly target");
4625}
4626
4627/// getScalableVectorType - Return the unique reference to a scalable vector
4628/// type of the specified element type and size. VectorType must be a built-in
4629/// type.
4631 unsigned NumFields) const {
4632 auto K = llvm::ScalableVecTyKey{EltTy, NumElts, NumFields};
4633 if (auto It = ScalableVecTyMap.find(K); It != ScalableVecTyMap.end())
4634 return It->second;
4635
4636 if (Target->hasAArch64ACLETypes()) {
4637 uint64_t EltTySize = getTypeSize(EltTy);
4638
4639#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4640 ElBits, NF, IsSigned) \
4641 if (EltTy->hasIntegerRepresentation() && !EltTy->isBooleanType() && \
4642 EltTy->hasSignedIntegerRepresentation() == IsSigned && \
4643 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4644 return ScalableVecTyMap[K] = SingletonId; \
4645 }
4646#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4647 ElBits, NF) \
4648 if (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4649 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4650 return ScalableVecTyMap[K] = SingletonId; \
4651 }
4652#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4653 ElBits, NF) \
4654 if (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4655 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4656 return ScalableVecTyMap[K] = SingletonId; \
4657 }
4658#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4659 ElBits, NF) \
4660 if (EltTy->isMFloat8Type() && EltTySize == ElBits && \
4661 NumElts == (NumEls * NF) && NumFields == 1) { \
4662 return ScalableVecTyMap[K] = SingletonId; \
4663 }
4664#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4665 if (EltTy->isBooleanType() && NumElts == (NumEls * NF) && NumFields == 1) \
4666 return ScalableVecTyMap[K] = SingletonId;
4667#include "clang/Basic/AArch64ACLETypes.def"
4668 } else if (Target->hasRISCVVTypes()) {
4669 uint64_t EltTySize = getTypeSize(EltTy);
4670#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4671 IsFP, IsBF) \
4672 if (!EltTy->isBooleanType() && \
4673 ((EltTy->hasIntegerRepresentation() && \
4674 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4675 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4676 IsFP && !IsBF) || \
4677 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4678 IsBF && !IsFP)) && \
4679 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4680 return ScalableVecTyMap[K] = SingletonId;
4681#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4682 if (EltTy->isBooleanType() && NumElts == NumEls) \
4683 return ScalableVecTyMap[K] = SingletonId;
4684#include "clang/Basic/RISCVVTypes.def"
4685 }
4686 return QualType();
4687}
4688
4689/// getVectorType - Return the unique reference to a vector type of
4690/// the specified element type and size. VectorType must be a built-in type.
4692 VectorKind VecKind) const {
4693 assert(vecType->isBuiltinType() ||
4694 (vecType->isBitIntType() &&
4695 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4696 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4697
4698 // Check if we've already instantiated a vector of this type.
4699 llvm::FoldingSetNodeID ID;
4700 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
4701
4702 void *InsertPos = nullptr;
4703 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4704 return QualType(VTP, 0);
4705
4706 // If the element type isn't canonical, this won't be a canonical type either,
4707 // so fill in the canonical type field.
4708 QualType Canonical;
4709 if (!vecType.isCanonical()) {
4710 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4711
4712 // Get the new insert position for the node we care about.
4713 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4714 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4715 }
4716 auto *New = new (*this, alignof(VectorType))
4717 VectorType(vecType, NumElts, Canonical, VecKind);
4718 VectorTypes.InsertNode(New, InsertPos);
4719 Types.push_back(New);
4720 return QualType(New, 0);
4721}
4722
4724 SourceLocation AttrLoc,
4725 VectorKind VecKind) const {
4726 llvm::FoldingSetNodeID ID;
4727 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4728 VecKind);
4729 void *InsertPos = nullptr;
4730 DependentVectorType *Canon =
4731 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4733
4734 if (Canon) {
4735 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4736 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4737 } else {
4738 QualType CanonVecTy = getCanonicalType(VecType);
4739 if (CanonVecTy == VecType) {
4740 New = new (*this, alignof(DependentVectorType))
4741 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4742
4743 DependentVectorType *CanonCheck =
4744 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4745 assert(!CanonCheck &&
4746 "Dependent-sized vector_size canonical type broken");
4747 (void)CanonCheck;
4748 DependentVectorTypes.InsertNode(New, InsertPos);
4749 } else {
4750 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4751 SourceLocation(), VecKind);
4752 New = new (*this, alignof(DependentVectorType))
4753 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4754 }
4755 }
4756
4757 Types.push_back(New);
4758 return QualType(New, 0);
4759}
4760
4761/// getExtVectorType - Return the unique reference to an extended vector type of
4762/// the specified element type and size. VectorType must be a built-in type.
4764 unsigned NumElts) const {
4765 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4766 (vecType->isBitIntType() &&
4767 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4768 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4769
4770 // Check if we've already instantiated a vector of this type.
4771 llvm::FoldingSetNodeID ID;
4772 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4774 void *InsertPos = nullptr;
4775 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4776 return QualType(VTP, 0);
4777
4778 // If the element type isn't canonical, this won't be a canonical type either,
4779 // so fill in the canonical type field.
4780 QualType Canonical;
4781 if (!vecType.isCanonical()) {
4782 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4783
4784 // Get the new insert position for the node we care about.
4785 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4786 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4787 }
4788 auto *New = new (*this, alignof(ExtVectorType))
4789 ExtVectorType(vecType, NumElts, Canonical);
4790 VectorTypes.InsertNode(New, InsertPos);
4791 Types.push_back(New);
4792 return QualType(New, 0);
4793}
4794
4797 Expr *SizeExpr,
4798 SourceLocation AttrLoc) const {
4799 llvm::FoldingSetNodeID ID;
4801 SizeExpr);
4802
4803 void *InsertPos = nullptr;
4805 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4807 if (Canon) {
4808 // We already have a canonical version of this array type; use it as
4809 // the canonical type for a newly-built type.
4810 New = new (*this, alignof(DependentSizedExtVectorType))
4811 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4812 AttrLoc);
4813 } else {
4814 QualType CanonVecTy = getCanonicalType(vecType);
4815 if (CanonVecTy == vecType) {
4816 New = new (*this, alignof(DependentSizedExtVectorType))
4817 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4818
4819 DependentSizedExtVectorType *CanonCheck
4820 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4821 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4822 (void)CanonCheck;
4823 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4824 } else {
4825 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4826 SourceLocation());
4827 New = new (*this, alignof(DependentSizedExtVectorType))
4828 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4829 }
4830 }
4831
4832 Types.push_back(New);
4833 return QualType(New, 0);
4834}
4835
4837 unsigned NumColumns) const {
4838 llvm::FoldingSetNodeID ID;
4839 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4840 Type::ConstantMatrix);
4841
4842 assert(MatrixType::isValidElementType(ElementTy, getLangOpts()) &&
4843 "need a valid element type");
4844 assert(NumRows > 0 && NumRows <= LangOpts.MaxMatrixDimension &&
4845 NumColumns > 0 && NumColumns <= LangOpts.MaxMatrixDimension &&
4846 "need valid matrix dimensions");
4847 void *InsertPos = nullptr;
4848 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4849 return QualType(MTP, 0);
4850
4851 QualType Canonical;
4852 if (!ElementTy.isCanonical()) {
4853 Canonical =
4854 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4855
4856 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4857 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4858 (void)NewIP;
4859 }
4860
4861 auto *New = new (*this, alignof(ConstantMatrixType))
4862 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4863 MatrixTypes.InsertNode(New, InsertPos);
4864 Types.push_back(New);
4865 return QualType(New, 0);
4866}
4867
4869 Expr *RowExpr,
4870 Expr *ColumnExpr,
4871 SourceLocation AttrLoc) const {
4872 QualType CanonElementTy = getCanonicalType(ElementTy);
4873 llvm::FoldingSetNodeID ID;
4874 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4875 ColumnExpr);
4876
4877 void *InsertPos = nullptr;
4879 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4880
4881 if (!Canon) {
4882 Canon = new (*this, alignof(DependentSizedMatrixType))
4883 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4884 ColumnExpr, AttrLoc);
4885#ifndef NDEBUG
4886 DependentSizedMatrixType *CanonCheck =
4887 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4888 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4889#endif
4890 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4891 Types.push_back(Canon);
4892 }
4893
4894 // Already have a canonical version of the matrix type
4895 //
4896 // If it exactly matches the requested type, use it directly.
4897 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4898 Canon->getRowExpr() == ColumnExpr)
4899 return QualType(Canon, 0);
4900
4901 // Use Canon as the canonical type for newly-built type.
4903 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4904 ColumnExpr, AttrLoc);
4905 Types.push_back(New);
4906 return QualType(New, 0);
4907}
4908
4910 Expr *AddrSpaceExpr,
4911 SourceLocation AttrLoc) const {
4912 assert(AddrSpaceExpr->isInstantiationDependent());
4913
4914 QualType canonPointeeType = getCanonicalType(PointeeType);
4915
4916 void *insertPos = nullptr;
4917 llvm::FoldingSetNodeID ID;
4918 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4919 AddrSpaceExpr);
4920
4921 DependentAddressSpaceType *canonTy =
4922 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4923
4924 if (!canonTy) {
4925 canonTy = new (*this, alignof(DependentAddressSpaceType))
4926 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
4927 AttrLoc);
4928 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4929 Types.push_back(canonTy);
4930 }
4931
4932 if (canonPointeeType == PointeeType &&
4933 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4934 return QualType(canonTy, 0);
4935
4936 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
4937 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
4938 AddrSpaceExpr, AttrLoc);
4939 Types.push_back(sugaredType);
4940 return QualType(sugaredType, 0);
4941}
4942
4943/// Determine whether \p T is canonical as the result type of a function.
4945 return T.isCanonical() &&
4946 (T.getObjCLifetime() == Qualifiers::OCL_None ||
4947 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4948}
4949
4950/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4951QualType
4953 const FunctionType::ExtInfo &Info) const {
4954 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
4955 // functionality creates a function without a prototype regardless of
4956 // language mode (so it makes them even in C++). Once the rewriter has been
4957 // fixed, this assertion can be enabled again.
4958 //assert(!LangOpts.requiresStrictPrototypes() &&
4959 // "strict prototypes are disabled");
4960
4961 // Unique functions, to guarantee there is only one function of a particular
4962 // structure.
4963 llvm::FoldingSetNodeID ID;
4964 FunctionNoProtoType::Profile(ID, ResultTy, Info);
4965
4966 void *InsertPos = nullptr;
4967 if (FunctionNoProtoType *FT =
4968 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4969 return QualType(FT, 0);
4970
4971 QualType Canonical;
4972 if (!isCanonicalResultType(ResultTy)) {
4973 Canonical =
4975
4976 // Get the new insert position for the node we care about.
4977 FunctionNoProtoType *NewIP =
4978 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4979 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4980 }
4981
4982 auto *New = new (*this, alignof(FunctionNoProtoType))
4983 FunctionNoProtoType(ResultTy, Canonical, Info);
4984 Types.push_back(New);
4985 FunctionNoProtoTypes.InsertNode(New, InsertPos);
4986 return QualType(New, 0);
4987}
4988
4991 CanQualType CanResultType = getCanonicalType(ResultType);
4992
4993 // Canonical result types do not have ARC lifetime qualifiers.
4994 if (CanResultType.getQualifiers().hasObjCLifetime()) {
4995 Qualifiers Qs = CanResultType.getQualifiers();
4996 Qs.removeObjCLifetime();
4998 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
4999 }
5000
5001 return CanResultType;
5002}
5003
5005 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
5006 if (ESI.Type == EST_None)
5007 return true;
5008 if (!NoexceptInType)
5009 return false;
5010
5011 // C++17 onwards: exception specification is part of the type, as a simple
5012 // boolean "can this function type throw".
5013 if (ESI.Type == EST_BasicNoexcept)
5014 return true;
5015
5016 // A noexcept(expr) specification is (possibly) canonical if expr is
5017 // value-dependent.
5018 if (ESI.Type == EST_DependentNoexcept)
5019 return true;
5020
5021 // A dynamic exception specification is canonical if it only contains pack
5022 // expansions (so we can't tell whether it's non-throwing) and all its
5023 // contained types are canonical.
5024 if (ESI.Type == EST_Dynamic) {
5025 bool AnyPackExpansions = false;
5026 for (QualType ET : ESI.Exceptions) {
5027 if (!ET.isCanonical())
5028 return false;
5029 if (ET->getAs<PackExpansionType>())
5030 AnyPackExpansions = true;
5031 }
5032 return AnyPackExpansions;
5033 }
5034
5035 return false;
5036}
5037
5038QualType ASTContext::getFunctionTypeInternal(
5039 QualType ResultTy, ArrayRef<QualType> ArgArray,
5040 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
5041 size_t NumArgs = ArgArray.size();
5042
5043 // Unique functions, to guarantee there is only one function of a particular
5044 // structure.
5045 llvm::FoldingSetNodeID ID;
5046 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
5047 *this, true);
5048
5049 QualType Canonical;
5050 bool Unique = false;
5051
5052 void *InsertPos = nullptr;
5053 if (FunctionProtoType *FPT =
5054 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
5055 QualType Existing = QualType(FPT, 0);
5056
5057 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
5058 // it so long as our exception specification doesn't contain a dependent
5059 // noexcept expression, or we're just looking for a canonical type.
5060 // Otherwise, we're going to need to create a type
5061 // sugar node to hold the concrete expression.
5062 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
5063 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
5064 return Existing;
5065
5066 // We need a new type sugar node for this one, to hold the new noexcept
5067 // expression. We do no canonicalization here, but that's OK since we don't
5068 // expect to see the same noexcept expression much more than once.
5069 Canonical = getCanonicalType(Existing);
5070 Unique = true;
5071 }
5072
5073 bool NoexceptInType = getLangOpts().CPlusPlus17;
5074 bool IsCanonicalExceptionSpec =
5076
5077 // Determine whether the type being created is already canonical or not.
5078 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
5079 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
5080 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
5081 if (!ArgArray[i].isCanonicalAsParam())
5082 isCanonical = false;
5083
5084 if (OnlyWantCanonical)
5085 assert(isCanonical &&
5086 "given non-canonical parameters constructing canonical type");
5087
5088 // If this type isn't canonical, get the canonical version of it if we don't
5089 // already have it. The exception spec is only partially part of the
5090 // canonical type, and only in C++17 onwards.
5091 if (!isCanonical && Canonical.isNull()) {
5092 SmallVector<QualType, 16> CanonicalArgs;
5093 CanonicalArgs.reserve(NumArgs);
5094 for (unsigned i = 0; i != NumArgs; ++i)
5095 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
5096
5097 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
5098 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
5099 CanonicalEPI.HasTrailingReturn = false;
5100
5101 if (IsCanonicalExceptionSpec) {
5102 // Exception spec is already OK.
5103 } else if (NoexceptInType) {
5104 switch (EPI.ExceptionSpec.Type) {
5106 // We don't know yet. It shouldn't matter what we pick here; no-one
5107 // should ever look at this.
5108 [[fallthrough]];
5109 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
5110 CanonicalEPI.ExceptionSpec.Type = EST_None;
5111 break;
5112
5113 // A dynamic exception specification is almost always "not noexcept",
5114 // with the exception that a pack expansion might expand to no types.
5115 case EST_Dynamic: {
5116 bool AnyPacks = false;
5117 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
5118 if (ET->getAs<PackExpansionType>())
5119 AnyPacks = true;
5120 ExceptionTypeStorage.push_back(getCanonicalType(ET));
5121 }
5122 if (!AnyPacks)
5123 CanonicalEPI.ExceptionSpec.Type = EST_None;
5124 else {
5125 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
5126 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
5127 }
5128 break;
5129 }
5130
5131 case EST_DynamicNone:
5132 case EST_BasicNoexcept:
5133 case EST_NoexceptTrue:
5134 case EST_NoThrow:
5135 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
5136 break;
5137
5139 llvm_unreachable("dependent noexcept is already canonical");
5140 }
5141 } else {
5142 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
5143 }
5144
5145 // Adjust the canonical function result type.
5146 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
5147 Canonical =
5148 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
5149
5150 // Get the new insert position for the node we care about.
5151 FunctionProtoType *NewIP =
5152 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
5153 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5154 }
5155
5156 // Compute the needed size to hold this FunctionProtoType and the
5157 // various trailing objects.
5158 auto ESH = FunctionProtoType::getExceptionSpecSize(
5159 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
5160 size_t Size = FunctionProtoType::totalSizeToAlloc<
5161 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
5162 FunctionType::FunctionTypeExtraAttributeInfo,
5163 FunctionType::FunctionTypeArmAttributes, FunctionType::ExceptionType,
5164 Expr *, FunctionDecl *, FunctionProtoType::ExtParameterInfo, Qualifiers,
5165 FunctionEffect, EffectConditionExpr>(
5168 EPI.requiresFunctionProtoTypeArmAttributes(), ESH.NumExceptionType,
5169 ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
5170 EPI.ExtParameterInfos ? NumArgs : 0,
5172 EPI.FunctionEffects.conditions().size());
5173
5174 auto *FTP = (FunctionProtoType *)Allocate(Size, alignof(FunctionProtoType));
5175 FunctionProtoType::ExtProtoInfo newEPI = EPI;
5176 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
5177 Types.push_back(FTP);
5178 if (!Unique)
5179 FunctionProtoTypes.InsertNode(FTP, InsertPos);
5180 if (!EPI.FunctionEffects.empty())
5181 AnyFunctionEffects = true;
5182 return QualType(FTP, 0);
5183}
5184
5185QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
5186 llvm::FoldingSetNodeID ID;
5187 PipeType::Profile(ID, T, ReadOnly);
5188
5189 void *InsertPos = nullptr;
5190 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
5191 return QualType(PT, 0);
5192
5193 // If the pipe element type isn't canonical, this won't be a canonical type
5194 // either, so fill in the canonical type field.
5195 QualType Canonical;
5196 if (!T.isCanonical()) {
5197 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
5198
5199 // Get the new insert position for the node we care about.
5200 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
5201 assert(!NewIP && "Shouldn't be in the map!");
5202 (void)NewIP;
5203 }
5204 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
5205 Types.push_back(New);
5206 PipeTypes.InsertNode(New, InsertPos);
5207 return QualType(New, 0);
5208}
5209
5211 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
5212 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
5213 : Ty;
5214}
5215
5217 return getPipeType(T, true);
5218}
5219
5221 return getPipeType(T, false);
5222}
5223
5224QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
5225 llvm::FoldingSetNodeID ID;
5226 BitIntType::Profile(ID, IsUnsigned, NumBits);
5227
5228 void *InsertPos = nullptr;
5229 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5230 return QualType(EIT, 0);
5231
5232 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
5233 BitIntTypes.InsertNode(New, InsertPos);
5234 Types.push_back(New);
5235 return QualType(New, 0);
5236}
5237
5239 Expr *NumBitsExpr) const {
5240 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
5241 llvm::FoldingSetNodeID ID;
5242 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
5243
5244 void *InsertPos = nullptr;
5245 if (DependentBitIntType *Existing =
5246 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5247 return QualType(Existing, 0);
5248
5249 auto *New = new (*this, alignof(DependentBitIntType))
5250 DependentBitIntType(IsUnsigned, NumBitsExpr);
5251 DependentBitIntTypes.InsertNode(New, InsertPos);
5252
5253 Types.push_back(New);
5254 return QualType(New, 0);
5255}
5256
5259 using Kind = PredefinedSugarType::Kind;
5260
5261 if (auto *Target = PredefinedSugarTypes[llvm::to_underlying(KD)];
5262 Target != nullptr)
5263 return QualType(Target, 0);
5264
5265 auto getCanonicalType = [](const ASTContext &Ctx, Kind KDI) -> QualType {
5266 switch (KDI) {
5267 // size_t (C99TC3 6.5.3.4), signed size_t (C++23 5.13.2) and
5268 // ptrdiff_t (C99TC3 6.5.6) Although these types are not built-in, they
5269 // are part of the core language and are widely used. Using
5270 // PredefinedSugarType makes these types as named sugar types rather than
5271 // standard integer types, enabling better hints and diagnostics.
5272 case Kind::SizeT:
5273 return Ctx.getFromTargetType(Ctx.Target->getSizeType());
5274 case Kind::SignedSizeT:
5275 return Ctx.getFromTargetType(Ctx.Target->getSignedSizeType());
5276 case Kind::PtrdiffT:
5277 return Ctx.getFromTargetType(Ctx.Target->getPtrDiffType(LangAS::Default));
5278 }
5279 llvm_unreachable("unexpected kind");
5280 };
5281 auto *New = new (*this, alignof(PredefinedSugarType))
5282 PredefinedSugarType(KD, &Idents.get(PredefinedSugarType::getName(KD)),
5283 getCanonicalType(*this, static_cast<Kind>(KD)));
5284 Types.push_back(New);
5285 PredefinedSugarTypes[llvm::to_underlying(KD)] = New;
5286 return QualType(New, 0);
5287}
5288
5290 NestedNameSpecifier Qualifier,
5291 const TypeDecl *Decl) const {
5292 if (auto *Tag = dyn_cast<TagDecl>(Decl))
5293 return getTagType(Keyword, Qualifier, Tag,
5294 /*OwnsTag=*/false);
5295 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
5296 return getTypedefType(Keyword, Qualifier, Typedef);
5297 if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5298 return getUnresolvedUsingType(Keyword, Qualifier, UD);
5299
5301 assert(!Qualifier);
5302 return QualType(Decl->TypeForDecl, 0);
5303}
5304
5306 if (auto *Tag = dyn_cast<TagDecl>(TD))
5307 return getCanonicalTagType(Tag);
5308 if (auto *TN = dyn_cast<TypedefNameDecl>(TD))
5309 return getCanonicalType(TN->getUnderlyingType());
5310 if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD))
5312 assert(TD->TypeForDecl);
5313 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5314}
5315
5317 if (const auto *TD = dyn_cast<TagDecl>(Decl))
5318 return getCanonicalTagType(TD);
5319 if (const auto *TD = dyn_cast<TypedefNameDecl>(Decl);
5320 isa_and_nonnull<TypedefDecl, TypeAliasDecl>(TD))
5322 /*Qualifier=*/std::nullopt, TD);
5323 if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5324 return getCanonicalUnresolvedUsingType(Using);
5325
5326 assert(Decl->TypeForDecl);
5327 return QualType(Decl->TypeForDecl, 0);
5328}
5329
5330/// getTypedefType - Return the unique reference to the type for the
5331/// specified typedef name decl.
5334 NestedNameSpecifier Qualifier,
5335 const TypedefNameDecl *Decl, QualType UnderlyingType,
5336 std::optional<bool> TypeMatchesDeclOrNone) const {
5337 if (!TypeMatchesDeclOrNone) {
5338 QualType DeclUnderlyingType = Decl->getUnderlyingType();
5339 assert(!DeclUnderlyingType.isNull());
5340 if (UnderlyingType.isNull())
5341 UnderlyingType = DeclUnderlyingType;
5342 else
5343 assert(hasSameType(UnderlyingType, DeclUnderlyingType));
5344 TypeMatchesDeclOrNone = UnderlyingType == DeclUnderlyingType;
5345 } else {
5346 // FIXME: This is a workaround for a serialization cycle: assume the decl
5347 // underlying type is not available; don't touch it.
5348 assert(!UnderlyingType.isNull());
5349 }
5350
5351 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier &&
5352 *TypeMatchesDeclOrNone) {
5353 if (Decl->TypeForDecl)
5354 return QualType(Decl->TypeForDecl, 0);
5355
5356 auto *NewType = new (*this, alignof(TypedefType))
5357 TypedefType(Type::Typedef, Keyword, Qualifier, Decl, UnderlyingType,
5358 !*TypeMatchesDeclOrNone);
5359
5360 Types.push_back(NewType);
5361 Decl->TypeForDecl = NewType;
5362 return QualType(NewType, 0);
5363 }
5364
5365 llvm::FoldingSetNodeID ID;
5366 TypedefType::Profile(ID, Keyword, Qualifier, Decl,
5367 *TypeMatchesDeclOrNone ? QualType() : UnderlyingType);
5368
5369 void *InsertPos = nullptr;
5370 if (FoldingSetPlaceholder<TypedefType> *Placeholder =
5371 TypedefTypes.FindNodeOrInsertPos(ID, InsertPos))
5372 return QualType(Placeholder->getType(), 0);
5373
5374 void *Mem =
5375 Allocate(TypedefType::totalSizeToAlloc<FoldingSetPlaceholder<TypedefType>,
5377 1, !!Qualifier, !*TypeMatchesDeclOrNone),
5378 alignof(TypedefType));
5379 auto *NewType =
5380 new (Mem) TypedefType(Type::Typedef, Keyword, Qualifier, Decl,
5381 UnderlyingType, !*TypeMatchesDeclOrNone);
5382 auto *Placeholder = new (NewType->getFoldingSetPlaceholder())
5384 TypedefTypes.InsertNode(Placeholder, InsertPos);
5385 Types.push_back(NewType);
5386 return QualType(NewType, 0);
5387}
5388
5390 NestedNameSpecifier Qualifier,
5391 const UsingShadowDecl *D,
5392 QualType UnderlyingType) const {
5393 // FIXME: This is expensive to compute every time!
5394 if (UnderlyingType.isNull()) {
5395 const auto *UD = cast<UsingDecl>(D->getIntroducer());
5396 UnderlyingType =
5399 UD->getQualifier(), cast<TypeDecl>(D->getTargetDecl()));
5400 }
5401
5402 llvm::FoldingSetNodeID ID;
5403 UsingType::Profile(ID, Keyword, Qualifier, D, UnderlyingType);
5404
5405 void *InsertPos = nullptr;
5406 if (const UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5407 return QualType(T, 0);
5408
5409 assert(!UnderlyingType.hasLocalQualifiers());
5410
5411 assert(
5413 UnderlyingType));
5414
5415 void *Mem =
5416 Allocate(UsingType::totalSizeToAlloc<NestedNameSpecifier>(!!Qualifier),
5417 alignof(UsingType));
5418 UsingType *T = new (Mem) UsingType(Keyword, Qualifier, D, UnderlyingType);
5419 Types.push_back(T);
5420 UsingTypes.InsertNode(T, InsertPos);
5421 return QualType(T, 0);
5422}
5423
5424TagType *ASTContext::getTagTypeInternal(ElaboratedTypeKeyword Keyword,
5425 NestedNameSpecifier Qualifier,
5426 const TagDecl *TD, bool OwnsTag,
5427 bool IsInjected,
5428 const Type *CanonicalType,
5429 bool WithFoldingSetNode) const {
5430 auto [TC, Size] = [&] {
5431 switch (TD->getDeclKind()) {
5432 case Decl::Enum:
5433 static_assert(alignof(EnumType) == alignof(TagType));
5434 return std::make_tuple(Type::Enum, sizeof(EnumType));
5435 case Decl::ClassTemplatePartialSpecialization:
5436 case Decl::ClassTemplateSpecialization:
5437 case Decl::CXXRecord:
5438 static_assert(alignof(RecordType) == alignof(TagType));
5439 static_assert(alignof(InjectedClassNameType) == alignof(TagType));
5440 if (cast<CXXRecordDecl>(TD)->hasInjectedClassType())
5441 return std::make_tuple(Type::InjectedClassName,
5442 sizeof(InjectedClassNameType));
5443 [[fallthrough]];
5444 case Decl::Record:
5445 return std::make_tuple(Type::Record, sizeof(RecordType));
5446 default:
5447 llvm_unreachable("unexpected decl kind");
5448 }
5449 }();
5450
5451 if (Qualifier) {
5452 static_assert(alignof(NestedNameSpecifier) <= alignof(TagType));
5453 Size = llvm::alignTo(Size, alignof(NestedNameSpecifier)) +
5454 sizeof(NestedNameSpecifier);
5455 }
5456 void *Mem;
5457 if (WithFoldingSetNode) {
5458 // FIXME: It would be more profitable to tail allocate the folding set node
5459 // from the type, instead of the other way around, due to the greater
5460 // alignment requirements of the type. But this makes it harder to deal with
5461 // the different type node sizes. This would require either uniquing from
5462 // different folding sets, or having the folding setaccept a
5463 // contextual parameter which is not fixed at construction.
5464 Mem = Allocate(
5465 sizeof(TagTypeFoldingSetPlaceholder) +
5466 TagTypeFoldingSetPlaceholder::getOffset() + Size,
5467 std::max(alignof(TagTypeFoldingSetPlaceholder), alignof(TagType)));
5468 auto *T = new (Mem) TagTypeFoldingSetPlaceholder();
5469 Mem = T->getTagType();
5470 } else {
5471 Mem = Allocate(Size, alignof(TagType));
5472 }
5473
5474 auto *T = [&, TC = TC]() -> TagType * {
5475 switch (TC) {
5476 case Type::Enum: {
5477 assert(isa<EnumDecl>(TD));
5478 auto *T = new (Mem) EnumType(TC, Keyword, Qualifier, TD, OwnsTag,
5479 IsInjected, CanonicalType);
5480 assert(reinterpret_cast<void *>(T) ==
5481 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5482 "TagType must be the first base of EnumType");
5483 return T;
5484 }
5485 case Type::Record: {
5486 assert(isa<RecordDecl>(TD));
5487 auto *T = new (Mem) RecordType(TC, Keyword, Qualifier, TD, OwnsTag,
5488 IsInjected, CanonicalType);
5489 assert(reinterpret_cast<void *>(T) ==
5490 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5491 "TagType must be the first base of RecordType");
5492 return T;
5493 }
5494 case Type::InjectedClassName: {
5495 auto *T = new (Mem) InjectedClassNameType(Keyword, Qualifier, TD,
5496 IsInjected, CanonicalType);
5497 assert(reinterpret_cast<void *>(T) ==
5498 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5499 "TagType must be the first base of InjectedClassNameType");
5500 return T;
5501 }
5502 default:
5503 llvm_unreachable("unexpected type class");
5504 }
5505 }();
5506 assert(T->getKeyword() == Keyword);
5507 assert(T->getQualifier() == Qualifier);
5508 assert(T->getDecl() == TD);
5509 assert(T->isInjected() == IsInjected);
5510 assert(T->isTagOwned() == OwnsTag);
5511 assert((T->isCanonicalUnqualified()
5512 ? QualType()
5513 : T->getCanonicalTypeInternal()) == QualType(CanonicalType, 0));
5514 Types.push_back(T);
5515 return T;
5516}
5517
5518static const TagDecl *getNonInjectedClassName(const TagDecl *TD) {
5519 if (const auto *RD = dyn_cast<CXXRecordDecl>(TD);
5520 RD && RD->isInjectedClassName())
5521 return cast<TagDecl>(RD->getDeclContext());
5522 return TD;
5523}
5524
5527 if (TD->TypeForDecl)
5528 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5529
5530 const Type *CanonicalType = getTagTypeInternal(
5532 /*Qualifier=*/std::nullopt, TD,
5533 /*OwnsTag=*/false, /*IsInjected=*/false, /*CanonicalType=*/nullptr,
5534 /*WithFoldingSetNode=*/false);
5535 TD->TypeForDecl = CanonicalType;
5536 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5537}
5538
5540 NestedNameSpecifier Qualifier,
5541 const TagDecl *TD, bool OwnsTag) const {
5542
5543 const TagDecl *NonInjectedTD = ::getNonInjectedClassName(TD);
5544 bool IsInjected = TD != NonInjectedTD;
5545
5546 ElaboratedTypeKeyword PreferredKeyword =
5549 NonInjectedTD->getTagKind());
5550
5551 if (Keyword == PreferredKeyword && !Qualifier && !OwnsTag) {
5552 if (const Type *T = TD->TypeForDecl; T && !T->isCanonicalUnqualified())
5553 return QualType(T, 0);
5554
5555 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5556 const Type *T =
5557 getTagTypeInternal(Keyword,
5558 /*Qualifier=*/std::nullopt, NonInjectedTD,
5559 /*OwnsTag=*/false, IsInjected, CanonicalType,
5560 /*WithFoldingSetNode=*/false);
5561 TD->TypeForDecl = T;
5562 return QualType(T, 0);
5563 }
5564
5565 llvm::FoldingSetNodeID ID;
5566 TagTypeFoldingSetPlaceholder::Profile(ID, Keyword, Qualifier, NonInjectedTD,
5567 OwnsTag, IsInjected);
5568
5569 void *InsertPos = nullptr;
5570 if (TagTypeFoldingSetPlaceholder *T =
5571 TagTypes.FindNodeOrInsertPos(ID, InsertPos))
5572 return QualType(T->getTagType(), 0);
5573
5574 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5575 TagType *T =
5576 getTagTypeInternal(Keyword, Qualifier, NonInjectedTD, OwnsTag, IsInjected,
5577 CanonicalType, /*WithFoldingSetNode=*/true);
5578 TagTypes.InsertNode(TagTypeFoldingSetPlaceholder::fromTagType(T), InsertPos);
5579 return QualType(T, 0);
5580}
5581
5582bool ASTContext::computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits,
5583 unsigned NumPositiveBits,
5584 QualType &BestType,
5585 QualType &BestPromotionType) {
5586 unsigned IntWidth = Target->getIntWidth();
5587 unsigned CharWidth = Target->getCharWidth();
5588 unsigned ShortWidth = Target->getShortWidth();
5589 bool EnumTooLarge = false;
5590 unsigned BestWidth;
5591 if (NumNegativeBits) {
5592 // If there is a negative value, figure out the smallest integer type (of
5593 // int/long/longlong) that fits.
5594 // If it's packed, check also if it fits a char or a short.
5595 if (IsPacked && NumNegativeBits <= CharWidth &&
5596 NumPositiveBits < CharWidth) {
5597 BestType = SignedCharTy;
5598 BestWidth = CharWidth;
5599 } else if (IsPacked && NumNegativeBits <= ShortWidth &&
5600 NumPositiveBits < ShortWidth) {
5601 BestType = ShortTy;
5602 BestWidth = ShortWidth;
5603 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5604 BestType = IntTy;
5605 BestWidth = IntWidth;
5606 } else {
5607 BestWidth = Target->getLongWidth();
5608
5609 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
5610 BestType = LongTy;
5611 } else {
5612 BestWidth = Target->getLongLongWidth();
5613
5614 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5615 EnumTooLarge = true;
5616 BestType = LongLongTy;
5617 }
5618 }
5619 BestPromotionType = (BestWidth <= IntWidth ? IntTy : BestType);
5620 } else {
5621 // If there is no negative value, figure out the smallest type that fits
5622 // all of the enumerator values.
5623 // If it's packed, check also if it fits a char or a short.
5624 if (IsPacked && NumPositiveBits <= CharWidth) {
5625 BestType = UnsignedCharTy;
5626 BestPromotionType = IntTy;
5627 BestWidth = CharWidth;
5628 } else if (IsPacked && NumPositiveBits <= ShortWidth) {
5629 BestType = UnsignedShortTy;
5630 BestPromotionType = IntTy;
5631 BestWidth = ShortWidth;
5632 } else if (NumPositiveBits <= IntWidth) {
5633 BestType = UnsignedIntTy;
5634 BestWidth = IntWidth;
5635 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5637 : IntTy;
5638 } else if (NumPositiveBits <= (BestWidth = Target->getLongWidth())) {
5639 BestType = UnsignedLongTy;
5640 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5642 : LongTy;
5643 } else {
5644 BestWidth = Target->getLongLongWidth();
5645 if (NumPositiveBits > BestWidth) {
5646 // This can happen with bit-precise integer types, but those are not
5647 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
5648 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
5649 // a 128-bit integer, we should consider doing the same.
5650 EnumTooLarge = true;
5651 }
5652 BestType = UnsignedLongLongTy;
5653 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5655 : LongLongTy;
5656 }
5657 }
5658 return EnumTooLarge;
5659}
5660
5662 assert((T->isIntegralType(*this) || T->isEnumeralType()) &&
5663 "Integral type required!");
5664 unsigned BitWidth = getIntWidth(T);
5665
5666 if (Value.isUnsigned() || Value.isNonNegative()) {
5667 if (T->isSignedIntegerOrEnumerationType())
5668 --BitWidth;
5669 return Value.getActiveBits() <= BitWidth;
5670 }
5671 return Value.getSignificantBits() <= BitWidth;
5672}
5673
5674UnresolvedUsingType *ASTContext::getUnresolvedUsingTypeInternal(
5676 const UnresolvedUsingTypenameDecl *D, void *InsertPos,
5677 const Type *CanonicalType) const {
5678 void *Mem = Allocate(
5679 UnresolvedUsingType::totalSizeToAlloc<
5681 !!InsertPos, !!Qualifier),
5682 alignof(UnresolvedUsingType));
5683 auto *T = new (Mem) UnresolvedUsingType(Keyword, Qualifier, D, CanonicalType);
5684 if (InsertPos) {
5685 auto *Placeholder = new (T->getFoldingSetPlaceholder())
5687 TypedefTypes.InsertNode(Placeholder, InsertPos);
5688 }
5689 Types.push_back(T);
5690 return T;
5691}
5692
5694 const UnresolvedUsingTypenameDecl *D) const {
5695 D = D->getCanonicalDecl();
5696 if (D->TypeForDecl)
5697 return D->TypeForDecl->getCanonicalTypeUnqualified();
5698
5699 const Type *CanonicalType = getUnresolvedUsingTypeInternal(
5701 /*Qualifier=*/std::nullopt, D,
5702 /*InsertPos=*/nullptr, /*CanonicalType=*/nullptr);
5703 D->TypeForDecl = CanonicalType;
5704 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5705}
5706
5709 NestedNameSpecifier Qualifier,
5710 const UnresolvedUsingTypenameDecl *D) const {
5711 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier) {
5712 if (const Type *T = D->TypeForDecl; T && !T->isCanonicalUnqualified())
5713 return QualType(T, 0);
5714
5715 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5716 const Type *T =
5717 getUnresolvedUsingTypeInternal(ElaboratedTypeKeyword::None,
5718 /*Qualifier=*/std::nullopt, D,
5719 /*InsertPos=*/nullptr, CanonicalType);
5720 D->TypeForDecl = T;
5721 return QualType(T, 0);
5722 }
5723
5724 llvm::FoldingSetNodeID ID;
5725 UnresolvedUsingType::Profile(ID, Keyword, Qualifier, D);
5726
5727 void *InsertPos = nullptr;
5729 UnresolvedUsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5730 return QualType(Placeholder->getType(), 0);
5731 assert(InsertPos);
5732
5733 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5734 const Type *T = getUnresolvedUsingTypeInternal(Keyword, Qualifier, D,
5735 InsertPos, CanonicalType);
5736 return QualType(T, 0);
5737}
5738
5740 QualType modifiedType,
5741 QualType equivalentType,
5742 const Attr *attr) const {
5743 llvm::FoldingSetNodeID id;
5744 AttributedType::Profile(id, attrKind, modifiedType, equivalentType, attr);
5745
5746 void *insertPos = nullptr;
5747 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
5748 if (type) return QualType(type, 0);
5749
5750 assert(!attr || attr->getKind() == attrKind);
5751
5752 QualType canon = getCanonicalType(equivalentType);
5753 type = new (*this, alignof(AttributedType))
5754 AttributedType(canon, attrKind, attr, modifiedType, equivalentType);
5755
5756 Types.push_back(type);
5757 AttributedTypes.InsertNode(type, insertPos);
5758
5759 return QualType(type, 0);
5760}
5761
5763 QualType equivalentType) const {
5764 return getAttributedType(attr->getKind(), modifiedType, equivalentType, attr);
5765}
5766
5768 QualType modifiedType,
5769 QualType equivalentType) {
5770 switch (nullability) {
5772 return getAttributedType(attr::TypeNonNull, modifiedType, equivalentType);
5773
5775 return getAttributedType(attr::TypeNullable, modifiedType, equivalentType);
5776
5778 return getAttributedType(attr::TypeNullableResult, modifiedType,
5779 equivalentType);
5780
5782 return getAttributedType(attr::TypeNullUnspecified, modifiedType,
5783 equivalentType);
5784 }
5785
5786 llvm_unreachable("Unknown nullability kind");
5787}
5788
5789QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
5790 QualType Wrapped) const {
5791 llvm::FoldingSetNodeID ID;
5792 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
5793
5794 void *InsertPos = nullptr;
5795 BTFTagAttributedType *Ty =
5796 BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
5797 if (Ty)
5798 return QualType(Ty, 0);
5799
5800 QualType Canon = getCanonicalType(Wrapped);
5801 Ty = new (*this, alignof(BTFTagAttributedType))
5802 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
5803
5804 Types.push_back(Ty);
5805 BTFTagAttributedTypes.InsertNode(Ty, InsertPos);
5806
5807 return QualType(Ty, 0);
5808}
5809
5811 QualType Underlying) const {
5812 const IdentifierInfo *II = Attr->getBehaviorKind();
5813 StringRef IdentName = II->getName();
5814 OverflowBehaviorType::OverflowBehaviorKind Kind;
5815 if (IdentName == "wrap") {
5816 Kind = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
5817 } else if (IdentName == "trap") {
5818 Kind = OverflowBehaviorType::OverflowBehaviorKind::Trap;
5819 } else {
5820 return Underlying;
5821 }
5822
5823 return getOverflowBehaviorType(Kind, Underlying);
5824}
5825
5827 OverflowBehaviorType::OverflowBehaviorKind Kind,
5828 QualType Underlying) const {
5829 assert(!Underlying->isOverflowBehaviorType() &&
5830 "Cannot have underlying types that are themselves OBTs");
5831 llvm::FoldingSetNodeID ID;
5832 OverflowBehaviorType::Profile(ID, Underlying, Kind);
5833 void *InsertPos = nullptr;
5834
5835 if (OverflowBehaviorType *OBT =
5836 OverflowBehaviorTypes.FindNodeOrInsertPos(ID, InsertPos)) {
5837 return QualType(OBT, 0);
5838 }
5839
5840 QualType Canonical;
5841 if (!Underlying.isCanonical() || Underlying.hasLocalQualifiers()) {
5842 SplitQualType canonSplit = getCanonicalType(Underlying).split();
5843 Canonical = getOverflowBehaviorType(Kind, QualType(canonSplit.Ty, 0));
5844 Canonical = getQualifiedType(Canonical, canonSplit.Quals);
5845 assert(!OverflowBehaviorTypes.FindNodeOrInsertPos(ID, InsertPos) &&
5846 "Shouldn't be in the map");
5847 }
5848
5849 OverflowBehaviorType *Ty = new (*this, alignof(OverflowBehaviorType))
5850 OverflowBehaviorType(Canonical, Underlying, Kind);
5851
5852 Types.push_back(Ty);
5853 OverflowBehaviorTypes.InsertNode(Ty, InsertPos);
5854 return QualType(Ty, 0);
5855}
5856
5858 QualType Wrapped, QualType Contained,
5859 const HLSLAttributedResourceType::Attributes &Attrs) {
5860
5861 llvm::FoldingSetNodeID ID;
5862 HLSLAttributedResourceType::Profile(ID, Wrapped, Contained, Attrs);
5863
5864 void *InsertPos = nullptr;
5865 HLSLAttributedResourceType *Ty =
5866 HLSLAttributedResourceTypes.FindNodeOrInsertPos(ID, InsertPos);
5867 if (Ty)
5868 return QualType(Ty, 0);
5869
5870 Ty = new (*this, alignof(HLSLAttributedResourceType))
5871 HLSLAttributedResourceType(Wrapped, Contained, Attrs);
5872
5873 Types.push_back(Ty);
5874 HLSLAttributedResourceTypes.InsertNode(Ty, InsertPos);
5875
5876 return QualType(Ty, 0);
5877}
5878
5879QualType ASTContext::getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size,
5880 uint32_t Alignment,
5881 ArrayRef<SpirvOperand> Operands) {
5882 llvm::FoldingSetNodeID ID;
5883 HLSLInlineSpirvType::Profile(ID, Opcode, Size, Alignment, Operands);
5884
5885 void *InsertPos = nullptr;
5886 HLSLInlineSpirvType *Ty =
5887 HLSLInlineSpirvTypes.FindNodeOrInsertPos(ID, InsertPos);
5888 if (Ty)
5889 return QualType(Ty, 0);
5890
5891 void *Mem = Allocate(
5892 HLSLInlineSpirvType::totalSizeToAlloc<SpirvOperand>(Operands.size()),
5893 alignof(HLSLInlineSpirvType));
5894
5895 Ty = new (Mem) HLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
5896
5897 Types.push_back(Ty);
5898 HLSLInlineSpirvTypes.InsertNode(Ty, InsertPos);
5899
5900 return QualType(Ty, 0);
5901}
5902
5903/// Retrieve a substitution-result type.
5905 Decl *AssociatedDecl,
5906 unsigned Index,
5907 UnsignedOrNone PackIndex,
5908 bool Final) const {
5909 llvm::FoldingSetNodeID ID;
5910 SubstTemplateTypeParmType::Profile(ID, Replacement, AssociatedDecl, Index,
5911 PackIndex, Final);
5912 void *InsertPos = nullptr;
5913 SubstTemplateTypeParmType *SubstParm =
5914 SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5915
5916 if (!SubstParm) {
5917 void *Mem = Allocate(SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
5918 !Replacement.isCanonical()),
5919 alignof(SubstTemplateTypeParmType));
5920 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
5921 Index, PackIndex, Final);
5922 Types.push_back(SubstParm);
5923 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
5924 }
5925
5926 return QualType(SubstParm, 0);
5927}
5928
5931 unsigned Index, bool Final,
5932 const TemplateArgument &ArgPack) {
5933#ifndef NDEBUG
5934 for (const auto &P : ArgPack.pack_elements())
5935 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
5936#endif
5937
5938 llvm::FoldingSetNodeID ID;
5939 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
5940 ArgPack);
5941 void *InsertPos = nullptr;
5942 if (SubstTemplateTypeParmPackType *SubstParm =
5943 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
5944 return QualType(SubstParm, 0);
5945
5946 QualType Canon;
5947 {
5948 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5949 if (!AssociatedDecl->isCanonicalDecl() ||
5950 !CanonArgPack.structurallyEquals(ArgPack)) {
5952 AssociatedDecl->getCanonicalDecl(), Index, Final, CanonArgPack);
5953 [[maybe_unused]] const auto *Nothing =
5954 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
5955 assert(!Nothing);
5956 }
5957 }
5958
5959 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
5960 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
5961 ArgPack);
5962 Types.push_back(SubstParm);
5963 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
5964 return QualType(SubstParm, 0);
5965}
5966
5969 assert(llvm::all_of(ArgPack.pack_elements(),
5970 [](const auto &P) {
5971 return P.getKind() == TemplateArgument::Type;
5972 }) &&
5973 "Pack contains a non-type");
5974
5975 llvm::FoldingSetNodeID ID;
5976 SubstBuiltinTemplatePackType::Profile(ID, ArgPack);
5977
5978 void *InsertPos = nullptr;
5979 if (auto *T =
5980 SubstBuiltinTemplatePackTypes.FindNodeOrInsertPos(ID, InsertPos))
5981 return QualType(T, 0);
5982
5983 QualType Canon;
5984 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5985 if (!CanonArgPack.structurallyEquals(ArgPack)) {
5986 Canon = getSubstBuiltinTemplatePack(CanonArgPack);
5987 // Refresh InsertPos, in case the recursive call above caused rehashing,
5988 // which would invalidate the bucket pointer.
5989 [[maybe_unused]] const auto *Nothing =
5990 SubstBuiltinTemplatePackTypes.FindNodeOrInsertPos(ID, InsertPos);
5991 assert(!Nothing);
5992 }
5993
5994 auto *PackType = new (*this, alignof(SubstBuiltinTemplatePackType))
5995 SubstBuiltinTemplatePackType(Canon, ArgPack);
5996 Types.push_back(PackType);
5997 SubstBuiltinTemplatePackTypes.InsertNode(PackType, InsertPos);
5998 return QualType(PackType, 0);
5999}
6000
6001/// Retrieve the template type parameter type for a template
6002/// parameter or parameter pack with the given depth, index, and (optionally)
6003/// name.
6005ASTContext::getTemplateTypeParmType(int Depth, int Index, bool ParameterPack,
6006 TemplateTypeParmDecl *TTPDecl) const {
6007 assert(Depth >= 0 && "Depth must be non-negative");
6008 assert(Index >= 0 && "Index must be non-negative");
6009
6010 llvm::FoldingSetNodeID ID;
6011 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
6012 void *InsertPos = nullptr;
6013 TemplateTypeParmType *TypeParm
6014 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
6015
6016 if (TypeParm)
6017 return QualType(TypeParm, 0);
6018
6019 if (TTPDecl) {
6020 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
6021 TypeParm = new (*this, alignof(TemplateTypeParmType))
6022 TemplateTypeParmType(Depth, Index, ParameterPack, TTPDecl, Canon);
6023
6024 TemplateTypeParmType *TypeCheck
6025 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
6026 assert(!TypeCheck && "Template type parameter canonical type broken");
6027 (void)TypeCheck;
6028 } else
6029 TypeParm = new (*this, alignof(TemplateTypeParmType)) TemplateTypeParmType(
6030 Depth, Index, ParameterPack, /*TTPDecl=*/nullptr, /*Canon=*/QualType());
6031
6032 Types.push_back(TypeParm);
6033 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
6034
6035 return QualType(TypeParm, 0);
6036}
6037
6040 switch (Keyword) {
6041 // These are just themselves.
6047 return Keyword;
6048
6049 // These are equivalent.
6052
6053 // These are functionally equivalent, so relying on their equivalence is
6054 // IFNDR. By making them equivalent, we disallow overloading, which at least
6055 // can produce a diagnostic.
6058 }
6059 llvm_unreachable("unexpected keyword kind");
6060}
6061
6063 ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc,
6064 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc,
6065 TemplateName Name, SourceLocation NameLoc,
6066 const TemplateArgumentListInfo &SpecifiedArgs,
6067 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6069 Keyword, Name, SpecifiedArgs.arguments(), CanonicalArgs, Underlying);
6070
6073 ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
6074 SpecifiedArgs);
6075 return TSI;
6076}
6077
6080 ArrayRef<TemplateArgumentLoc> SpecifiedArgs,
6081 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6082 SmallVector<TemplateArgument, 4> SpecifiedArgVec;
6083 SpecifiedArgVec.reserve(SpecifiedArgs.size());
6084 for (const TemplateArgumentLoc &Arg : SpecifiedArgs)
6085 SpecifiedArgVec.push_back(Arg.getArgument());
6086
6087 return getTemplateSpecializationType(Keyword, Template, SpecifiedArgVec,
6088 CanonicalArgs, Underlying);
6089}
6090
6091[[maybe_unused]] static bool
6093 for (const TemplateArgument &Arg : Args)
6094 if (Arg.isPackExpansion())
6095 return true;
6096 return false;
6097}
6098
6101 ArrayRef<TemplateArgument> Args) const {
6102 assert(Template ==
6103 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true));
6105 Template.getAsDependentTemplateName()));
6106#ifndef NDEBUG
6107 for (const auto &Arg : Args)
6108 assert(Arg.structurallyEquals(getCanonicalTemplateArgument(Arg)));
6109#endif
6110
6111 llvm::FoldingSetNodeID ID;
6112 TemplateSpecializationType::Profile(ID, Keyword, Template, Args, QualType(),
6113 *this);
6114 void *InsertPos = nullptr;
6115 if (auto *T = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6116 return QualType(T, 0);
6117
6118 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
6119 sizeof(TemplateArgument) * Args.size(),
6120 alignof(TemplateSpecializationType));
6121 auto *Spec =
6122 new (Mem) TemplateSpecializationType(Keyword, Template,
6123 /*IsAlias=*/false, Args, QualType());
6124 assert(Spec->isDependentType() &&
6125 "canonical template specialization must be dependent");
6126 Types.push_back(Spec);
6127 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
6128 return QualType(Spec, 0);
6129}
6130
6133 ArrayRef<TemplateArgument> SpecifiedArgs,
6134 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6135 const auto *TD = Template.getAsTemplateDecl(/*IgnoreDeduced=*/true);
6136 bool IsTypeAlias = TD && TD->isTypeAlias();
6137 if (Underlying.isNull()) {
6138 TemplateName CanonTemplate =
6139 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true);
6140 ElaboratedTypeKeyword CanonKeyword =
6141 CanonTemplate.getAsDependentTemplateName()
6144 bool NonCanonical = Template != CanonTemplate || Keyword != CanonKeyword;
6146 if (CanonicalArgs.empty()) {
6147 CanonArgsVec = SmallVector<TemplateArgument, 4>(SpecifiedArgs);
6148 NonCanonical |= canonicalizeTemplateArguments(CanonArgsVec);
6149 CanonicalArgs = CanonArgsVec;
6150 } else {
6151 NonCanonical |= !llvm::equal(
6152 SpecifiedArgs, CanonicalArgs,
6153 [](const TemplateArgument &A, const TemplateArgument &B) {
6154 return A.structurallyEquals(B);
6155 });
6156 }
6157
6158 // We can get here with an alias template when the specialization
6159 // contains a pack expansion that does not match up with a parameter
6160 // pack, or a builtin template which cannot be resolved due to dependency.
6161 assert((!isa_and_nonnull<TypeAliasTemplateDecl>(TD) ||
6162 hasAnyPackExpansions(CanonicalArgs)) &&
6163 "Caller must compute aliased type");
6164 IsTypeAlias = false;
6165
6167 CanonKeyword, CanonTemplate, CanonicalArgs);
6168 if (!NonCanonical)
6169 return Underlying;
6170 }
6171 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
6172 sizeof(TemplateArgument) * SpecifiedArgs.size() +
6173 (IsTypeAlias ? sizeof(QualType) : 0),
6174 alignof(TemplateSpecializationType));
6175 auto *Spec = new (Mem) TemplateSpecializationType(
6176 Keyword, Template, IsTypeAlias, SpecifiedArgs, Underlying);
6177 Types.push_back(Spec);
6178 return QualType(Spec, 0);
6179}
6180
6183 llvm::FoldingSetNodeID ID;
6184 ParenType::Profile(ID, InnerType);
6185
6186 void *InsertPos = nullptr;
6187 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6188 if (T)
6189 return QualType(T, 0);
6190
6191 QualType Canon = InnerType;
6192 if (!Canon.isCanonical()) {
6193 Canon = getCanonicalType(InnerType);
6194 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6195 assert(!CheckT && "Paren canonical type broken");
6196 (void)CheckT;
6197 }
6198
6199 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
6200 Types.push_back(T);
6201 ParenTypes.InsertNode(T, InsertPos);
6202 return QualType(T, 0);
6203}
6204
6207 const IdentifierInfo *MacroII) const {
6208 QualType Canon = UnderlyingTy;
6209 if (!Canon.isCanonical())
6210 Canon = getCanonicalType(UnderlyingTy);
6211
6212 auto *newType = new (*this, alignof(MacroQualifiedType))
6213 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
6214 Types.push_back(newType);
6215 return QualType(newType, 0);
6216}
6217
6220 const IdentifierInfo *Name) const {
6221 llvm::FoldingSetNodeID ID;
6222 DependentNameType::Profile(ID, Keyword, NNS, Name);
6223
6224 void *InsertPos = nullptr;
6225 if (DependentNameType *T =
6226 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos))
6227 return QualType(T, 0);
6228
6229 ElaboratedTypeKeyword CanonKeyword =
6231 NestedNameSpecifier CanonNNS = NNS.getCanonical();
6232
6233 QualType Canon;
6234 if (CanonKeyword != Keyword || CanonNNS != NNS) {
6235 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
6236 [[maybe_unused]] DependentNameType *T =
6237 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
6238 assert(!T && "broken canonicalization");
6239 assert(Canon.isCanonical());
6240 }
6241
6242 DependentNameType *T = new (*this, alignof(DependentNameType))
6243 DependentNameType(Keyword, NNS, Name, Canon);
6244 Types.push_back(T);
6245 DependentNameTypes.InsertNode(T, InsertPos);
6246 return QualType(T, 0);
6247}
6248
6250 TemplateArgument Arg;
6251 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6253 if (TTP->isParameterPack())
6254 ArgType = getPackExpansionType(ArgType, std::nullopt);
6255
6257 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6258 QualType T =
6259 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
6260 // For class NTTPs, ensure we include the 'const' so the type matches that
6261 // of a real template argument.
6262 // FIXME: It would be more faithful to model this as something like an
6263 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
6265 if (T->isRecordType()) {
6266 // C++ [temp.param]p8: An id-expression naming a non-type
6267 // template-parameter of class type T denotes a static storage duration
6268 // object of type const T.
6269 T.addConst();
6270 VK = VK_LValue;
6271 } else {
6272 VK = Expr::getValueKindForType(NTTP->getType());
6273 }
6274 Expr *E = new (*this)
6275 DeclRefExpr(*this, NTTP, /*RefersToEnclosingVariableOrCapture=*/false,
6276 T, VK, NTTP->getLocation());
6277
6278 if (NTTP->isParameterPack())
6279 E = new (*this) PackExpansionExpr(E, NTTP->getLocation(), std::nullopt);
6280 Arg = TemplateArgument(E, /*IsCanonical=*/false);
6281 } else {
6282 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
6284 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
6285 TemplateName(TTP));
6286 if (TTP->isParameterPack())
6287 Arg = TemplateArgument(Name, /*NumExpansions=*/std::nullopt);
6288 else
6289 Arg = TemplateArgument(Name);
6290 }
6291
6292 if (Param->isTemplateParameterPack())
6293 Arg =
6294 TemplateArgument::CreatePackCopy(const_cast<ASTContext &>(*this), Arg);
6295
6296 return Arg;
6297}
6298
6300 UnsignedOrNone NumExpansions,
6301 bool ExpectPackInType) const {
6302 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
6303 "Pack expansions must expand one or more parameter packs");
6304
6305 llvm::FoldingSetNodeID ID;
6306 PackExpansionType::Profile(ID, Pattern, NumExpansions);
6307
6308 void *InsertPos = nullptr;
6309 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6310 if (T)
6311 return QualType(T, 0);
6312
6313 QualType Canon;
6314 if (!Pattern.isCanonical()) {
6315 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
6316 /*ExpectPackInType=*/false);
6317
6318 // Find the insert position again, in case we inserted an element into
6319 // PackExpansionTypes and invalidated our insert position.
6320 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6321 }
6322
6323 T = new (*this, alignof(PackExpansionType))
6324 PackExpansionType(Pattern, Canon, NumExpansions);
6325 Types.push_back(T);
6326 PackExpansionTypes.InsertNode(T, InsertPos);
6327 return QualType(T, 0);
6328}
6329
6330/// CmpProtocolNames - Comparison predicate for sorting protocols
6331/// alphabetically.
6332static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
6333 ObjCProtocolDecl *const *RHS) {
6334 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
6335}
6336
6338 if (Protocols.empty()) return true;
6339
6340 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
6341 return false;
6342
6343 for (unsigned i = 1; i != Protocols.size(); ++i)
6344 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
6345 Protocols[i]->getCanonicalDecl() != Protocols[i])
6346 return false;
6347 return true;
6348}
6349
6350static void
6352 // Sort protocols, keyed by name.
6353 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
6354
6355 // Canonicalize.
6356 for (ObjCProtocolDecl *&P : Protocols)
6357 P = P->getCanonicalDecl();
6358
6359 // Remove duplicates.
6360 auto ProtocolsEnd = llvm::unique(Protocols);
6361 Protocols.erase(ProtocolsEnd, Protocols.end());
6362}
6363
6365 ObjCProtocolDecl * const *Protocols,
6366 unsigned NumProtocols) const {
6367 return getObjCObjectType(BaseType, {}, ArrayRef(Protocols, NumProtocols),
6368 /*isKindOf=*/false);
6369}
6370
6372 QualType baseType,
6373 ArrayRef<QualType> typeArgs,
6375 bool isKindOf) const {
6376 // If the base type is an interface and there aren't any protocols or
6377 // type arguments to add, then the interface type will do just fine.
6378 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
6379 isa<ObjCInterfaceType>(baseType))
6380 return baseType;
6381
6382 // Look in the folding set for an existing type.
6383 llvm::FoldingSetNodeID ID;
6384 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
6385 void *InsertPos = nullptr;
6386 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
6387 return QualType(QT, 0);
6388
6389 // Determine the type arguments to be used for canonicalization,
6390 // which may be explicitly specified here or written on the base
6391 // type.
6392 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
6393 if (effectiveTypeArgs.empty()) {
6394 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
6395 effectiveTypeArgs = baseObject->getTypeArgs();
6396 }
6397
6398 // Build the canonical type, which has the canonical base type and a
6399 // sorted-and-uniqued list of protocols and the type arguments
6400 // canonicalized.
6401 QualType canonical;
6402 bool typeArgsAreCanonical = llvm::all_of(
6403 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
6404 bool protocolsSorted = areSortedAndUniqued(protocols);
6405 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
6406 // Determine the canonical type arguments.
6407 ArrayRef<QualType> canonTypeArgs;
6408 SmallVector<QualType, 4> canonTypeArgsVec;
6409 if (!typeArgsAreCanonical) {
6410 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
6411 for (auto typeArg : effectiveTypeArgs)
6412 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
6413 canonTypeArgs = canonTypeArgsVec;
6414 } else {
6415 canonTypeArgs = effectiveTypeArgs;
6416 }
6417
6418 ArrayRef<ObjCProtocolDecl *> canonProtocols;
6419 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
6420 if (!protocolsSorted) {
6421 canonProtocolsVec.append(protocols.begin(), protocols.end());
6422 SortAndUniqueProtocols(canonProtocolsVec);
6423 canonProtocols = canonProtocolsVec;
6424 } else {
6425 canonProtocols = protocols;
6426 }
6427
6428 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
6429 canonProtocols, isKindOf);
6430
6431 // Regenerate InsertPos.
6432 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
6433 }
6434
6435 unsigned size = sizeof(ObjCObjectTypeImpl);
6436 size += typeArgs.size() * sizeof(QualType);
6437 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6438 void *mem = Allocate(size, alignof(ObjCObjectTypeImpl));
6439 auto *T =
6440 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
6441 isKindOf);
6442
6443 Types.push_back(T);
6444 ObjCObjectTypes.InsertNode(T, InsertPos);
6445 return QualType(T, 0);
6446}
6447
6448/// Apply Objective-C protocol qualifiers to the given type.
6449/// If this is for the canonical type of a type parameter, we can apply
6450/// protocol qualifiers on the ObjCObjectPointerType.
6453 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
6454 bool allowOnPointerType) const {
6455 hasError = false;
6456
6457 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
6458 return getObjCTypeParamType(objT->getDecl(), protocols);
6459 }
6460
6461 // Apply protocol qualifiers to ObjCObjectPointerType.
6462 if (allowOnPointerType) {
6463 if (const auto *objPtr =
6464 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
6465 const ObjCObjectType *objT = objPtr->getObjectType();
6466 // Merge protocol lists and construct ObjCObjectType.
6468 protocolsVec.append(objT->qual_begin(),
6469 objT->qual_end());
6470 protocolsVec.append(protocols.begin(), protocols.end());
6471 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
6473 objT->getBaseType(),
6474 objT->getTypeArgsAsWritten(),
6475 protocols,
6476 objT->isKindOfTypeAsWritten());
6478 }
6479 }
6480
6481 // Apply protocol qualifiers to ObjCObjectType.
6482 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
6483 // FIXME: Check for protocols to which the class type is already
6484 // known to conform.
6485
6486 return getObjCObjectType(objT->getBaseType(),
6487 objT->getTypeArgsAsWritten(),
6488 protocols,
6489 objT->isKindOfTypeAsWritten());
6490 }
6491
6492 // If the canonical type is ObjCObjectType, ...
6493 if (type->isObjCObjectType()) {
6494 // Silently overwrite any existing protocol qualifiers.
6495 // TODO: determine whether that's the right thing to do.
6496
6497 // FIXME: Check for protocols to which the class type is already
6498 // known to conform.
6499 return getObjCObjectType(type, {}, protocols, false);
6500 }
6501
6502 // id<protocol-list>
6503 if (type->isObjCIdType()) {
6504 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6505 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
6506 objPtr->isKindOfType());
6508 }
6509
6510 // Class<protocol-list>
6511 if (type->isObjCClassType()) {
6512 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6513 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
6514 objPtr->isKindOfType());
6516 }
6517
6518 hasError = true;
6519 return type;
6520}
6521
6524 ArrayRef<ObjCProtocolDecl *> protocols) const {
6525 // Look in the folding set for an existing type.
6526 llvm::FoldingSetNodeID ID;
6527 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
6528 void *InsertPos = nullptr;
6529 if (ObjCTypeParamType *TypeParam =
6530 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
6531 return QualType(TypeParam, 0);
6532
6533 // We canonicalize to the underlying type.
6534 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
6535 if (!protocols.empty()) {
6536 // Apply the protocol qualifers.
6537 bool hasError;
6539 Canonical, protocols, hasError, true /*allowOnPointerType*/));
6540 assert(!hasError && "Error when apply protocol qualifier to bound type");
6541 }
6542
6543 unsigned size = sizeof(ObjCTypeParamType);
6544 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6545 void *mem = Allocate(size, alignof(ObjCTypeParamType));
6546 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
6547
6548 Types.push_back(newType);
6549 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
6550 return QualType(newType, 0);
6551}
6552
6554 ObjCTypeParamDecl *New) const {
6555 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
6556 // Update TypeForDecl after updating TypeSourceInfo.
6557 auto *NewTypeParamTy = cast<ObjCTypeParamType>(New->TypeForDecl);
6559 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
6560 QualType UpdatedTy = getObjCTypeParamType(New, protocols);
6561 New->TypeForDecl = UpdatedTy.getTypePtr();
6562}
6563
6564/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
6565/// protocol list adopt all protocols in QT's qualified-id protocol
6566/// list.
6568 ObjCInterfaceDecl *IC) {
6569 if (!QT->isObjCQualifiedIdType())
6570 return false;
6571
6572 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
6573 // If both the right and left sides have qualifiers.
6574 for (auto *Proto : OPT->quals()) {
6575 if (!IC->ClassImplementsProtocol(Proto, false))
6576 return false;
6577 }
6578 return true;
6579 }
6580 return false;
6581}
6582
6583/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
6584/// QT's qualified-id protocol list adopt all protocols in IDecl's list
6585/// of protocols.
6587 ObjCInterfaceDecl *IDecl) {
6588 if (!QT->isObjCQualifiedIdType())
6589 return false;
6590 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
6591 if (!OPT)
6592 return false;
6593 if (!IDecl->hasDefinition())
6594 return false;
6596 CollectInheritedProtocols(IDecl, InheritedProtocols);
6597 if (InheritedProtocols.empty())
6598 return false;
6599 // Check that if every protocol in list of id<plist> conforms to a protocol
6600 // of IDecl's, then bridge casting is ok.
6601 bool Conforms = false;
6602 for (auto *Proto : OPT->quals()) {
6603 Conforms = false;
6604 for (auto *PI : InheritedProtocols) {
6605 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
6606 Conforms = true;
6607 break;
6608 }
6609 }
6610 if (!Conforms)
6611 break;
6612 }
6613 if (Conforms)
6614 return true;
6615
6616 for (auto *PI : InheritedProtocols) {
6617 // If both the right and left sides have qualifiers.
6618 bool Adopts = false;
6619 for (auto *Proto : OPT->quals()) {
6620 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
6621 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
6622 break;
6623 }
6624 if (!Adopts)
6625 return false;
6626 }
6627 return true;
6628}
6629
6630/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
6631/// the given object type.
6633 llvm::FoldingSetNodeID ID;
6634 ObjCObjectPointerType::Profile(ID, ObjectT);
6635
6636 void *InsertPos = nullptr;
6637 if (ObjCObjectPointerType *QT =
6638 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
6639 return QualType(QT, 0);
6640
6641 // Find the canonical object type.
6642 QualType Canonical;
6643 if (!ObjectT.isCanonical()) {
6644 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
6645
6646 // Regenerate InsertPos.
6647 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
6648 }
6649
6650 // No match.
6651 void *Mem =
6653 auto *QType =
6654 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
6655
6656 Types.push_back(QType);
6657 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
6658 return QualType(QType, 0);
6659}
6660
6661/// getObjCInterfaceType - Return the unique reference to the type for the
6662/// specified ObjC interface decl. The list of protocols is optional.
6664 ObjCInterfaceDecl *PrevDecl) const {
6665 if (Decl->TypeForDecl)
6666 return QualType(Decl->TypeForDecl, 0);
6667
6668 if (PrevDecl) {
6669 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
6670 Decl->TypeForDecl = PrevDecl->TypeForDecl;
6671 return QualType(PrevDecl->TypeForDecl, 0);
6672 }
6673
6674 // Prefer the definition, if there is one.
6675 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
6676 Decl = Def;
6677
6678 void *Mem = Allocate(sizeof(ObjCInterfaceType), alignof(ObjCInterfaceType));
6679 auto *T = new (Mem) ObjCInterfaceType(Decl);
6680 Decl->TypeForDecl = T;
6681 Types.push_back(T);
6682 return QualType(T, 0);
6683}
6684
6685/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
6686/// TypeOfExprType AST's (since expression's are never shared). For example,
6687/// multiple declarations that refer to "typeof(x)" all contain different
6688/// DeclRefExpr's. This doesn't effect the type checker, since it operates
6689/// on canonical type's (which are always unique).
6691 TypeOfExprType *toe;
6692 if (tofExpr->isTypeDependent()) {
6693 llvm::FoldingSetNodeID ID;
6694 DependentTypeOfExprType::Profile(ID, *this, tofExpr,
6695 Kind == TypeOfKind::Unqualified);
6696
6697 void *InsertPos = nullptr;
6699 DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
6700 if (Canon) {
6701 // We already have a "canonical" version of an identical, dependent
6702 // typeof(expr) type. Use that as our canonical type.
6703 toe = new (*this, alignof(TypeOfExprType)) TypeOfExprType(
6704 *this, tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
6705 } else {
6706 // Build a new, canonical typeof(expr) type.
6707 Canon = new (*this, alignof(DependentTypeOfExprType))
6708 DependentTypeOfExprType(*this, tofExpr, Kind);
6709 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
6710 toe = Canon;
6711 }
6712 } else {
6713 QualType Canonical = getCanonicalType(tofExpr->getType());
6714 toe = new (*this, alignof(TypeOfExprType))
6715 TypeOfExprType(*this, tofExpr, Kind, Canonical);
6716 }
6717 Types.push_back(toe);
6718 return QualType(toe, 0);
6719}
6720
6721/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
6722/// TypeOfType nodes. The only motivation to unique these nodes would be
6723/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
6724/// an issue. This doesn't affect the type checker, since it operates
6725/// on canonical types (which are always unique).
6727 QualType Canonical = getCanonicalType(tofType);
6728 auto *tot = new (*this, alignof(TypeOfType))
6729 TypeOfType(*this, tofType, Canonical, Kind);
6730 Types.push_back(tot);
6731 return QualType(tot, 0);
6732}
6733
6734/// getReferenceQualifiedType - Given an expr, will return the type for
6735/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
6736/// and class member access into account.
6738 // C++11 [dcl.type.simple]p4:
6739 // [...]
6740 QualType T = E->getType();
6741 switch (E->getValueKind()) {
6742 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6743 // type of e;
6744 case VK_XValue:
6745 return getRValueReferenceType(T);
6746 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6747 // type of e;
6748 case VK_LValue:
6749 return getLValueReferenceType(T);
6750 // - otherwise, decltype(e) is the type of e.
6751 case VK_PRValue:
6752 return T;
6753 }
6754 llvm_unreachable("Unknown value kind");
6755}
6756
6757/// Unlike many "get<Type>" functions, we don't unique DecltypeType
6758/// nodes. This would never be helpful, since each such type has its own
6759/// expression, and would not give a significant memory saving, since there
6760/// is an Expr tree under each such type.
6762 // C++11 [temp.type]p2:
6763 // If an expression e involves a template parameter, decltype(e) denotes a
6764 // unique dependent type. Two such decltype-specifiers refer to the same
6765 // type only if their expressions are equivalent (14.5.6.1).
6766 QualType CanonType;
6767 if (!E->isInstantiationDependent()) {
6768 CanonType = getCanonicalType(UnderlyingType);
6769 } else if (!UnderlyingType.isNull()) {
6770 CanonType = getDecltypeType(E, QualType());
6771 } else {
6772 llvm::FoldingSetNodeID ID;
6773 DependentDecltypeType::Profile(ID, *this, E);
6774
6775 void *InsertPos = nullptr;
6776 if (DependentDecltypeType *Canon =
6777 DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos))
6778 return QualType(Canon, 0);
6779
6780 // Build a new, canonical decltype(expr) type.
6781 auto *DT =
6782 new (*this, alignof(DependentDecltypeType)) DependentDecltypeType(E);
6783 DependentDecltypeTypes.InsertNode(DT, InsertPos);
6784 Types.push_back(DT);
6785 return QualType(DT, 0);
6786 }
6787 auto *DT = new (*this, alignof(DecltypeType))
6788 DecltypeType(E, UnderlyingType, CanonType);
6789 Types.push_back(DT);
6790 return QualType(DT, 0);
6791}
6792
6794 bool FullySubstituted,
6795 ArrayRef<QualType> Expansions,
6796 UnsignedOrNone Index) const {
6797 QualType Canonical;
6798 if (FullySubstituted && Index) {
6799 Canonical = getCanonicalType(Expansions[*Index]);
6800 } else {
6801 llvm::FoldingSetNodeID ID;
6802 PackIndexingType::Profile(ID, *this, Pattern.getCanonicalType(), IndexExpr,
6803 FullySubstituted, Expansions);
6804 void *InsertPos = nullptr;
6805 PackIndexingType *Canon =
6806 DependentPackIndexingTypes.FindNodeOrInsertPos(ID, InsertPos);
6807 if (!Canon) {
6808 void *Mem = Allocate(
6809 PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6811 Canon =
6812 new (Mem) PackIndexingType(QualType(), Pattern.getCanonicalType(),
6813 IndexExpr, FullySubstituted, Expansions);
6814 DependentPackIndexingTypes.InsertNode(Canon, InsertPos);
6815 }
6816 Canonical = QualType(Canon, 0);
6817 }
6818
6819 void *Mem =
6820 Allocate(PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6822 auto *T = new (Mem) PackIndexingType(Canonical, Pattern, IndexExpr,
6823 FullySubstituted, Expansions);
6824 Types.push_back(T);
6825 return QualType(T, 0);
6826}
6827
6828/// getUnaryTransformationType - We don't unique these, since the memory
6829/// savings are minimal and these are rare.
6832 UnaryTransformType::UTTKind Kind) const {
6833
6834 llvm::FoldingSetNodeID ID;
6835 UnaryTransformType::Profile(ID, BaseType, UnderlyingType, Kind);
6836
6837 void *InsertPos = nullptr;
6838 if (UnaryTransformType *UT =
6839 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos))
6840 return QualType(UT, 0);
6841
6842 QualType CanonType;
6843 if (!BaseType->isDependentType()) {
6844 CanonType = UnderlyingType.getCanonicalType();
6845 } else {
6846 assert(UnderlyingType.isNull() || BaseType == UnderlyingType);
6847 UnderlyingType = QualType();
6848 if (QualType CanonBase = BaseType.getCanonicalType();
6849 BaseType != CanonBase) {
6850 CanonType = getUnaryTransformType(CanonBase, QualType(), Kind);
6851 assert(CanonType.isCanonical());
6852
6853 // Find the insertion position again.
6854 [[maybe_unused]] UnaryTransformType *UT =
6855 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
6856 assert(!UT && "broken canonicalization");
6857 }
6858 }
6859
6860 auto *UT = new (*this, alignof(UnaryTransformType))
6861 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
6862 UnaryTransformTypes.InsertNode(UT, InsertPos);
6863 Types.push_back(UT);
6864 return QualType(UT, 0);
6865}
6866
6867/// getAutoType - Return the uniqued reference to the 'auto' type which has been
6868/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
6869/// canonical deduced-but-dependent 'auto' type.
6873 TemplateDecl *TypeConstraintConcept,
6874 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
6876 !TypeConstraintConcept) {
6877 assert(DeducedAsType.isNull() && "");
6878 assert(TypeConstraintArgs.empty() && "");
6879 return getAutoDeductType();
6880 }
6881
6882 // Look in the folding set for an existing type.
6883 llvm::FoldingSetNodeID ID;
6884 AutoType::Profile(ID, *this, DK, DeducedAsType, Keyword,
6885 TypeConstraintConcept, TypeConstraintArgs);
6886 if (auto const AT_iter = AutoTypes.find(ID); AT_iter != AutoTypes.end())
6887 return QualType(AT_iter->getSecond(), 0);
6888
6889 if (DK == DeducedKind::Deduced) {
6890 assert(!DeducedAsType.isNull() && "deduced type must be provided");
6891 } else {
6892 assert(DeducedAsType.isNull() && "deduced type must not be provided");
6893 if (TypeConstraintConcept) {
6894 bool AnyNonCanonArgs = false;
6895 auto *CanonicalConcept =
6896 cast<TemplateDecl>(TypeConstraintConcept->getCanonicalDecl());
6897 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
6898 *this, TypeConstraintArgs, AnyNonCanonArgs);
6899 if (TypeConstraintConcept != CanonicalConcept || AnyNonCanonArgs)
6900 DeducedAsType = getAutoType(DK, QualType(), Keyword, CanonicalConcept,
6901 CanonicalConceptArgs);
6902 }
6903 }
6904
6905 void *Mem = Allocate(sizeof(AutoType) +
6906 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
6907 alignof(AutoType));
6908 auto *AT = new (Mem) AutoType(DK, DeducedAsType, Keyword,
6909 TypeConstraintConcept, TypeConstraintArgs);
6910#ifndef NDEBUG
6911 llvm::FoldingSetNodeID InsertedID;
6912 AT->Profile(InsertedID, *this);
6913 assert(InsertedID == ID && "ID does not match");
6914#endif
6915 Types.push_back(AT);
6916 AutoTypes.try_emplace(ID, AT);
6917 return QualType(AT, 0);
6918}
6919
6922
6923 // Remove a type-constraint from a top-level auto or decltype(auto).
6924 if (auto *AT = CanonT->getAs<AutoType>()) {
6925 if (!AT->isConstrained())
6926 return T;
6927 return getQualifiedType(
6928 getAutoType(AT->getDeducedKind(), QualType(), AT->getKeyword()),
6929 T.getQualifiers());
6930 }
6931
6932 // FIXME: We only support constrained auto at the top level in the type of a
6933 // non-type template parameter at the moment. Once we lift that restriction,
6934 // we'll need to recursively build types containing auto here.
6935 assert(!CanonT->getContainedAutoType() ||
6936 !CanonT->getContainedAutoType()->isConstrained());
6937 return T;
6938}
6939
6940/// Return the uniqued reference to the deduced template specialization type
6941/// which has been deduced to the given type, or to the canonical undeduced
6942/// such type, or the canonical deduced-but-dependent such type.
6945 TemplateName Template) const {
6946 // DeducedAsPack only ever occurs for lambda init-capture pack, which always
6947 // use AutoType.
6948 assert(DK != DeducedKind::DeducedAsPack &&
6949 "unexpected DeducedAsPack for DeducedTemplateSpecializationType");
6950
6951 // Look in the folding set for an existing type.
6952 void *InsertPos = nullptr;
6953 llvm::FoldingSetNodeID ID;
6954 DeducedTemplateSpecializationType::Profile(ID, DK, DeducedAsType, Keyword,
6955 Template);
6956 if (DeducedTemplateSpecializationType *DTST =
6957 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6958 return QualType(DTST, 0);
6959
6960 if (DK == DeducedKind::Deduced) {
6961 assert(!DeducedAsType.isNull() && "deduced type must be provided");
6962 } else {
6963 assert(DeducedAsType.isNull() && "deduced type must not be provided");
6964 TemplateName CanonTemplateName = getCanonicalTemplateName(Template);
6965 // FIXME: Can this be formed from a DependentTemplateName, such that the
6966 // keyword should be part of the canonical type?
6968 Template != CanonTemplateName) {
6970 DK, QualType(), ElaboratedTypeKeyword::None, CanonTemplateName);
6971 // Find the insertion position again.
6972 [[maybe_unused]] DeducedTemplateSpecializationType *DTST =
6973 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
6974 assert(!DTST && "broken canonicalization");
6975 }
6976 }
6977
6978 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
6979 DeducedTemplateSpecializationType(DK, DeducedAsType, Keyword, Template);
6980
6981#ifndef NDEBUG
6982 llvm::FoldingSetNodeID TempID;
6983 DTST->Profile(TempID);
6984 assert(ID == TempID && "ID does not match");
6985#endif
6986 Types.push_back(DTST);
6987 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
6988 return QualType(DTST, 0);
6989}
6990
6991/// getAtomicType - Return the uniqued reference to the atomic type for
6992/// the given value type.
6994 // Unique pointers, to guarantee there is only one pointer of a particular
6995 // structure.
6996 llvm::FoldingSetNodeID ID;
6997 AtomicType::Profile(ID, T);
6998
6999 void *InsertPos = nullptr;
7000 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
7001 return QualType(AT, 0);
7002
7003 // If the atomic value type isn't canonical, this won't be a canonical type
7004 // either, so fill in the canonical type field.
7005 QualType Canonical;
7006 if (!T.isCanonical()) {
7007 Canonical = getAtomicType(getCanonicalType(T));
7008
7009 // Get the new insert position for the node we care about.
7010 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
7011 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
7012 }
7013 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
7014 Types.push_back(New);
7015 AtomicTypes.InsertNode(New, InsertPos);
7016 return QualType(New, 0);
7017}
7018
7019/// getAutoDeductType - Get type pattern for deducing against 'auto'.
7021 if (AutoDeductTy.isNull())
7022 AutoDeductTy = QualType(new (*this, alignof(AutoType))
7023 AutoType(DeducedKind::Undeduced, QualType(),
7025 /*TypeConstraintConcept=*/nullptr,
7026 /*TypeConstraintArgs=*/{}),
7027 0);
7028 return AutoDeductTy;
7029}
7030
7031/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
7033 if (AutoRRefDeductTy.isNull())
7035 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
7036 return AutoRRefDeductTy;
7037}
7038
7039/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
7040/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
7041/// needs to agree with the definition in <stddef.h>.
7045
7047 return getFromTargetType(Target->getSizeType());
7048}
7049
7050/// Return the unique signed counterpart of the integer type
7051/// corresponding to size_t.
7055
7056/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
7057/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
7061
7062/// Return the unique unsigned counterpart of "ptrdiff_t"
7063/// integer type. The standard (C11 7.21.6.1p7) refers to this type
7064/// in the definition of %tu format specifier.
7066 return getFromTargetType(Target->getUnsignedPtrDiffType(LangAS::Default));
7067}
7068
7069/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
7071 return getFromTargetType(Target->getIntMaxType());
7072}
7073
7074/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
7076 return getFromTargetType(Target->getUIntMaxType());
7077}
7078
7079/// getSignedWCharType - Return the type of "signed wchar_t".
7080/// Used when in C++, as a GCC extension.
7082 // FIXME: derive from "Target" ?
7083 return WCharTy;
7084}
7085
7086/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
7087/// Used when in C++, as a GCC extension.
7089 // FIXME: derive from "Target" ?
7090 return UnsignedIntTy;
7091}
7092
7094 return getFromTargetType(Target->getIntPtrType());
7095}
7096
7100
7101/// Return the unique type for "pid_t" defined in
7102/// <sys/types.h>. We need this to compute the correct type for vfork().
7104 return getFromTargetType(Target->getProcessIDType());
7105}
7106
7107//===----------------------------------------------------------------------===//
7108// Type Operators
7109//===----------------------------------------------------------------------===//
7110
7112 // Push qualifiers into arrays, and then discard any remaining
7113 // qualifiers.
7114 T = getCanonicalType(T);
7116 const Type *Ty = T.getTypePtr();
7120 } else if (isa<ArrayType>(Ty)) {
7122 } else if (isa<FunctionType>(Ty)) {
7123 Result = getPointerType(QualType(Ty, 0));
7124 } else {
7125 Result = QualType(Ty, 0);
7126 }
7127
7129}
7130
7132 Qualifiers &quals) const {
7133 SplitQualType splitType = type.getSplitUnqualifiedType();
7134
7135 // FIXME: getSplitUnqualifiedType() actually walks all the way to
7136 // the unqualified desugared type and then drops it on the floor.
7137 // We then have to strip that sugar back off with
7138 // getUnqualifiedDesugaredType(), which is silly.
7139 const auto *AT =
7140 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
7141
7142 // If we don't have an array, just use the results in splitType.
7143 if (!AT) {
7144 quals = splitType.Quals;
7145 return QualType(splitType.Ty, 0);
7146 }
7147
7148 // Otherwise, recurse on the array's element type.
7149 QualType elementType = AT->getElementType();
7150 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
7151
7152 // If that didn't change the element type, AT has no qualifiers, so we
7153 // can just use the results in splitType.
7154 if (elementType == unqualElementType) {
7155 assert(quals.empty()); // from the recursive call
7156 quals = splitType.Quals;
7157 return QualType(splitType.Ty, 0);
7158 }
7159
7160 // Otherwise, add in the qualifiers from the outermost type, then
7161 // build the type back up.
7162 quals.addConsistentQualifiers(splitType.Quals);
7163
7164 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
7165 return getConstantArrayType(unqualElementType, CAT->getSize(),
7166 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
7167 }
7168
7169 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
7170 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
7171 }
7172
7173 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
7174 return getVariableArrayType(unqualElementType, VAT->getSizeExpr(),
7175 VAT->getSizeModifier(),
7176 VAT->getIndexTypeCVRQualifiers());
7177 }
7178
7179 const auto *DSAT = cast<DependentSizedArrayType>(AT);
7180 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
7181 DSAT->getSizeModifier(), 0);
7182}
7183
7184/// Attempt to unwrap two types that may both be array types with the same bound
7185/// (or both be array types of unknown bound) for the purpose of comparing the
7186/// cv-decomposition of two types per C++ [conv.qual].
7187///
7188/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7189/// C++20 [conv.qual], if permitted by the current language mode.
7191 bool AllowPiMismatch) const {
7192 while (true) {
7193 auto *AT1 = getAsArrayType(T1);
7194 if (!AT1)
7195 return;
7196
7197 auto *AT2 = getAsArrayType(T2);
7198 if (!AT2)
7199 return;
7200
7201 // If we don't have two array types with the same constant bound nor two
7202 // incomplete array types, we've unwrapped everything we can.
7203 // C++20 also permits one type to be a constant array type and the other
7204 // to be an incomplete array type.
7205 // FIXME: Consider also unwrapping array of unknown bound and VLA.
7206 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
7207 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
7208 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
7209 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7211 return;
7212 } else if (isa<IncompleteArrayType>(AT1)) {
7213 if (!(isa<IncompleteArrayType>(AT2) ||
7214 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7216 return;
7217 } else {
7218 return;
7219 }
7220
7221 T1 = AT1->getElementType();
7222 T2 = AT2->getElementType();
7223 }
7224}
7225
7226/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
7227///
7228/// If T1 and T2 are both pointer types of the same kind, or both array types
7229/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
7230/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
7231///
7232/// This function will typically be called in a loop that successively
7233/// "unwraps" pointer and pointer-to-member types to compare them at each
7234/// level.
7235///
7236/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7237/// C++20 [conv.qual], if permitted by the current language mode.
7238///
7239/// \return \c true if a pointer type was unwrapped, \c false if we reached a
7240/// pair of types that can't be unwrapped further.
7242 bool AllowPiMismatch) const {
7243 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
7244
7245 const auto *T1PtrType = T1->getAs<PointerType>();
7246 const auto *T2PtrType = T2->getAs<PointerType>();
7247 if (T1PtrType && T2PtrType) {
7248 T1 = T1PtrType->getPointeeType();
7249 T2 = T2PtrType->getPointeeType();
7250 return true;
7251 }
7252
7253 if (const auto *T1MPType = T1->getAsCanonical<MemberPointerType>(),
7254 *T2MPType = T2->getAsCanonical<MemberPointerType>();
7255 T1MPType && T2MPType) {
7256 // Compare the qualifiers of the canonical type, as the non-canonical type
7257 // may have qualifiers pointing to a base or derived class.
7258 if (T1MPType->getQualifier() != T2MPType->getQualifier())
7259 return false;
7260 // Get the pointee types of the non-canonical type, in order to preserve
7261 // their sugar.
7262 T1 = T1->getAs<MemberPointerType>()->getPointeeType();
7263 T2 = T2->getAs<MemberPointerType>()->getPointeeType();
7264 return true;
7265 }
7266
7267 if (getLangOpts().ObjC) {
7268 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
7269 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
7270 if (T1OPType && T2OPType) {
7271 T1 = T1OPType->getPointeeType();
7272 T2 = T2OPType->getPointeeType();
7273 return true;
7274 }
7275 }
7276
7277 // FIXME: Block pointers, too?
7278
7279 return false;
7280}
7281
7283 while (true) {
7284 Qualifiers Quals;
7285 T1 = getUnqualifiedArrayType(T1, Quals);
7286 T2 = getUnqualifiedArrayType(T2, Quals);
7287 if (hasSameType(T1, T2))
7288 return true;
7289 if (!UnwrapSimilarTypes(T1, T2))
7290 return false;
7291 }
7292}
7293
7295 while (true) {
7296 Qualifiers Quals1, Quals2;
7297 T1 = getUnqualifiedArrayType(T1, Quals1);
7298 T2 = getUnqualifiedArrayType(T2, Quals2);
7299
7300 Quals1.removeCVRQualifiers();
7301 Quals2.removeCVRQualifiers();
7302 if (Quals1 != Quals2)
7303 return false;
7304
7305 if (hasSameType(T1, T2))
7306 return true;
7307
7308 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
7309 return false;
7310 }
7311}
7312
7315 SourceLocation NameLoc) const {
7316 switch (Name.getKind()) {
7319 // DNInfo work in progress: CHECKME: what about DNLoc?
7321 NameLoc);
7322
7325 // DNInfo work in progress: CHECKME: what about DNLoc?
7326 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
7327 }
7328
7331 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
7332 }
7333
7337 DeclarationName DName;
7338 if (const IdentifierInfo *II = TN.getIdentifier()) {
7339 DName = DeclarationNames.getIdentifier(II);
7340 return DeclarationNameInfo(DName, NameLoc);
7341 } else {
7342 DName = DeclarationNames.getCXXOperatorName(TN.getOperator());
7343 // DNInfo work in progress: FIXME: source locations?
7344 DeclarationNameLoc DNLoc =
7346 return DeclarationNameInfo(DName, NameLoc, DNLoc);
7347 }
7348 }
7349
7353 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
7354 NameLoc);
7355 }
7356
7361 NameLoc);
7362 }
7365 NameLoc);
7368 return getNameForTemplate(DTS->getUnderlying(), NameLoc);
7369 }
7370 }
7371
7372 llvm_unreachable("bad template name kind!");
7373}
7374
7375const TemplateArgument *
7377 auto handleParam = [](auto *TP) -> const TemplateArgument * {
7378 if (!TP->hasDefaultArgument())
7379 return nullptr;
7380 return &TP->getDefaultArgument().getArgument();
7381 };
7382 switch (P->getKind()) {
7383 case NamedDecl::TemplateTypeParm:
7384 return handleParam(cast<TemplateTypeParmDecl>(P));
7385 case NamedDecl::NonTypeTemplateParm:
7386 return handleParam(cast<NonTypeTemplateParmDecl>(P));
7387 case NamedDecl::TemplateTemplateParm:
7388 return handleParam(cast<TemplateTemplateParmDecl>(P));
7389 default:
7390 llvm_unreachable("Unexpected template parameter kind");
7391 }
7392}
7393
7395 bool IgnoreDeduced) const {
7396 while (std::optional<TemplateName> UnderlyingOrNone =
7397 Name.desugar(IgnoreDeduced))
7398 Name = *UnderlyingOrNone;
7399
7400 switch (Name.getKind()) {
7403 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
7405
7406 // The canonical template name is the canonical template declaration.
7407 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
7408 }
7409
7411 // An assumed template is just a name, so it is already canonical.
7412 return Name;
7413
7415 llvm_unreachable("cannot canonicalize overloaded template");
7416
7419 assert(DTN && "Non-dependent template names must refer to template decls.");
7420 NestedNameSpecifier Qualifier = DTN->getQualifier();
7421 NestedNameSpecifier CanonQualifier = Qualifier.getCanonical();
7422 if (Qualifier != CanonQualifier || !DTN->hasTemplateKeyword())
7423 return getDependentTemplateName({CanonQualifier, DTN->getName(),
7424 /*HasTemplateKeyword=*/true});
7425 return Name;
7426 }
7427
7431 TemplateArgument canonArgPack =
7434 canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
7435 subst->getIndex(), subst->getFinal());
7436 }
7438 assert(IgnoreDeduced == false);
7440 DefaultArguments DefArgs = DTS->getDefaultArguments();
7441 TemplateName Underlying = DTS->getUnderlying();
7442
7443 TemplateName CanonUnderlying =
7444 getCanonicalTemplateName(Underlying, /*IgnoreDeduced=*/true);
7445 bool NonCanonical = CanonUnderlying != Underlying;
7446 auto CanonArgs =
7447 getCanonicalTemplateArguments(*this, DefArgs.Args, NonCanonical);
7448
7449 ArrayRef<NamedDecl *> Params =
7450 CanonUnderlying.getAsTemplateDecl()->getTemplateParameters()->asArray();
7451 assert(CanonArgs.size() <= Params.size());
7452 // A deduced template name which deduces the same default arguments already
7453 // declared in the underlying template is the same template as the
7454 // underlying template. We need need to note any arguments which differ from
7455 // the corresponding declaration. If any argument differs, we must build a
7456 // deduced template name.
7457 for (int I = CanonArgs.size() - 1; I >= 0; --I) {
7459 if (!A)
7460 break;
7461 auto CanonParamDefArg = getCanonicalTemplateArgument(*A);
7462 TemplateArgument &CanonDefArg = CanonArgs[I];
7463 if (CanonDefArg.structurallyEquals(CanonParamDefArg))
7464 continue;
7465 // Keep popping from the back any deault arguments which are the same.
7466 if (I == int(CanonArgs.size() - 1))
7467 CanonArgs.pop_back();
7468 NonCanonical = true;
7469 }
7470 return NonCanonical ? getDeducedTemplateName(
7471 CanonUnderlying,
7472 /*DefaultArgs=*/{DefArgs.StartPos, CanonArgs})
7473 : Name;
7474 }
7478 llvm_unreachable("always sugar node");
7479 }
7480
7481 llvm_unreachable("bad template name!");
7482}
7483
7485 const TemplateName &Y,
7486 bool IgnoreDeduced) const {
7487 return getCanonicalTemplateName(X, IgnoreDeduced) ==
7488 getCanonicalTemplateName(Y, IgnoreDeduced);
7489}
7490
7492 const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const {
7493 if (ACX.ArgPackSubstIndex != ACY.ArgPackSubstIndex)
7494 return false;
7496 return false;
7497 return true;
7498}
7499
7500bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
7501 if (!XCE != !YCE)
7502 return false;
7503
7504 if (!XCE)
7505 return true;
7506
7507 llvm::FoldingSetNodeID XCEID, YCEID;
7508 XCE->Profile(XCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7509 YCE->Profile(YCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7510 return XCEID == YCEID;
7511}
7512
7514 const TypeConstraint *YTC) const {
7515 if (!XTC != !YTC)
7516 return false;
7517
7518 if (!XTC)
7519 return true;
7520
7521 auto *NCX = XTC->getNamedConcept();
7522 auto *NCY = YTC->getNamedConcept();
7523 if (!NCX || !NCY || !isSameEntity(NCX, NCY))
7524 return false;
7527 return false;
7529 if (XTC->getConceptReference()
7531 ->NumTemplateArgs !=
7533 return false;
7534
7535 // Compare slowly by profiling.
7536 //
7537 // We couldn't compare the profiling result for the template
7538 // args here. Consider the following example in different modules:
7539 //
7540 // template <__integer_like _Tp, C<_Tp> Sentinel>
7541 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
7542 // return __t;
7543 // }
7544 //
7545 // When we compare the profiling result for `C<_Tp>` in different
7546 // modules, it will compare the type of `_Tp` in different modules.
7547 // However, the type of `_Tp` in different modules refer to different
7548 // types here naturally. So we couldn't compare the profiling result
7549 // for the template args directly.
7552}
7553
7555 const NamedDecl *Y) const {
7556 if (X->getKind() != Y->getKind())
7557 return false;
7558
7559 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
7560 auto *TY = cast<TemplateTypeParmDecl>(Y);
7561 if (TX->isParameterPack() != TY->isParameterPack())
7562 return false;
7563 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
7564 return false;
7565 return isSameTypeConstraint(TX->getTypeConstraint(),
7566 TY->getTypeConstraint());
7567 }
7568
7569 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7570 auto *TY = cast<NonTypeTemplateParmDecl>(Y);
7571 return TX->isParameterPack() == TY->isParameterPack() &&
7572 TX->getASTContext().hasSameType(TX->getType(), TY->getType()) &&
7573 isSameConstraintExpr(TX->getPlaceholderTypeConstraint(),
7574 TY->getPlaceholderTypeConstraint());
7575 }
7576
7578 auto *TY = cast<TemplateTemplateParmDecl>(Y);
7579 return TX->isParameterPack() == TY->isParameterPack() &&
7580 isSameTemplateParameterList(TX->getTemplateParameters(),
7581 TY->getTemplateParameters());
7582}
7583
7585 const TemplateParameterList *X, const TemplateParameterList *Y) const {
7586 if (X->size() != Y->size())
7587 return false;
7588
7589 for (unsigned I = 0, N = X->size(); I != N; ++I)
7590 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
7591 return false;
7592
7593 return isSameConstraintExpr(X->getRequiresClause(), Y->getRequiresClause());
7594}
7595
7597 const NamedDecl *Y) const {
7598 // If the type parameter isn't the same already, we don't need to check the
7599 // default argument further.
7600 if (!isSameTemplateParameter(X, Y))
7601 return false;
7602
7603 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(X)) {
7604 auto *TTPY = cast<TemplateTypeParmDecl>(Y);
7605 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7606 return false;
7607
7608 return hasSameType(TTPX->getDefaultArgument().getArgument().getAsType(),
7609 TTPY->getDefaultArgument().getArgument().getAsType());
7610 }
7611
7612 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7613 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Y);
7614 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
7615 return false;
7616
7617 Expr *DefaultArgumentX =
7618 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7619 Expr *DefaultArgumentY =
7620 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7621 llvm::FoldingSetNodeID XID, YID;
7622 DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true);
7623 DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true);
7624 return XID == YID;
7625 }
7626
7627 auto *TTPX = cast<TemplateTemplateParmDecl>(X);
7628 auto *TTPY = cast<TemplateTemplateParmDecl>(Y);
7629
7630 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7631 return false;
7632
7633 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
7634 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
7635 return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate());
7636}
7637
7639 const NestedNameSpecifier Y) {
7640 if (X == Y)
7641 return true;
7642 if (!X || !Y)
7643 return false;
7644
7645 auto Kind = X.getKind();
7646 if (Kind != Y.getKind())
7647 return false;
7648
7649 // FIXME: For namespaces and types, we're permitted to check that the entity
7650 // is named via the same tokens. We should probably do so.
7651 switch (Kind) {
7653 auto [NamespaceX, PrefixX] = X.getAsNamespaceAndPrefix();
7654 auto [NamespaceY, PrefixY] = Y.getAsNamespaceAndPrefix();
7655 if (!declaresSameEntity(NamespaceX->getNamespace(),
7656 NamespaceY->getNamespace()))
7657 return false;
7658 return isSameQualifier(PrefixX, PrefixY);
7659 }
7661 const auto *TX = X.getAsType(), *TY = Y.getAsType();
7662 if (TX->getCanonicalTypeInternal() != TY->getCanonicalTypeInternal())
7663 return false;
7664 return isSameQualifier(TX->getPrefix(), TY->getPrefix());
7665 }
7669 return true;
7670 }
7671 llvm_unreachable("unhandled qualifier kind");
7672}
7673
7674static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B) {
7675 if (!A->getASTContext().getLangOpts().CUDA)
7676 return true; // Target attributes are overloadable in CUDA compilation only.
7677 if (A->hasAttr<CUDADeviceAttr>() != B->hasAttr<CUDADeviceAttr>())
7678 return false;
7679 if (A->hasAttr<CUDADeviceAttr>() && B->hasAttr<CUDADeviceAttr>())
7680 return A->hasAttr<CUDAHostAttr>() == B->hasAttr<CUDAHostAttr>();
7681 return true; // unattributed and __host__ functions are the same.
7682}
7683
7684/// Determine whether the attributes we can overload on are identical for A and
7685/// B. Will ignore any overloadable attrs represented in the type of A and B.
7687 const FunctionDecl *B) {
7688 // Note that pass_object_size attributes are represented in the function's
7689 // ExtParameterInfo, so we don't need to check them here.
7690
7691 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
7692 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
7693 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
7694
7695 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
7696 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
7697 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
7698
7699 // Return false if the number of enable_if attributes is different.
7700 if (!Cand1A || !Cand2A)
7701 return false;
7702
7703 Cand1ID.clear();
7704 Cand2ID.clear();
7705
7706 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
7707 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
7708
7709 // Return false if any of the enable_if expressions of A and B are
7710 // different.
7711 if (Cand1ID != Cand2ID)
7712 return false;
7713 }
7714 return hasSameCudaAttrs(A, B);
7715}
7716
7717bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
7718 // Caution: this function is called by the AST reader during deserialization,
7719 // so it cannot rely on AST invariants being met. Non-trivial accessors
7720 // should be avoided, along with any traversal of redeclaration chains.
7721
7722 if (X == Y)
7723 return true;
7724
7725 if (X->getDeclName() != Y->getDeclName())
7726 return false;
7727
7728 // Must be in the same context.
7729 //
7730 // Note that we can't use DeclContext::Equals here, because the DeclContexts
7731 // could be two different declarations of the same function. (We will fix the
7732 // semantic DC to refer to the primary definition after merging.)
7733 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
7735 return false;
7736
7737 // If either X or Y are local to the owning module, they are only possible to
7738 // be the same entity if they are in the same module.
7739 if (X->isModuleLocal() || Y->isModuleLocal())
7740 if (!isInSameModule(X->getOwningModule(), Y->getOwningModule()))
7741 return false;
7742
7743 // Two typedefs refer to the same entity if they have the same underlying
7744 // type.
7745 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
7746 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
7747 return hasSameType(TypedefX->getUnderlyingType(),
7748 TypedefY->getUnderlyingType());
7749
7750 // Must have the same kind.
7751 if (X->getKind() != Y->getKind())
7752 return false;
7753
7754 // Objective-C classes and protocols with the same name always match.
7756 return true;
7757
7759 // No need to handle these here: we merge them when adding them to the
7760 // template.
7761 return false;
7762 }
7763
7764 // Compatible tags match.
7765 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
7766 const auto *TagY = cast<TagDecl>(Y);
7767 return (TagX->getTagKind() == TagY->getTagKind()) ||
7768 ((TagX->getTagKind() == TagTypeKind::Struct ||
7769 TagX->getTagKind() == TagTypeKind::Class ||
7770 TagX->getTagKind() == TagTypeKind::Interface) &&
7771 (TagY->getTagKind() == TagTypeKind::Struct ||
7772 TagY->getTagKind() == TagTypeKind::Class ||
7773 TagY->getTagKind() == TagTypeKind::Interface));
7774 }
7775
7776 // Functions with the same type and linkage match.
7777 // FIXME: This needs to cope with merging of prototyped/non-prototyped
7778 // functions, etc.
7779 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
7780 const auto *FuncY = cast<FunctionDecl>(Y);
7781 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
7782 const auto *CtorY = cast<CXXConstructorDecl>(Y);
7783 if (CtorX->getInheritedConstructor() &&
7784 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
7785 CtorY->getInheritedConstructor().getConstructor()))
7786 return false;
7787 }
7788
7789 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
7790 return false;
7791
7792 // Multiversioned functions with different feature strings are represented
7793 // as separate declarations.
7794 if (FuncX->isMultiVersion()) {
7795 const auto *TAX = FuncX->getAttr<TargetAttr>();
7796 const auto *TAY = FuncY->getAttr<TargetAttr>();
7797 assert(TAX && TAY && "Multiversion Function without target attribute");
7798
7799 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
7800 return false;
7801 }
7802
7803 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
7804 // not the same entity if they are constrained.
7805 if ((FuncX->isMemberLikeConstrainedFriend() ||
7806 FuncY->isMemberLikeConstrainedFriend()) &&
7807 !FuncX->getLexicalDeclContext()->Equals(
7808 FuncY->getLexicalDeclContext())) {
7809 return false;
7810 }
7811
7812 if (!isSameAssociatedConstraint(FuncX->getTrailingRequiresClause(),
7813 FuncY->getTrailingRequiresClause()))
7814 return false;
7815
7816 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
7817 // Map to the first declaration that we've already merged into this one.
7818 // The TSI of redeclarations might not match (due to calling conventions
7819 // being inherited onto the type but not the TSI), but the TSI type of
7820 // the first declaration of the function should match across modules.
7821 FD = FD->getCanonicalDecl();
7822 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
7823 : FD->getType();
7824 };
7825 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
7826 if (!hasSameType(XT, YT)) {
7827 // We can get functions with different types on the redecl chain in C++17
7828 // if they have differing exception specifications and at least one of
7829 // the excpetion specs is unresolved.
7830 auto *XFPT = XT->getAs<FunctionProtoType>();
7831 auto *YFPT = YT->getAs<FunctionProtoType>();
7832 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
7833 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
7836 return true;
7837 return false;
7838 }
7839
7840 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
7841 hasSameOverloadableAttrs(FuncX, FuncY);
7842 }
7843
7844 // Variables with the same type and linkage match.
7845 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
7846 const auto *VarY = cast<VarDecl>(Y);
7847 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
7848 // During deserialization, we might compare variables before we load
7849 // their types. Assume the types will end up being the same.
7850 if (VarX->getType().isNull() || VarY->getType().isNull())
7851 return true;
7852
7853 if (hasSameType(VarX->getType(), VarY->getType()))
7854 return true;
7855
7856 // We can get decls with different types on the redecl chain. Eg.
7857 // template <typename T> struct S { static T Var[]; }; // #1
7858 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
7859 // Only? happens when completing an incomplete array type. In this case
7860 // when comparing #1 and #2 we should go through their element type.
7861 const ArrayType *VarXTy = getAsArrayType(VarX->getType());
7862 const ArrayType *VarYTy = getAsArrayType(VarY->getType());
7863 if (!VarXTy || !VarYTy)
7864 return false;
7865 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
7866 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
7867 }
7868 return false;
7869 }
7870
7871 // Namespaces with the same name and inlinedness match.
7872 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
7873 const auto *NamespaceY = cast<NamespaceDecl>(Y);
7874 return NamespaceX->isInline() == NamespaceY->isInline();
7875 }
7876
7877 // Identical template names and kinds match if their template parameter lists
7878 // and patterns match.
7879 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
7880 const auto *TemplateY = cast<TemplateDecl>(Y);
7881
7882 // ConceptDecl wouldn't be the same if their constraint expression differs.
7883 if (const auto *ConceptX = dyn_cast<ConceptDecl>(X)) {
7884 const auto *ConceptY = cast<ConceptDecl>(Y);
7885 if (!isSameConstraintExpr(ConceptX->getConstraintExpr(),
7886 ConceptY->getConstraintExpr()))
7887 return false;
7888 }
7889
7890 return isSameEntity(TemplateX->getTemplatedDecl(),
7891 TemplateY->getTemplatedDecl()) &&
7892 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
7893 TemplateY->getTemplateParameters());
7894 }
7895
7896 // Fields with the same name and the same type match.
7897 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
7898 const auto *FDY = cast<FieldDecl>(Y);
7899 // FIXME: Also check the bitwidth is odr-equivalent, if any.
7900 return hasSameType(FDX->getType(), FDY->getType());
7901 }
7902
7903 // Indirect fields with the same target field match.
7904 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
7905 const auto *IFDY = cast<IndirectFieldDecl>(Y);
7906 return IFDX->getAnonField()->getCanonicalDecl() ==
7907 IFDY->getAnonField()->getCanonicalDecl();
7908 }
7909
7910 // Enumerators with the same name match.
7912 // FIXME: Also check the value is odr-equivalent.
7913 return true;
7914
7915 // Using shadow declarations with the same target match.
7916 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
7917 const auto *USY = cast<UsingShadowDecl>(Y);
7918 return declaresSameEntity(USX->getTargetDecl(), USY->getTargetDecl());
7919 }
7920
7921 // Using declarations with the same qualifier match. (We already know that
7922 // the name matches.)
7923 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
7924 const auto *UY = cast<UsingDecl>(Y);
7925 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7926 UX->hasTypename() == UY->hasTypename() &&
7927 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7928 }
7929 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
7930 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
7931 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7932 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7933 }
7934 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
7935 return isSameQualifier(
7936 UX->getQualifier(),
7937 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
7938 }
7939
7940 // Using-pack declarations are only created by instantiation, and match if
7941 // they're instantiated from matching UnresolvedUsing...Decls.
7942 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
7943 return declaresSameEntity(
7944 UX->getInstantiatedFromUsingDecl(),
7945 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
7946 }
7947
7948 // Namespace alias definitions with the same target match.
7949 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
7950 const auto *NAY = cast<NamespaceAliasDecl>(Y);
7951 return NAX->getNamespace()->Equals(NAY->getNamespace());
7952 }
7953
7954 return false;
7955}
7956
7959 switch (Arg.getKind()) {
7961 return Arg;
7962
7964 return TemplateArgument(Arg.getAsExpr(), /*IsCanonical=*/true,
7965 Arg.getIsDefaulted());
7966
7968 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
7970 Arg.getIsDefaulted());
7971 }
7972
7975 /*isNullPtr*/ true, Arg.getIsDefaulted());
7976
7979 Arg.getIsDefaulted());
7980
7982 return TemplateArgument(
7985
7988
7990 return TemplateArgument(*this,
7993
7996 /*isNullPtr*/ false, Arg.getIsDefaulted());
7997
7999 bool AnyNonCanonArgs = false;
8000 auto CanonArgs = ::getCanonicalTemplateArguments(
8001 *this, Arg.pack_elements(), AnyNonCanonArgs);
8002 if (!AnyNonCanonArgs)
8003 return Arg;
8005 const_cast<ASTContext &>(*this), CanonArgs);
8006 NewArg.setIsDefaulted(Arg.getIsDefaulted());
8007 return NewArg;
8008 }
8009 }
8010
8011 // Silence GCC warning
8012 llvm_unreachable("Unhandled template argument kind");
8013}
8014
8016 const TemplateArgument &Arg2) const {
8017 if (Arg1.getKind() != Arg2.getKind())
8018 return false;
8019
8020 switch (Arg1.getKind()) {
8022 llvm_unreachable("Comparing NULL template argument");
8023
8025 return hasSameType(Arg1.getAsType(), Arg2.getAsType());
8026
8028 return Arg1.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl() ==
8030
8032 return hasSameType(Arg1.getNullPtrType(), Arg2.getNullPtrType());
8033
8038
8040 return llvm::APSInt::isSameValue(Arg1.getAsIntegral(),
8041 Arg2.getAsIntegral());
8042
8044 return Arg1.structurallyEquals(Arg2);
8045
8047 llvm::FoldingSetNodeID ID1, ID2;
8048 Arg1.getAsExpr()->Profile(ID1, *this, /*Canonical=*/true);
8049 Arg2.getAsExpr()->Profile(ID2, *this, /*Canonical=*/true);
8050 return ID1 == ID2;
8051 }
8052
8054 return llvm::equal(
8055 Arg1.getPackAsArray(), Arg2.getPackAsArray(),
8056 [&](const TemplateArgument &Arg1, const TemplateArgument &Arg2) {
8057 return isSameTemplateArgument(Arg1, Arg2);
8058 });
8059 }
8060
8061 llvm_unreachable("Unhandled template argument kind");
8062}
8063
8065 // Handle the non-qualified case efficiently.
8066 if (!T.hasLocalQualifiers()) {
8067 // Handle the common positive case fast.
8068 if (const auto *AT = dyn_cast<ArrayType>(T))
8069 return AT;
8070 }
8071
8072 // Handle the common negative case fast.
8073 if (!isa<ArrayType>(T.getCanonicalType()))
8074 return nullptr;
8075
8076 // Apply any qualifiers from the array type to the element type. This
8077 // implements C99 6.7.3p8: "If the specification of an array type includes
8078 // any type qualifiers, the element type is so qualified, not the array type."
8079
8080 // If we get here, we either have type qualifiers on the type, or we have
8081 // sugar such as a typedef in the way. If we have type qualifiers on the type
8082 // we must propagate them down into the element type.
8083
8084 SplitQualType split = T.getSplitDesugaredType();
8085 Qualifiers qs = split.Quals;
8086
8087 // If we have a simple case, just return now.
8088 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
8089 if (!ATy || qs.empty())
8090 return ATy;
8091
8092 // Otherwise, we have an array and we have qualifiers on it. Push the
8093 // qualifiers into the array element type and return a new array type.
8094 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
8095
8096 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
8097 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
8098 CAT->getSizeExpr(),
8099 CAT->getSizeModifier(),
8100 CAT->getIndexTypeCVRQualifiers()));
8101 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
8103 IAT->getSizeModifier(),
8104 IAT->getIndexTypeCVRQualifiers()));
8105
8106 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
8108 NewEltTy, DSAT->getSizeExpr(), DSAT->getSizeModifier(),
8109 DSAT->getIndexTypeCVRQualifiers()));
8110
8111 const auto *VAT = cast<VariableArrayType>(ATy);
8112 return cast<ArrayType>(
8113 getVariableArrayType(NewEltTy, VAT->getSizeExpr(), VAT->getSizeModifier(),
8114 VAT->getIndexTypeCVRQualifiers()));
8115}
8116
8118 if (getLangOpts().HLSL && T.getAddressSpace() == LangAS::hlsl_groupshared)
8119 return getLValueReferenceType(T);
8120 if (getLangOpts().HLSL && T->isConstantArrayType())
8121 return getArrayParameterType(T);
8122 if (T->isArrayType() || T->isFunctionType())
8123 return getDecayedType(T);
8124 return T;
8125}
8126
8130 return T.getUnqualifiedType();
8131}
8132
8134 // C++ [except.throw]p3:
8135 // A throw-expression initializes a temporary object, called the exception
8136 // object, the type of which is determined by removing any top-level
8137 // cv-qualifiers from the static type of the operand of throw and adjusting
8138 // the type from "array of T" or "function returning T" to "pointer to T"
8139 // or "pointer to function returning T", [...]
8141 if (T->isArrayType() || T->isFunctionType())
8142 T = getDecayedType(T);
8143 return T.getUnqualifiedType();
8144}
8145
8146/// getArrayDecayedType - Return the properly qualified result of decaying the
8147/// specified array type to a pointer. This operation is non-trivial when
8148/// handling typedefs etc. The canonical type of "T" must be an array type,
8149/// this returns a pointer to a properly qualified element of the array.
8150///
8151/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
8153 // Get the element type with 'getAsArrayType' so that we don't lose any
8154 // typedefs in the element type of the array. This also handles propagation
8155 // of type qualifiers from the array type into the element type if present
8156 // (C99 6.7.3p8).
8157 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
8158 assert(PrettyArrayType && "Not an array type!");
8159
8160 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
8161
8162 // int x[restrict 4] -> int *restrict
8164 PrettyArrayType->getIndexTypeQualifiers());
8165
8166 // int x[_Nullable] -> int * _Nullable
8167 if (auto Nullability = Ty->getNullability()) {
8168 Result = const_cast<ASTContext *>(this)->getAttributedType(*Nullability,
8169 Result, Result);
8170 }
8171 return Result;
8172}
8173
8175 return getBaseElementType(array->getElementType());
8176}
8177
8179 Qualifiers qs;
8180 while (true) {
8181 SplitQualType split = type.getSplitDesugaredType();
8182 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
8183 if (!array) break;
8184
8185 type = array->getElementType();
8187 }
8188
8189 return getQualifiedType(type, qs);
8190}
8191
8192/// getConstantArrayElementCount - Returns number of constant array elements.
8193uint64_t
8195 uint64_t ElementCount = 1;
8196 do {
8197 ElementCount *= CA->getZExtSize();
8198 CA = dyn_cast_or_null<ConstantArrayType>(
8200 } while (CA);
8201 return ElementCount;
8202}
8203
8205 const ArrayInitLoopExpr *AILE) const {
8206 if (!AILE)
8207 return 0;
8208
8209 uint64_t ElementCount = 1;
8210
8211 do {
8212 ElementCount *= AILE->getArraySize().getZExtValue();
8213 AILE = dyn_cast<ArrayInitLoopExpr>(AILE->getSubExpr());
8214 } while (AILE);
8215
8216 return ElementCount;
8217}
8218
8219/// getFloatingRank - Return a relative rank for floating point types.
8220/// This routine will assert if passed a built-in type that isn't a float.
8222 if (const auto *CT = T->getAs<ComplexType>())
8223 return getFloatingRank(CT->getElementType());
8224
8225 switch (T->castAs<BuiltinType>()->getKind()) {
8226 default: llvm_unreachable("getFloatingRank(): not a floating type");
8227 case BuiltinType::Float16: return Float16Rank;
8228 case BuiltinType::Half: return HalfRank;
8229 case BuiltinType::Float: return FloatRank;
8230 case BuiltinType::Double: return DoubleRank;
8231 case BuiltinType::LongDouble: return LongDoubleRank;
8232 case BuiltinType::Float128: return Float128Rank;
8233 case BuiltinType::BFloat16: return BFloat16Rank;
8234 case BuiltinType::Ibm128: return Ibm128Rank;
8235 }
8236}
8237
8238/// getFloatingTypeOrder - Compare the rank of the two specified floating
8239/// point types, ignoring the domain of the type (i.e. 'double' ==
8240/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
8241/// LHS < RHS, return -1.
8243 FloatingRank LHSR = getFloatingRank(LHS);
8244 FloatingRank RHSR = getFloatingRank(RHS);
8245
8246 if (LHSR == RHSR)
8247 return 0;
8248 if (LHSR > RHSR)
8249 return 1;
8250 return -1;
8251}
8252
8255 return 0;
8256 return getFloatingTypeOrder(LHS, RHS);
8257}
8258
8259/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
8260/// routine will assert if passed a built-in type that isn't an integer or enum,
8261/// or if it is not canonicalized.
8262unsigned ASTContext::getIntegerRank(const Type *T) const {
8263 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
8264
8265 // Results in this 'losing' to any type of the same size, but winning if
8266 // larger.
8267 if (const auto *EIT = dyn_cast<BitIntType>(T))
8268 return 0 + (EIT->getNumBits() << 3);
8269
8270 if (const auto *OBT = dyn_cast<OverflowBehaviorType>(T))
8271 return getIntegerRank(OBT->getUnderlyingType().getTypePtr());
8272
8273 switch (cast<BuiltinType>(T)->getKind()) {
8274 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
8275 case BuiltinType::Bool:
8276 return 1 + (getIntWidth(BoolTy) << 3);
8277 case BuiltinType::Char_S:
8278 case BuiltinType::Char_U:
8279 case BuiltinType::SChar:
8280 case BuiltinType::UChar:
8281 return 2 + (getIntWidth(CharTy) << 3);
8282 case BuiltinType::Short:
8283 case BuiltinType::UShort:
8284 return 3 + (getIntWidth(ShortTy) << 3);
8285 case BuiltinType::Int:
8286 case BuiltinType::UInt:
8287 return 4 + (getIntWidth(IntTy) << 3);
8288 case BuiltinType::Long:
8289 case BuiltinType::ULong:
8290 return 5 + (getIntWidth(LongTy) << 3);
8291 case BuiltinType::LongLong:
8292 case BuiltinType::ULongLong:
8293 return 6 + (getIntWidth(LongLongTy) << 3);
8294 case BuiltinType::Int128:
8295 case BuiltinType::UInt128:
8296 return 7 + (getIntWidth(Int128Ty) << 3);
8297
8298 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
8299 // their underlying types" [c++20 conv.rank]
8300 case BuiltinType::Char8:
8301 return getIntegerRank(UnsignedCharTy.getTypePtr());
8302 case BuiltinType::Char16:
8303 return getIntegerRank(
8304 getFromTargetType(Target->getChar16Type()).getTypePtr());
8305 case BuiltinType::Char32:
8306 return getIntegerRank(
8307 getFromTargetType(Target->getChar32Type()).getTypePtr());
8308 case BuiltinType::WChar_S:
8309 case BuiltinType::WChar_U:
8310 return getIntegerRank(
8311 getFromTargetType(Target->getWCharType()).getTypePtr());
8312 }
8313}
8314
8315/// Whether this is a promotable bitfield reference according
8316/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
8317///
8318/// \returns the type this bit-field will promote to, or NULL if no
8319/// promotion occurs.
8321 if (E->isTypeDependent() || E->isValueDependent())
8322 return {};
8323
8324 // C++ [conv.prom]p5:
8325 // If the bit-field has an enumerated type, it is treated as any other
8326 // value of that type for promotion purposes.
8328 return {};
8329
8330 // FIXME: We should not do this unless E->refersToBitField() is true. This
8331 // matters in C where getSourceBitField() will find bit-fields for various
8332 // cases where the source expression is not a bit-field designator.
8333
8334 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
8335 if (!Field)
8336 return {};
8337
8338 QualType FT = Field->getType();
8339
8340 uint64_t BitWidth = Field->getBitWidthValue();
8341 uint64_t IntSize = getTypeSize(IntTy);
8342 // C++ [conv.prom]p5:
8343 // A prvalue for an integral bit-field can be converted to a prvalue of type
8344 // int if int can represent all the values of the bit-field; otherwise, it
8345 // can be converted to unsigned int if unsigned int can represent all the
8346 // values of the bit-field. If the bit-field is larger yet, no integral
8347 // promotion applies to it.
8348 // C11 6.3.1.1/2:
8349 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
8350 // If an int can represent all values of the original type (as restricted by
8351 // the width, for a bit-field), the value is converted to an int; otherwise,
8352 // it is converted to an unsigned int.
8353 //
8354 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
8355 // We perform that promotion here to match GCC and C++.
8356 // FIXME: C does not permit promotion of an enum bit-field whose rank is
8357 // greater than that of 'int'. We perform that promotion to match GCC.
8358 //
8359 // C23 6.3.1.1p2:
8360 // The value from a bit-field of a bit-precise integer type is converted to
8361 // the corresponding bit-precise integer type. (The rest is the same as in
8362 // C11.)
8363 if (QualType QT = Field->getType(); QT->isBitIntType())
8364 return QT;
8365
8366 if (BitWidth < IntSize)
8367 return IntTy;
8368
8369 if (BitWidth == IntSize)
8370 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
8371
8372 // Bit-fields wider than int are not subject to promotions, and therefore act
8373 // like the base type. GCC has some weird bugs in this area that we
8374 // deliberately do not follow (GCC follows a pre-standard resolution to
8375 // C's DR315 which treats bit-width as being part of the type, and this leaks
8376 // into their semantics in some cases).
8377 return {};
8378}
8379
8380/// getPromotedIntegerType - Returns the type that Promotable will
8381/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
8382/// integer type.
8384 assert(!Promotable.isNull());
8385 assert(isPromotableIntegerType(Promotable));
8386 if (const auto *ED = Promotable->getAsEnumDecl())
8387 return ED->getPromotionType();
8388
8389 // OverflowBehaviorTypes promote their underlying type and preserve OBT
8390 // qualifier.
8391 if (const auto *OBT = Promotable->getAs<OverflowBehaviorType>()) {
8392 QualType PromotedUnderlying =
8393 getPromotedIntegerType(OBT->getUnderlyingType());
8394 return getOverflowBehaviorType(OBT->getBehaviorKind(), PromotedUnderlying);
8395 }
8396
8397 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
8398 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
8399 // (3.9.1) can be converted to a prvalue of the first of the following
8400 // types that can represent all the values of its underlying type:
8401 // int, unsigned int, long int, unsigned long int, long long int, or
8402 // unsigned long long int [...]
8403 // FIXME: Is there some better way to compute this?
8404 if (BT->getKind() == BuiltinType::WChar_S ||
8405 BT->getKind() == BuiltinType::WChar_U ||
8406 BT->getKind() == BuiltinType::Char8 ||
8407 BT->getKind() == BuiltinType::Char16 ||
8408 BT->getKind() == BuiltinType::Char32) {
8409 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
8410 uint64_t FromSize = getTypeSize(BT);
8411 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
8413 for (const auto &PT : PromoteTypes) {
8414 uint64_t ToSize = getTypeSize(PT);
8415 if (FromSize < ToSize ||
8416 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
8417 return PT;
8418 }
8419 llvm_unreachable("char type should fit into long long");
8420 }
8421 }
8422
8423 // At this point, we should have a signed or unsigned integer type.
8424 if (Promotable->isSignedIntegerType())
8425 return IntTy;
8426 uint64_t PromotableSize = getIntWidth(Promotable);
8427 uint64_t IntSize = getIntWidth(IntTy);
8428 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
8429 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
8430}
8431
8432/// Recurses in pointer/array types until it finds an objc retainable
8433/// type and returns its ownership.
8435 while (!T.isNull()) {
8436 if (T.getObjCLifetime() != Qualifiers::OCL_None)
8437 return T.getObjCLifetime();
8438 if (T->isArrayType())
8439 T = getBaseElementType(T);
8440 else if (const auto *PT = T->getAs<PointerType>())
8441 T = PT->getPointeeType();
8442 else if (const auto *RT = T->getAs<ReferenceType>())
8443 T = RT->getPointeeType();
8444 else
8445 break;
8446 }
8447
8448 return Qualifiers::OCL_None;
8449}
8450
8451static const Type *getIntegerTypeForEnum(const EnumType *ET) {
8452 // Incomplete enum types are not treated as integer types.
8453 // FIXME: In C++, enum types are never integer types.
8454 const EnumDecl *ED = ET->getDecl()->getDefinitionOrSelf();
8455 if (ED->isComplete() && !ED->isScoped())
8456 return ED->getIntegerType().getTypePtr();
8457 return nullptr;
8458}
8459
8460/// getIntegerTypeOrder - Returns the highest ranked integer type:
8461/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
8462/// LHS < RHS, return -1.
8464 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
8465 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
8466
8467 // Unwrap enums to their underlying type.
8468 if (const auto *ET = dyn_cast<EnumType>(LHSC))
8469 LHSC = getIntegerTypeForEnum(ET);
8470 if (const auto *ET = dyn_cast<EnumType>(RHSC))
8471 RHSC = getIntegerTypeForEnum(ET);
8472
8473 if (LHSC == RHSC) return 0;
8474
8475 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
8476 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
8477
8478 unsigned LHSRank = getIntegerRank(LHSC);
8479 unsigned RHSRank = getIntegerRank(RHSC);
8480
8481 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
8482 if (LHSRank == RHSRank) return 0;
8483 return LHSRank > RHSRank ? 1 : -1;
8484 }
8485
8486 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
8487 if (LHSUnsigned) {
8488 // If the unsigned [LHS] type is larger, return it.
8489 if (LHSRank >= RHSRank)
8490 return 1;
8491
8492 // If the signed type can represent all values of the unsigned type, it
8493 // wins. Because we are dealing with 2's complement and types that are
8494 // powers of two larger than each other, this is always safe.
8495 return -1;
8496 }
8497
8498 // If the unsigned [RHS] type is larger, return it.
8499 if (RHSRank >= LHSRank)
8500 return -1;
8501
8502 // If the signed type can represent all values of the unsigned type, it
8503 // wins. Because we are dealing with 2's complement and types that are
8504 // powers of two larger than each other, this is always safe.
8505 return 1;
8506}
8507
8509 if (CFConstantStringTypeDecl)
8510 return CFConstantStringTypeDecl;
8511
8512 assert(!CFConstantStringTagDecl &&
8513 "tag and typedef should be initialized together");
8514 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
8515 CFConstantStringTagDecl->startDefinition();
8516
8517 struct {
8518 QualType Type;
8519 const char *Name;
8520 } Fields[5];
8521 unsigned Count = 0;
8522
8523 /// Objective-C ABI
8524 ///
8525 /// typedef struct __NSConstantString_tag {
8526 /// const int *isa;
8527 /// int flags;
8528 /// const char *str;
8529 /// long length;
8530 /// } __NSConstantString;
8531 ///
8532 /// Swift ABI (4.1, 4.2)
8533 ///
8534 /// typedef struct __NSConstantString_tag {
8535 /// uintptr_t _cfisa;
8536 /// uintptr_t _swift_rc;
8537 /// _Atomic(uint64_t) _cfinfoa;
8538 /// const char *_ptr;
8539 /// uint32_t _length;
8540 /// } __NSConstantString;
8541 ///
8542 /// Swift ABI (5.0)
8543 ///
8544 /// typedef struct __NSConstantString_tag {
8545 /// uintptr_t _cfisa;
8546 /// uintptr_t _swift_rc;
8547 /// _Atomic(uint64_t) _cfinfoa;
8548 /// const char *_ptr;
8549 /// uintptr_t _length;
8550 /// } __NSConstantString;
8551
8552 const auto CFRuntime = getLangOpts().CFRuntime;
8553 if (static_cast<unsigned>(CFRuntime) <
8554 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
8555 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
8556 Fields[Count++] = { IntTy, "flags" };
8557 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
8558 Fields[Count++] = { LongTy, "length" };
8559 } else {
8560 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
8561 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
8562 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
8563 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
8566 Fields[Count++] = { IntTy, "_ptr" };
8567 else
8568 Fields[Count++] = { getUIntPtrType(), "_ptr" };
8569 }
8570
8571 // Create fields
8572 for (unsigned i = 0; i < Count; ++i) {
8573 FieldDecl *Field =
8574 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
8575 SourceLocation(), &Idents.get(Fields[i].Name),
8576 Fields[i].Type, /*TInfo=*/nullptr,
8577 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8578 Field->setAccess(AS_public);
8579 CFConstantStringTagDecl->addDecl(Field);
8580 }
8581
8582 CFConstantStringTagDecl->completeDefinition();
8583 // This type is designed to be compatible with NSConstantString, but cannot
8584 // use the same name, since NSConstantString is an interface.
8585 CanQualType tagType = getCanonicalTagType(CFConstantStringTagDecl);
8586 CFConstantStringTypeDecl =
8587 buildImplicitTypedef(tagType, "__NSConstantString");
8588
8589 return CFConstantStringTypeDecl;
8590}
8591
8593 if (!CFConstantStringTagDecl)
8594 getCFConstantStringDecl(); // Build the tag and the typedef.
8595 return CFConstantStringTagDecl;
8596}
8597
8598// getCFConstantStringType - Return the type used for constant CFStrings.
8603
8605 if (ObjCSuperType.isNull()) {
8606 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
8607 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
8608 ObjCSuperType = getCanonicalTagType(ObjCSuperTypeDecl);
8609 }
8610 return ObjCSuperType;
8611}
8612
8614 const auto *TT = T->castAs<TypedefType>();
8615 CFConstantStringTypeDecl = cast<TypedefDecl>(TT->getDecl());
8616 CFConstantStringTagDecl = TT->castAsRecordDecl();
8617}
8618
8620 if (BlockDescriptorType)
8621 return getCanonicalTagType(BlockDescriptorType);
8622
8623 RecordDecl *RD;
8624 // FIXME: Needs the FlagAppleBlock bit.
8625 RD = buildImplicitRecord("__block_descriptor");
8626 RD->startDefinition();
8627
8628 QualType FieldTypes[] = {
8631 };
8632
8633 static const char *const FieldNames[] = {
8634 "reserved",
8635 "Size"
8636 };
8637
8638 for (size_t i = 0; i < 2; ++i) {
8640 *this, RD, SourceLocation(), SourceLocation(),
8641 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8642 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8643 Field->setAccess(AS_public);
8644 RD->addDecl(Field);
8645 }
8646
8647 RD->completeDefinition();
8648
8649 BlockDescriptorType = RD;
8650
8651 return getCanonicalTagType(BlockDescriptorType);
8652}
8653
8655 if (BlockDescriptorExtendedType)
8656 return getCanonicalTagType(BlockDescriptorExtendedType);
8657
8658 RecordDecl *RD;
8659 // FIXME: Needs the FlagAppleBlock bit.
8660 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
8661 RD->startDefinition();
8662
8663 QualType FieldTypes[] = {
8668 };
8669
8670 static const char *const FieldNames[] = {
8671 "reserved",
8672 "Size",
8673 "CopyFuncPtr",
8674 "DestroyFuncPtr"
8675 };
8676
8677 for (size_t i = 0; i < 4; ++i) {
8679 *this, RD, SourceLocation(), SourceLocation(),
8680 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8681 /*BitWidth=*/nullptr,
8682 /*Mutable=*/false, ICIS_NoInit);
8683 Field->setAccess(AS_public);
8684 RD->addDecl(Field);
8685 }
8686
8687 RD->completeDefinition();
8688
8689 BlockDescriptorExtendedType = RD;
8690 return getCanonicalTagType(BlockDescriptorExtendedType);
8691}
8692
8694 const auto *BT = dyn_cast<BuiltinType>(T);
8695
8696 if (!BT) {
8697 if (isa<PipeType>(T))
8698 return OCLTK_Pipe;
8699
8700 return OCLTK_Default;
8701 }
8702
8703 switch (BT->getKind()) {
8704#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8705 case BuiltinType::Id: \
8706 return OCLTK_Image;
8707#include "clang/Basic/OpenCLImageTypes.def"
8708
8709 case BuiltinType::OCLClkEvent:
8710 return OCLTK_ClkEvent;
8711
8712 case BuiltinType::OCLEvent:
8713 return OCLTK_Event;
8714
8715 case BuiltinType::OCLQueue:
8716 return OCLTK_Queue;
8717
8718 case BuiltinType::OCLReserveID:
8719 return OCLTK_ReserveID;
8720
8721 case BuiltinType::OCLSampler:
8722 return OCLTK_Sampler;
8723
8724 default:
8725 return OCLTK_Default;
8726 }
8727}
8728
8730 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
8731}
8732
8733/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
8734/// requires copy/dispose. Note that this must match the logic
8735/// in buildByrefHelpers.
8737 const VarDecl *D) {
8738 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
8739 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
8740 if (!copyExpr && record->hasTrivialDestructor()) return false;
8741
8742 return true;
8743 }
8744
8746 return true;
8747
8748 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
8749 // move or destroy.
8751 return true;
8752
8753 if (!Ty->isObjCRetainableType()) return false;
8754
8755 Qualifiers qs = Ty.getQualifiers();
8756
8757 // If we have lifetime, that dominates.
8758 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
8759 switch (lifetime) {
8760 case Qualifiers::OCL_None: llvm_unreachable("impossible");
8761
8762 // These are just bits as far as the runtime is concerned.
8765 return false;
8766
8767 // These cases should have been taken care of when checking the type's
8768 // non-triviality.
8771 llvm_unreachable("impossible");
8772 }
8773 llvm_unreachable("fell out of lifetime switch!");
8774 }
8775 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
8777}
8778
8780 Qualifiers::ObjCLifetime &LifeTime,
8781 bool &HasByrefExtendedLayout) const {
8782 if (!getLangOpts().ObjC ||
8783 getLangOpts().getGC() != LangOptions::NonGC)
8784 return false;
8785
8786 HasByrefExtendedLayout = false;
8787 if (Ty->isRecordType()) {
8788 HasByrefExtendedLayout = true;
8789 LifeTime = Qualifiers::OCL_None;
8790 } else if ((LifeTime = Ty.getObjCLifetime())) {
8791 // Honor the ARC qualifiers.
8792 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
8793 // The MRR rule.
8795 } else {
8796 LifeTime = Qualifiers::OCL_None;
8797 }
8798 return true;
8799}
8800
8802 assert(Target && "Expected target to be initialized");
8803 const llvm::Triple &T = Target->getTriple();
8804 // Windows is LLP64 rather than LP64
8805 if (T.isOSWindows() && T.isArch64Bit())
8806 return UnsignedLongLongTy;
8807 return UnsignedLongTy;
8808}
8809
8811 assert(Target && "Expected target to be initialized");
8812 const llvm::Triple &T = Target->getTriple();
8813 // Windows is LLP64 rather than LP64
8814 if (T.isOSWindows() && T.isArch64Bit())
8815 return LongLongTy;
8816 return LongTy;
8817}
8818
8820 if (!ObjCInstanceTypeDecl)
8821 ObjCInstanceTypeDecl =
8822 buildImplicitTypedef(getObjCIdType(), "instancetype");
8823 return ObjCInstanceTypeDecl;
8824}
8825
8826// This returns true if a type has been typedefed to BOOL:
8827// typedef <type> BOOL;
8829 if (const auto *TT = dyn_cast<TypedefType>(T))
8830 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
8831 return II->isStr("BOOL");
8832
8833 return false;
8834}
8835
8836/// getObjCEncodingTypeSize returns size of type for objective-c encoding
8837/// purpose.
8839 if (!type->isIncompleteArrayType() && type->isIncompleteType())
8840 return CharUnits::Zero();
8841
8843
8844 // Make all integer and enum types at least as large as an int
8845 if (sz.isPositive() && type->isIntegralOrEnumerationType())
8846 sz = std::max(sz, getTypeSizeInChars(IntTy));
8847 // Treat arrays as pointers, since that's how they're passed in.
8848 else if (type->isArrayType())
8850 return sz;
8851}
8852
8859
8862 if (!VD->isInline())
8864
8865 // In almost all cases, it's a weak definition.
8866 auto *First = VD->getFirstDecl();
8867 if (First->isInlineSpecified() || !First->isStaticDataMember())
8869
8870 // If there's a file-context declaration in this translation unit, it's a
8871 // non-discardable definition.
8872 for (auto *D : VD->redecls())
8874 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
8876
8877 // If we've not seen one yet, we don't know.
8879}
8880
8881static std::string charUnitsToString(const CharUnits &CU) {
8882 return llvm::itostr(CU.getQuantity());
8883}
8884
8885/// getObjCEncodingForBlock - Return the encoded type for this block
8886/// declaration.
8888 std::string S;
8889
8890 const BlockDecl *Decl = Expr->getBlockDecl();
8891 QualType BlockTy =
8893 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
8894 // Encode result type.
8895 if (getLangOpts().EncodeExtendedBlockSig)
8897 true /*Extended*/);
8898 else
8899 getObjCEncodingForType(BlockReturnTy, S);
8900 // Compute size of all parameters.
8901 // Start with computing size of a pointer in number of bytes.
8902 // FIXME: There might(should) be a better way of doing this computation!
8904 CharUnits ParmOffset = PtrSize;
8905 for (auto *PI : Decl->parameters()) {
8906 QualType PType = PI->getType();
8908 if (sz.isZero())
8909 continue;
8910 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
8911 ParmOffset += sz;
8912 }
8913 // Size of the argument frame
8914 S += charUnitsToString(ParmOffset);
8915 // Block pointer and offset.
8916 S += "@?0";
8917
8918 // Argument types.
8919 ParmOffset = PtrSize;
8920 for (auto *PVDecl : Decl->parameters()) {
8921 QualType PType = PVDecl->getOriginalType();
8922 if (const auto *AT =
8923 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8924 // Use array's original type only if it has known number of
8925 // elements.
8926 if (!isa<ConstantArrayType>(AT))
8927 PType = PVDecl->getType();
8928 } else if (PType->isFunctionType())
8929 PType = PVDecl->getType();
8930 if (getLangOpts().EncodeExtendedBlockSig)
8932 S, true /*Extended*/);
8933 else
8934 getObjCEncodingForType(PType, S);
8935 S += charUnitsToString(ParmOffset);
8936 ParmOffset += getObjCEncodingTypeSize(PType);
8937 }
8938
8939 return S;
8940}
8941
8942std::string
8944 std::string S;
8945 // Encode result type.
8946 getObjCEncodingForType(Decl->getReturnType(), S);
8947 CharUnits ParmOffset;
8948 // Compute size of all parameters.
8949 for (auto *PI : Decl->parameters()) {
8950 QualType PType = PI->getType();
8952 if (sz.isZero())
8953 continue;
8954
8955 assert(sz.isPositive() &&
8956 "getObjCEncodingForFunctionDecl - Incomplete param type");
8957 ParmOffset += sz;
8958 }
8959 S += charUnitsToString(ParmOffset);
8960 ParmOffset = CharUnits::Zero();
8961
8962 // Argument types.
8963 for (auto *PVDecl : Decl->parameters()) {
8964 QualType PType = PVDecl->getOriginalType();
8965 if (const auto *AT =
8966 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8967 // Use array's original type only if it has known number of
8968 // elements.
8969 if (!isa<ConstantArrayType>(AT))
8970 PType = PVDecl->getType();
8971 } else if (PType->isFunctionType())
8972 PType = PVDecl->getType();
8973 getObjCEncodingForType(PType, S);
8974 S += charUnitsToString(ParmOffset);
8975 ParmOffset += getObjCEncodingTypeSize(PType);
8976 }
8977
8978 return S;
8979}
8980
8981/// getObjCEncodingForMethodParameter - Return the encoded type for a single
8982/// method parameter or return type. If Extended, include class names and
8983/// block object types.
8985 QualType T, std::string& S,
8986 bool Extended) const {
8987 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
8989 // Encode parameter type.
8990 ObjCEncOptions Options = ObjCEncOptions()
8991 .setExpandPointedToStructures()
8992 .setExpandStructures()
8993 .setIsOutermostType();
8994 if (Extended)
8995 Options.setEncodeBlockParameters().setEncodeClassNames();
8996 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
8997}
8998
8999/// getObjCEncodingForMethodDecl - Return the encoded type for this method
9000/// declaration.
9002 bool Extended) const {
9003 // FIXME: This is not very efficient.
9004 // Encode return type.
9005 std::string S;
9006 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
9007 Decl->getReturnType(), S, Extended);
9008 // Compute size of all parameters.
9009 // Start with computing size of a pointer in number of bytes.
9010 // FIXME: There might(should) be a better way of doing this computation!
9012 // The first two arguments (self and _cmd) are pointers; account for
9013 // their size.
9014 CharUnits ParmOffset = 2 * PtrSize;
9015 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
9016 E = Decl->sel_param_end(); PI != E; ++PI) {
9017 QualType PType = (*PI)->getType();
9019 if (sz.isZero())
9020 continue;
9021
9022 assert(sz.isPositive() &&
9023 "getObjCEncodingForMethodDecl - Incomplete param type");
9024 ParmOffset += sz;
9025 }
9026 S += charUnitsToString(ParmOffset);
9027 S += "@0:";
9028 S += charUnitsToString(PtrSize);
9029
9030 // Argument types.
9031 ParmOffset = 2 * PtrSize;
9032 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
9033 E = Decl->sel_param_end(); PI != E; ++PI) {
9034 const ParmVarDecl *PVDecl = *PI;
9035 QualType PType = PVDecl->getOriginalType();
9036 if (const auto *AT =
9037 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
9038 // Use array's original type only if it has known number of
9039 // elements.
9040 if (!isa<ConstantArrayType>(AT))
9041 PType = PVDecl->getType();
9042 } else if (PType->isFunctionType())
9043 PType = PVDecl->getType();
9045 PType, S, Extended);
9046 S += charUnitsToString(ParmOffset);
9047 ParmOffset += getObjCEncodingTypeSize(PType);
9048 }
9049
9050 return S;
9051}
9052
9055 const ObjCPropertyDecl *PD,
9056 const Decl *Container) const {
9057 if (!Container)
9058 return nullptr;
9059 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
9060 for (auto *PID : CID->property_impls())
9061 if (PID->getPropertyDecl() == PD)
9062 return PID;
9063 } else {
9064 const auto *OID = cast<ObjCImplementationDecl>(Container);
9065 for (auto *PID : OID->property_impls())
9066 if (PID->getPropertyDecl() == PD)
9067 return PID;
9068 }
9069 return nullptr;
9070}
9071
9072/// getObjCEncodingForPropertyDecl - Return the encoded type for this
9073/// property declaration. If non-NULL, Container must be either an
9074/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
9075/// NULL when getting encodings for protocol properties.
9076/// Property attributes are stored as a comma-delimited C string. The simple
9077/// attributes readonly and bycopy are encoded as single characters. The
9078/// parametrized attributes, getter=name, setter=name, and ivar=name, are
9079/// encoded as single characters, followed by an identifier. Property types
9080/// are also encoded as a parametrized attribute. The characters used to encode
9081/// these attributes are defined by the following enumeration:
9082/// @code
9083/// enum PropertyAttributes {
9084/// kPropertyReadOnly = 'R', // property is read-only.
9085/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
9086/// kPropertyByref = '&', // property is a reference to the value last assigned
9087/// kPropertyDynamic = 'D', // property is dynamic
9088/// kPropertyGetter = 'G', // followed by getter selector name
9089/// kPropertySetter = 'S', // followed by setter selector name
9090/// kPropertyInstanceVariable = 'V' // followed by instance variable name
9091/// kPropertyType = 'T' // followed by old-style type encoding.
9092/// kPropertyWeak = 'W' // 'weak' property
9093/// kPropertyStrong = 'P' // property GC'able
9094/// kPropertyNonAtomic = 'N' // property non-atomic
9095/// kPropertyOptional = '?' // property optional
9096/// };
9097/// @endcode
9098std::string
9100 const Decl *Container) const {
9101 // Collect information from the property implementation decl(s).
9102 bool Dynamic = false;
9103 ObjCPropertyImplDecl *SynthesizePID = nullptr;
9104
9105 if (ObjCPropertyImplDecl *PropertyImpDecl =
9107 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
9108 Dynamic = true;
9109 else
9110 SynthesizePID = PropertyImpDecl;
9111 }
9112
9113 // FIXME: This is not very efficient.
9114 std::string S = "T";
9115
9116 // Encode result type.
9117 // GCC has some special rules regarding encoding of properties which
9118 // closely resembles encoding of ivars.
9120
9121 if (PD->isOptional())
9122 S += ",?";
9123
9124 if (PD->isReadOnly()) {
9125 S += ",R";
9127 S += ",C";
9129 S += ",&";
9131 S += ",W";
9132 } else {
9133 switch (PD->getSetterKind()) {
9134 case ObjCPropertyDecl::Assign: break;
9135 case ObjCPropertyDecl::Copy: S += ",C"; break;
9136 case ObjCPropertyDecl::Retain: S += ",&"; break;
9137 case ObjCPropertyDecl::Weak: S += ",W"; break;
9138 }
9139 }
9140
9141 // It really isn't clear at all what this means, since properties
9142 // are "dynamic by default".
9143 if (Dynamic)
9144 S += ",D";
9145
9147 S += ",N";
9148
9150 S += ",G";
9151 S += PD->getGetterName().getAsString();
9152 }
9153
9155 S += ",S";
9156 S += PD->getSetterName().getAsString();
9157 }
9158
9159 if (SynthesizePID) {
9160 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
9161 S += ",V";
9162 S += OID->getNameAsString();
9163 }
9164
9165 // FIXME: OBJCGC: weak & strong
9166 return S;
9167}
9168
9169/// getLegacyIntegralTypeEncoding -
9170/// Another legacy compatibility encoding: 32-bit longs are encoded as
9171/// 'l' or 'L' , but not always. For typedefs, we need to use
9172/// 'i' or 'I' instead if encoding a struct field, or a pointer!
9174 if (PointeeTy->getAs<TypedefType>()) {
9175 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
9176 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
9177 PointeeTy = UnsignedIntTy;
9178 else
9179 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
9180 PointeeTy = IntTy;
9181 }
9182 }
9183}
9184
9186 const FieldDecl *Field,
9187 QualType *NotEncodedT) const {
9188 // We follow the behavior of gcc, expanding structures which are
9189 // directly pointed to, and expanding embedded structures. Note that
9190 // these rules are sufficient to prevent recursive encoding of the
9191 // same type.
9192 getObjCEncodingForTypeImpl(T, S,
9193 ObjCEncOptions()
9194 .setExpandPointedToStructures()
9195 .setExpandStructures()
9196 .setIsOutermostType(),
9197 Field, NotEncodedT);
9198}
9199
9201 std::string& S) const {
9202 // Encode result type.
9203 // GCC has some special rules regarding encoding of properties which
9204 // closely resembles encoding of ivars.
9205 getObjCEncodingForTypeImpl(T, S,
9206 ObjCEncOptions()
9207 .setExpandPointedToStructures()
9208 .setExpandStructures()
9209 .setIsOutermostType()
9210 .setEncodingProperty(),
9211 /*Field=*/nullptr);
9212}
9213
9215 const BuiltinType *BT) {
9217 switch (kind) {
9218 case BuiltinType::Void: return 'v';
9219 case BuiltinType::Bool: return 'B';
9220 case BuiltinType::Char8:
9221 case BuiltinType::Char_U:
9222 case BuiltinType::UChar: return 'C';
9223 case BuiltinType::Char16:
9224 case BuiltinType::UShort: return 'S';
9225 case BuiltinType::Char32:
9226 case BuiltinType::UInt: return 'I';
9227 case BuiltinType::ULong:
9228 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
9229 case BuiltinType::UInt128: return 'T';
9230 case BuiltinType::ULongLong: return 'Q';
9231 case BuiltinType::Char_S:
9232 case BuiltinType::SChar: return 'c';
9233 case BuiltinType::Short: return 's';
9234 case BuiltinType::WChar_S:
9235 case BuiltinType::WChar_U:
9236 case BuiltinType::Int: return 'i';
9237 case BuiltinType::Long:
9238 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
9239 case BuiltinType::LongLong: return 'q';
9240 case BuiltinType::Int128: return 't';
9241 case BuiltinType::Float: return 'f';
9242 case BuiltinType::Double: return 'd';
9243 case BuiltinType::LongDouble: return 'D';
9244 case BuiltinType::NullPtr: return '*'; // like char*
9245
9246 case BuiltinType::BFloat16:
9247 case BuiltinType::Float16:
9248 case BuiltinType::Float128:
9249 case BuiltinType::Ibm128:
9250 case BuiltinType::Half:
9251 case BuiltinType::ShortAccum:
9252 case BuiltinType::Accum:
9253 case BuiltinType::LongAccum:
9254 case BuiltinType::UShortAccum:
9255 case BuiltinType::UAccum:
9256 case BuiltinType::ULongAccum:
9257 case BuiltinType::ShortFract:
9258 case BuiltinType::Fract:
9259 case BuiltinType::LongFract:
9260 case BuiltinType::UShortFract:
9261 case BuiltinType::UFract:
9262 case BuiltinType::ULongFract:
9263 case BuiltinType::SatShortAccum:
9264 case BuiltinType::SatAccum:
9265 case BuiltinType::SatLongAccum:
9266 case BuiltinType::SatUShortAccum:
9267 case BuiltinType::SatUAccum:
9268 case BuiltinType::SatULongAccum:
9269 case BuiltinType::SatShortFract:
9270 case BuiltinType::SatFract:
9271 case BuiltinType::SatLongFract:
9272 case BuiltinType::SatUShortFract:
9273 case BuiltinType::SatUFract:
9274 case BuiltinType::SatULongFract:
9275 // FIXME: potentially need @encodes for these!
9276 return ' ';
9277
9278#define SVE_TYPE(Name, Id, SingletonId) \
9279 case BuiltinType::Id:
9280#include "clang/Basic/AArch64ACLETypes.def"
9281#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9282#include "clang/Basic/RISCVVTypes.def"
9283#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9284#include "clang/Basic/WebAssemblyReferenceTypes.def"
9285#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
9286#include "clang/Basic/AMDGPUTypes.def"
9287 {
9288 DiagnosticsEngine &Diags = C->getDiagnostics();
9289 Diags.Report(diag::err_unsupported_objc_primitive_encoding)
9290 << QualType(BT, 0);
9291 return ' ';
9292 }
9293
9294 case BuiltinType::ObjCId:
9295 case BuiltinType::ObjCClass:
9296 case BuiltinType::ObjCSel:
9297 llvm_unreachable("@encoding ObjC primitive type");
9298
9299 // OpenCL and placeholder types don't need @encodings.
9300#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
9301 case BuiltinType::Id:
9302#include "clang/Basic/OpenCLImageTypes.def"
9303#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9304 case BuiltinType::Id:
9305#include "clang/Basic/OpenCLExtensionTypes.def"
9306 case BuiltinType::OCLEvent:
9307 case BuiltinType::OCLClkEvent:
9308 case BuiltinType::OCLQueue:
9309 case BuiltinType::OCLReserveID:
9310 case BuiltinType::OCLSampler:
9311 case BuiltinType::Dependent:
9312#define PPC_VECTOR_TYPE(Name, Id, Size) \
9313 case BuiltinType::Id:
9314#include "clang/Basic/PPCTypes.def"
9315#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9316#include "clang/Basic/HLSLIntangibleTypes.def"
9317#define BUILTIN_TYPE(KIND, ID)
9318#define PLACEHOLDER_TYPE(KIND, ID) \
9319 case BuiltinType::KIND:
9320#include "clang/AST/BuiltinTypes.def"
9321 llvm_unreachable("invalid builtin type for @encode");
9322 }
9323 llvm_unreachable("invalid BuiltinType::Kind value");
9324}
9325
9326static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED) {
9328
9329 // The encoding of an non-fixed enum type is always 'i', regardless of size.
9330 if (!Enum->isFixed())
9331 return 'i';
9332
9333 // The encoding of a fixed enum type matches its fixed underlying type.
9334 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
9336}
9337
9338static void EncodeBitField(const ASTContext *Ctx, std::string& S,
9339 QualType T, const FieldDecl *FD) {
9340 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
9341 S += 'b';
9342 // The NeXT runtime encodes bit fields as b followed by the number of bits.
9343 // The GNU runtime requires more information; bitfields are encoded as b,
9344 // then the offset (in bits) of the first element, then the type of the
9345 // bitfield, then the size in bits. For example, in this structure:
9346 //
9347 // struct
9348 // {
9349 // int integer;
9350 // int flags:2;
9351 // };
9352 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
9353 // runtime, but b32i2 for the GNU runtime. The reason for this extra
9354 // information is not especially sensible, but we're stuck with it for
9355 // compatibility with GCC, although providing it breaks anything that
9356 // actually uses runtime introspection and wants to work on both runtimes...
9357 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
9358 uint64_t Offset;
9359
9360 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
9361 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), IVD);
9362 } else {
9363 const RecordDecl *RD = FD->getParent();
9364 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
9365 Offset = RL.getFieldOffset(FD->getFieldIndex());
9366 }
9367
9368 S += llvm::utostr(Offset);
9369
9370 if (const auto *ET = T->getAsCanonical<EnumType>())
9371 S += ObjCEncodingForEnumDecl(Ctx, ET->getDecl());
9372 else {
9373 const auto *BT = T->castAs<BuiltinType>();
9374 S += getObjCEncodingForPrimitiveType(Ctx, BT);
9375 }
9376 }
9377 S += llvm::utostr(FD->getBitWidthValue());
9378}
9379
9380// Helper function for determining whether the encoded type string would include
9381// a template specialization type.
9383 bool VisitBasesAndFields) {
9384 T = T->getBaseElementTypeUnsafe();
9385
9386 if (auto *PT = T->getAs<PointerType>())
9388 PT->getPointeeType().getTypePtr(), false);
9389
9390 auto *CXXRD = T->getAsCXXRecordDecl();
9391
9392 if (!CXXRD)
9393 return false;
9394
9396 return true;
9397
9398 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
9399 return false;
9400
9401 for (const auto &B : CXXRD->bases())
9402 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
9403 true))
9404 return true;
9405
9406 for (auto *FD : CXXRD->fields())
9407 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
9408 true))
9409 return true;
9410
9411 return false;
9412}
9413
9414// FIXME: Use SmallString for accumulating string.
9415void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
9416 const ObjCEncOptions Options,
9417 const FieldDecl *FD,
9418 QualType *NotEncodedT) const {
9420 switch (CT->getTypeClass()) {
9421 case Type::Builtin:
9422 case Type::Enum:
9423 if (FD && FD->isBitField())
9424 return EncodeBitField(this, S, T, FD);
9425 if (const auto *BT = dyn_cast<BuiltinType>(CT))
9426 S += getObjCEncodingForPrimitiveType(this, BT);
9427 else
9428 S += ObjCEncodingForEnumDecl(this, cast<EnumType>(CT)->getDecl());
9429 return;
9430
9431 case Type::Complex:
9432 S += 'j';
9433 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
9434 ObjCEncOptions(),
9435 /*Field=*/nullptr);
9436 return;
9437
9438 case Type::Atomic:
9439 S += 'A';
9440 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
9441 ObjCEncOptions(),
9442 /*Field=*/nullptr);
9443 return;
9444
9445 // encoding for pointer or reference types.
9446 case Type::Pointer:
9447 case Type::LValueReference:
9448 case Type::RValueReference: {
9449 QualType PointeeTy;
9450 if (isa<PointerType>(CT)) {
9451 const auto *PT = T->castAs<PointerType>();
9452 if (PT->isObjCSelType()) {
9453 S += ':';
9454 return;
9455 }
9456 PointeeTy = PT->getPointeeType();
9457 } else {
9458 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
9459 }
9460
9461 bool isReadOnly = false;
9462 // For historical/compatibility reasons, the read-only qualifier of the
9463 // pointee gets emitted _before_ the '^'. The read-only qualifier of
9464 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
9465 // Also, do not emit the 'r' for anything but the outermost type!
9466 if (T->getAs<TypedefType>()) {
9467 if (Options.IsOutermostType() && T.isConstQualified()) {
9468 isReadOnly = true;
9469 S += 'r';
9470 }
9471 } else if (Options.IsOutermostType()) {
9472 QualType P = PointeeTy;
9473 while (auto PT = P->getAs<PointerType>())
9474 P = PT->getPointeeType();
9475 if (P.isConstQualified()) {
9476 isReadOnly = true;
9477 S += 'r';
9478 }
9479 }
9480 if (isReadOnly) {
9481 // Another legacy compatibility encoding. Some ObjC qualifier and type
9482 // combinations need to be rearranged.
9483 // Rewrite "in const" from "nr" to "rn"
9484 if (StringRef(S).ends_with("nr"))
9485 S.replace(S.end()-2, S.end(), "rn");
9486 }
9487
9488 if (PointeeTy->isCharType()) {
9489 // char pointer types should be encoded as '*' unless it is a
9490 // type that has been typedef'd to 'BOOL'.
9491 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
9492 S += '*';
9493 return;
9494 }
9495 } else if (const auto *RTy = PointeeTy->getAsCanonical<RecordType>()) {
9496 const IdentifierInfo *II = RTy->getDecl()->getIdentifier();
9497 // GCC binary compat: Need to convert "struct objc_class *" to "#".
9498 if (II == &Idents.get("objc_class")) {
9499 S += '#';
9500 return;
9501 }
9502 // GCC binary compat: Need to convert "struct objc_object *" to "@".
9503 if (II == &Idents.get("objc_object")) {
9504 S += '@';
9505 return;
9506 }
9507 // If the encoded string for the class includes template names, just emit
9508 // "^v" for pointers to the class.
9509 if (getLangOpts().CPlusPlus &&
9510 (!getLangOpts().EncodeCXXClassTemplateSpec &&
9512 RTy, Options.ExpandPointedToStructures()))) {
9513 S += "^v";
9514 return;
9515 }
9516 // fall through...
9517 }
9518 S += '^';
9520
9521 ObjCEncOptions NewOptions;
9522 if (Options.ExpandPointedToStructures())
9523 NewOptions.setExpandStructures();
9524 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
9525 /*Field=*/nullptr, NotEncodedT);
9526 return;
9527 }
9528
9529 case Type::ConstantArray:
9530 case Type::IncompleteArray:
9531 case Type::VariableArray: {
9532 const auto *AT = cast<ArrayType>(CT);
9533
9534 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
9535 // Incomplete arrays are encoded as a pointer to the array element.
9536 S += '^';
9537
9538 getObjCEncodingForTypeImpl(
9539 AT->getElementType(), S,
9540 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
9541 } else {
9542 S += '[';
9543
9544 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
9545 S += llvm::utostr(CAT->getZExtSize());
9546 else {
9547 //Variable length arrays are encoded as a regular array with 0 elements.
9549 "Unknown array type!");
9550 S += '0';
9551 }
9552
9553 getObjCEncodingForTypeImpl(
9554 AT->getElementType(), S,
9555 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
9556 NotEncodedT);
9557 S += ']';
9558 }
9559 return;
9560 }
9561
9562 case Type::FunctionNoProto:
9563 case Type::FunctionProto:
9564 S += '?';
9565 return;
9566
9567 case Type::Record: {
9568 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
9569 S += RDecl->isUnion() ? '(' : '{';
9570 // Anonymous structures print as '?'
9571 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
9572 S += II->getName();
9573 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
9574 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
9575 llvm::raw_string_ostream OS(S);
9576 printTemplateArgumentList(OS, TemplateArgs.asArray(),
9578 }
9579 } else {
9580 S += '?';
9581 }
9582 if (Options.ExpandStructures()) {
9583 S += '=';
9584 if (!RDecl->isUnion()) {
9585 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
9586 } else {
9587 for (const auto *Field : RDecl->fields()) {
9588 if (FD) {
9589 S += '"';
9590 S += Field->getNameAsString();
9591 S += '"';
9592 }
9593
9594 // Special case bit-fields.
9595 if (Field->isBitField()) {
9596 getObjCEncodingForTypeImpl(Field->getType(), S,
9597 ObjCEncOptions().setExpandStructures(),
9598 Field);
9599 } else {
9600 QualType qt = Field->getType();
9602 getObjCEncodingForTypeImpl(
9603 qt, S,
9604 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
9605 NotEncodedT);
9606 }
9607 }
9608 }
9609 }
9610 S += RDecl->isUnion() ? ')' : '}';
9611 return;
9612 }
9613
9614 case Type::BlockPointer: {
9615 const auto *BT = T->castAs<BlockPointerType>();
9616 S += "@?"; // Unlike a pointer-to-function, which is "^?".
9617 if (Options.EncodeBlockParameters()) {
9618 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
9619
9620 S += '<';
9621 // Block return type
9622 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
9623 Options.forComponentType(), FD, NotEncodedT);
9624 // Block self
9625 S += "@?";
9626 // Block parameters
9627 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
9628 for (const auto &I : FPT->param_types())
9629 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
9630 NotEncodedT);
9631 }
9632 S += '>';
9633 }
9634 return;
9635 }
9636
9637 case Type::ObjCObject: {
9638 // hack to match legacy encoding of *id and *Class
9639 QualType Ty = getObjCObjectPointerType(CT);
9640 if (Ty->isObjCIdType()) {
9641 S += "{objc_object=}";
9642 return;
9643 }
9644 else if (Ty->isObjCClassType()) {
9645 S += "{objc_class=}";
9646 return;
9647 }
9648 // TODO: Double check to make sure this intentionally falls through.
9649 [[fallthrough]];
9650 }
9651
9652 case Type::ObjCInterface: {
9653 // Ignore protocol qualifiers when mangling at this level.
9654 // @encode(class_name)
9655 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
9656 S += '{';
9657 S += OI->getObjCRuntimeNameAsString();
9658 if (Options.ExpandStructures()) {
9659 S += '=';
9660 SmallVector<const ObjCIvarDecl*, 32> Ivars;
9661 DeepCollectObjCIvars(OI, true, Ivars);
9662 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
9663 const FieldDecl *Field = Ivars[i];
9664 if (Field->isBitField())
9665 getObjCEncodingForTypeImpl(Field->getType(), S,
9666 ObjCEncOptions().setExpandStructures(),
9667 Field);
9668 else
9669 getObjCEncodingForTypeImpl(Field->getType(), S,
9670 ObjCEncOptions().setExpandStructures(), FD,
9671 NotEncodedT);
9672 }
9673 }
9674 S += '}';
9675 return;
9676 }
9677
9678 case Type::ObjCObjectPointer: {
9679 const auto *OPT = T->castAs<ObjCObjectPointerType>();
9680 if (OPT->isObjCIdType()) {
9681 S += '@';
9682 return;
9683 }
9684
9685 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
9686 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
9687 // Since this is a binary compatibility issue, need to consult with
9688 // runtime folks. Fortunately, this is a *very* obscure construct.
9689 S += '#';
9690 return;
9691 }
9692
9693 if (OPT->isObjCQualifiedIdType()) {
9694 getObjCEncodingForTypeImpl(
9695 getObjCIdType(), S,
9696 Options.keepingOnly(ObjCEncOptions()
9697 .setExpandPointedToStructures()
9698 .setExpandStructures()),
9699 FD);
9700 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
9701 // Note that we do extended encoding of protocol qualifier list
9702 // Only when doing ivar or property encoding.
9703 S += '"';
9704 for (const auto *I : OPT->quals()) {
9705 S += '<';
9706 S += I->getObjCRuntimeNameAsString();
9707 S += '>';
9708 }
9709 S += '"';
9710 }
9711 return;
9712 }
9713
9714 S += '@';
9715 if (OPT->getInterfaceDecl() &&
9716 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
9717 S += '"';
9718 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
9719 for (const auto *I : OPT->quals()) {
9720 S += '<';
9721 S += I->getObjCRuntimeNameAsString();
9722 S += '>';
9723 }
9724 S += '"';
9725 }
9726 return;
9727 }
9728
9729 // gcc just blithely ignores member pointers.
9730 // FIXME: we should do better than that. 'M' is available.
9731 case Type::MemberPointer:
9732 // This matches gcc's encoding, even though technically it is insufficient.
9733 //FIXME. We should do a better job than gcc.
9734 case Type::Vector:
9735 case Type::ExtVector:
9736 // Until we have a coherent encoding of these three types, issue warning.
9737 if (NotEncodedT)
9738 *NotEncodedT = T;
9739 return;
9740
9741 case Type::ConstantMatrix:
9742 if (NotEncodedT)
9743 *NotEncodedT = T;
9744 return;
9745
9746 case Type::BitInt:
9747 if (NotEncodedT)
9748 *NotEncodedT = T;
9749 return;
9750
9751 // We could see an undeduced auto type here during error recovery.
9752 // Just ignore it.
9753 case Type::Auto:
9754 case Type::DeducedTemplateSpecialization:
9755 return;
9756
9757 case Type::HLSLAttributedResource:
9758 case Type::HLSLInlineSpirv:
9759 case Type::OverflowBehavior:
9760 llvm_unreachable("unexpected type");
9761
9762 case Type::ArrayParameter:
9763 case Type::Pipe:
9764#define ABSTRACT_TYPE(KIND, BASE)
9765#define TYPE(KIND, BASE)
9766#define DEPENDENT_TYPE(KIND, BASE) \
9767 case Type::KIND:
9768#define NON_CANONICAL_TYPE(KIND, BASE) \
9769 case Type::KIND:
9770#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
9771 case Type::KIND:
9772#include "clang/AST/TypeNodes.inc"
9773 llvm_unreachable("@encode for dependent type!");
9774 }
9775 llvm_unreachable("bad type kind!");
9776}
9777
9778void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
9779 std::string &S,
9780 const FieldDecl *FD,
9781 bool includeVBases,
9782 QualType *NotEncodedT) const {
9783 assert(RDecl && "Expected non-null RecordDecl");
9784 assert(!RDecl->isUnion() && "Should not be called for unions");
9785 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
9786 return;
9787
9788 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
9789 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
9790 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
9791
9792 if (CXXRec) {
9793 for (const auto &BI : CXXRec->bases()) {
9794 if (!BI.isVirtual()) {
9795 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9796 if (base->isEmpty())
9797 continue;
9798 uint64_t offs = toBits(layout.getBaseClassOffset(base));
9799 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9800 std::make_pair(offs, base));
9801 }
9802 }
9803 }
9804
9805 for (FieldDecl *Field : RDecl->fields()) {
9806 if (!Field->isZeroLengthBitField() && Field->isZeroSize(*this))
9807 continue;
9808 uint64_t offs = layout.getFieldOffset(Field->getFieldIndex());
9809 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9810 std::make_pair(offs, Field));
9811 }
9812
9813 if (CXXRec && includeVBases) {
9814 for (const auto &BI : CXXRec->vbases()) {
9815 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9816 if (base->isEmpty())
9817 continue;
9818 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
9819 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
9820 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
9821 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
9822 std::make_pair(offs, base));
9823 }
9824 }
9825
9826 CharUnits size;
9827 if (CXXRec) {
9828 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
9829 } else {
9830 size = layout.getSize();
9831 }
9832
9833#ifndef NDEBUG
9834 uint64_t CurOffs = 0;
9835#endif
9836 std::multimap<uint64_t, NamedDecl *>::iterator
9837 CurLayObj = FieldOrBaseOffsets.begin();
9838
9839 if (CXXRec && CXXRec->isDynamicClass() &&
9840 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
9841 if (FD) {
9842 S += "\"_vptr$";
9843 std::string recname = CXXRec->getNameAsString();
9844 if (recname.empty()) recname = "?";
9845 S += recname;
9846 S += '"';
9847 }
9848 S += "^^?";
9849#ifndef NDEBUG
9850 CurOffs += getTypeSize(VoidPtrTy);
9851#endif
9852 }
9853
9854 if (!RDecl->hasFlexibleArrayMember()) {
9855 // Mark the end of the structure.
9856 uint64_t offs = toBits(size);
9857 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9858 std::make_pair(offs, nullptr));
9859 }
9860
9861 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
9862#ifndef NDEBUG
9863 assert(CurOffs <= CurLayObj->first);
9864 if (CurOffs < CurLayObj->first) {
9865 uint64_t padding = CurLayObj->first - CurOffs;
9866 // FIXME: There doesn't seem to be a way to indicate in the encoding that
9867 // packing/alignment of members is different that normal, in which case
9868 // the encoding will be out-of-sync with the real layout.
9869 // If the runtime switches to just consider the size of types without
9870 // taking into account alignment, we could make padding explicit in the
9871 // encoding (e.g. using arrays of chars). The encoding strings would be
9872 // longer then though.
9873 CurOffs += padding;
9874 }
9875#endif
9876
9877 NamedDecl *dcl = CurLayObj->second;
9878 if (!dcl)
9879 break; // reached end of structure.
9880
9881 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
9882 // We expand the bases without their virtual bases since those are going
9883 // in the initial structure. Note that this differs from gcc which
9884 // expands virtual bases each time one is encountered in the hierarchy,
9885 // making the encoding type bigger than it really is.
9886 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
9887 NotEncodedT);
9888 assert(!base->isEmpty());
9889#ifndef NDEBUG
9890 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
9891#endif
9892 } else {
9893 const auto *field = cast<FieldDecl>(dcl);
9894 if (FD) {
9895 S += '"';
9896 S += field->getNameAsString();
9897 S += '"';
9898 }
9899
9900 if (field->isBitField()) {
9901 EncodeBitField(this, S, field->getType(), field);
9902#ifndef NDEBUG
9903 CurOffs += field->getBitWidthValue();
9904#endif
9905 } else {
9906 QualType qt = field->getType();
9908 getObjCEncodingForTypeImpl(
9909 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
9910 FD, NotEncodedT);
9911#ifndef NDEBUG
9912 CurOffs += getTypeSize(field->getType());
9913#endif
9914 }
9915 }
9916 }
9917}
9918
9920 std::string& S) const {
9921 if (QT & Decl::OBJC_TQ_In)
9922 S += 'n';
9923 if (QT & Decl::OBJC_TQ_Inout)
9924 S += 'N';
9925 if (QT & Decl::OBJC_TQ_Out)
9926 S += 'o';
9927 if (QT & Decl::OBJC_TQ_Bycopy)
9928 S += 'O';
9929 if (QT & Decl::OBJC_TQ_Byref)
9930 S += 'R';
9931 if (QT & Decl::OBJC_TQ_Oneway)
9932 S += 'V';
9933}
9934
9936 if (!ObjCIdDecl) {
9939 ObjCIdDecl = buildImplicitTypedef(T, "id");
9940 }
9941 return ObjCIdDecl;
9942}
9943
9945 if (!ObjCSelDecl) {
9947 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
9948 }
9949 return ObjCSelDecl;
9950}
9951
9953 if (!ObjCClassDecl) {
9956 ObjCClassDecl = buildImplicitTypedef(T, "Class");
9957 }
9958 return ObjCClassDecl;
9959}
9960
9962 if (!ObjCProtocolClassDecl) {
9963 ObjCProtocolClassDecl
9966 &Idents.get("Protocol"),
9967 /*typeParamList=*/nullptr,
9968 /*PrevDecl=*/nullptr,
9969 SourceLocation(), true);
9970 }
9971
9972 return ObjCProtocolClassDecl;
9973}
9974
9976 if (!getLangOpts().PointerAuthObjcInterfaceSel)
9977 return PointerAuthQualifier();
9979 getLangOpts().PointerAuthObjcInterfaceSelKey,
9980 /*isAddressDiscriminated=*/true, SelPointerConstantDiscriminator,
9982 /*isIsaPointer=*/false,
9983 /*authenticatesNullValues=*/false);
9984}
9985
9986//===----------------------------------------------------------------------===//
9987// __builtin_va_list Construction Functions
9988//===----------------------------------------------------------------------===//
9989
9991 StringRef Name) {
9992 // typedef char* __builtin[_ms]_va_list;
9993 QualType T = Context->getPointerType(Context->CharTy);
9994 return Context->buildImplicitTypedef(T, Name);
9995}
9996
9998 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
9999}
10000
10002 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
10003}
10004
10006 // typedef void* __builtin_va_list;
10007 QualType T = Context->getPointerType(Context->VoidTy);
10008 return Context->buildImplicitTypedef(T, "__builtin_va_list");
10009}
10010
10011static TypedefDecl *
10013 // struct __va_list
10014 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
10015 if (Context->getLangOpts().CPlusPlus) {
10016 // namespace std { struct __va_list {
10017 auto *NS = NamespaceDecl::Create(
10018 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
10019 /*Inline=*/false, SourceLocation(), SourceLocation(),
10020 &Context->Idents.get("std"),
10021 /*PrevDecl=*/nullptr, /*Nested=*/false);
10022 NS->setImplicit();
10024 }
10025
10026 VaListTagDecl->startDefinition();
10027
10028 const size_t NumFields = 5;
10029 QualType FieldTypes[NumFields];
10030 const char *FieldNames[NumFields];
10031
10032 // void *__stack;
10033 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
10034 FieldNames[0] = "__stack";
10035
10036 // void *__gr_top;
10037 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
10038 FieldNames[1] = "__gr_top";
10039
10040 // void *__vr_top;
10041 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10042 FieldNames[2] = "__vr_top";
10043
10044 // int __gr_offs;
10045 FieldTypes[3] = Context->IntTy;
10046 FieldNames[3] = "__gr_offs";
10047
10048 // int __vr_offs;
10049 FieldTypes[4] = Context->IntTy;
10050 FieldNames[4] = "__vr_offs";
10051
10052 // Create fields
10053 for (unsigned i = 0; i < NumFields; ++i) {
10054 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10058 &Context->Idents.get(FieldNames[i]),
10059 FieldTypes[i], /*TInfo=*/nullptr,
10060 /*BitWidth=*/nullptr,
10061 /*Mutable=*/false,
10062 ICIS_NoInit);
10063 Field->setAccess(AS_public);
10064 VaListTagDecl->addDecl(Field);
10065 }
10066 VaListTagDecl->completeDefinition();
10067 Context->VaListTagDecl = VaListTagDecl;
10068 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10069
10070 // } __builtin_va_list;
10071 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10072}
10073
10075 // typedef struct __va_list_tag {
10077
10078 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10079 VaListTagDecl->startDefinition();
10080
10081 const size_t NumFields = 5;
10082 QualType FieldTypes[NumFields];
10083 const char *FieldNames[NumFields];
10084
10085 // unsigned char gpr;
10086 FieldTypes[0] = Context->UnsignedCharTy;
10087 FieldNames[0] = "gpr";
10088
10089 // unsigned char fpr;
10090 FieldTypes[1] = Context->UnsignedCharTy;
10091 FieldNames[1] = "fpr";
10092
10093 // unsigned short reserved;
10094 FieldTypes[2] = Context->UnsignedShortTy;
10095 FieldNames[2] = "reserved";
10096
10097 // void* overflow_arg_area;
10098 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10099 FieldNames[3] = "overflow_arg_area";
10100
10101 // void* reg_save_area;
10102 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
10103 FieldNames[4] = "reg_save_area";
10104
10105 // Create fields
10106 for (unsigned i = 0; i < NumFields; ++i) {
10107 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
10110 &Context->Idents.get(FieldNames[i]),
10111 FieldTypes[i], /*TInfo=*/nullptr,
10112 /*BitWidth=*/nullptr,
10113 /*Mutable=*/false,
10114 ICIS_NoInit);
10115 Field->setAccess(AS_public);
10116 VaListTagDecl->addDecl(Field);
10117 }
10118 VaListTagDecl->completeDefinition();
10119 Context->VaListTagDecl = VaListTagDecl;
10120 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10121
10122 // } __va_list_tag;
10123 TypedefDecl *VaListTagTypedefDecl =
10124 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10125
10126 QualType VaListTagTypedefType =
10127 Context->getTypedefType(ElaboratedTypeKeyword::None,
10128 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10129
10130 // typedef __va_list_tag __builtin_va_list[1];
10131 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10132 QualType VaListTagArrayType = Context->getConstantArrayType(
10133 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10134 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10135}
10136
10137static TypedefDecl *
10139 // struct __va_list_tag {
10141 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10142 VaListTagDecl->startDefinition();
10143
10144 const size_t NumFields = 4;
10145 QualType FieldTypes[NumFields];
10146 const char *FieldNames[NumFields];
10147
10148 // unsigned gp_offset;
10149 FieldTypes[0] = Context->UnsignedIntTy;
10150 FieldNames[0] = "gp_offset";
10151
10152 // unsigned fp_offset;
10153 FieldTypes[1] = Context->UnsignedIntTy;
10154 FieldNames[1] = "fp_offset";
10155
10156 // void* overflow_arg_area;
10157 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10158 FieldNames[2] = "overflow_arg_area";
10159
10160 // void* reg_save_area;
10161 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10162 FieldNames[3] = "reg_save_area";
10163
10164 // Create fields
10165 for (unsigned i = 0; i < NumFields; ++i) {
10166 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10170 &Context->Idents.get(FieldNames[i]),
10171 FieldTypes[i], /*TInfo=*/nullptr,
10172 /*BitWidth=*/nullptr,
10173 /*Mutable=*/false,
10174 ICIS_NoInit);
10175 Field->setAccess(AS_public);
10176 VaListTagDecl->addDecl(Field);
10177 }
10178 VaListTagDecl->completeDefinition();
10179 Context->VaListTagDecl = VaListTagDecl;
10180 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10181
10182 // };
10183
10184 // typedef struct __va_list_tag __builtin_va_list[1];
10185 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10186 QualType VaListTagArrayType = Context->getConstantArrayType(
10187 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10188 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10189}
10190
10191static TypedefDecl *
10193 // struct __va_list
10194 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
10195 if (Context->getLangOpts().CPlusPlus) {
10196 // namespace std { struct __va_list {
10197 NamespaceDecl *NS;
10198 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
10199 Context->getTranslationUnitDecl(),
10200 /*Inline=*/false, SourceLocation(),
10201 SourceLocation(), &Context->Idents.get("std"),
10202 /*PrevDecl=*/nullptr, /*Nested=*/false);
10203 NS->setImplicit();
10204 VaListDecl->setDeclContext(NS);
10205 }
10206
10207 VaListDecl->startDefinition();
10208
10209 // void * __ap;
10210 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10211 VaListDecl,
10214 &Context->Idents.get("__ap"),
10215 Context->getPointerType(Context->VoidTy),
10216 /*TInfo=*/nullptr,
10217 /*BitWidth=*/nullptr,
10218 /*Mutable=*/false,
10219 ICIS_NoInit);
10220 Field->setAccess(AS_public);
10221 VaListDecl->addDecl(Field);
10222
10223 // };
10224 VaListDecl->completeDefinition();
10225 Context->VaListTagDecl = VaListDecl;
10226
10227 // typedef struct __va_list __builtin_va_list;
10228 CanQualType T = Context->getCanonicalTagType(VaListDecl);
10229 return Context->buildImplicitTypedef(T, "__builtin_va_list");
10230}
10231
10232static TypedefDecl *
10234 // struct __va_list_tag {
10236 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10237 VaListTagDecl->startDefinition();
10238
10239 const size_t NumFields = 4;
10240 QualType FieldTypes[NumFields];
10241 const char *FieldNames[NumFields];
10242
10243 // long __gpr;
10244 FieldTypes[0] = Context->LongTy;
10245 FieldNames[0] = "__gpr";
10246
10247 // long __fpr;
10248 FieldTypes[1] = Context->LongTy;
10249 FieldNames[1] = "__fpr";
10250
10251 // void *__overflow_arg_area;
10252 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10253 FieldNames[2] = "__overflow_arg_area";
10254
10255 // void *__reg_save_area;
10256 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10257 FieldNames[3] = "__reg_save_area";
10258
10259 // Create fields
10260 for (unsigned i = 0; i < NumFields; ++i) {
10261 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10265 &Context->Idents.get(FieldNames[i]),
10266 FieldTypes[i], /*TInfo=*/nullptr,
10267 /*BitWidth=*/nullptr,
10268 /*Mutable=*/false,
10269 ICIS_NoInit);
10270 Field->setAccess(AS_public);
10271 VaListTagDecl->addDecl(Field);
10272 }
10273 VaListTagDecl->completeDefinition();
10274 Context->VaListTagDecl = VaListTagDecl;
10275 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10276
10277 // };
10278
10279 // typedef __va_list_tag __builtin_va_list[1];
10280 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10281 QualType VaListTagArrayType = Context->getConstantArrayType(
10282 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10283
10284 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10285}
10286
10288 // typedef struct __va_list_tag {
10290 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10291 VaListTagDecl->startDefinition();
10292
10293 const size_t NumFields = 3;
10294 QualType FieldTypes[NumFields];
10295 const char *FieldNames[NumFields];
10296
10297 // void *CurrentSavedRegisterArea;
10298 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
10299 FieldNames[0] = "__current_saved_reg_area_pointer";
10300
10301 // void *SavedRegAreaEnd;
10302 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
10303 FieldNames[1] = "__saved_reg_area_end_pointer";
10304
10305 // void *OverflowArea;
10306 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10307 FieldNames[2] = "__overflow_area_pointer";
10308
10309 // Create fields
10310 for (unsigned i = 0; i < NumFields; ++i) {
10312 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
10313 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
10314 /*TInfo=*/nullptr,
10315 /*BitWidth=*/nullptr,
10316 /*Mutable=*/false, ICIS_NoInit);
10317 Field->setAccess(AS_public);
10318 VaListTagDecl->addDecl(Field);
10319 }
10320 VaListTagDecl->completeDefinition();
10321 Context->VaListTagDecl = VaListTagDecl;
10322 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10323
10324 // } __va_list_tag;
10325 TypedefDecl *VaListTagTypedefDecl =
10326 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10327
10328 QualType VaListTagTypedefType =
10329 Context->getTypedefType(ElaboratedTypeKeyword::None,
10330 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10331
10332 // typedef __va_list_tag __builtin_va_list[1];
10333 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10334 QualType VaListTagArrayType = Context->getConstantArrayType(
10335 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10336
10337 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10338}
10339
10340static TypedefDecl *
10342 // typedef struct __va_list_tag {
10343 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10344
10345 VaListTagDecl->startDefinition();
10346
10347 // int* __va_stk;
10348 // int* __va_reg;
10349 // int __va_ndx;
10350 constexpr size_t NumFields = 3;
10351 QualType FieldTypes[NumFields] = {Context->getPointerType(Context->IntTy),
10352 Context->getPointerType(Context->IntTy),
10353 Context->IntTy};
10354 const char *FieldNames[NumFields] = {"__va_stk", "__va_reg", "__va_ndx"};
10355
10356 // Create fields
10357 for (unsigned i = 0; i < NumFields; ++i) {
10360 &Context->Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
10361 /*BitWidth=*/nullptr,
10362 /*Mutable=*/false, ICIS_NoInit);
10363 Field->setAccess(AS_public);
10364 VaListTagDecl->addDecl(Field);
10365 }
10366 VaListTagDecl->completeDefinition();
10367 Context->VaListTagDecl = VaListTagDecl;
10368 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10369
10370 // } __va_list_tag;
10371 TypedefDecl *VaListTagTypedefDecl =
10372 Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10373
10374 return VaListTagTypedefDecl;
10375}
10376
10379 switch (Kind) {
10381 return CreateCharPtrBuiltinVaListDecl(Context);
10383 return CreateVoidPtrBuiltinVaListDecl(Context);
10385 return CreateAArch64ABIBuiltinVaListDecl(Context);
10387 return CreatePowerABIBuiltinVaListDecl(Context);
10389 return CreateX86_64ABIBuiltinVaListDecl(Context);
10391 return CreateAAPCSABIBuiltinVaListDecl(Context);
10393 return CreateSystemZBuiltinVaListDecl(Context);
10395 return CreateHexagonBuiltinVaListDecl(Context);
10397 return CreateXtensaABIBuiltinVaListDecl(Context);
10398 }
10399
10400 llvm_unreachable("Unhandled __builtin_va_list type kind");
10401}
10402
10404 if (!BuiltinVaListDecl) {
10405 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
10406 assert(BuiltinVaListDecl->isImplicit());
10407 }
10408
10409 return BuiltinVaListDecl;
10410}
10411
10413 // Force the creation of VaListTagDecl by building the __builtin_va_list
10414 // declaration.
10415 if (!VaListTagDecl)
10416 (void)getBuiltinVaListDecl();
10417
10418 return VaListTagDecl;
10419}
10420
10422 if (!BuiltinMSVaListDecl)
10423 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
10424
10425 return BuiltinMSVaListDecl;
10426}
10427
10429 // Allow redecl custom type checking builtin for HLSL.
10430 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
10431 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10432 return true;
10433 // Allow redecl custom type checking builtin for SPIR-V.
10434 if (getTargetInfo().getTriple().isSPIROrSPIRV() &&
10435 BuiltinInfo.isTSBuiltin(FD->getBuiltinID()) &&
10436 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10437 return true;
10438 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
10439}
10440
10442 assert(ObjCConstantStringType.isNull() &&
10443 "'NSConstantString' type already set!");
10444
10445 ObjCConstantStringType = getObjCInterfaceType(Decl);
10446}
10447
10448/// Retrieve the template name that corresponds to a non-empty
10449/// lookup.
10452 UnresolvedSetIterator End) const {
10453 unsigned size = End - Begin;
10454 assert(size > 1 && "set is not overloaded!");
10455
10456 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
10457 size * sizeof(FunctionTemplateDecl*));
10458 auto *OT = new (memory) OverloadedTemplateStorage(size);
10459
10460 NamedDecl **Storage = OT->getStorage();
10461 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
10462 NamedDecl *D = *I;
10463 assert(isa<FunctionTemplateDecl>(D) ||
10467 *Storage++ = D;
10468 }
10469
10470 return TemplateName(OT);
10471}
10472
10473/// Retrieve a template name representing an unqualified-id that has been
10474/// assumed to name a template for ADL purposes.
10476 auto *OT = new (*this) AssumedTemplateStorage(Name);
10477 return TemplateName(OT);
10478}
10479
10480/// Retrieve the template name that represents a qualified
10481/// template name such as \c std::vector.
10483 bool TemplateKeyword,
10484 TemplateName Template) const {
10485 assert(Template.getKind() == TemplateName::Template ||
10487
10488 if (Template.getAsTemplateDecl()->getKind() == Decl::TemplateTemplateParm) {
10489 assert(!Qualifier && "unexpected qualified template template parameter");
10490 assert(TemplateKeyword == false);
10491 return Template;
10492 }
10493
10494 // FIXME: Canonicalization?
10495 llvm::FoldingSetNodeID ID;
10496 QualifiedTemplateName::Profile(ID, Qualifier, TemplateKeyword, Template);
10497
10498 void *InsertPos = nullptr;
10500 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
10501 if (!QTN) {
10502 QTN = new (*this, alignof(QualifiedTemplateName))
10503 QualifiedTemplateName(Qualifier, TemplateKeyword, Template);
10504 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
10505 }
10506
10507 return TemplateName(QTN);
10508}
10509
10510/// Retrieve the template name that represents a dependent
10511/// template name such as \c MetaFun::template operator+.
10514 llvm::FoldingSetNodeID ID;
10515 S.Profile(ID);
10516
10517 void *InsertPos = nullptr;
10518 if (DependentTemplateName *QTN =
10519 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos))
10520 return TemplateName(QTN);
10521
10523 new (*this, alignof(DependentTemplateName)) DependentTemplateName(S);
10524 DependentTemplateNames.InsertNode(QTN, InsertPos);
10525 return TemplateName(QTN);
10526}
10527
10529 Decl *AssociatedDecl,
10530 unsigned Index,
10531 UnsignedOrNone PackIndex,
10532 bool Final) const {
10533 llvm::FoldingSetNodeID ID;
10534 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
10535 Index, PackIndex, Final);
10536
10537 void *insertPos = nullptr;
10539 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
10540
10541 if (!subst) {
10542 subst = new (*this) SubstTemplateTemplateParmStorage(
10543 Replacement, AssociatedDecl, Index, PackIndex, Final);
10544 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
10545 }
10546
10547 return TemplateName(subst);
10548}
10549
10552 Decl *AssociatedDecl,
10553 unsigned Index, bool Final) const {
10554 auto &Self = const_cast<ASTContext &>(*this);
10555 llvm::FoldingSetNodeID ID;
10557 AssociatedDecl, Index, Final);
10558
10559 void *InsertPos = nullptr;
10561 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
10562
10563 if (!Subst) {
10564 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
10565 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
10566 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
10567 }
10568
10569 return TemplateName(Subst);
10570}
10571
10572/// Retrieve the template name that represents a template name
10573/// deduced from a specialization.
10576 DefaultArguments DefaultArgs) const {
10577 if (!DefaultArgs)
10578 return Underlying;
10579
10580 llvm::FoldingSetNodeID ID;
10581 DeducedTemplateStorage::Profile(ID, *this, Underlying, DefaultArgs);
10582
10583 void *InsertPos = nullptr;
10585 DeducedTemplates.FindNodeOrInsertPos(ID, InsertPos);
10586 if (!DTS) {
10587 void *Mem = Allocate(sizeof(DeducedTemplateStorage) +
10588 sizeof(TemplateArgument) * DefaultArgs.Args.size(),
10589 alignof(DeducedTemplateStorage));
10590 DTS = new (Mem) DeducedTemplateStorage(Underlying, DefaultArgs);
10591 DeducedTemplates.InsertNode(DTS, InsertPos);
10592 }
10593 return TemplateName(DTS);
10594}
10595
10596/// getFromTargetType - Given one of the integer types provided by
10597/// TargetInfo, produce the corresponding type. The unsigned @p Type
10598/// is actually a value of type @c TargetInfo::IntType.
10599CanQualType ASTContext::getFromTargetType(unsigned Type) const {
10600 switch (Type) {
10601 case TargetInfo::NoInt: return {};
10604 case TargetInfo::SignedShort: return ShortTy;
10606 case TargetInfo::SignedInt: return IntTy;
10608 case TargetInfo::SignedLong: return LongTy;
10612 }
10613
10614 llvm_unreachable("Unhandled TargetInfo::IntType value");
10615}
10616
10617//===----------------------------------------------------------------------===//
10618// Type Predicates.
10619//===----------------------------------------------------------------------===//
10620
10621/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
10622/// garbage collection attribute.
10623///
10625 if (getLangOpts().getGC() == LangOptions::NonGC)
10626 return Qualifiers::GCNone;
10627
10628 assert(getLangOpts().ObjC);
10629 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
10630
10631 // Default behaviour under objective-C's gc is for ObjC pointers
10632 // (or pointers to them) be treated as though they were declared
10633 // as __strong.
10634 if (GCAttrs == Qualifiers::GCNone) {
10636 return Qualifiers::Strong;
10637 else if (Ty->isPointerType())
10639 } else {
10640 // It's not valid to set GC attributes on anything that isn't a
10641 // pointer.
10642#ifndef NDEBUG
10644 while (const auto *AT = dyn_cast<ArrayType>(CT))
10645 CT = AT->getElementType();
10646 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
10647#endif
10648 }
10649 return GCAttrs;
10650}
10651
10652//===----------------------------------------------------------------------===//
10653// Type Compatibility Testing
10654//===----------------------------------------------------------------------===//
10655
10656/// areCompatVectorTypes - Return true if the two specified vector types are
10657/// compatible.
10658static bool areCompatVectorTypes(const VectorType *LHS,
10659 const VectorType *RHS) {
10660 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10661 return LHS->getElementType() == RHS->getElementType() &&
10662 LHS->getNumElements() == RHS->getNumElements();
10663}
10664
10665/// areCompatMatrixTypes - Return true if the two specified matrix types are
10666/// compatible.
10668 const ConstantMatrixType *RHS) {
10669 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10670 return LHS->getElementType() == RHS->getElementType() &&
10671 LHS->getNumRows() == RHS->getNumRows() &&
10672 LHS->getNumColumns() == RHS->getNumColumns();
10673}
10674
10676 QualType SecondVec) {
10677 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
10678 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
10679
10680 if (hasSameUnqualifiedType(FirstVec, SecondVec))
10681 return true;
10682
10683 // Treat Neon vector types and most AltiVec vector types as if they are the
10684 // equivalent GCC vector types.
10685 const auto *First = FirstVec->castAs<VectorType>();
10686 const auto *Second = SecondVec->castAs<VectorType>();
10687 if (First->getNumElements() == Second->getNumElements() &&
10688 hasSameType(First->getElementType(), Second->getElementType()) &&
10689 First->getVectorKind() != VectorKind::AltiVecPixel &&
10690 First->getVectorKind() != VectorKind::AltiVecBool &&
10693 First->getVectorKind() != VectorKind::SveFixedLengthData &&
10694 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10697 First->getVectorKind() != VectorKind::RVVFixedLengthData &&
10699 First->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10701 First->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10703 First->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10705 First->getVectorKind() != VectorKind::RVVFixedLengthMask_4 &&
10707 return true;
10708
10709 // In OpenCL, treat half and _Float16 vector types as compatible.
10710 if (getLangOpts().OpenCL &&
10711 First->getNumElements() == Second->getNumElements()) {
10712 QualType FirstElt = First->getElementType();
10713 QualType SecondElt = Second->getElementType();
10714
10715 if ((FirstElt->isFloat16Type() && SecondElt->isHalfType()) ||
10716 (FirstElt->isHalfType() && SecondElt->isFloat16Type())) {
10717 if (First->getVectorKind() != VectorKind::AltiVecPixel &&
10718 First->getVectorKind() != VectorKind::AltiVecBool &&
10721 return true;
10722 }
10723 }
10724 return false;
10725}
10726
10732
10735 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
10736 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
10737
10738 if (!LHSOBT && !RHSOBT)
10740
10741 if (LHSOBT && RHSOBT) {
10742 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
10745 }
10746
10747 QualType LHSUnderlying = LHSOBT ? LHSOBT->desugar() : LHS;
10748 QualType RHSUnderlying = RHSOBT ? RHSOBT->desugar() : RHS;
10749
10750 if (RHSOBT && !LHSOBT) {
10751 if (LHSUnderlying->isIntegerType() && RHSUnderlying->isIntegerType())
10753 }
10754
10756}
10757
10758/// getRVVTypeSize - Return RVV vector register size.
10759static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
10760 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
10761 auto VScale = Context.getTargetInfo().getVScaleRange(
10762 Context.getLangOpts(), TargetInfo::ArmStreamingKind::NotStreaming);
10763 if (!VScale)
10764 return 0;
10765
10766 ASTContext::BuiltinVectorTypeInfo Info = Context.getBuiltinVectorTypeInfo(Ty);
10767
10768 uint64_t EltSize = Context.getTypeSize(Info.ElementType);
10769 if (Info.ElementType == Context.BoolTy)
10770 EltSize = 1;
10771
10772 uint64_t MinElts = Info.EC.getKnownMinValue();
10773 return VScale->first * MinElts * EltSize;
10774}
10775
10777 QualType SecondType) {
10778 assert(
10779 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10780 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10781 "Expected RVV builtin type and vector type!");
10782
10783 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10784 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10785 if (const auto *VT = SecondType->getAs<VectorType>()) {
10786 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10788 return FirstType->isRVVVLSBuiltinType() &&
10789 Info.ElementType == BoolTy &&
10790 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)));
10791 }
10792 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1) {
10794 return FirstType->isRVVVLSBuiltinType() &&
10795 Info.ElementType == BoolTy &&
10796 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT) * 8));
10797 }
10798 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2) {
10800 return FirstType->isRVVVLSBuiltinType() &&
10801 Info.ElementType == BoolTy &&
10802 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 4);
10803 }
10804 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10806 return FirstType->isRVVVLSBuiltinType() &&
10807 Info.ElementType == BoolTy &&
10808 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 2);
10809 }
10810 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
10811 VT->getVectorKind() == VectorKind::Generic)
10812 return FirstType->isRVVVLSBuiltinType() &&
10813 getTypeSize(SecondType) == getRVVTypeSize(*this, BT) &&
10814 hasSameType(VT->getElementType(),
10815 getBuiltinVectorTypeInfo(BT).ElementType);
10816 }
10817 }
10818 return false;
10819 };
10820
10821 return IsValidCast(FirstType, SecondType) ||
10822 IsValidCast(SecondType, FirstType);
10823}
10824
10826 QualType SecondType) {
10827 assert(
10828 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10829 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10830 "Expected RVV builtin type and vector type!");
10831
10832 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10833 const auto *BT = FirstType->getAs<BuiltinType>();
10834 if (!BT)
10835 return false;
10836
10837 if (!BT->isRVVVLSBuiltinType())
10838 return false;
10839
10840 const auto *VecTy = SecondType->getAs<VectorType>();
10841 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
10843 getLangOpts().getLaxVectorConversions();
10844
10845 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
10846 if (getTypeSize(SecondType) != getRVVTypeSize(*this, BT))
10847 return false;
10848
10849 // If -flax-vector-conversions=all is specified, the types are
10850 // certainly compatible.
10852 return true;
10853
10854 // If -flax-vector-conversions=integer is specified, the types are
10855 // compatible if the elements are integer types.
10857 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10858 FirstType->getRVVEltType(*this)->isIntegerType();
10859 }
10860
10861 return false;
10862 };
10863
10864 return IsLaxCompatible(FirstType, SecondType) ||
10865 IsLaxCompatible(SecondType, FirstType);
10866}
10867
10869 while (true) {
10870 // __strong id
10871 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
10872 if (Attr->getAttrKind() == attr::ObjCOwnership)
10873 return true;
10874
10875 Ty = Attr->getModifiedType();
10876
10877 // X *__strong (...)
10878 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
10879 Ty = Paren->getInnerType();
10880
10881 // We do not want to look through typedefs, typeof(expr),
10882 // typeof(type), or any other way that the type is somehow
10883 // abstracted.
10884 } else {
10885 return false;
10886 }
10887 }
10888}
10889
10890//===----------------------------------------------------------------------===//
10891// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
10892//===----------------------------------------------------------------------===//
10893
10894/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
10895/// inheritance hierarchy of 'rProto'.
10896bool
10898 ObjCProtocolDecl *rProto) const {
10899 if (declaresSameEntity(lProto, rProto))
10900 return true;
10901 for (auto *PI : rProto->protocols())
10902 if (ProtocolCompatibleWithProtocol(lProto, PI))
10903 return true;
10904 return false;
10905}
10906
10907/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
10908/// Class<pr1, ...>.
10910 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
10911 for (auto *lhsProto : lhs->quals()) {
10912 bool match = false;
10913 for (auto *rhsProto : rhs->quals()) {
10914 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
10915 match = true;
10916 break;
10917 }
10918 }
10919 if (!match)
10920 return false;
10921 }
10922 return true;
10923}
10924
10925/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
10926/// ObjCQualifiedIDType.
10928 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
10929 bool compare) {
10930 // Allow id<P..> and an 'id' in all cases.
10931 if (lhs->isObjCIdType() || rhs->isObjCIdType())
10932 return true;
10933
10934 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
10935 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
10937 return false;
10938
10939 if (lhs->isObjCQualifiedIdType()) {
10940 if (rhs->qual_empty()) {
10941 // If the RHS is a unqualified interface pointer "NSString*",
10942 // make sure we check the class hierarchy.
10943 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10944 for (auto *I : lhs->quals()) {
10945 // when comparing an id<P> on lhs with a static type on rhs,
10946 // see if static class implements all of id's protocols, directly or
10947 // through its super class and categories.
10948 if (!rhsID->ClassImplementsProtocol(I, true))
10949 return false;
10950 }
10951 }
10952 // If there are no qualifiers and no interface, we have an 'id'.
10953 return true;
10954 }
10955 // Both the right and left sides have qualifiers.
10956 for (auto *lhsProto : lhs->quals()) {
10957 bool match = false;
10958
10959 // when comparing an id<P> on lhs with a static type on rhs,
10960 // see if static class implements all of id's protocols, directly or
10961 // through its super class and categories.
10962 for (auto *rhsProto : rhs->quals()) {
10963 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10964 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10965 match = true;
10966 break;
10967 }
10968 }
10969 // If the RHS is a qualified interface pointer "NSString<P>*",
10970 // make sure we check the class hierarchy.
10971 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10972 for (auto *I : lhs->quals()) {
10973 // when comparing an id<P> on lhs with a static type on rhs,
10974 // see if static class implements all of id's protocols, directly or
10975 // through its super class and categories.
10976 if (rhsID->ClassImplementsProtocol(I, true)) {
10977 match = true;
10978 break;
10979 }
10980 }
10981 }
10982 if (!match)
10983 return false;
10984 }
10985
10986 return true;
10987 }
10988
10989 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
10990
10991 if (lhs->getInterfaceType()) {
10992 // If both the right and left sides have qualifiers.
10993 for (auto *lhsProto : lhs->quals()) {
10994 bool match = false;
10995
10996 // when comparing an id<P> on rhs with a static type on lhs,
10997 // see if static class implements all of id's protocols, directly or
10998 // through its super class and categories.
10999 // First, lhs protocols in the qualifier list must be found, direct
11000 // or indirect in rhs's qualifier list or it is a mismatch.
11001 for (auto *rhsProto : rhs->quals()) {
11002 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
11003 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
11004 match = true;
11005 break;
11006 }
11007 }
11008 if (!match)
11009 return false;
11010 }
11011
11012 // Static class's protocols, or its super class or category protocols
11013 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
11014 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
11015 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
11016 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
11017 // This is rather dubious but matches gcc's behavior. If lhs has
11018 // no type qualifier and its class has no static protocol(s)
11019 // assume that it is mismatch.
11020 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
11021 return false;
11022 for (auto *lhsProto : LHSInheritedProtocols) {
11023 bool match = false;
11024 for (auto *rhsProto : rhs->quals()) {
11025 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
11026 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
11027 match = true;
11028 break;
11029 }
11030 }
11031 if (!match)
11032 return false;
11033 }
11034 }
11035 return true;
11036 }
11037 return false;
11038}
11039
11040/// canAssignObjCInterfaces - Return true if the two interface types are
11041/// compatible for assignment from RHS to LHS. This handles validation of any
11042/// protocol qualifiers on the LHS or RHS.
11044 const ObjCObjectPointerType *RHSOPT) {
11045 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11046 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11047
11048 // If either type represents the built-in 'id' type, return true.
11049 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
11050 return true;
11051
11052 // Function object that propagates a successful result or handles
11053 // __kindof types.
11054 auto finish = [&](bool succeeded) -> bool {
11055 if (succeeded)
11056 return true;
11057
11058 if (!RHS->isKindOfType())
11059 return false;
11060
11061 // Strip off __kindof and protocol qualifiers, then check whether
11062 // we can assign the other way.
11064 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
11065 };
11066
11067 // Casts from or to id<P> are allowed when the other side has compatible
11068 // protocols.
11069 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
11070 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
11071 }
11072
11073 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
11074 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
11075 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
11076 }
11077
11078 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
11079 if (LHS->isObjCClass() && RHS->isObjCClass()) {
11080 return true;
11081 }
11082
11083 // If we have 2 user-defined types, fall into that path.
11084 if (LHS->getInterface() && RHS->getInterface()) {
11085 return finish(canAssignObjCInterfaces(LHS, RHS));
11086 }
11087
11088 return false;
11089}
11090
11091/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
11092/// for providing type-safety for objective-c pointers used to pass/return
11093/// arguments in block literals. When passed as arguments, passing 'A*' where
11094/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
11095/// not OK. For the return type, the opposite is not OK.
11097 const ObjCObjectPointerType *LHSOPT,
11098 const ObjCObjectPointerType *RHSOPT,
11099 bool BlockReturnType) {
11100
11101 // Function object that propagates a successful result or handles
11102 // __kindof types.
11103 auto finish = [&](bool succeeded) -> bool {
11104 if (succeeded)
11105 return true;
11106
11107 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
11108 if (!Expected->isKindOfType())
11109 return false;
11110
11111 // Strip off __kindof and protocol qualifiers, then check whether
11112 // we can assign the other way.
11114 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
11115 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
11116 BlockReturnType);
11117 };
11118
11119 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
11120 return true;
11121
11122 if (LHSOPT->isObjCBuiltinType()) {
11123 return finish(RHSOPT->isObjCBuiltinType() ||
11124 RHSOPT->isObjCQualifiedIdType());
11125 }
11126
11127 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
11128 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
11129 // Use for block parameters previous type checking for compatibility.
11130 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
11131 // Or corrected type checking as in non-compat mode.
11132 (!BlockReturnType &&
11133 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
11134 else
11136 (BlockReturnType ? LHSOPT : RHSOPT),
11137 (BlockReturnType ? RHSOPT : LHSOPT), false));
11138 }
11139
11140 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
11141 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
11142 if (LHS && RHS) { // We have 2 user-defined types.
11143 if (LHS != RHS) {
11144 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
11145 return finish(BlockReturnType);
11146 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
11147 return finish(!BlockReturnType);
11148 }
11149 else
11150 return true;
11151 }
11152 return false;
11153}
11154
11155/// Comparison routine for Objective-C protocols to be used with
11156/// llvm::array_pod_sort.
11158 ObjCProtocolDecl * const *rhs) {
11159 return (*lhs)->getName().compare((*rhs)->getName());
11160}
11161
11162/// getIntersectionOfProtocols - This routine finds the intersection of set
11163/// of protocols inherited from two distinct objective-c pointer objects with
11164/// the given common base.
11165/// It is used to build composite qualifier list of the composite type of
11166/// the conditional expression involving two objective-c pointer objects.
11167static
11169 const ObjCInterfaceDecl *CommonBase,
11170 const ObjCObjectPointerType *LHSOPT,
11171 const ObjCObjectPointerType *RHSOPT,
11172 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
11173
11174 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11175 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11176 assert(LHS->getInterface() && "LHS must have an interface base");
11177 assert(RHS->getInterface() && "RHS must have an interface base");
11178
11179 // Add all of the protocols for the LHS.
11181
11182 // Start with the protocol qualifiers.
11183 for (auto *proto : LHS->quals()) {
11184 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
11185 }
11186
11187 // Also add the protocols associated with the LHS interface.
11188 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
11189
11190 // Add all of the protocols for the RHS.
11192
11193 // Start with the protocol qualifiers.
11194 for (auto *proto : RHS->quals()) {
11195 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
11196 }
11197
11198 // Also add the protocols associated with the RHS interface.
11199 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
11200
11201 // Compute the intersection of the collected protocol sets.
11202 for (auto *proto : LHSProtocolSet) {
11203 if (RHSProtocolSet.count(proto))
11204 IntersectionSet.push_back(proto);
11205 }
11206
11207 // Compute the set of protocols that is implied by either the common type or
11208 // the protocols within the intersection.
11210 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
11211
11212 // Remove any implied protocols from the list of inherited protocols.
11213 if (!ImpliedProtocols.empty()) {
11214 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
11215 return ImpliedProtocols.contains(proto);
11216 });
11217 }
11218
11219 // Sort the remaining protocols by name.
11220 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
11222}
11223
11224/// Determine whether the first type is a subtype of the second.
11226 QualType rhs) {
11227 // Common case: two object pointers.
11228 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
11229 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
11230 if (lhsOPT && rhsOPT)
11231 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
11232
11233 // Two block pointers.
11234 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
11235 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
11236 if (lhsBlock && rhsBlock)
11237 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
11238
11239 // If either is an unqualified 'id' and the other is a block, it's
11240 // acceptable.
11241 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
11242 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
11243 return true;
11244
11245 return false;
11246}
11247
11248// Check that the given Objective-C type argument lists are equivalent.
11250 const ObjCInterfaceDecl *iface,
11251 ArrayRef<QualType> lhsArgs,
11252 ArrayRef<QualType> rhsArgs,
11253 bool stripKindOf) {
11254 if (lhsArgs.size() != rhsArgs.size())
11255 return false;
11256
11257 ObjCTypeParamList *typeParams = iface->getTypeParamList();
11258 if (!typeParams)
11259 return false;
11260
11261 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
11262 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
11263 continue;
11264
11265 switch (typeParams->begin()[i]->getVariance()) {
11267 if (!stripKindOf ||
11268 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
11269 rhsArgs[i].stripObjCKindOfType(ctx))) {
11270 return false;
11271 }
11272 break;
11273
11275 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
11276 return false;
11277 break;
11278
11280 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
11281 return false;
11282 break;
11283 }
11284 }
11285
11286 return true;
11287}
11288
11290 const ObjCObjectPointerType *Lptr,
11291 const ObjCObjectPointerType *Rptr) {
11292 const ObjCObjectType *LHS = Lptr->getObjectType();
11293 const ObjCObjectType *RHS = Rptr->getObjectType();
11294 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
11295 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
11296
11297 if (!LDecl || !RDecl)
11298 return {};
11299
11300 // When either LHS or RHS is a kindof type, we should return a kindof type.
11301 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
11302 // kindof(A).
11303 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
11304
11305 // Follow the left-hand side up the class hierarchy until we either hit a
11306 // root or find the RHS. Record the ancestors in case we don't find it.
11307 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
11308 LHSAncestors;
11309 while (true) {
11310 // Record this ancestor. We'll need this if the common type isn't in the
11311 // path from the LHS to the root.
11312 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
11313
11314 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
11315 // Get the type arguments.
11316 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
11317 bool anyChanges = false;
11318 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11319 // Both have type arguments, compare them.
11320 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11321 LHS->getTypeArgs(), RHS->getTypeArgs(),
11322 /*stripKindOf=*/true))
11323 return {};
11324 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11325 // If only one has type arguments, the result will not have type
11326 // arguments.
11327 LHSTypeArgs = {};
11328 anyChanges = true;
11329 }
11330
11331 // Compute the intersection of protocols.
11333 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
11334 Protocols);
11335 if (!Protocols.empty())
11336 anyChanges = true;
11337
11338 // If anything in the LHS will have changed, build a new result type.
11339 // If we need to return a kindof type but LHS is not a kindof type, we
11340 // build a new result type.
11341 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
11342 QualType Result = getObjCInterfaceType(LHS->getInterface());
11343 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
11344 anyKindOf || LHS->isKindOfType());
11346 }
11347
11348 return getObjCObjectPointerType(QualType(LHS, 0));
11349 }
11350
11351 // Find the superclass.
11352 QualType LHSSuperType = LHS->getSuperClassType();
11353 if (LHSSuperType.isNull())
11354 break;
11355
11356 LHS = LHSSuperType->castAs<ObjCObjectType>();
11357 }
11358
11359 // We didn't find anything by following the LHS to its root; now check
11360 // the RHS against the cached set of ancestors.
11361 while (true) {
11362 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
11363 if (KnownLHS != LHSAncestors.end()) {
11364 LHS = KnownLHS->second;
11365
11366 // Get the type arguments.
11367 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
11368 bool anyChanges = false;
11369 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11370 // Both have type arguments, compare them.
11371 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11372 LHS->getTypeArgs(), RHS->getTypeArgs(),
11373 /*stripKindOf=*/true))
11374 return {};
11375 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11376 // If only one has type arguments, the result will not have type
11377 // arguments.
11378 RHSTypeArgs = {};
11379 anyChanges = true;
11380 }
11381
11382 // Compute the intersection of protocols.
11384 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
11385 Protocols);
11386 if (!Protocols.empty())
11387 anyChanges = true;
11388
11389 // If we need to return a kindof type but RHS is not a kindof type, we
11390 // build a new result type.
11391 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
11392 QualType Result = getObjCInterfaceType(RHS->getInterface());
11393 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
11394 anyKindOf || RHS->isKindOfType());
11396 }
11397
11398 return getObjCObjectPointerType(QualType(RHS, 0));
11399 }
11400
11401 // Find the superclass of the RHS.
11402 QualType RHSSuperType = RHS->getSuperClassType();
11403 if (RHSSuperType.isNull())
11404 break;
11405
11406 RHS = RHSSuperType->castAs<ObjCObjectType>();
11407 }
11408
11409 return {};
11410}
11411
11413 const ObjCObjectType *RHS) {
11414 assert(LHS->getInterface() && "LHS is not an interface type");
11415 assert(RHS->getInterface() && "RHS is not an interface type");
11416
11417 // Verify that the base decls are compatible: the RHS must be a subclass of
11418 // the LHS.
11419 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
11420 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
11421 if (!IsSuperClass)
11422 return false;
11423
11424 // If the LHS has protocol qualifiers, determine whether all of them are
11425 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
11426 // LHS).
11427 if (LHS->getNumProtocols() > 0) {
11428 // OK if conversion of LHS to SuperClass results in narrowing of types
11429 // ; i.e., SuperClass may implement at least one of the protocols
11430 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
11431 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
11432 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
11433 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
11434 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
11435 // qualifiers.
11436 for (auto *RHSPI : RHS->quals())
11437 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
11438 // If there is no protocols associated with RHS, it is not a match.
11439 if (SuperClassInheritedProtocols.empty())
11440 return false;
11441
11442 for (const auto *LHSProto : LHS->quals()) {
11443 bool SuperImplementsProtocol = false;
11444 for (auto *SuperClassProto : SuperClassInheritedProtocols)
11445 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
11446 SuperImplementsProtocol = true;
11447 break;
11448 }
11449 if (!SuperImplementsProtocol)
11450 return false;
11451 }
11452 }
11453
11454 // If the LHS is specialized, we may need to check type arguments.
11455 if (LHS->isSpecialized()) {
11456 // Follow the superclass chain until we've matched the LHS class in the
11457 // hierarchy. This substitutes type arguments through.
11458 const ObjCObjectType *RHSSuper = RHS;
11459 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
11460 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
11461
11462 // If the RHS is specializd, compare type arguments.
11463 if (RHSSuper->isSpecialized() &&
11464 !sameObjCTypeArgs(*this, LHS->getInterface(),
11465 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
11466 /*stripKindOf=*/true)) {
11467 return false;
11468 }
11469 }
11470
11471 return true;
11472}
11473
11475 // get the "pointed to" types
11476 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
11477 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
11478
11479 if (!LHSOPT || !RHSOPT)
11480 return false;
11481
11482 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
11483 canAssignObjCInterfaces(RHSOPT, LHSOPT);
11484}
11485
11488 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
11489 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
11490}
11491
11492/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
11493/// both shall have the identically qualified version of a compatible type.
11494/// C99 6.2.7p1: Two types have compatible types if their types are the
11495/// same. See 6.7.[2,3,5] for additional rules.
11497 bool CompareUnqualified) {
11498 if (getLangOpts().CPlusPlus)
11499 return hasSameType(LHS, RHS);
11500
11501 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
11502}
11503
11505 return typesAreCompatible(LHS, RHS);
11506}
11507
11509 return !mergeTypes(LHS, RHS, true).isNull();
11510}
11511
11512/// mergeTransparentUnionType - if T is a transparent union type and a member
11513/// of T is compatible with SubType, return the merged type, else return
11514/// QualType()
11516 bool OfBlockPointer,
11517 bool Unqualified) {
11518 if (const RecordType *UT = T->getAsUnionType()) {
11519 RecordDecl *UD = UT->getDecl()->getMostRecentDecl();
11520 if (UD->hasAttr<TransparentUnionAttr>()) {
11521 for (const auto *I : UD->fields()) {
11522 QualType ET = I->getType().getUnqualifiedType();
11523 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
11524 if (!MT.isNull())
11525 return MT;
11526 }
11527 }
11528 }
11529
11530 return {};
11531}
11532
11533/// mergeFunctionParameterTypes - merge two types which appear as function
11534/// parameter types
11536 bool OfBlockPointer,
11537 bool Unqualified) {
11538 // GNU extension: two types are compatible if they appear as a function
11539 // argument, one of the types is a transparent union type and the other
11540 // type is compatible with a union member
11541 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
11542 Unqualified);
11543 if (!lmerge.isNull())
11544 return lmerge;
11545
11546 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
11547 Unqualified);
11548 if (!rmerge.isNull())
11549 return rmerge;
11550
11551 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
11552}
11553
11555 bool OfBlockPointer, bool Unqualified,
11556 bool AllowCXX,
11557 bool IsConditionalOperator) {
11558 const auto *lbase = lhs->castAs<FunctionType>();
11559 const auto *rbase = rhs->castAs<FunctionType>();
11560 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
11561 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
11562 bool allLTypes = true;
11563 bool allRTypes = true;
11564
11565 // Check return type
11566 QualType retType;
11567 if (OfBlockPointer) {
11568 QualType RHS = rbase->getReturnType();
11569 QualType LHS = lbase->getReturnType();
11570 bool UnqualifiedResult = Unqualified;
11571 if (!UnqualifiedResult)
11572 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
11573 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
11574 }
11575 else
11576 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
11577 Unqualified);
11578 if (retType.isNull())
11579 return {};
11580
11581 if (Unqualified)
11582 retType = retType.getUnqualifiedType();
11583
11584 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
11585 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
11586 if (Unqualified) {
11587 LRetType = LRetType.getUnqualifiedType();
11588 RRetType = RRetType.getUnqualifiedType();
11589 }
11590
11591 if (getCanonicalType(retType) != LRetType)
11592 allLTypes = false;
11593 if (getCanonicalType(retType) != RRetType)
11594 allRTypes = false;
11595
11596 // FIXME: double check this
11597 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
11598 // rbase->getRegParmAttr() != 0 &&
11599 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
11600 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
11601 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
11602
11603 // Compatible functions must have compatible calling conventions
11604 if (lbaseInfo.getCC() != rbaseInfo.getCC())
11605 return {};
11606
11607 // Regparm is part of the calling convention.
11608 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
11609 return {};
11610 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
11611 return {};
11612
11613 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
11614 return {};
11615 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
11616 return {};
11617 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
11618 return {};
11619
11620 // When merging declarations, it's common for supplemental information like
11621 // attributes to only be present in one of the declarations, and we generally
11622 // want type merging to preserve the union of information. So a merged
11623 // function type should be noreturn if it was noreturn in *either* operand
11624 // type.
11625 //
11626 // But for the conditional operator, this is backwards. The result of the
11627 // operator could be either operand, and its type should conservatively
11628 // reflect that. So a function type in a composite type is noreturn only
11629 // if it's noreturn in *both* operand types.
11630 //
11631 // Arguably, noreturn is a kind of subtype, and the conditional operator
11632 // ought to produce the most specific common supertype of its operand types.
11633 // That would differ from this rule in contravariant positions. However,
11634 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
11635 // as a practical matter, it would only affect C code that does abstraction of
11636 // higher-order functions (taking noreturn callbacks!), which is uncommon to
11637 // say the least. So we use the simpler rule.
11638 bool NoReturn = IsConditionalOperator
11639 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
11640 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
11641 if (lbaseInfo.getNoReturn() != NoReturn)
11642 allLTypes = false;
11643 if (rbaseInfo.getNoReturn() != NoReturn)
11644 allRTypes = false;
11645
11646 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
11647
11648 std::optional<FunctionEffectSet> MergedFX;
11649
11650 if (lproto && rproto) { // two C99 style function prototypes
11651 assert((AllowCXX ||
11652 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
11653 "C++ shouldn't be here");
11654 // Compatible functions must have the same number of parameters
11655 if (lproto->getNumParams() != rproto->getNumParams())
11656 return {};
11657
11658 // Variadic and non-variadic functions aren't compatible
11659 if (lproto->isVariadic() != rproto->isVariadic())
11660 return {};
11661
11662 if (lproto->getMethodQuals() != rproto->getMethodQuals())
11663 return {};
11664
11665 // Function protos with different 'cfi_salt' values aren't compatible.
11666 if (lproto->getExtraAttributeInfo().CFISalt !=
11667 rproto->getExtraAttributeInfo().CFISalt)
11668 return {};
11669
11670 // Function effects are handled similarly to noreturn, see above.
11671 FunctionEffectsRef LHSFX = lproto->getFunctionEffects();
11672 FunctionEffectsRef RHSFX = rproto->getFunctionEffects();
11673 if (LHSFX != RHSFX) {
11674 if (IsConditionalOperator)
11675 MergedFX = FunctionEffectSet::getIntersection(LHSFX, RHSFX);
11676 else {
11678 MergedFX = FunctionEffectSet::getUnion(LHSFX, RHSFX, Errs);
11679 // Here we're discarding a possible error due to conflicts in the effect
11680 // sets. But we're not in a context where we can report it. The
11681 // operation does however guarantee maintenance of invariants.
11682 }
11683 if (*MergedFX != LHSFX)
11684 allLTypes = false;
11685 if (*MergedFX != RHSFX)
11686 allRTypes = false;
11687 }
11688
11690 bool canUseLeft, canUseRight;
11691 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
11692 newParamInfos))
11693 return {};
11694
11695 if (!canUseLeft)
11696 allLTypes = false;
11697 if (!canUseRight)
11698 allRTypes = false;
11699
11700 // Check parameter type compatibility
11702 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
11703 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
11704 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
11706 lParamType, rParamType, OfBlockPointer, Unqualified);
11707 if (paramType.isNull())
11708 return {};
11709
11710 if (Unqualified)
11711 paramType = paramType.getUnqualifiedType();
11712
11713 types.push_back(paramType);
11714 if (Unqualified) {
11715 lParamType = lParamType.getUnqualifiedType();
11716 rParamType = rParamType.getUnqualifiedType();
11717 }
11718
11719 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
11720 allLTypes = false;
11721 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
11722 allRTypes = false;
11723 }
11724
11725 if (allLTypes) return lhs;
11726 if (allRTypes) return rhs;
11727
11728 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
11729 EPI.ExtInfo = einfo;
11730 EPI.ExtParameterInfos =
11731 newParamInfos.empty() ? nullptr : newParamInfos.data();
11732 if (MergedFX)
11733 EPI.FunctionEffects = *MergedFX;
11734 return getFunctionType(retType, types, EPI);
11735 }
11736
11737 if (lproto) allRTypes = false;
11738 if (rproto) allLTypes = false;
11739
11740 const FunctionProtoType *proto = lproto ? lproto : rproto;
11741 if (proto) {
11742 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
11743 if (proto->isVariadic())
11744 return {};
11745 // Check that the types are compatible with the types that
11746 // would result from default argument promotions (C99 6.7.5.3p15).
11747 // The only types actually affected are promotable integer
11748 // types and floats, which would be passed as a different
11749 // type depending on whether the prototype is visible.
11750 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
11751 QualType paramTy = proto->getParamType(i);
11752
11753 // Look at the converted type of enum types, since that is the type used
11754 // to pass enum values.
11755 if (const auto *ED = paramTy->getAsEnumDecl()) {
11756 paramTy = ED->getIntegerType();
11757 if (paramTy.isNull())
11758 return {};
11759 }
11760
11761 if (isPromotableIntegerType(paramTy) ||
11762 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
11763 return {};
11764 }
11765
11766 if (allLTypes) return lhs;
11767 if (allRTypes) return rhs;
11768
11770 EPI.ExtInfo = einfo;
11771 if (MergedFX)
11772 EPI.FunctionEffects = *MergedFX;
11773 return getFunctionType(retType, proto->getParamTypes(), EPI);
11774 }
11775
11776 if (allLTypes) return lhs;
11777 if (allRTypes) return rhs;
11778 return getFunctionNoProtoType(retType, einfo);
11779}
11780
11781/// Given that we have an enum type and a non-enum type, try to merge them.
11782static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
11783 QualType other, bool isBlockReturnType) {
11784 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
11785 // a signed integer type, or an unsigned integer type.
11786 // Compatibility is based on the underlying type, not the promotion
11787 // type.
11788 QualType underlyingType =
11789 ET->getDecl()->getDefinitionOrSelf()->getIntegerType();
11790 if (underlyingType.isNull())
11791 return {};
11792 if (Context.hasSameType(underlyingType, other))
11793 return other;
11794
11795 // In block return types, we're more permissive and accept any
11796 // integral type of the same size.
11797 if (isBlockReturnType && other->isIntegerType() &&
11798 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
11799 return other;
11800
11801 return {};
11802}
11803
11805 // C17 and earlier and C++ disallow two tag definitions within the same TU
11806 // from being compatible.
11807 if (LangOpts.CPlusPlus || !LangOpts.C23)
11808 return {};
11809
11810 // Nameless tags are comparable only within outer definitions. At the top
11811 // level they are not comparable.
11812 const TagDecl *LTagD = LHS->castAsTagDecl(), *RTagD = RHS->castAsTagDecl();
11813 if (!LTagD->getIdentifier() || !RTagD->getIdentifier())
11814 return {};
11815
11816 // C23, on the other hand, requires the members to be "the same enough", so
11817 // we use a structural equivalence check.
11820 getLangOpts(), *this, *this, NonEquivalentDecls,
11821 StructuralEquivalenceKind::Default, /*StrictTypeSpelling=*/false,
11822 /*Complain=*/false, /*ErrorOnTagTypeMismatch=*/true);
11823 return Ctx.IsEquivalent(LHS, RHS) ? LHS : QualType{};
11824}
11825
11827 QualType LHS, QualType RHS, bool OfBlockPointer, bool Unqualified,
11828 bool BlockReturnType, bool IsConditionalOperator) {
11829 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
11830 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
11831
11832 if (!LHSOBT && !RHSOBT)
11833 return std::nullopt;
11834
11835 if (LHSOBT) {
11836 if (RHSOBT) {
11837 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
11838 return QualType();
11839
11840 QualType MergedUnderlying = mergeTypes(
11841 LHSOBT->getUnderlyingType(), RHSOBT->getUnderlyingType(),
11842 OfBlockPointer, Unqualified, BlockReturnType, IsConditionalOperator);
11843
11844 if (MergedUnderlying.isNull())
11845 return QualType();
11846
11847 if (getCanonicalType(LHSOBT) == getCanonicalType(RHSOBT)) {
11848 if (LHSOBT->getUnderlyingType() == RHSOBT->getUnderlyingType())
11849 return getCommonSugaredType(LHS, RHS);
11851 LHSOBT->getBehaviorKind(),
11852 getCanonicalType(LHSOBT->getUnderlyingType()));
11853 }
11854
11855 // For different underlying types that successfully merge, wrap the
11856 // merged underlying type with the common overflow behavior
11857 return getOverflowBehaviorType(LHSOBT->getBehaviorKind(),
11858 MergedUnderlying);
11859 }
11860 return mergeTypes(LHSOBT->getUnderlyingType(), RHS, OfBlockPointer,
11861 Unqualified, BlockReturnType, IsConditionalOperator);
11862 }
11863
11864 return mergeTypes(LHS, RHSOBT->getUnderlyingType(), OfBlockPointer,
11865 Unqualified, BlockReturnType, IsConditionalOperator);
11866}
11867
11868QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
11869 bool Unqualified, bool BlockReturnType,
11870 bool IsConditionalOperator) {
11871 // For C++ we will not reach this code with reference types (see below),
11872 // for OpenMP variant call overloading we might.
11873 //
11874 // C++ [expr]: If an expression initially has the type "reference to T", the
11875 // type is adjusted to "T" prior to any further analysis, the expression
11876 // designates the object or function denoted by the reference, and the
11877 // expression is an lvalue unless the reference is an rvalue reference and
11878 // the expression is a function call (possibly inside parentheses).
11879 auto *LHSRefTy = LHS->getAs<ReferenceType>();
11880 auto *RHSRefTy = RHS->getAs<ReferenceType>();
11881 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
11882 LHS->getTypeClass() == RHS->getTypeClass())
11883 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
11884 OfBlockPointer, Unqualified, BlockReturnType);
11885 if (LHSRefTy || RHSRefTy)
11886 return {};
11887
11888 if (std::optional<QualType> MergedOBT =
11889 tryMergeOverflowBehaviorTypes(LHS, RHS, OfBlockPointer, Unqualified,
11890 BlockReturnType, IsConditionalOperator))
11891 return *MergedOBT;
11892
11893 if (Unqualified) {
11894 LHS = LHS.getUnqualifiedType();
11895 RHS = RHS.getUnqualifiedType();
11896 }
11897
11898 QualType LHSCan = getCanonicalType(LHS),
11899 RHSCan = getCanonicalType(RHS);
11900
11901 // If two types are identical, they are compatible.
11902 if (LHSCan == RHSCan)
11903 return LHS;
11904
11905 // If the qualifiers are different, the types aren't compatible... mostly.
11906 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11907 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11908 if (LQuals != RQuals) {
11909 // If any of these qualifiers are different, we have a type
11910 // mismatch.
11911 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11912 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
11913 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
11914 !LQuals.getPointerAuth().isEquivalent(RQuals.getPointerAuth()) ||
11915 LQuals.hasUnaligned() != RQuals.hasUnaligned())
11916 return {};
11917
11918 // Exactly one GC qualifier difference is allowed: __strong is
11919 // okay if the other type has no GC qualifier but is an Objective
11920 // C object pointer (i.e. implicitly strong by default). We fix
11921 // this by pretending that the unqualified type was actually
11922 // qualified __strong.
11923 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11924 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11925 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11926
11927 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11928 return {};
11929
11930 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
11932 }
11933 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
11935 }
11936 return {};
11937 }
11938
11939 // Okay, qualifiers are equal.
11940
11941 Type::TypeClass LHSClass = LHSCan->getTypeClass();
11942 Type::TypeClass RHSClass = RHSCan->getTypeClass();
11943
11944 // We want to consider the two function types to be the same for these
11945 // comparisons, just force one to the other.
11946 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
11947 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
11948
11949 // Same as above for arrays
11950 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
11951 LHSClass = Type::ConstantArray;
11952 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
11953 RHSClass = Type::ConstantArray;
11954
11955 // ObjCInterfaces are just specialized ObjCObjects.
11956 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
11957 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
11958
11959 // Canonicalize ExtVector -> Vector.
11960 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
11961 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
11962
11963 // If the canonical type classes don't match.
11964 if (LHSClass != RHSClass) {
11965 // Note that we only have special rules for turning block enum
11966 // returns into block int returns, not vice-versa.
11967 if (const auto *ETy = LHS->getAsCanonical<EnumType>()) {
11968 return mergeEnumWithInteger(*this, ETy, RHS, false);
11969 }
11970 if (const EnumType *ETy = RHS->getAsCanonical<EnumType>()) {
11971 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
11972 }
11973 // allow block pointer type to match an 'id' type.
11974 if (OfBlockPointer && !BlockReturnType) {
11975 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
11976 return LHS;
11977 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
11978 return RHS;
11979 }
11980 // Allow __auto_type to match anything; it merges to the type with more
11981 // information.
11982 if (const auto *AT = LHS->getAs<AutoType>()) {
11983 if (!AT->isDeduced() && AT->isGNUAutoType())
11984 return RHS;
11985 }
11986 if (const auto *AT = RHS->getAs<AutoType>()) {
11987 if (!AT->isDeduced() && AT->isGNUAutoType())
11988 return LHS;
11989 }
11990 return {};
11991 }
11992
11993 // The canonical type classes match.
11994 switch (LHSClass) {
11995#define TYPE(Class, Base)
11996#define ABSTRACT_TYPE(Class, Base)
11997#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
11998#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
11999#define DEPENDENT_TYPE(Class, Base) case Type::Class:
12000#include "clang/AST/TypeNodes.inc"
12001 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
12002
12003 case Type::Auto:
12004 case Type::DeducedTemplateSpecialization:
12005 case Type::LValueReference:
12006 case Type::RValueReference:
12007 case Type::MemberPointer:
12008 llvm_unreachable("C++ should never be in mergeTypes");
12009
12010 case Type::ObjCInterface:
12011 case Type::IncompleteArray:
12012 case Type::VariableArray:
12013 case Type::FunctionProto:
12014 case Type::ExtVector:
12015 case Type::OverflowBehavior:
12016 llvm_unreachable("Types are eliminated above");
12017
12018 case Type::Pointer:
12019 {
12020 // Merge two pointer types, while trying to preserve typedef info
12021 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
12022 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
12023 if (Unqualified) {
12024 LHSPointee = LHSPointee.getUnqualifiedType();
12025 RHSPointee = RHSPointee.getUnqualifiedType();
12026 }
12027 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
12028 Unqualified);
12029 if (ResultType.isNull())
12030 return {};
12031 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
12032 return LHS;
12033 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
12034 return RHS;
12035 return getPointerType(ResultType);
12036 }
12037 case Type::BlockPointer:
12038 {
12039 // Merge two block pointer types, while trying to preserve typedef info
12040 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
12041 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
12042 if (Unqualified) {
12043 LHSPointee = LHSPointee.getUnqualifiedType();
12044 RHSPointee = RHSPointee.getUnqualifiedType();
12045 }
12046 if (getLangOpts().OpenCL) {
12047 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
12048 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
12049 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
12050 // 6.12.5) thus the following check is asymmetric.
12051 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual, *this))
12052 return {};
12053 LHSPteeQual.removeAddressSpace();
12054 RHSPteeQual.removeAddressSpace();
12055 LHSPointee =
12056 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
12057 RHSPointee =
12058 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
12059 }
12060 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
12061 Unqualified);
12062 if (ResultType.isNull())
12063 return {};
12064 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
12065 return LHS;
12066 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
12067 return RHS;
12068 return getBlockPointerType(ResultType);
12069 }
12070 case Type::Atomic:
12071 {
12072 // Merge two pointer types, while trying to preserve typedef info
12073 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
12074 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
12075 if (Unqualified) {
12076 LHSValue = LHSValue.getUnqualifiedType();
12077 RHSValue = RHSValue.getUnqualifiedType();
12078 }
12079 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
12080 Unqualified);
12081 if (ResultType.isNull())
12082 return {};
12083 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
12084 return LHS;
12085 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
12086 return RHS;
12087 return getAtomicType(ResultType);
12088 }
12089 case Type::ConstantArray:
12090 {
12091 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
12092 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
12093 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
12094 return {};
12095
12096 QualType LHSElem = getAsArrayType(LHS)->getElementType();
12097 QualType RHSElem = getAsArrayType(RHS)->getElementType();
12098 if (Unqualified) {
12099 LHSElem = LHSElem.getUnqualifiedType();
12100 RHSElem = RHSElem.getUnqualifiedType();
12101 }
12102
12103 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
12104 if (ResultType.isNull())
12105 return {};
12106
12107 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
12108 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
12109
12110 // If either side is a variable array, and both are complete, check whether
12111 // the current dimension is definite.
12112 if (LVAT || RVAT) {
12113 auto SizeFetch = [this](const VariableArrayType* VAT,
12114 const ConstantArrayType* CAT)
12115 -> std::pair<bool,llvm::APInt> {
12116 if (VAT) {
12117 std::optional<llvm::APSInt> TheInt;
12118 Expr *E = VAT->getSizeExpr();
12119 if (E && (TheInt = E->getIntegerConstantExpr(*this)))
12120 return std::make_pair(true, *TheInt);
12121 return std::make_pair(false, llvm::APSInt());
12122 }
12123 if (CAT)
12124 return std::make_pair(true, CAT->getSize());
12125 return std::make_pair(false, llvm::APInt());
12126 };
12127
12128 bool HaveLSize, HaveRSize;
12129 llvm::APInt LSize, RSize;
12130 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
12131 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
12132 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
12133 return {}; // Definite, but unequal, array dimension
12134 }
12135
12136 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
12137 return LHS;
12138 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
12139 return RHS;
12140 if (LCAT)
12141 return getConstantArrayType(ResultType, LCAT->getSize(),
12142 LCAT->getSizeExpr(), ArraySizeModifier(), 0);
12143 if (RCAT)
12144 return getConstantArrayType(ResultType, RCAT->getSize(),
12145 RCAT->getSizeExpr(), ArraySizeModifier(), 0);
12146 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
12147 return LHS;
12148 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
12149 return RHS;
12150 if (LVAT) {
12151 // FIXME: This isn't correct! But tricky to implement because
12152 // the array's size has to be the size of LHS, but the type
12153 // has to be different.
12154 return LHS;
12155 }
12156 if (RVAT) {
12157 // FIXME: This isn't correct! But tricky to implement because
12158 // the array's size has to be the size of RHS, but the type
12159 // has to be different.
12160 return RHS;
12161 }
12162 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
12163 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
12164 return getIncompleteArrayType(ResultType, ArraySizeModifier(), 0);
12165 }
12166 case Type::FunctionNoProto:
12167 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified,
12168 /*AllowCXX=*/false, IsConditionalOperator);
12169 case Type::Record:
12170 case Type::Enum:
12171 return mergeTagDefinitions(LHS, RHS);
12172 case Type::Builtin:
12173 // Only exactly equal builtin types are compatible, which is tested above.
12174 return {};
12175 case Type::Complex:
12176 // Distinct complex types are incompatible.
12177 return {};
12178 case Type::Vector:
12179 // FIXME: The merged type should be an ExtVector!
12180 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
12181 RHSCan->castAs<VectorType>()))
12182 return LHS;
12183 return {};
12184 case Type::ConstantMatrix:
12186 RHSCan->castAs<ConstantMatrixType>()))
12187 return LHS;
12188 return {};
12189 case Type::ObjCObject: {
12190 // Check if the types are assignment compatible.
12191 // FIXME: This should be type compatibility, e.g. whether
12192 // "LHS x; RHS x;" at global scope is legal.
12194 RHS->castAs<ObjCObjectType>()))
12195 return LHS;
12196 return {};
12197 }
12198 case Type::ObjCObjectPointer:
12199 if (OfBlockPointer) {
12202 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
12203 return LHS;
12204 return {};
12205 }
12208 return LHS;
12209 return {};
12210 case Type::Pipe:
12211 assert(LHS != RHS &&
12212 "Equivalent pipe types should have already been handled!");
12213 return {};
12214 case Type::ArrayParameter:
12215 assert(LHS != RHS &&
12216 "Equivalent ArrayParameter types should have already been handled!");
12217 return {};
12218 case Type::BitInt: {
12219 // Merge two bit-precise int types, while trying to preserve typedef info.
12220 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
12221 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
12222 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
12223 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
12224
12225 // Like unsigned/int, shouldn't have a type if they don't match.
12226 if (LHSUnsigned != RHSUnsigned)
12227 return {};
12228
12229 if (LHSBits != RHSBits)
12230 return {};
12231 return LHS;
12232 }
12233 case Type::HLSLAttributedResource: {
12234 const HLSLAttributedResourceType *LHSTy =
12235 LHS->castAs<HLSLAttributedResourceType>();
12236 const HLSLAttributedResourceType *RHSTy =
12237 RHS->castAs<HLSLAttributedResourceType>();
12238 assert(LHSTy->getWrappedType() == RHSTy->getWrappedType() &&
12239 LHSTy->getWrappedType()->isHLSLResourceType() &&
12240 "HLSLAttributedResourceType should always wrap __hlsl_resource_t");
12241
12242 if (LHSTy->getAttrs() == RHSTy->getAttrs() &&
12243 LHSTy->getContainedType() == RHSTy->getContainedType())
12244 return LHS;
12245 return {};
12246 }
12247 case Type::HLSLInlineSpirv:
12248 const HLSLInlineSpirvType *LHSTy = LHS->castAs<HLSLInlineSpirvType>();
12249 const HLSLInlineSpirvType *RHSTy = RHS->castAs<HLSLInlineSpirvType>();
12250
12251 if (LHSTy->getOpcode() == RHSTy->getOpcode() &&
12252 LHSTy->getSize() == RHSTy->getSize() &&
12253 LHSTy->getAlignment() == RHSTy->getAlignment()) {
12254 for (size_t I = 0; I < LHSTy->getOperands().size(); I++)
12255 if (LHSTy->getOperands()[I] != RHSTy->getOperands()[I])
12256 return {};
12257
12258 return LHS;
12259 }
12260 return {};
12261 }
12262
12263 llvm_unreachable("Invalid Type::Class!");
12264}
12265
12267 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
12268 bool &CanUseFirst, bool &CanUseSecond,
12270 assert(NewParamInfos.empty() && "param info list not empty");
12271 CanUseFirst = CanUseSecond = true;
12272 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
12273 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
12274
12275 // Fast path: if the first type doesn't have ext parameter infos,
12276 // we match if and only if the second type also doesn't have them.
12277 if (!FirstHasInfo && !SecondHasInfo)
12278 return true;
12279
12280 bool NeedParamInfo = false;
12281 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
12282 : SecondFnType->getExtParameterInfos().size();
12283
12284 for (size_t I = 0; I < E; ++I) {
12285 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
12286 if (FirstHasInfo)
12287 FirstParam = FirstFnType->getExtParameterInfo(I);
12288 if (SecondHasInfo)
12289 SecondParam = SecondFnType->getExtParameterInfo(I);
12290
12291 // Cannot merge unless everything except the noescape flag matches.
12292 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
12293 return false;
12294
12295 bool FirstNoEscape = FirstParam.isNoEscape();
12296 bool SecondNoEscape = SecondParam.isNoEscape();
12297 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
12298 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
12299 if (NewParamInfos.back().getOpaqueValue())
12300 NeedParamInfo = true;
12301 if (FirstNoEscape != IsNoEscape)
12302 CanUseFirst = false;
12303 if (SecondNoEscape != IsNoEscape)
12304 CanUseSecond = false;
12305 }
12306
12307 if (!NeedParamInfo)
12308 NewParamInfos.clear();
12309
12310 return true;
12311}
12312
12314 if (auto It = ObjCLayouts.find(D); It != ObjCLayouts.end()) {
12315 It->second = nullptr;
12316 for (auto *SubClass : ObjCSubClasses.lookup(D))
12317 ResetObjCLayout(SubClass);
12318 }
12319}
12320
12321/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
12322/// 'RHS' attributes and returns the merged version; including for function
12323/// return types.
12325 QualType LHSCan = getCanonicalType(LHS),
12326 RHSCan = getCanonicalType(RHS);
12327 // If two types are identical, they are compatible.
12328 if (LHSCan == RHSCan)
12329 return LHS;
12330 if (RHSCan->isFunctionType()) {
12331 if (!LHSCan->isFunctionType())
12332 return {};
12333 QualType OldReturnType =
12334 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
12335 QualType NewReturnType =
12336 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
12337 QualType ResReturnType =
12338 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
12339 if (ResReturnType.isNull())
12340 return {};
12341 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
12342 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
12343 // In either case, use OldReturnType to build the new function type.
12344 const auto *F = LHS->castAs<FunctionType>();
12345 if (const auto *FPT = cast<FunctionProtoType>(F)) {
12346 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12347 EPI.ExtInfo = getFunctionExtInfo(LHS);
12348 QualType ResultType =
12349 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
12350 return ResultType;
12351 }
12352 }
12353 return {};
12354 }
12355
12356 // If the qualifiers are different, the types can still be merged.
12357 Qualifiers LQuals = LHSCan.getLocalQualifiers();
12358 Qualifiers RQuals = RHSCan.getLocalQualifiers();
12359 if (LQuals != RQuals) {
12360 // If any of these qualifiers are different, we have a type mismatch.
12361 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
12362 LQuals.getAddressSpace() != RQuals.getAddressSpace())
12363 return {};
12364
12365 // Exactly one GC qualifier difference is allowed: __strong is
12366 // okay if the other type has no GC qualifier but is an Objective
12367 // C object pointer (i.e. implicitly strong by default). We fix
12368 // this by pretending that the unqualified type was actually
12369 // qualified __strong.
12370 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
12371 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
12372 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
12373
12374 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
12375 return {};
12376
12377 if (GC_L == Qualifiers::Strong)
12378 return LHS;
12379 if (GC_R == Qualifiers::Strong)
12380 return RHS;
12381 return {};
12382 }
12383
12384 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
12385 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12386 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12387 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
12388 if (ResQT == LHSBaseQT)
12389 return LHS;
12390 if (ResQT == RHSBaseQT)
12391 return RHS;
12392 }
12393 return {};
12394}
12395
12396//===----------------------------------------------------------------------===//
12397// Integer Predicates
12398//===----------------------------------------------------------------------===//
12399
12401 if (const auto *ED = T->getAsEnumDecl())
12402 T = ED->getIntegerType();
12403 if (T->isBooleanType())
12404 return 1;
12405 if (const auto *EIT = T->getAs<BitIntType>())
12406 return EIT->getNumBits();
12407 // For builtin types, just use the standard type sizing method
12408 return (unsigned)getTypeSize(T);
12409}
12410
12412 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12413 T->isFixedPointType()) &&
12414 "Unexpected type");
12415
12416 // Turn <4 x signed int> -> <4 x unsigned int>
12417 if (const auto *VTy = T->getAs<VectorType>())
12418 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
12419 VTy->getNumElements(), VTy->getVectorKind());
12420
12421 // For _BitInt, return an unsigned _BitInt with same width.
12422 if (const auto *EITy = T->getAs<BitIntType>())
12423 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
12424
12425 // For the overflow behavior types, construct a new unsigned variant
12426 if (const auto *OBT = T->getAs<OverflowBehaviorType>())
12428 OBT->getBehaviorKind(),
12429 getCorrespondingUnsignedType(OBT->getUnderlyingType()));
12430
12431 // For enums, get the underlying integer type of the enum, and let the general
12432 // integer type signchanging code handle it.
12433 if (const auto *ED = T->getAsEnumDecl())
12434 T = ED->getIntegerType();
12435
12436 switch (T->castAs<BuiltinType>()->getKind()) {
12437 case BuiltinType::Char_U:
12438 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
12439 case BuiltinType::Char_S:
12440 case BuiltinType::SChar:
12441 case BuiltinType::Char8:
12442 return UnsignedCharTy;
12443 case BuiltinType::Short:
12444 return UnsignedShortTy;
12445 case BuiltinType::Int:
12446 return UnsignedIntTy;
12447 case BuiltinType::Long:
12448 return UnsignedLongTy;
12449 case BuiltinType::LongLong:
12450 return UnsignedLongLongTy;
12451 case BuiltinType::Int128:
12452 return UnsignedInt128Ty;
12453 // wchar_t is special. It is either signed or not, but when it's signed,
12454 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
12455 // version of its underlying type instead.
12456 case BuiltinType::WChar_S:
12457 return getUnsignedWCharType();
12458
12459 case BuiltinType::ShortAccum:
12460 return UnsignedShortAccumTy;
12461 case BuiltinType::Accum:
12462 return UnsignedAccumTy;
12463 case BuiltinType::LongAccum:
12464 return UnsignedLongAccumTy;
12465 case BuiltinType::SatShortAccum:
12467 case BuiltinType::SatAccum:
12468 return SatUnsignedAccumTy;
12469 case BuiltinType::SatLongAccum:
12471 case BuiltinType::ShortFract:
12472 return UnsignedShortFractTy;
12473 case BuiltinType::Fract:
12474 return UnsignedFractTy;
12475 case BuiltinType::LongFract:
12476 return UnsignedLongFractTy;
12477 case BuiltinType::SatShortFract:
12479 case BuiltinType::SatFract:
12480 return SatUnsignedFractTy;
12481 case BuiltinType::SatLongFract:
12483 default:
12484 assert((T->hasUnsignedIntegerRepresentation() ||
12485 T->isUnsignedFixedPointType()) &&
12486 "Unexpected signed integer or fixed point type");
12487 return T;
12488 }
12489}
12490
12492 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12493 T->isFixedPointType()) &&
12494 "Unexpected type");
12495
12496 // Turn <4 x unsigned int> -> <4 x signed int>
12497 if (const auto *VTy = T->getAs<VectorType>())
12498 return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
12499 VTy->getNumElements(), VTy->getVectorKind());
12500
12501 // For _BitInt, return a signed _BitInt with same width.
12502 if (const auto *EITy = T->getAs<BitIntType>())
12503 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
12504
12505 // For enums, get the underlying integer type of the enum, and let the general
12506 // integer type signchanging code handle it.
12507 if (const auto *ED = T->getAsEnumDecl())
12508 T = ED->getIntegerType();
12509
12510 switch (T->castAs<BuiltinType>()->getKind()) {
12511 case BuiltinType::Char_S:
12512 // Plain `char` is mapped to `signed char` even if it's already signed
12513 case BuiltinType::Char_U:
12514 case BuiltinType::UChar:
12515 case BuiltinType::Char8:
12516 return SignedCharTy;
12517 case BuiltinType::UShort:
12518 return ShortTy;
12519 case BuiltinType::UInt:
12520 return IntTy;
12521 case BuiltinType::ULong:
12522 return LongTy;
12523 case BuiltinType::ULongLong:
12524 return LongLongTy;
12525 case BuiltinType::UInt128:
12526 return Int128Ty;
12527 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
12528 // there's no matching "signed wchar_t". Therefore we return the signed
12529 // version of its underlying type instead.
12530 case BuiltinType::WChar_U:
12531 return getSignedWCharType();
12532
12533 case BuiltinType::UShortAccum:
12534 return ShortAccumTy;
12535 case BuiltinType::UAccum:
12536 return AccumTy;
12537 case BuiltinType::ULongAccum:
12538 return LongAccumTy;
12539 case BuiltinType::SatUShortAccum:
12540 return SatShortAccumTy;
12541 case BuiltinType::SatUAccum:
12542 return SatAccumTy;
12543 case BuiltinType::SatULongAccum:
12544 return SatLongAccumTy;
12545 case BuiltinType::UShortFract:
12546 return ShortFractTy;
12547 case BuiltinType::UFract:
12548 return FractTy;
12549 case BuiltinType::ULongFract:
12550 return LongFractTy;
12551 case BuiltinType::SatUShortFract:
12552 return SatShortFractTy;
12553 case BuiltinType::SatUFract:
12554 return SatFractTy;
12555 case BuiltinType::SatULongFract:
12556 return SatLongFractTy;
12557 default:
12558 assert(
12559 (T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
12560 "Unexpected signed integer or fixed point type");
12561 return T;
12562 }
12563}
12564
12566
12569
12570//===----------------------------------------------------------------------===//
12571// Builtin Type Computation
12572//===----------------------------------------------------------------------===//
12573
12574/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
12575/// pointer over the consumed characters. This returns the resultant type. If
12576/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
12577/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
12578/// a vector of "i*".
12579///
12580/// RequiresICE is filled in on return to indicate whether the value is required
12581/// to be an Integer Constant Expression.
12582static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
12584 bool &RequiresICE,
12585 bool AllowTypeModifiers) {
12586 // Modifiers.
12587 int HowLong = 0;
12588 bool Signed = false, Unsigned = false;
12589 RequiresICE = false;
12590
12591 // Read the prefixed modifiers first.
12592 bool Done = false;
12593 #ifndef NDEBUG
12594 bool IsSpecial = false;
12595 #endif
12596 while (!Done) {
12597 switch (*Str++) {
12598 default: Done = true; --Str; break;
12599 case 'I':
12600 RequiresICE = true;
12601 break;
12602 case 'S':
12603 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
12604 assert(!Signed && "Can't use 'S' modifier multiple times!");
12605 Signed = true;
12606 break;
12607 case 'U':
12608 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
12609 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
12610 Unsigned = true;
12611 break;
12612 case 'L':
12613 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
12614 assert(HowLong <= 2 && "Can't have LLLL modifier");
12615 ++HowLong;
12616 break;
12617 case 'N':
12618 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
12619 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12620 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
12621 #ifndef NDEBUG
12622 IsSpecial = true;
12623 #endif
12624 if (Context.getTargetInfo().getLongWidth() == 32)
12625 ++HowLong;
12626 break;
12627 case 'W':
12628 // This modifier represents int64 type.
12629 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12630 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
12631 #ifndef NDEBUG
12632 IsSpecial = true;
12633 #endif
12634 switch (Context.getTargetInfo().getInt64Type()) {
12635 default:
12636 llvm_unreachable("Unexpected integer type");
12638 HowLong = 1;
12639 break;
12641 HowLong = 2;
12642 break;
12643 }
12644 break;
12645 case 'Z':
12646 // This modifier represents int32 type.
12647 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12648 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
12649 #ifndef NDEBUG
12650 IsSpecial = true;
12651 #endif
12652 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
12653 default:
12654 llvm_unreachable("Unexpected integer type");
12656 HowLong = 0;
12657 break;
12659 HowLong = 1;
12660 break;
12662 HowLong = 2;
12663 break;
12664 }
12665 break;
12666 case 'O':
12667 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12668 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
12669 #ifndef NDEBUG
12670 IsSpecial = true;
12671 #endif
12672 if (Context.getLangOpts().OpenCL)
12673 HowLong = 1;
12674 else
12675 HowLong = 2;
12676 break;
12677 }
12678 }
12679
12680 QualType Type;
12681
12682 // Read the base type.
12683 switch (*Str++) {
12684 default:
12685 llvm_unreachable("Unknown builtin type letter!");
12686 case 'x':
12687 assert(HowLong == 0 && !Signed && !Unsigned &&
12688 "Bad modifiers used with 'x'!");
12689 Type = Context.Float16Ty;
12690 break;
12691 case 'y':
12692 assert(HowLong == 0 && !Signed && !Unsigned &&
12693 "Bad modifiers used with 'y'!");
12694 Type = Context.BFloat16Ty;
12695 break;
12696 case 'v':
12697 assert(HowLong == 0 && !Signed && !Unsigned &&
12698 "Bad modifiers used with 'v'!");
12699 Type = Context.VoidTy;
12700 break;
12701 case 'h':
12702 assert(HowLong == 0 && !Signed && !Unsigned &&
12703 "Bad modifiers used with 'h'!");
12704 Type = Context.HalfTy;
12705 break;
12706 case 'f':
12707 assert(HowLong == 0 && !Signed && !Unsigned &&
12708 "Bad modifiers used with 'f'!");
12709 Type = Context.FloatTy;
12710 break;
12711 case 'd':
12712 assert(HowLong < 3 && !Signed && !Unsigned &&
12713 "Bad modifiers used with 'd'!");
12714 if (HowLong == 1)
12715 Type = Context.LongDoubleTy;
12716 else if (HowLong == 2)
12717 Type = Context.Float128Ty;
12718 else
12719 Type = Context.DoubleTy;
12720 break;
12721 case 's':
12722 assert(HowLong == 0 && "Bad modifiers used with 's'!");
12723 if (Unsigned)
12724 Type = Context.UnsignedShortTy;
12725 else
12726 Type = Context.ShortTy;
12727 break;
12728 case 'i':
12729 if (HowLong == 3)
12730 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
12731 else if (HowLong == 2)
12732 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
12733 else if (HowLong == 1)
12734 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
12735 else
12736 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
12737 break;
12738 case 'c':
12739 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
12740 if (Signed)
12741 Type = Context.SignedCharTy;
12742 else if (Unsigned)
12743 Type = Context.UnsignedCharTy;
12744 else
12745 Type = Context.CharTy;
12746 break;
12747 case 'b': // boolean
12748 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
12749 Type = Context.BoolTy;
12750 break;
12751 case 'z': // size_t.
12752 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
12753 Type = Context.getSizeType();
12754 break;
12755 case 'w': // wchar_t.
12756 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
12757 Type = Context.getWideCharType();
12758 break;
12759 case 'F':
12760 Type = Context.getCFConstantStringType();
12761 break;
12762 case 'G':
12763 Type = Context.getObjCIdType();
12764 break;
12765 case 'H':
12766 Type = Context.getObjCSelType();
12767 break;
12768 case 'M':
12769 Type = Context.getObjCSuperType();
12770 break;
12771 case 'a':
12772 Type = Context.getBuiltinVaListType();
12773 assert(!Type.isNull() && "builtin va list type not initialized!");
12774 break;
12775 case 'A':
12776 // This is a "reference" to a va_list; however, what exactly
12777 // this means depends on how va_list is defined. There are two
12778 // different kinds of va_list: ones passed by value, and ones
12779 // passed by reference. An example of a by-value va_list is
12780 // x86, where va_list is a char*. An example of by-ref va_list
12781 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
12782 // we want this argument to be a char*&; for x86-64, we want
12783 // it to be a __va_list_tag*.
12784 Type = Context.getBuiltinVaListType();
12785 assert(!Type.isNull() && "builtin va list type not initialized!");
12786 if (Type->isArrayType())
12787 Type = Context.getArrayDecayedType(Type);
12788 else
12789 Type = Context.getLValueReferenceType(Type);
12790 break;
12791 case 'q': {
12792 char *End;
12793 unsigned NumElements = strtoul(Str, &End, 10);
12794 assert(End != Str && "Missing vector size");
12795 Str = End;
12796
12797 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12798 RequiresICE, false);
12799 assert(!RequiresICE && "Can't require vector ICE");
12800
12801 Type = Context.getScalableVectorType(ElementType, NumElements);
12802 break;
12803 }
12804 case 'Q': {
12805 switch (*Str++) {
12806 case 'a': {
12807 Type = Context.SveCountTy;
12808 break;
12809 }
12810 case 'b': {
12811 Type = Context.AMDGPUBufferRsrcTy;
12812 break;
12813 }
12814 case 'c': {
12815 Type = Context.AMDGPUFeaturePredicateTy;
12816 break;
12817 }
12818 case 't': {
12819 Type = Context.AMDGPUTextureTy;
12820 break;
12821 }
12822 case 'r': {
12823 Type = Context.HLSLResourceTy;
12824 break;
12825 }
12826 default:
12827 llvm_unreachable("Unexpected target builtin type");
12828 }
12829 break;
12830 }
12831 case 'V': {
12832 char *End;
12833 unsigned NumElements = strtoul(Str, &End, 10);
12834 assert(End != Str && "Missing vector size");
12835 Str = End;
12836
12837 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12838 RequiresICE, false);
12839 assert(!RequiresICE && "Can't require vector ICE");
12840
12841 // TODO: No way to make AltiVec vectors in builtins yet.
12842 Type = Context.getVectorType(ElementType, NumElements, VectorKind::Generic);
12843 break;
12844 }
12845 case 'E': {
12846 char *End;
12847
12848 unsigned NumElements = strtoul(Str, &End, 10);
12849 assert(End != Str && "Missing vector size");
12850
12851 Str = End;
12852
12853 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12854 false);
12855 Type = Context.getExtVectorType(ElementType, NumElements);
12856 break;
12857 }
12858 case 'X': {
12859 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12860 false);
12861 assert(!RequiresICE && "Can't require complex ICE");
12862 Type = Context.getComplexType(ElementType);
12863 break;
12864 }
12865 case 'Y':
12866 Type = Context.getPointerDiffType();
12867 break;
12868 case 'P':
12869 Type = Context.getFILEType();
12870 if (Type.isNull()) {
12872 return {};
12873 }
12874 break;
12875 case 'J':
12876 if (Signed)
12877 Type = Context.getsigjmp_bufType();
12878 else
12879 Type = Context.getjmp_bufType();
12880
12881 if (Type.isNull()) {
12883 return {};
12884 }
12885 break;
12886 case 'K':
12887 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
12888 Type = Context.getucontext_tType();
12889
12890 if (Type.isNull()) {
12892 return {};
12893 }
12894 break;
12895 case 'p':
12896 Type = Context.getProcessIDType();
12897 break;
12898 case 'm':
12899 Type = Context.MFloat8Ty;
12900 break;
12901 }
12902
12903 // If there are modifiers and if we're allowed to parse them, go for it.
12904 Done = !AllowTypeModifiers;
12905 while (!Done) {
12906 switch (char c = *Str++) {
12907 default: Done = true; --Str; break;
12908 case '*':
12909 case '&': {
12910 // Both pointers and references can have their pointee types
12911 // qualified with an address space.
12912 char *End;
12913 unsigned AddrSpace = strtoul(Str, &End, 10);
12914 if (End != Str) {
12915 // Note AddrSpace == 0 is not the same as an unspecified address space.
12916 Type = Context.getAddrSpaceQualType(
12917 Type,
12918 Context.getLangASForBuiltinAddressSpace(AddrSpace));
12919 Str = End;
12920 }
12921 if (c == '*')
12922 Type = Context.getPointerType(Type);
12923 else
12924 Type = Context.getLValueReferenceType(Type);
12925 break;
12926 }
12927 // FIXME: There's no way to have a built-in with an rvalue ref arg.
12928 case 'C':
12929 Type = Type.withConst();
12930 break;
12931 case 'D':
12932 Type = Context.getVolatileType(Type);
12933 break;
12934 case 'R':
12935 Type = Type.withRestrict();
12936 break;
12937 }
12938 }
12939
12940 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
12941 "Integer constant 'I' type must be an integer");
12942
12943 return Type;
12944}
12945
12946// On some targets such as PowerPC, some of the builtins are defined with custom
12947// type descriptors for target-dependent types. These descriptors are decoded in
12948// other functions, but it may be useful to be able to fall back to default
12949// descriptor decoding to define builtins mixing target-dependent and target-
12950// independent types. This function allows decoding one type descriptor with
12951// default decoding.
12952QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
12953 GetBuiltinTypeError &Error, bool &RequireICE,
12954 bool AllowTypeModifiers) const {
12955 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
12956}
12957
12958/// GetBuiltinType - Return the type for the specified builtin.
12961 unsigned *IntegerConstantArgs) const {
12962 const char *TypeStr = BuiltinInfo.getTypeString(Id);
12963 if (TypeStr[0] == '\0') {
12965 return {};
12966 }
12967
12968 SmallVector<QualType, 8> ArgTypes;
12969
12970 bool RequiresICE = false;
12971 Error = GE_None;
12972 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
12973 RequiresICE, true);
12974 if (Error != GE_None)
12975 return {};
12976
12977 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
12978
12979 while (TypeStr[0] && TypeStr[0] != '.') {
12980 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
12981 if (Error != GE_None)
12982 return {};
12983
12984 // If this argument is required to be an IntegerConstantExpression and the
12985 // caller cares, fill in the bitmask we return.
12986 if (RequiresICE && IntegerConstantArgs)
12987 *IntegerConstantArgs |= 1 << ArgTypes.size();
12988
12989 // Do array -> pointer decay. The builtin should use the decayed type.
12990 if (Ty->isArrayType())
12991 Ty = getArrayDecayedType(Ty);
12992
12993 ArgTypes.push_back(Ty);
12994 }
12995
12996 if (Id == Builtin::BI__GetExceptionInfo)
12997 return {};
12998
12999 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
13000 "'.' should only occur at end of builtin type list!");
13001
13002 bool Variadic = (TypeStr[0] == '.');
13003
13004 FunctionType::ExtInfo EI(Target->getDefaultCallingConv());
13005 if (BuiltinInfo.isNoReturn(Id))
13006 EI = EI.withNoReturn(true);
13007
13008 // We really shouldn't be making a no-proto type here.
13009 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
13010 return getFunctionNoProtoType(ResType, EI);
13011
13013 EPI.ExtInfo = EI;
13014 EPI.Variadic = Variadic;
13015 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
13016 EPI.ExceptionSpec.Type =
13018
13019 return getFunctionType(ResType, ArgTypes, EPI);
13020}
13021
13023 const FunctionDecl *FD) {
13024 if (!FD->isExternallyVisible())
13025 return GVA_Internal;
13026
13027 // Non-user-provided functions get emitted as weak definitions with every
13028 // use, no matter whether they've been explicitly instantiated etc.
13029 if (!FD->isUserProvided())
13030 return GVA_DiscardableODR;
13031
13033 switch (FD->getTemplateSpecializationKind()) {
13034 case TSK_Undeclared:
13037 break;
13038
13040 return GVA_StrongODR;
13041
13042 // C++11 [temp.explicit]p10:
13043 // [ Note: The intent is that an inline function that is the subject of
13044 // an explicit instantiation declaration will still be implicitly
13045 // instantiated when used so that the body can be considered for
13046 // inlining, but that no out-of-line copy of the inline function would be
13047 // generated in the translation unit. -- end note ]
13050
13053 break;
13054 }
13055
13056 if (!FD->isInlined())
13057 return External;
13058
13059 if ((!Context.getLangOpts().CPlusPlus &&
13060 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13061 !FD->hasAttr<DLLExportAttr>()) ||
13062 FD->hasAttr<GNUInlineAttr>()) {
13063 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
13064
13065 // GNU or C99 inline semantics. Determine whether this symbol should be
13066 // externally visible.
13068 return External;
13069
13070 // C99 inline semantics, where the symbol is not externally visible.
13072 }
13073
13074 // Functions specified with extern and inline in -fms-compatibility mode
13075 // forcibly get emitted. While the body of the function cannot be later
13076 // replaced, the function definition cannot be discarded.
13077 if (FD->isMSExternInline())
13078 return GVA_StrongODR;
13079
13080 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13082 cast<CXXConstructorDecl>(FD)->isInheritingConstructor() &&
13083 !FD->hasAttr<DLLExportAttr>()) {
13084 // Both Clang and MSVC implement inherited constructors as forwarding
13085 // thunks that delegate to the base constructor. Keep non-dllexport
13086 // inheriting constructor thunks internal since they are not needed
13087 // outside the translation unit.
13088 //
13089 // dllexport inherited constructors are exempted so they are externally
13090 // visible, matching MSVC's export behavior. Inherited constructors
13091 // whose parameters prevent ABI-compatible forwarding (e.g. callee-
13092 // cleanup types) are excluded from export in Sema to avoid silent
13093 // runtime mismatches.
13094 return GVA_Internal;
13095 }
13096
13097 return GVA_DiscardableODR;
13098}
13099
13101 const Decl *D, GVALinkage L) {
13102 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
13103 // dllexport/dllimport on inline functions.
13104 if (D->hasAttr<DLLImportAttr>()) {
13105 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
13107 } else if (D->hasAttr<DLLExportAttr>()) {
13108 if (L == GVA_DiscardableODR)
13109 return GVA_StrongODR;
13110 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
13111 // Device-side functions with __global__ attribute must always be
13112 // visible externally so they can be launched from host.
13113 if (D->hasAttr<CUDAGlobalAttr>() &&
13114 (L == GVA_DiscardableODR || L == GVA_Internal))
13115 return GVA_StrongODR;
13116 // Single source offloading languages like CUDA/HIP need to be able to
13117 // access static device variables from host code of the same compilation
13118 // unit. This is done by externalizing the static variable with a shared
13119 // name between the host and device compilation which is the same for the
13120 // same compilation unit whereas different among different compilation
13121 // units.
13122 if (Context.shouldExternalize(D))
13123 return GVA_StrongExternal;
13124 }
13125 return L;
13126}
13127
13128/// Adjust the GVALinkage for a declaration based on what an external AST source
13129/// knows about whether there can be other definitions of this declaration.
13130static GVALinkage
13132 GVALinkage L) {
13133 ExternalASTSource *Source = Ctx.getExternalSource();
13134 if (!Source)
13135 return L;
13136
13137 switch (Source->hasExternalDefinitions(D)) {
13139 // Other translation units rely on us to provide the definition.
13140 if (L == GVA_DiscardableODR)
13141 return GVA_StrongODR;
13142 break;
13143
13146
13148 break;
13149 }
13150 return L;
13151}
13152
13158
13160 const VarDecl *VD) {
13161 // As an extension for interactive REPLs, make sure constant variables are
13162 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
13163 // marking them as internal.
13164 if (Context.getLangOpts().CPlusPlus &&
13165 Context.getLangOpts().IncrementalExtensions &&
13166 VD->getType().isConstQualified() &&
13167 !VD->getType().isVolatileQualified() && !VD->isInline() &&
13169 return GVA_DiscardableODR;
13170
13171 if (!VD->isExternallyVisible())
13172 return GVA_Internal;
13173
13174 if (VD->isStaticLocal()) {
13175 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
13176 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
13177 LexicalContext = LexicalContext->getLexicalParent();
13178
13179 // ObjC Blocks can create local variables that don't have a FunctionDecl
13180 // LexicalContext.
13181 if (!LexicalContext)
13182 return GVA_DiscardableODR;
13183
13184 // Otherwise, let the static local variable inherit its linkage from the
13185 // nearest enclosing function.
13186 auto StaticLocalLinkage =
13187 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
13188
13189 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
13190 // be emitted in any object with references to the symbol for the object it
13191 // contains, whether inline or out-of-line."
13192 // Similar behavior is observed with MSVC. An alternative ABI could use
13193 // StrongODR/AvailableExternally to match the function, but none are
13194 // known/supported currently.
13195 if (StaticLocalLinkage == GVA_StrongODR ||
13196 StaticLocalLinkage == GVA_AvailableExternally)
13197 return GVA_DiscardableODR;
13198 return StaticLocalLinkage;
13199 }
13200
13201 // MSVC treats in-class initialized static data members as definitions.
13202 // By giving them non-strong linkage, out-of-line definitions won't
13203 // cause link errors.
13204 if (Context.isMSStaticDataMemberInlineDefinition(VD))
13205 return GVA_DiscardableODR;
13206
13207 // Most non-template variables have strong linkage; inline variables are
13208 // linkonce_odr or (occasionally, for compatibility) weak_odr.
13209 GVALinkage StrongLinkage;
13210 switch (Context.getInlineVariableDefinitionKind(VD)) {
13212 StrongLinkage = GVA_StrongExternal;
13213 break;
13216 StrongLinkage = GVA_DiscardableODR;
13217 break;
13219 StrongLinkage = GVA_StrongODR;
13220 break;
13221 }
13222
13223 switch (VD->getTemplateSpecializationKind()) {
13224 case TSK_Undeclared:
13225 return StrongLinkage;
13226
13228 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13229 VD->isStaticDataMember()
13231 : StrongLinkage;
13232
13234 return GVA_StrongODR;
13235
13238
13240 return GVA_DiscardableODR;
13241 }
13242
13243 llvm_unreachable("Invalid Linkage!");
13244}
13245
13251
13253 if (const auto *VD = dyn_cast<VarDecl>(D)) {
13254 if (!VD->isFileVarDecl())
13255 return false;
13256 // Global named register variables (GNU extension) are never emitted.
13257 if (VD->getStorageClass() == SC_Register)
13258 return false;
13259 if (VD->getDescribedVarTemplate() ||
13261 return false;
13262 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13263 // We never need to emit an uninstantiated function template.
13264 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13265 return false;
13266 } else if (isa<PragmaCommentDecl>(D))
13267 return true;
13269 return true;
13270 else if (isa<OMPRequiresDecl>(D))
13271 return true;
13272 else if (isa<OMPThreadPrivateDecl>(D))
13273 return !D->getDeclContext()->isDependentContext();
13274 else if (isa<OMPAllocateDecl>(D))
13275 return !D->getDeclContext()->isDependentContext();
13277 return !D->getDeclContext()->isDependentContext();
13278 else if (isa<ImportDecl>(D))
13279 return true;
13280 else
13281 return false;
13282
13283 // If this is a member of a class template, we do not need to emit it.
13285 return false;
13286
13287 // Weak references don't produce any output by themselves.
13288 if (D->hasAttr<WeakRefAttr>())
13289 return false;
13290
13291 // SYCL device compilation requires that functions defined with the
13292 // sycl_kernel_entry_point or sycl_external attributes be emitted. All
13293 // other entities are emitted only if they are used by a function
13294 // defined with one of those attributes.
13295 if (LangOpts.SYCLIsDevice)
13296 return isa<FunctionDecl>(D) && (D->hasAttr<SYCLKernelEntryPointAttr>() ||
13297 D->hasAttr<SYCLExternalAttr>());
13298
13299 // Aliases and used decls are required.
13300 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
13301 return true;
13302
13303 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13304 // Forward declarations aren't required.
13305 if (!FD->doesThisDeclarationHaveABody())
13306 return FD->doesDeclarationForceExternallyVisibleDefinition();
13307
13308 // Constructors and destructors are required.
13309 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
13310 return true;
13311
13312 // The key function for a class is required. This rule only comes
13313 // into play when inline functions can be key functions, though.
13314 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13315 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13316 const CXXRecordDecl *RD = MD->getParent();
13317 if (MD->isOutOfLine() && RD->isDynamicClass()) {
13318 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
13319 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
13320 return true;
13321 }
13322 }
13323 }
13324
13326
13327 // static, static inline, always_inline, and extern inline functions can
13328 // always be deferred. Normal inline functions can be deferred in C99/C++.
13329 // Implicit template instantiations can also be deferred in C++.
13331 }
13332
13333 const auto *VD = cast<VarDecl>(D);
13334 assert(VD->isFileVarDecl() && "Expected file scoped var");
13335
13336 // If the decl is marked as `declare target to`, it should be emitted for the
13337 // host and for the device.
13338 if (LangOpts.OpenMP &&
13339 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
13340 return true;
13341
13342 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
13344 return false;
13345
13346 if (VD->shouldEmitInExternalSource())
13347 return false;
13348
13349 // Variables that can be needed in other TUs are required.
13352 return true;
13353
13354 // We never need to emit a variable that is available in another TU.
13356 return false;
13357
13358 // Variables that have destruction with side-effects are required.
13359 if (VD->needsDestruction(*this))
13360 return true;
13361
13362 // Variables that have initialization with side-effects are required.
13363 if (VD->hasInitWithSideEffects())
13364 return true;
13365
13366 // Likewise, variables with tuple-like bindings are required if their
13367 // bindings have side-effects.
13368 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) {
13369 for (const auto *BD : DD->flat_bindings())
13370 if (const auto *BindingVD = BD->getHoldingVar())
13371 if (DeclMustBeEmitted(BindingVD))
13372 return true;
13373 }
13374
13375 return false;
13376}
13377
13379 const FunctionDecl *FD,
13380 llvm::function_ref<void(FunctionDecl *)> Pred) const {
13381 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
13382 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
13383 FD = FD->getMostRecentDecl();
13384 // FIXME: The order of traversal here matters and depends on the order of
13385 // lookup results, which happens to be (mostly) oldest-to-newest, but we
13386 // shouldn't rely on that.
13387 for (auto *CurDecl :
13389 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
13390 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
13391 SeenDecls.insert(CurFD).second) {
13392 Pred(CurFD);
13393 }
13394 }
13395}
13396
13398 bool IsCXXMethod) const {
13399 // Pass through to the C++ ABI object
13400 if (IsCXXMethod)
13401 return ABI->getDefaultMethodCallConv(IsVariadic);
13402
13403 switch (LangOpts.getDefaultCallingConv()) {
13405 break;
13407 return CC_C;
13409 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
13410 return CC_X86FastCall;
13411 break;
13413 if (!IsVariadic)
13414 return CC_X86StdCall;
13415 break;
13417 // __vectorcall cannot be applied to variadic functions.
13418 if (!IsVariadic)
13419 return CC_X86VectorCall;
13420 break;
13422 // __regcall cannot be applied to variadic functions.
13423 if (!IsVariadic)
13424 return CC_X86RegCall;
13425 break;
13427 if (!IsVariadic)
13428 return CC_M68kRTD;
13429 break;
13430 }
13431 return Target->getDefaultCallingConv();
13432}
13433
13435 // Pass through to the C++ ABI object
13436 return ABI->isNearlyEmpty(RD);
13437}
13438
13440 if (!VTContext) {
13441 auto ABI = Target->getCXXABI();
13442 if (ABI.isMicrosoft())
13443 VTContext.reset(new MicrosoftVTableContext(*this));
13444 else {
13445 VTContext.reset(new ItaniumVTableContext(*this));
13446 }
13447 }
13448 return VTContext.get();
13449}
13450
13452 if (!T)
13453 T = Target;
13454 switch (T->getCXXABI().getKind()) {
13455 case TargetCXXABI::AppleARM64:
13456 case TargetCXXABI::Fuchsia:
13457 case TargetCXXABI::GenericAArch64:
13458 case TargetCXXABI::GenericItanium:
13459 case TargetCXXABI::GenericARM:
13460 case TargetCXXABI::GenericMIPS:
13461 case TargetCXXABI::iOS:
13462 case TargetCXXABI::WebAssembly:
13463 case TargetCXXABI::WatchOS:
13464 case TargetCXXABI::XL:
13466 case TargetCXXABI::Microsoft:
13468 }
13469 llvm_unreachable("Unsupported ABI");
13470}
13471
13473 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
13474 "Device mangle context does not support Microsoft mangling.");
13475 switch (T.getCXXABI().getKind()) {
13476 case TargetCXXABI::AppleARM64:
13477 case TargetCXXABI::Fuchsia:
13478 case TargetCXXABI::GenericAArch64:
13479 case TargetCXXABI::GenericItanium:
13480 case TargetCXXABI::GenericARM:
13481 case TargetCXXABI::GenericMIPS:
13482 case TargetCXXABI::iOS:
13483 case TargetCXXABI::WebAssembly:
13484 case TargetCXXABI::WatchOS:
13485 case TargetCXXABI::XL:
13487 *this, getDiagnostics(),
13488 [](ASTContext &, const NamedDecl *ND) -> UnsignedOrNone {
13489 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
13490 return RD->getDeviceLambdaManglingNumber();
13491 return std::nullopt;
13492 },
13493 /*IsAux=*/true);
13494 case TargetCXXABI::Microsoft:
13496 /*IsAux=*/true);
13497 }
13498 llvm_unreachable("Unsupported ABI");
13499}
13500
13502 // If the host and device have different C++ ABIs, mark it as the device
13503 // mangle context so that the mangling needs to retrieve the additional
13504 // device lambda mangling number instead of the regular host one.
13505 if (getAuxTargetInfo() && getTargetInfo().getCXXABI().isMicrosoft() &&
13506 getAuxTargetInfo()->getCXXABI().isItaniumFamily()) {
13508 }
13509
13511}
13512
13513CXXABI::~CXXABI() = default;
13514
13516 return ASTRecordLayouts.getMemorySize() +
13517 llvm::capacity_in_bytes(ObjCLayouts) +
13518 llvm::capacity_in_bytes(KeyFunctions) +
13519 llvm::capacity_in_bytes(ObjCImpls) +
13520 llvm::capacity_in_bytes(BlockVarCopyInits) +
13521 llvm::capacity_in_bytes(DeclAttrs) +
13522 llvm::capacity_in_bytes(TemplateOrInstantiation) +
13523 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
13524 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
13525 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
13526 llvm::capacity_in_bytes(OverriddenMethods) +
13527 llvm::capacity_in_bytes(Types) +
13528 llvm::capacity_in_bytes(VariableArrayTypes);
13529}
13530
13531/// getIntTypeForBitwidth -
13532/// sets integer QualTy according to specified details:
13533/// bitwidth, signed/unsigned.
13534/// Returns empty type if there is no appropriate target types.
13536 unsigned Signed) const {
13538 CanQualType QualTy = getFromTargetType(Ty);
13539 if (!QualTy && DestWidth == 128)
13540 return Signed ? Int128Ty : UnsignedInt128Ty;
13541 return QualTy;
13542}
13543
13544/// getRealTypeForBitwidth -
13545/// sets floating point QualTy according to specified bitwidth.
13546/// Returns empty type if there is no appropriate target types.
13548 FloatModeKind ExplicitType) const {
13549 FloatModeKind Ty =
13550 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
13551 switch (Ty) {
13553 return HalfTy;
13555 return FloatTy;
13557 return DoubleTy;
13559 return LongDoubleTy;
13561 return Float128Ty;
13563 return Ibm128Ty;
13565 return {};
13566 }
13567
13568 llvm_unreachable("Unhandled TargetInfo::RealType value");
13569}
13570
13571void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
13572 if (Number <= 1)
13573 return;
13574
13575 MangleNumbers[ND] = Number;
13576
13577 if (Listener)
13578 Listener->AddedManglingNumber(ND, Number);
13579}
13580
13582 bool ForAuxTarget) const {
13583 auto I = MangleNumbers.find(ND);
13584 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
13585 // CUDA/HIP host compilation encodes host and device mangling numbers
13586 // as lower and upper half of 32 bit integer.
13587 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
13588 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
13589 } else {
13590 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
13591 "number for aux target");
13592 }
13593 return Res > 1 ? Res : 1;
13594}
13595
13596void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
13597 if (Number <= 1)
13598 return;
13599
13600 StaticLocalNumbers[VD] = Number;
13601
13602 if (Listener)
13603 Listener->AddedStaticLocalNumbers(VD, Number);
13604}
13605
13607 auto I = StaticLocalNumbers.find(VD);
13608 return I != StaticLocalNumbers.end() ? I->second : 1;
13609}
13610
13612 bool IsDestroying) {
13613 if (!IsDestroying) {
13614 assert(!DestroyingOperatorDeletes.contains(FD->getCanonicalDecl()));
13615 return;
13616 }
13617 DestroyingOperatorDeletes.insert(FD->getCanonicalDecl());
13618}
13619
13621 return DestroyingOperatorDeletes.contains(FD->getCanonicalDecl());
13622}
13623
13625 bool IsTypeAware) {
13626 if (!IsTypeAware) {
13627 assert(!TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl()));
13628 return;
13629 }
13630 TypeAwareOperatorNewAndDeletes.insert(FD->getCanonicalDecl());
13631}
13632
13634 return TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl());
13635}
13636
13638 FunctionDecl *OperatorDelete,
13639 OperatorDeleteKind K) const {
13640 switch (K) {
13642 OperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] = OperatorDelete;
13643 break;
13645 GlobalOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13646 OperatorDelete;
13647 break;
13649 ArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13650 OperatorDelete;
13651 break;
13653 GlobalArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13654 OperatorDelete;
13655 break;
13656 }
13657}
13658
13660 OperatorDeleteKind K) const {
13661 switch (K) {
13663 return OperatorDeletesForVirtualDtor.contains(Dtor->getCanonicalDecl());
13665 return GlobalOperatorDeletesForVirtualDtor.contains(
13666 Dtor->getCanonicalDecl());
13668 return ArrayOperatorDeletesForVirtualDtor.contains(
13669 Dtor->getCanonicalDecl());
13671 return GlobalArrayOperatorDeletesForVirtualDtor.contains(
13672 Dtor->getCanonicalDecl());
13673 }
13674 return false;
13675}
13676
13679 OperatorDeleteKind K) const {
13680 const CXXDestructorDecl *Canon = Dtor->getCanonicalDecl();
13681 switch (K) {
13683 if (OperatorDeletesForVirtualDtor.contains(Canon))
13684 return OperatorDeletesForVirtualDtor[Canon];
13685 return nullptr;
13687 if (GlobalOperatorDeletesForVirtualDtor.contains(Canon))
13688 return GlobalOperatorDeletesForVirtualDtor[Canon];
13689 return nullptr;
13691 if (ArrayOperatorDeletesForVirtualDtor.contains(Canon))
13692 return ArrayOperatorDeletesForVirtualDtor[Canon];
13693 return nullptr;
13695 if (GlobalArrayOperatorDeletesForVirtualDtor.contains(Canon))
13696 return GlobalArrayOperatorDeletesForVirtualDtor[Canon];
13697 return nullptr;
13698 }
13699 return nullptr;
13700}
13701
13703 const CXXRecordDecl *RD) {
13704 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13705 return false;
13706
13707 return MaybeRequireVectorDeletingDtor.count(RD);
13708}
13709
13711 const CXXRecordDecl *RD) {
13712 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13713 return;
13714
13715 MaybeRequireVectorDeletingDtor.insert(RD);
13716}
13717
13720 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13721 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
13722 if (!MCtx)
13724 return *MCtx;
13725}
13726
13729 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13730 std::unique_ptr<MangleNumberingContext> &MCtx =
13731 ExtraMangleNumberingContexts[D];
13732 if (!MCtx)
13734 return *MCtx;
13735}
13736
13737std::unique_ptr<MangleNumberingContext>
13739 return ABI->createMangleNumberingContext();
13740}
13741
13742const CXXConstructorDecl *
13744 return ABI->getCopyConstructorForExceptionObject(
13746}
13747
13749 CXXConstructorDecl *CD) {
13750 return ABI->addCopyConstructorForExceptionObject(
13753}
13754
13756 TypedefNameDecl *DD) {
13757 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
13758}
13759
13762 return ABI->getTypedefNameForUnnamedTagDecl(TD);
13763}
13764
13766 DeclaratorDecl *DD) {
13767 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
13768}
13769
13771 return ABI->getDeclaratorForUnnamedTagDecl(TD);
13772}
13773
13775 ParamIndices[D] = index;
13776}
13777
13779 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
13780 assert(I != ParamIndices.end() &&
13781 "ParmIndices lacks entry set by ParmVarDecl");
13782 return I->second;
13783}
13784
13786 unsigned Length) const {
13787 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
13788 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
13789 EltTy = EltTy.withConst();
13790
13791 EltTy = adjustStringLiteralBaseType(EltTy);
13792
13793 // Get an array type for the string, according to C99 6.4.5. This includes
13794 // the null terminator character.
13795 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
13796 ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
13797}
13798
13801 StringLiteral *&Result = StringLiteralCache[Key];
13802 if (!Result)
13804 *this, Key, StringLiteralKind::Ordinary,
13805 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
13806 SourceLocation());
13807 return Result;
13808}
13809
13810MSGuidDecl *
13812 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
13813
13814 llvm::FoldingSetNodeID ID;
13815 MSGuidDecl::Profile(ID, Parts);
13816
13817 void *InsertPos;
13818 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
13819 return Existing;
13820
13821 QualType GUIDType = getMSGuidType().withConst();
13822 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
13823 MSGuidDecls.InsertNode(New, InsertPos);
13824 return New;
13825}
13826
13829 const APValue &APVal) const {
13830 llvm::FoldingSetNodeID ID;
13832
13833 void *InsertPos;
13834 if (UnnamedGlobalConstantDecl *Existing =
13835 UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos))
13836 return Existing;
13837
13839 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
13840 UnnamedGlobalConstantDecls.InsertNode(New, InsertPos);
13841 return New;
13842}
13843
13846 assert(T->isRecordType() && "template param object of unexpected type");
13847
13848 // C++ [temp.param]p8:
13849 // [...] a static storage duration object of type 'const T' [...]
13850 T.addConst();
13851
13852 llvm::FoldingSetNodeID ID;
13854
13855 void *InsertPos;
13856 if (TemplateParamObjectDecl *Existing =
13857 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
13858 return Existing;
13859
13860 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
13861 TemplateParamObjectDecls.InsertNode(New, InsertPos);
13862 return New;
13863}
13864
13866 const llvm::Triple &T = getTargetInfo().getTriple();
13867 if (!T.isOSDarwin())
13868 return false;
13869
13870 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
13871 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
13872 return false;
13873
13874 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
13875 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
13876 uint64_t Size = sizeChars.getQuantity();
13877 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
13878 unsigned Align = alignChars.getQuantity();
13879 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
13880 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
13881}
13882
13883bool
13885 const ObjCMethodDecl *MethodImpl) {
13886 // No point trying to match an unavailable/deprecated mothod.
13887 if (MethodDecl->hasAttr<UnavailableAttr>()
13888 || MethodDecl->hasAttr<DeprecatedAttr>())
13889 return false;
13890 if (MethodDecl->getObjCDeclQualifier() !=
13891 MethodImpl->getObjCDeclQualifier())
13892 return false;
13893 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
13894 return false;
13895
13896 if (MethodDecl->param_size() != MethodImpl->param_size())
13897 return false;
13898
13899 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
13900 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
13901 EF = MethodDecl->param_end();
13902 IM != EM && IF != EF; ++IM, ++IF) {
13903 const ParmVarDecl *DeclVar = (*IF);
13904 const ParmVarDecl *ImplVar = (*IM);
13905 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
13906 return false;
13907 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
13908 return false;
13909 }
13910
13911 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
13912}
13913
13915 LangAS AS;
13917 AS = LangAS::Default;
13918 else
13919 AS = QT->getPointeeType().getAddressSpace();
13920
13922}
13923
13926}
13927
13928bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
13929 if (X == Y)
13930 return true;
13931 if (!X || !Y)
13932 return false;
13933 llvm::FoldingSetNodeID IDX, IDY;
13934 X->Profile(IDX, *this, /*Canonical=*/true);
13935 Y->Profile(IDY, *this, /*Canonical=*/true);
13936 return IDX == IDY;
13937}
13938
13939// The getCommon* helpers return, for given 'same' X and Y entities given as
13940// inputs, another entity which is also the 'same' as the inputs, but which
13941// is closer to the canonical form of the inputs, each according to a given
13942// criteria.
13943// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
13944// the regular ones.
13945
13947 if (!declaresSameEntity(X, Y))
13948 return nullptr;
13949 for (const Decl *DX : X->redecls()) {
13950 // If we reach Y before reaching the first decl, that means X is older.
13951 if (DX == Y)
13952 return X;
13953 // If we reach the first decl, then Y is older.
13954 if (DX->isFirstDecl())
13955 return Y;
13956 }
13957 llvm_unreachable("Corrupt redecls chain");
13958}
13959
13960template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13961static T *getCommonDecl(T *X, T *Y) {
13962 return cast_or_null<T>(
13963 getCommonDecl(const_cast<Decl *>(cast_or_null<Decl>(X)),
13964 const_cast<Decl *>(cast_or_null<Decl>(Y))));
13965}
13966
13967template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13968static T *getCommonDeclChecked(T *X, T *Y) {
13969 return cast<T>(getCommonDecl(const_cast<Decl *>(cast<Decl>(X)),
13970 const_cast<Decl *>(cast<Decl>(Y))));
13971}
13972
13974 TemplateName Y,
13975 bool IgnoreDeduced = false) {
13976 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
13977 return X;
13978 // FIXME: There are cases here where we could find a common template name
13979 // with more sugar. For example one could be a SubstTemplateTemplate*
13980 // replacing the other.
13981 TemplateName CX = Ctx.getCanonicalTemplateName(X, IgnoreDeduced);
13982 if (CX.getAsVoidPointer() !=
13984 return TemplateName();
13985 return CX;
13986}
13987
13990 bool IgnoreDeduced) {
13991 TemplateName R = getCommonTemplateName(Ctx, X, Y, IgnoreDeduced);
13992 assert(R.getAsVoidPointer() != nullptr);
13993 return R;
13994}
13995
13997 ArrayRef<QualType> Ys, bool Unqualified = false) {
13998 assert(Xs.size() == Ys.size());
13999 SmallVector<QualType, 8> Rs(Xs.size());
14000 for (size_t I = 0; I < Rs.size(); ++I)
14001 Rs[I] = Ctx.getCommonSugaredType(Xs[I], Ys[I], Unqualified);
14002 return Rs;
14003}
14004
14005template <class T>
14006static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
14007 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
14008 : SourceLocation();
14009}
14010
14012 const TemplateArgument &X,
14013 const TemplateArgument &Y) {
14014 if (X.getKind() != Y.getKind())
14015 return TemplateArgument();
14016
14017 switch (X.getKind()) {
14019 if (!Ctx.hasSameType(X.getAsType(), Y.getAsType()))
14020 return TemplateArgument();
14021 return TemplateArgument(
14022 Ctx.getCommonSugaredType(X.getAsType(), Y.getAsType()));
14024 if (!Ctx.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
14025 return TemplateArgument();
14026 return TemplateArgument(
14027 Ctx.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
14028 /*Unqualified=*/true);
14030 if (!Ctx.hasSameType(X.getAsExpr()->getType(), Y.getAsExpr()->getType()))
14031 return TemplateArgument();
14032 // FIXME: Try to keep the common sugar.
14033 return X;
14035 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
14036 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
14037 if (!CTN.getAsVoidPointer())
14038 return TemplateArgument();
14039 return TemplateArgument(CTN);
14040 }
14042 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
14044 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
14045 if (!CTN.getAsVoidPointer())
14046 return TemplateName();
14047 auto NExpX = X.getNumTemplateExpansions();
14048 assert(NExpX == Y.getNumTemplateExpansions());
14049 return TemplateArgument(CTN, NExpX);
14050 }
14051 default:
14052 // FIXME: Handle the other argument kinds.
14053 return X;
14054 }
14055}
14056
14061 if (Xs.size() != Ys.size())
14062 return true;
14063 R.resize(Xs.size());
14064 for (size_t I = 0; I < R.size(); ++I) {
14065 R[I] = getCommonTemplateArgument(Ctx, Xs[I], Ys[I]);
14066 if (R[I].isNull())
14067 return true;
14068 }
14069 return false;
14070}
14071
14076 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
14077 assert(!Different);
14078 (void)Different;
14079 return R;
14080}
14081
14082template <class T>
14084 bool IsSame) {
14085 ElaboratedTypeKeyword KX = X->getKeyword(), KY = Y->getKeyword();
14086 if (KX == KY)
14087 return KX;
14089 assert(!IsSame || KX == getCanonicalElaboratedTypeKeyword(KY));
14090 return KX;
14091}
14092
14093/// Returns a NestedNameSpecifier which has only the common sugar
14094/// present in both NNS1 and NNS2.
14097 NestedNameSpecifier NNS2, bool IsSame) {
14098 // If they are identical, all sugar is common.
14099 if (NNS1 == NNS2)
14100 return NNS1;
14101
14102 // IsSame implies both Qualifiers are equivalent.
14103 NestedNameSpecifier Canon = NNS1.getCanonical();
14104 if (Canon != NNS2.getCanonical()) {
14105 assert(!IsSame && "Should be the same NestedNameSpecifier");
14106 // If they are not the same, there is nothing to unify.
14107 return std::nullopt;
14108 }
14109
14110 NestedNameSpecifier R = std::nullopt;
14111 NestedNameSpecifier::Kind Kind = NNS1.getKind();
14112 assert(Kind == NNS2.getKind());
14113 switch (Kind) {
14115 auto [Namespace1, Prefix1] = NNS1.getAsNamespaceAndPrefix();
14116 auto [Namespace2, Prefix2] = NNS2.getAsNamespaceAndPrefix();
14117 auto Kind = Namespace1->getKind();
14118 if (Kind != Namespace2->getKind() ||
14119 (Kind == Decl::NamespaceAlias &&
14120 !declaresSameEntity(Namespace1, Namespace2))) {
14122 Ctx,
14123 ::getCommonDeclChecked(Namespace1->getNamespace(),
14124 Namespace2->getNamespace()),
14125 /*Prefix=*/std::nullopt);
14126 break;
14127 }
14128 // The prefixes for namespaces are not significant, its declaration
14129 // identifies it uniquely.
14130 NestedNameSpecifier Prefix = ::getCommonNNS(Ctx, Prefix1, Prefix2,
14131 /*IsSame=*/false);
14132 R = NestedNameSpecifier(Ctx, ::getCommonDeclChecked(Namespace1, Namespace2),
14133 Prefix);
14134 break;
14135 }
14137 const Type *T1 = NNS1.getAsType(), *T2 = NNS2.getAsType();
14138 const Type *T = Ctx.getCommonSugaredType(QualType(T1, 0), QualType(T2, 0),
14139 /*Unqualified=*/true)
14140 .getTypePtr();
14141 R = NestedNameSpecifier(T);
14142 break;
14143 }
14145 // FIXME: Can __super even be used with data members?
14146 // If it's only usable in functions, we will never see it here,
14147 // unless we save the qualifiers used in function types.
14148 // In that case, it might be possible NNS2 is a type,
14149 // in which case we should degrade the result to
14150 // a CXXRecordType.
14152 NNS2.getAsMicrosoftSuper()));
14153 break;
14154 }
14157 // These are singletons.
14158 llvm_unreachable("singletons did not compare equal");
14159 }
14160 assert(R.getCanonical() == Canon);
14161 return R;
14162}
14163
14164template <class T>
14166 const T *Y, bool IsSame) {
14167 return ::getCommonNNS(Ctx, X->getQualifier(), Y->getQualifier(), IsSame);
14168}
14169
14170template <class T>
14171static QualType getCommonElementType(const ASTContext &Ctx, const T *X,
14172 const T *Y) {
14173 return Ctx.getCommonSugaredType(X->getElementType(), Y->getElementType());
14174}
14175
14177 QualType X, QualType Y,
14178 Qualifiers &QX,
14179 Qualifiers &QY) {
14180 QualType R = Ctx.getCommonSugaredType(X, Y,
14181 /*Unqualified=*/true);
14182 // Qualifiers common to both element types.
14183 Qualifiers RQ = R.getQualifiers();
14184 // For each side, move to the top level any qualifiers which are not common to
14185 // both element types. The caller must assume top level qualifiers might
14186 // be different, even if they are the same type, and can be treated as sugar.
14187 QX += X.getQualifiers() - RQ;
14188 QY += Y.getQualifiers() - RQ;
14189 return R;
14190}
14191
14192template <class T>
14194 Qualifiers &QX, const T *Y,
14195 Qualifiers &QY) {
14196 return getCommonTypeWithQualifierLifting(Ctx, X->getElementType(),
14197 Y->getElementType(), QX, QY);
14198}
14199
14200template <class T>
14201static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X,
14202 const T *Y) {
14203 return Ctx.getCommonSugaredType(X->getPointeeType(), Y->getPointeeType());
14204}
14205
14206template <class T>
14207static auto *getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y) {
14208 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
14209 return X->getSizeExpr();
14210}
14211
14212static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
14213 assert(X->getSizeModifier() == Y->getSizeModifier());
14214 return X->getSizeModifier();
14215}
14216
14218 const ArrayType *Y) {
14219 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
14220 return X->getIndexTypeCVRQualifiers();
14221}
14222
14223// Merges two type lists such that the resulting vector will contain
14224// each type (in a canonical sense) only once, in the order they appear
14225// from X to Y. If they occur in both X and Y, the result will contain
14226// the common sugared type between them.
14227static void mergeTypeLists(const ASTContext &Ctx,
14230 llvm::DenseMap<QualType, unsigned> Found;
14231 for (auto Ts : {X, Y}) {
14232 for (QualType T : Ts) {
14233 auto Res = Found.try_emplace(Ctx.getCanonicalType(T), Out.size());
14234 if (!Res.second) {
14235 QualType &U = Out[Res.first->second];
14236 U = Ctx.getCommonSugaredType(U, T);
14237 } else {
14238 Out.emplace_back(T);
14239 }
14240 }
14241 }
14242}
14243
14244FunctionProtoType::ExceptionSpecInfo
14247 SmallVectorImpl<QualType> &ExceptionTypeStorage,
14248 bool AcceptDependent) const {
14249 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
14250
14251 // If either of them can throw anything, that is the result.
14252 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
14253 if (EST1 == I)
14254 return ESI1;
14255 if (EST2 == I)
14256 return ESI2;
14257 }
14258
14259 // If either of them is non-throwing, the result is the other.
14260 for (auto I :
14262 if (EST1 == I)
14263 return ESI2;
14264 if (EST2 == I)
14265 return ESI1;
14266 }
14267
14268 // If we're left with value-dependent computed noexcept expressions, we're
14269 // stuck. Before C++17, we can just drop the exception specification entirely,
14270 // since it's not actually part of the canonical type. And this should never
14271 // happen in C++17, because it would mean we were computing the composite
14272 // pointer type of dependent types, which should never happen.
14273 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
14274 assert(AcceptDependent &&
14275 "computing composite pointer type of dependent types");
14277 }
14278
14279 // Switch over the possibilities so that people adding new values know to
14280 // update this function.
14281 switch (EST1) {
14282 case EST_None:
14283 case EST_DynamicNone:
14284 case EST_MSAny:
14285 case EST_BasicNoexcept:
14287 case EST_NoexceptFalse:
14288 case EST_NoexceptTrue:
14289 case EST_NoThrow:
14290 llvm_unreachable("These ESTs should be handled above");
14291
14292 case EST_Dynamic: {
14293 // This is the fun case: both exception specifications are dynamic. Form
14294 // the union of the two lists.
14295 assert(EST2 == EST_Dynamic && "other cases should already be handled");
14296 mergeTypeLists(*this, ExceptionTypeStorage, ESI1.Exceptions,
14297 ESI2.Exceptions);
14299 Result.Exceptions = ExceptionTypeStorage;
14300 return Result;
14301 }
14302
14303 case EST_Unevaluated:
14304 case EST_Uninstantiated:
14305 case EST_Unparsed:
14306 llvm_unreachable("shouldn't see unresolved exception specifications here");
14307 }
14308
14309 llvm_unreachable("invalid ExceptionSpecificationType");
14310}
14311
14313 Qualifiers &QX, const Type *Y,
14314 Qualifiers &QY) {
14315 Type::TypeClass TC = X->getTypeClass();
14316 assert(TC == Y->getTypeClass());
14317 switch (TC) {
14318#define UNEXPECTED_TYPE(Class, Kind) \
14319 case Type::Class: \
14320 llvm_unreachable("Unexpected " Kind ": " #Class);
14321
14322#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
14323#define TYPE(Class, Base)
14324#include "clang/AST/TypeNodes.inc"
14325
14326#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
14328 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
14329 SUGAR_FREE_TYPE(DependentBitInt)
14331 SUGAR_FREE_TYPE(ObjCInterface)
14332 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
14333 SUGAR_FREE_TYPE(SubstBuiltinTemplatePack)
14334 SUGAR_FREE_TYPE(UnresolvedUsing)
14335 SUGAR_FREE_TYPE(HLSLAttributedResource)
14336 SUGAR_FREE_TYPE(HLSLInlineSpirv)
14337#undef SUGAR_FREE_TYPE
14338#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
14339 NON_UNIQUE_TYPE(TypeOfExpr)
14340 NON_UNIQUE_TYPE(VariableArray)
14341#undef NON_UNIQUE_TYPE
14342
14343 UNEXPECTED_TYPE(TypeOf, "sugar")
14344
14345#undef UNEXPECTED_TYPE
14346
14347 case Type::Auto: {
14348 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14349 assert(AX->getDeducedKind() == AY->getDeducedKind());
14350 assert(AX->getDeducedKind() != DeducedKind::Deduced);
14351 assert(AX->getKeyword() == AY->getKeyword());
14352 TemplateDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(),
14353 AY->getTypeConstraintConcept());
14355 if (CD &&
14356 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
14357 AY->getTypeConstraintArguments())) {
14358 CD = nullptr; // The arguments differ, so make it unconstrained.
14359 As.clear();
14360 }
14361 return Ctx.getAutoType(AX->getDeducedKind(), QualType(), AX->getKeyword(),
14362 CD, As);
14363 }
14364 case Type::IncompleteArray: {
14365 const auto *AX = cast<IncompleteArrayType>(X),
14367 return Ctx.getIncompleteArrayType(
14368 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14370 }
14371 case Type::DependentSizedArray: {
14372 const auto *AX = cast<DependentSizedArrayType>(X),
14374 return Ctx.getDependentSizedArrayType(
14375 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14376 getCommonSizeExpr(Ctx, AX, AY), getCommonSizeModifier(AX, AY),
14378 }
14379 case Type::ConstantArray: {
14380 const auto *AX = cast<ConstantArrayType>(X),
14381 *AY = cast<ConstantArrayType>(Y);
14382 assert(AX->getSize() == AY->getSize());
14383 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14384 ? AX->getSizeExpr()
14385 : nullptr;
14386 return Ctx.getConstantArrayType(
14387 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14389 }
14390 case Type::ArrayParameter: {
14391 const auto *AX = cast<ArrayParameterType>(X),
14392 *AY = cast<ArrayParameterType>(Y);
14393 assert(AX->getSize() == AY->getSize());
14394 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14395 ? AX->getSizeExpr()
14396 : nullptr;
14397 auto ArrayTy = Ctx.getConstantArrayType(
14398 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14400 return Ctx.getArrayParameterType(ArrayTy);
14401 }
14402 case Type::Atomic: {
14403 const auto *AX = cast<AtomicType>(X), *AY = cast<AtomicType>(Y);
14404 return Ctx.getAtomicType(
14405 Ctx.getCommonSugaredType(AX->getValueType(), AY->getValueType()));
14406 }
14407 case Type::Complex: {
14408 const auto *CX = cast<ComplexType>(X), *CY = cast<ComplexType>(Y);
14409 return Ctx.getComplexType(getCommonArrayElementType(Ctx, CX, QX, CY, QY));
14410 }
14411 case Type::Pointer: {
14412 const auto *PX = cast<PointerType>(X), *PY = cast<PointerType>(Y);
14413 return Ctx.getPointerType(getCommonPointeeType(Ctx, PX, PY));
14414 }
14415 case Type::BlockPointer: {
14416 const auto *PX = cast<BlockPointerType>(X), *PY = cast<BlockPointerType>(Y);
14417 return Ctx.getBlockPointerType(getCommonPointeeType(Ctx, PX, PY));
14418 }
14419 case Type::ObjCObjectPointer: {
14420 const auto *PX = cast<ObjCObjectPointerType>(X),
14422 return Ctx.getObjCObjectPointerType(getCommonPointeeType(Ctx, PX, PY));
14423 }
14424 case Type::MemberPointer: {
14425 const auto *PX = cast<MemberPointerType>(X),
14426 *PY = cast<MemberPointerType>(Y);
14427 assert(declaresSameEntity(PX->getMostRecentCXXRecordDecl(),
14428 PY->getMostRecentCXXRecordDecl()));
14429 return Ctx.getMemberPointerType(
14430 getCommonPointeeType(Ctx, PX, PY),
14431 getCommonQualifier(Ctx, PX, PY, /*IsSame=*/true),
14432 PX->getMostRecentCXXRecordDecl());
14433 }
14434 case Type::LValueReference: {
14435 const auto *PX = cast<LValueReferenceType>(X),
14437 // FIXME: Preserve PointeeTypeAsWritten.
14438 return Ctx.getLValueReferenceType(getCommonPointeeType(Ctx, PX, PY),
14439 PX->isSpelledAsLValue() ||
14440 PY->isSpelledAsLValue());
14441 }
14442 case Type::RValueReference: {
14443 const auto *PX = cast<RValueReferenceType>(X),
14445 // FIXME: Preserve PointeeTypeAsWritten.
14446 return Ctx.getRValueReferenceType(getCommonPointeeType(Ctx, PX, PY));
14447 }
14448 case Type::DependentAddressSpace: {
14449 const auto *PX = cast<DependentAddressSpaceType>(X),
14451 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
14452 return Ctx.getDependentAddressSpaceType(getCommonPointeeType(Ctx, PX, PY),
14453 PX->getAddrSpaceExpr(),
14454 getCommonAttrLoc(PX, PY));
14455 }
14456 case Type::FunctionNoProto: {
14457 const auto *FX = cast<FunctionNoProtoType>(X),
14459 assert(FX->getExtInfo() == FY->getExtInfo());
14460 return Ctx.getFunctionNoProtoType(
14461 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType()),
14462 FX->getExtInfo());
14463 }
14464 case Type::FunctionProto: {
14465 const auto *FX = cast<FunctionProtoType>(X),
14466 *FY = cast<FunctionProtoType>(Y);
14467 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
14468 EPIY = FY->getExtProtoInfo();
14469 assert(EPIX.ExtInfo == EPIY.ExtInfo);
14470 assert(!EPIX.ExtParameterInfos == !EPIY.ExtParameterInfos);
14471 assert(!EPIX.ExtParameterInfos ||
14472 llvm::equal(
14473 llvm::ArrayRef(EPIX.ExtParameterInfos, FX->getNumParams()),
14474 llvm::ArrayRef(EPIY.ExtParameterInfos, FY->getNumParams())));
14475 assert(EPIX.RefQualifier == EPIY.RefQualifier);
14476 assert(EPIX.TypeQuals == EPIY.TypeQuals);
14477 assert(EPIX.Variadic == EPIY.Variadic);
14478
14479 // FIXME: Can we handle an empty EllipsisLoc?
14480 // Use emtpy EllipsisLoc if X and Y differ.
14481
14482 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
14483
14484 QualType R =
14485 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType());
14486 auto P = getCommonTypes(Ctx, FX->param_types(), FY->param_types(),
14487 /*Unqualified=*/true);
14488
14489 SmallVector<QualType, 8> Exceptions;
14491 EPIX.ExceptionSpec, EPIY.ExceptionSpec, Exceptions, true);
14492 return Ctx.getFunctionType(R, P, EPIX);
14493 }
14494 case Type::ObjCObject: {
14495 const auto *OX = cast<ObjCObjectType>(X), *OY = cast<ObjCObjectType>(Y);
14496 assert(
14497 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
14498 OY->getProtocols().begin(), OY->getProtocols().end(),
14499 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
14500 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
14501 }) &&
14502 "protocol lists must be the same");
14503 auto TAs = getCommonTypes(Ctx, OX->getTypeArgsAsWritten(),
14504 OY->getTypeArgsAsWritten());
14505 return Ctx.getObjCObjectType(
14506 Ctx.getCommonSugaredType(OX->getBaseType(), OY->getBaseType()), TAs,
14507 OX->getProtocols(),
14508 OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
14509 }
14510 case Type::ConstantMatrix: {
14511 const auto *MX = cast<ConstantMatrixType>(X),
14512 *MY = cast<ConstantMatrixType>(Y);
14513 assert(MX->getNumRows() == MY->getNumRows());
14514 assert(MX->getNumColumns() == MY->getNumColumns());
14515 return Ctx.getConstantMatrixType(getCommonElementType(Ctx, MX, MY),
14516 MX->getNumRows(), MX->getNumColumns());
14517 }
14518 case Type::DependentSizedMatrix: {
14519 const auto *MX = cast<DependentSizedMatrixType>(X),
14521 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
14522 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
14523 return Ctx.getDependentSizedMatrixType(
14524 getCommonElementType(Ctx, MX, MY), MX->getRowExpr(),
14525 MX->getColumnExpr(), getCommonAttrLoc(MX, MY));
14526 }
14527 case Type::Vector: {
14528 const auto *VX = cast<VectorType>(X), *VY = cast<VectorType>(Y);
14529 assert(VX->getNumElements() == VY->getNumElements());
14530 assert(VX->getVectorKind() == VY->getVectorKind());
14531 return Ctx.getVectorType(getCommonElementType(Ctx, VX, VY),
14532 VX->getNumElements(), VX->getVectorKind());
14533 }
14534 case Type::ExtVector: {
14535 const auto *VX = cast<ExtVectorType>(X), *VY = cast<ExtVectorType>(Y);
14536 assert(VX->getNumElements() == VY->getNumElements());
14537 return Ctx.getExtVectorType(getCommonElementType(Ctx, VX, VY),
14538 VX->getNumElements());
14539 }
14540 case Type::DependentSizedExtVector: {
14541 const auto *VX = cast<DependentSizedExtVectorType>(X),
14544 getCommonSizeExpr(Ctx, VX, VY),
14545 getCommonAttrLoc(VX, VY));
14546 }
14547 case Type::DependentVector: {
14548 const auto *VX = cast<DependentVectorType>(X),
14550 assert(VX->getVectorKind() == VY->getVectorKind());
14551 return Ctx.getDependentVectorType(
14552 getCommonElementType(Ctx, VX, VY), getCommonSizeExpr(Ctx, VX, VY),
14553 getCommonAttrLoc(VX, VY), VX->getVectorKind());
14554 }
14555 case Type::Enum:
14556 case Type::Record:
14557 case Type::InjectedClassName: {
14558 const auto *TX = cast<TagType>(X), *TY = cast<TagType>(Y);
14559 return Ctx.getTagType(::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14560 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false),
14561 ::getCommonDeclChecked(TX->getDecl(), TY->getDecl()),
14562 /*OwnedTag=*/false);
14563 }
14564 case Type::TemplateSpecialization: {
14565 const auto *TX = cast<TemplateSpecializationType>(X),
14567 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
14568 TY->template_arguments());
14570 getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14571 ::getCommonTemplateNameChecked(Ctx, TX->getTemplateName(),
14572 TY->getTemplateName(),
14573 /*IgnoreDeduced=*/true),
14574 As, /*CanonicalArgs=*/{}, X->getCanonicalTypeInternal());
14575 }
14576 case Type::Decltype: {
14577 const auto *DX = cast<DecltypeType>(X);
14578 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Y);
14579 assert(DX->isDependentType());
14580 assert(DY->isDependentType());
14581 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
14582 // As Decltype is not uniqued, building a common type would be wasteful.
14583 return QualType(DX, 0);
14584 }
14585 case Type::PackIndexing: {
14586 const auto *DX = cast<PackIndexingType>(X);
14587 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Y);
14588 assert(DX->isDependentType());
14589 assert(DY->isDependentType());
14590 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
14591 return QualType(DX, 0);
14592 }
14593 case Type::DependentName: {
14594 const auto *NX = cast<DependentNameType>(X),
14595 *NY = cast<DependentNameType>(Y);
14596 assert(NX->getIdentifier() == NY->getIdentifier());
14597 return Ctx.getDependentNameType(
14598 getCommonTypeKeyword(NX, NY, /*IsSame=*/true),
14599 getCommonQualifier(Ctx, NX, NY, /*IsSame=*/true), NX->getIdentifier());
14600 }
14601 case Type::OverflowBehavior: {
14602 const auto *NX = cast<OverflowBehaviorType>(X),
14604 assert(NX->getBehaviorKind() == NY->getBehaviorKind());
14605 return Ctx.getOverflowBehaviorType(
14606 NX->getBehaviorKind(),
14607 getCommonTypeWithQualifierLifting(Ctx, NX->getUnderlyingType(),
14608 NY->getUnderlyingType(), QX, QY));
14609 }
14610 case Type::UnaryTransform: {
14611 const auto *TX = cast<UnaryTransformType>(X),
14612 *TY = cast<UnaryTransformType>(Y);
14613 assert(TX->getUTTKind() == TY->getUTTKind());
14614 return Ctx.getUnaryTransformType(
14615 Ctx.getCommonSugaredType(TX->getBaseType(), TY->getBaseType()),
14616 Ctx.getCommonSugaredType(TX->getUnderlyingType(),
14617 TY->getUnderlyingType()),
14618 TX->getUTTKind());
14619 }
14620 case Type::PackExpansion: {
14621 const auto *PX = cast<PackExpansionType>(X),
14622 *PY = cast<PackExpansionType>(Y);
14623 assert(PX->getNumExpansions() == PY->getNumExpansions());
14624 return Ctx.getPackExpansionType(
14625 Ctx.getCommonSugaredType(PX->getPattern(), PY->getPattern()),
14626 PX->getNumExpansions(), false);
14627 }
14628 case Type::Pipe: {
14629 const auto *PX = cast<PipeType>(X), *PY = cast<PipeType>(Y);
14630 assert(PX->isReadOnly() == PY->isReadOnly());
14631 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
14633 return (Ctx.*MP)(getCommonElementType(Ctx, PX, PY));
14634 }
14635 case Type::TemplateTypeParm: {
14636 const auto *TX = cast<TemplateTypeParmType>(X),
14638 assert(TX->getDepth() == TY->getDepth());
14639 assert(TX->getIndex() == TY->getIndex());
14640 assert(TX->isParameterPack() == TY->isParameterPack());
14641 return Ctx.getTemplateTypeParmType(
14642 TX->getDepth(), TX->getIndex(), TX->isParameterPack(),
14643 getCommonDecl(TX->getDecl(), TY->getDecl()));
14644 }
14645 }
14646 llvm_unreachable("Unknown Type Class");
14647}
14648
14650 const Type *Y,
14651 SplitQualType Underlying) {
14652 Type::TypeClass TC = X->getTypeClass();
14653 if (TC != Y->getTypeClass())
14654 return QualType();
14655 switch (TC) {
14656#define UNEXPECTED_TYPE(Class, Kind) \
14657 case Type::Class: \
14658 llvm_unreachable("Unexpected " Kind ": " #Class);
14659#define TYPE(Class, Base)
14660#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
14661#include "clang/AST/TypeNodes.inc"
14662
14663#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
14666 CANONICAL_TYPE(BlockPointer)
14669 CANONICAL_TYPE(ConstantArray)
14670 CANONICAL_TYPE(ArrayParameter)
14671 CANONICAL_TYPE(ConstantMatrix)
14673 CANONICAL_TYPE(ExtVector)
14674 CANONICAL_TYPE(FunctionNoProto)
14675 CANONICAL_TYPE(FunctionProto)
14676 CANONICAL_TYPE(IncompleteArray)
14677 CANONICAL_TYPE(HLSLAttributedResource)
14678 CANONICAL_TYPE(HLSLInlineSpirv)
14679 CANONICAL_TYPE(LValueReference)
14680 CANONICAL_TYPE(ObjCInterface)
14681 CANONICAL_TYPE(ObjCObject)
14682 CANONICAL_TYPE(ObjCObjectPointer)
14683 CANONICAL_TYPE(OverflowBehavior)
14687 CANONICAL_TYPE(RValueReference)
14688 CANONICAL_TYPE(VariableArray)
14690#undef CANONICAL_TYPE
14691
14692#undef UNEXPECTED_TYPE
14693
14694 case Type::Adjusted: {
14695 const auto *AX = cast<AdjustedType>(X), *AY = cast<AdjustedType>(Y);
14696 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
14697 if (!Ctx.hasSameType(OX, OY))
14698 return QualType();
14699 // FIXME: It's inefficient to have to unify the original types.
14700 return Ctx.getAdjustedType(Ctx.getCommonSugaredType(OX, OY),
14701 Ctx.getQualifiedType(Underlying));
14702 }
14703 case Type::Decayed: {
14704 const auto *DX = cast<DecayedType>(X), *DY = cast<DecayedType>(Y);
14705 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
14706 if (!Ctx.hasSameType(OX, OY))
14707 return QualType();
14708 // FIXME: It's inefficient to have to unify the original types.
14709 return Ctx.getDecayedType(Ctx.getCommonSugaredType(OX, OY),
14710 Ctx.getQualifiedType(Underlying));
14711 }
14712 case Type::Attributed: {
14713 const auto *AX = cast<AttributedType>(X), *AY = cast<AttributedType>(Y);
14714 AttributedType::Kind Kind = AX->getAttrKind();
14715 if (Kind != AY->getAttrKind())
14716 return QualType();
14717 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
14718 if (!Ctx.hasSameType(MX, MY))
14719 return QualType();
14720 // FIXME: It's inefficient to have to unify the modified types.
14721 return Ctx.getAttributedType(Kind, Ctx.getCommonSugaredType(MX, MY),
14722 Ctx.getQualifiedType(Underlying),
14723 AX->getAttr());
14724 }
14725 case Type::BTFTagAttributed: {
14726 const auto *BX = cast<BTFTagAttributedType>(X);
14727 const BTFTypeTagAttr *AX = BX->getAttr();
14728 // The attribute is not uniqued, so just compare the tag.
14729 if (AX->getBTFTypeTag() !=
14730 cast<BTFTagAttributedType>(Y)->getAttr()->getBTFTypeTag())
14731 return QualType();
14732 return Ctx.getBTFTagAttributedType(AX, Ctx.getQualifiedType(Underlying));
14733 }
14734 case Type::Auto: {
14735 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14736 assert(AX->getDeducedKind() == DeducedKind::Deduced);
14737 assert(AY->getDeducedKind() == DeducedKind::Deduced);
14738
14739 AutoTypeKeyword KW = AX->getKeyword();
14740 if (KW != AY->getKeyword())
14741 return QualType();
14742
14743 TemplateDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(),
14744 AY->getTypeConstraintConcept());
14746 if (CD &&
14747 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
14748 AY->getTypeConstraintArguments())) {
14749 CD = nullptr; // The arguments differ, so make it unconstrained.
14750 As.clear();
14751 }
14752
14753 // Both auto types can't be dependent, otherwise they wouldn't have been
14754 // sugar. This implies they can't contain unexpanded packs either.
14756 Ctx.getQualifiedType(Underlying), AX->getKeyword(),
14757 CD, As);
14758 }
14759 case Type::PackIndexing:
14760 case Type::Decltype:
14761 return QualType();
14762 case Type::DeducedTemplateSpecialization:
14763 // FIXME: Try to merge these.
14764 return QualType();
14765 case Type::MacroQualified: {
14766 const auto *MX = cast<MacroQualifiedType>(X),
14767 *MY = cast<MacroQualifiedType>(Y);
14768 const IdentifierInfo *IX = MX->getMacroIdentifier();
14769 if (IX != MY->getMacroIdentifier())
14770 return QualType();
14771 return Ctx.getMacroQualifiedType(Ctx.getQualifiedType(Underlying), IX);
14772 }
14773 case Type::SubstTemplateTypeParm: {
14774 const auto *SX = cast<SubstTemplateTypeParmType>(X),
14776 Decl *CD =
14777 ::getCommonDecl(SX->getAssociatedDecl(), SY->getAssociatedDecl());
14778 if (!CD)
14779 return QualType();
14780 unsigned Index = SX->getIndex();
14781 if (Index != SY->getIndex())
14782 return QualType();
14783 auto PackIndex = SX->getPackIndex();
14784 if (PackIndex != SY->getPackIndex())
14785 return QualType();
14786 return Ctx.getSubstTemplateTypeParmType(Ctx.getQualifiedType(Underlying),
14787 CD, Index, PackIndex,
14788 SX->getFinal() && SY->getFinal());
14789 }
14790 case Type::ObjCTypeParam:
14791 // FIXME: Try to merge these.
14792 return QualType();
14793 case Type::Paren:
14794 return Ctx.getParenType(Ctx.getQualifiedType(Underlying));
14795
14796 case Type::TemplateSpecialization: {
14797 const auto *TX = cast<TemplateSpecializationType>(X),
14799 TemplateName CTN =
14800 ::getCommonTemplateName(Ctx, TX->getTemplateName(),
14801 TY->getTemplateName(), /*IgnoreDeduced=*/true);
14802 if (!CTN.getAsVoidPointer())
14803 return QualType();
14805 if (getCommonTemplateArguments(Ctx, As, TX->template_arguments(),
14806 TY->template_arguments()))
14807 return QualType();
14809 getCommonTypeKeyword(TX, TY, /*IsSame=*/false), CTN, As,
14810 /*CanonicalArgs=*/{}, Ctx.getQualifiedType(Underlying));
14811 }
14812 case Type::Typedef: {
14813 const auto *TX = cast<TypedefType>(X), *TY = cast<TypedefType>(Y);
14814 const TypedefNameDecl *CD = ::getCommonDecl(TX->getDecl(), TY->getDecl());
14815 if (!CD)
14816 return QualType();
14817 return Ctx.getTypedefType(
14818 ::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14819 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false), CD,
14820 Ctx.getQualifiedType(Underlying));
14821 }
14822 case Type::TypeOf: {
14823 // The common sugar between two typeof expressions, where one is
14824 // potentially a typeof_unqual and the other is not, we unify to the
14825 // qualified type as that retains the most information along with the type.
14826 // We only return a typeof_unqual type when both types are unqual types.
14831 return Ctx.getTypeOfType(Ctx.getQualifiedType(Underlying), Kind);
14832 }
14833 case Type::TypeOfExpr:
14834 return QualType();
14835
14836 case Type::UnaryTransform: {
14837 const auto *UX = cast<UnaryTransformType>(X),
14838 *UY = cast<UnaryTransformType>(Y);
14839 UnaryTransformType::UTTKind KX = UX->getUTTKind();
14840 if (KX != UY->getUTTKind())
14841 return QualType();
14842 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
14843 if (!Ctx.hasSameType(BX, BY))
14844 return QualType();
14845 // FIXME: It's inefficient to have to unify the base types.
14846 return Ctx.getUnaryTransformType(Ctx.getCommonSugaredType(BX, BY),
14847 Ctx.getQualifiedType(Underlying), KX);
14848 }
14849 case Type::Using: {
14850 const auto *UX = cast<UsingType>(X), *UY = cast<UsingType>(Y);
14851 const UsingShadowDecl *CD = ::getCommonDecl(UX->getDecl(), UY->getDecl());
14852 if (!CD)
14853 return QualType();
14854 return Ctx.getUsingType(::getCommonTypeKeyword(UX, UY, /*IsSame=*/false),
14855 ::getCommonQualifier(Ctx, UX, UY, /*IsSame=*/false),
14856 CD, Ctx.getQualifiedType(Underlying));
14857 }
14858 case Type::MemberPointer: {
14859 const auto *PX = cast<MemberPointerType>(X),
14860 *PY = cast<MemberPointerType>(Y);
14861 CXXRecordDecl *Cls = PX->getMostRecentCXXRecordDecl();
14862 assert(Cls == PY->getMostRecentCXXRecordDecl());
14863 return Ctx.getMemberPointerType(
14864 ::getCommonPointeeType(Ctx, PX, PY),
14865 ::getCommonQualifier(Ctx, PX, PY, /*IsSame=*/false), Cls);
14866 }
14867 case Type::CountAttributed: {
14868 const auto *DX = cast<CountAttributedType>(X),
14870 if (DX->isCountInBytes() != DY->isCountInBytes())
14871 return QualType();
14872 if (DX->isOrNull() != DY->isOrNull())
14873 return QualType();
14874 Expr *CEX = DX->getCountExpr();
14875 Expr *CEY = DY->getCountExpr();
14876 ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
14877 if (Ctx.hasSameExpr(CEX, CEY))
14878 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14879 DX->isCountInBytes(), DX->isOrNull(),
14880 CDX);
14881 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
14882 return QualType();
14883 // Two declarations with the same integer constant may still differ in their
14884 // expression pointers, so we need to evaluate them.
14885 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
14886 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
14887 if (VX != VY)
14888 return QualType();
14889 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14890 DX->isCountInBytes(), DX->isOrNull(),
14891 CDX);
14892 }
14893 case Type::PredefinedSugar:
14894 assert(cast<PredefinedSugarType>(X)->getKind() !=
14896 return QualType();
14897 }
14898 llvm_unreachable("Unhandled Type Class");
14899}
14900
14901static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
14903 while (true) {
14904 QTotal.addConsistentQualifiers(T.Quals);
14906 if (NT == QualType(T.Ty, 0))
14907 break;
14908 R.push_back(T);
14909 T = NT.split();
14910 }
14911 return R;
14912}
14913
14915 bool Unqualified) const {
14916 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
14917 if (X == Y)
14918 return X;
14919 if (!Unqualified) {
14920 if (X.isCanonical())
14921 return X;
14922 if (Y.isCanonical())
14923 return Y;
14924 }
14925
14926 SplitQualType SX = X.split(), SY = Y.split();
14927 Qualifiers QX, QY;
14928 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
14929 // until we reach their underlying "canonical nodes". Note these are not
14930 // necessarily canonical types, as they may still have sugared properties.
14931 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
14932 auto Xs = ::unwrapSugar(SX, QX), Ys = ::unwrapSugar(SY, QY);
14933
14934 // If this is an ArrayType, the element qualifiers are interchangeable with
14935 // the top level qualifiers.
14936 // * In case the canonical nodes are the same, the elements types are already
14937 // the same.
14938 // * Otherwise, the element types will be made the same, and any different
14939 // element qualifiers will be moved up to the top level qualifiers, per
14940 // 'getCommonArrayElementType'.
14941 // In both cases, this means there may be top level qualifiers which differ
14942 // between X and Y. If so, these differing qualifiers are redundant with the
14943 // element qualifiers, and can be removed without changing the canonical type.
14944 // The desired behaviour is the same as for the 'Unqualified' case here:
14945 // treat the redundant qualifiers as sugar, remove the ones which are not
14946 // common to both sides.
14947 bool KeepCommonQualifiers =
14949
14950 if (SX.Ty != SY.Ty) {
14951 // The canonical nodes differ. Build a common canonical node out of the two,
14952 // unifying their sugar. This may recurse back here.
14953 SX.Ty =
14954 ::getCommonNonSugarTypeNode(*this, SX.Ty, QX, SY.Ty, QY).getTypePtr();
14955 } else {
14956 // The canonical nodes were identical: We may have desugared too much.
14957 // Add any common sugar back in.
14958 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
14959 QX -= SX.Quals;
14960 QY -= SY.Quals;
14961 SX = Xs.pop_back_val();
14962 SY = Ys.pop_back_val();
14963 }
14964 }
14965 if (KeepCommonQualifiers)
14967 else
14968 assert(QX == QY);
14969
14970 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
14971 // related. Walk up these nodes, unifying them and adding the result.
14972 while (!Xs.empty() && !Ys.empty()) {
14973 auto Underlying = SplitQualType(
14974 SX.Ty, Qualifiers::removeCommonQualifiers(SX.Quals, SY.Quals));
14975 SX = Xs.pop_back_val();
14976 SY = Ys.pop_back_val();
14977 SX.Ty = ::getCommonSugarTypeNode(*this, SX.Ty, SY.Ty, Underlying)
14979 // Stop at the first pair which is unrelated.
14980 if (!SX.Ty) {
14981 SX.Ty = Underlying.Ty;
14982 break;
14983 }
14984 QX -= Underlying.Quals;
14985 };
14986
14987 // Add back the missing accumulated qualifiers, which were stripped off
14988 // with the sugar nodes we could not unify.
14989 QualType R = getQualifiedType(SX.Ty, QX);
14990 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
14991 return R;
14992}
14993
14995 assert(Ty->isFixedPointType());
14996
14998 return Ty;
14999
15000 switch (Ty->castAs<BuiltinType>()->getKind()) {
15001 default:
15002 llvm_unreachable("Not a saturated fixed point type!");
15003 case BuiltinType::SatShortAccum:
15004 return ShortAccumTy;
15005 case BuiltinType::SatAccum:
15006 return AccumTy;
15007 case BuiltinType::SatLongAccum:
15008 return LongAccumTy;
15009 case BuiltinType::SatUShortAccum:
15010 return UnsignedShortAccumTy;
15011 case BuiltinType::SatUAccum:
15012 return UnsignedAccumTy;
15013 case BuiltinType::SatULongAccum:
15014 return UnsignedLongAccumTy;
15015 case BuiltinType::SatShortFract:
15016 return ShortFractTy;
15017 case BuiltinType::SatFract:
15018 return FractTy;
15019 case BuiltinType::SatLongFract:
15020 return LongFractTy;
15021 case BuiltinType::SatUShortFract:
15022 return UnsignedShortFractTy;
15023 case BuiltinType::SatUFract:
15024 return UnsignedFractTy;
15025 case BuiltinType::SatULongFract:
15026 return UnsignedLongFractTy;
15027 }
15028}
15029
15031 assert(Ty->isFixedPointType());
15032
15033 if (Ty->isSaturatedFixedPointType()) return Ty;
15034
15035 switch (Ty->castAs<BuiltinType>()->getKind()) {
15036 default:
15037 llvm_unreachable("Not a fixed point type!");
15038 case BuiltinType::ShortAccum:
15039 return SatShortAccumTy;
15040 case BuiltinType::Accum:
15041 return SatAccumTy;
15042 case BuiltinType::LongAccum:
15043 return SatLongAccumTy;
15044 case BuiltinType::UShortAccum:
15046 case BuiltinType::UAccum:
15047 return SatUnsignedAccumTy;
15048 case BuiltinType::ULongAccum:
15050 case BuiltinType::ShortFract:
15051 return SatShortFractTy;
15052 case BuiltinType::Fract:
15053 return SatFractTy;
15054 case BuiltinType::LongFract:
15055 return SatLongFractTy;
15056 case BuiltinType::UShortFract:
15058 case BuiltinType::UFract:
15059 return SatUnsignedFractTy;
15060 case BuiltinType::ULongFract:
15062 }
15063}
15064
15066 if (LangOpts.OpenCL)
15068
15069 if (LangOpts.CUDA)
15071
15072 return getLangASFromTargetAS(AS);
15073}
15074
15075// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
15076// doesn't include ASTContext.h
15077template
15079 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
15081 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
15082 const clang::ASTContext &Ctx, Decl *Value);
15083
15085 assert(Ty->isFixedPointType());
15086
15087 const TargetInfo &Target = getTargetInfo();
15088 switch (Ty->castAs<BuiltinType>()->getKind()) {
15089 default:
15090 llvm_unreachable("Not a fixed point type!");
15091 case BuiltinType::ShortAccum:
15092 case BuiltinType::SatShortAccum:
15093 return Target.getShortAccumScale();
15094 case BuiltinType::Accum:
15095 case BuiltinType::SatAccum:
15096 return Target.getAccumScale();
15097 case BuiltinType::LongAccum:
15098 case BuiltinType::SatLongAccum:
15099 return Target.getLongAccumScale();
15100 case BuiltinType::UShortAccum:
15101 case BuiltinType::SatUShortAccum:
15102 return Target.getUnsignedShortAccumScale();
15103 case BuiltinType::UAccum:
15104 case BuiltinType::SatUAccum:
15105 return Target.getUnsignedAccumScale();
15106 case BuiltinType::ULongAccum:
15107 case BuiltinType::SatULongAccum:
15108 return Target.getUnsignedLongAccumScale();
15109 case BuiltinType::ShortFract:
15110 case BuiltinType::SatShortFract:
15111 return Target.getShortFractScale();
15112 case BuiltinType::Fract:
15113 case BuiltinType::SatFract:
15114 return Target.getFractScale();
15115 case BuiltinType::LongFract:
15116 case BuiltinType::SatLongFract:
15117 return Target.getLongFractScale();
15118 case BuiltinType::UShortFract:
15119 case BuiltinType::SatUShortFract:
15120 return Target.getUnsignedShortFractScale();
15121 case BuiltinType::UFract:
15122 case BuiltinType::SatUFract:
15123 return Target.getUnsignedFractScale();
15124 case BuiltinType::ULongFract:
15125 case BuiltinType::SatULongFract:
15126 return Target.getUnsignedLongFractScale();
15127 }
15128}
15129
15131 assert(Ty->isFixedPointType());
15132
15133 const TargetInfo &Target = getTargetInfo();
15134 switch (Ty->castAs<BuiltinType>()->getKind()) {
15135 default:
15136 llvm_unreachable("Not a fixed point type!");
15137 case BuiltinType::ShortAccum:
15138 case BuiltinType::SatShortAccum:
15139 return Target.getShortAccumIBits();
15140 case BuiltinType::Accum:
15141 case BuiltinType::SatAccum:
15142 return Target.getAccumIBits();
15143 case BuiltinType::LongAccum:
15144 case BuiltinType::SatLongAccum:
15145 return Target.getLongAccumIBits();
15146 case BuiltinType::UShortAccum:
15147 case BuiltinType::SatUShortAccum:
15148 return Target.getUnsignedShortAccumIBits();
15149 case BuiltinType::UAccum:
15150 case BuiltinType::SatUAccum:
15151 return Target.getUnsignedAccumIBits();
15152 case BuiltinType::ULongAccum:
15153 case BuiltinType::SatULongAccum:
15154 return Target.getUnsignedLongAccumIBits();
15155 case BuiltinType::ShortFract:
15156 case BuiltinType::SatShortFract:
15157 case BuiltinType::Fract:
15158 case BuiltinType::SatFract:
15159 case BuiltinType::LongFract:
15160 case BuiltinType::SatLongFract:
15161 case BuiltinType::UShortFract:
15162 case BuiltinType::SatUShortFract:
15163 case BuiltinType::UFract:
15164 case BuiltinType::SatUFract:
15165 case BuiltinType::ULongFract:
15166 case BuiltinType::SatULongFract:
15167 return 0;
15168 }
15169}
15170
15171llvm::FixedPointSemantics
15173 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
15174 "Can only get the fixed point semantics for a "
15175 "fixed point or integer type.");
15176 if (Ty->isIntegerType())
15177 return llvm::FixedPointSemantics::GetIntegerSemantics(
15178 getIntWidth(Ty), Ty->isSignedIntegerType());
15179
15180 bool isSigned = Ty->isSignedFixedPointType();
15181 return llvm::FixedPointSemantics(
15182 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
15184 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
15185}
15186
15187llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
15188 assert(Ty->isFixedPointType());
15189 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
15190}
15191
15192llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
15193 assert(Ty->isFixedPointType());
15194 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
15195}
15196
15198 assert(Ty->isUnsignedFixedPointType() &&
15199 "Expected unsigned fixed point type");
15200
15201 switch (Ty->castAs<BuiltinType>()->getKind()) {
15202 case BuiltinType::UShortAccum:
15203 return ShortAccumTy;
15204 case BuiltinType::UAccum:
15205 return AccumTy;
15206 case BuiltinType::ULongAccum:
15207 return LongAccumTy;
15208 case BuiltinType::SatUShortAccum:
15209 return SatShortAccumTy;
15210 case BuiltinType::SatUAccum:
15211 return SatAccumTy;
15212 case BuiltinType::SatULongAccum:
15213 return SatLongAccumTy;
15214 case BuiltinType::UShortFract:
15215 return ShortFractTy;
15216 case BuiltinType::UFract:
15217 return FractTy;
15218 case BuiltinType::ULongFract:
15219 return LongFractTy;
15220 case BuiltinType::SatUShortFract:
15221 return SatShortFractTy;
15222 case BuiltinType::SatUFract:
15223 return SatFractTy;
15224 case BuiltinType::SatULongFract:
15225 return SatLongFractTy;
15226 default:
15227 llvm_unreachable("Unexpected unsigned fixed point type");
15228 }
15229}
15230
15231// Given a list of FMV features, return a concatenated list of the
15232// corresponding backend features (which may contain duplicates).
15233static std::vector<std::string> getFMVBackendFeaturesFor(
15234 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) {
15235 std::vector<std::string> BackendFeats;
15236 llvm::AArch64::ExtensionSet FeatureBits;
15237 for (StringRef F : FMVFeatStrings)
15238 if (auto FMVExt = llvm::AArch64::parseFMVExtension(F))
15239 if (FMVExt->ID)
15240 FeatureBits.enable(*FMVExt->ID);
15241 FeatureBits.toLLVMFeatureList(BackendFeats);
15242 return BackendFeats;
15243}
15244
15245ParsedTargetAttr
15246ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
15247 assert(TD != nullptr);
15248 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TD->getFeaturesStr());
15249
15250 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
15251 return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
15252 });
15253 return ParsedAttr;
15254}
15255
15256void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15257 const FunctionDecl *FD) const {
15258 if (FD)
15259 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
15260 else
15261 Target->initFeatureMap(FeatureMap, getDiagnostics(),
15262 Target->getTargetOpts().CPU,
15263 Target->getTargetOpts().Features);
15264}
15265
15266// Fills in the supplied string map with the set of target features for the
15267// passed in function.
15268void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15269 GlobalDecl GD) const {
15270 StringRef TargetCPU = Target->getTargetOpts().CPU;
15271 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
15272 if (const auto *TD = FD->getAttr<TargetAttr>()) {
15274
15275 // Make a copy of the features as passed on the command line into the
15276 // beginning of the additional features from the function to override.
15277 // AArch64 handles command line option features in parseTargetAttr().
15278 if (!Target->getTriple().isAArch64())
15279 ParsedAttr.Features.insert(
15280 ParsedAttr.Features.begin(),
15281 Target->getTargetOpts().FeaturesAsWritten.begin(),
15282 Target->getTargetOpts().FeaturesAsWritten.end());
15283
15284 if (ParsedAttr.CPU != "" && Target->isValidCPUName(ParsedAttr.CPU))
15285 TargetCPU = ParsedAttr.CPU;
15286
15287 // Now populate the feature map, first with the TargetCPU which is either
15288 // the default or a new one from the target attribute string. Then we'll use
15289 // the passed in features (FeaturesAsWritten) along with the new ones from
15290 // the attribute.
15291 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
15292 ParsedAttr.Features);
15293 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
15295 Target->getCPUSpecificCPUDispatchFeatures(
15296 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
15297 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
15298 Features.insert(Features.begin(),
15299 Target->getTargetOpts().FeaturesAsWritten.begin(),
15300 Target->getTargetOpts().FeaturesAsWritten.end());
15301 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15302 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
15303 if (Target->getTriple().isAArch64()) {
15305 TC->getFeatures(Feats, GD.getMultiVersionIndex());
15306 std::vector<std::string> Features = getFMVBackendFeaturesFor(Feats);
15307 Features.insert(Features.begin(),
15308 Target->getTargetOpts().FeaturesAsWritten.begin(),
15309 Target->getTargetOpts().FeaturesAsWritten.end());
15310 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15311 } else if (Target->getTriple().isRISCV()) {
15312 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15313 std::vector<std::string> Features;
15314 if (VersionStr != "default") {
15315 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(VersionStr);
15316 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
15317 ParsedAttr.Features.end());
15318 }
15319 Features.insert(Features.begin(),
15320 Target->getTargetOpts().FeaturesAsWritten.begin(),
15321 Target->getTargetOpts().FeaturesAsWritten.end());
15322 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15323 } else if (Target->getTriple().isOSAIX()) {
15324 std::vector<std::string> Features;
15325 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15326 if (VersionStr.starts_with("cpu="))
15327 TargetCPU = VersionStr.drop_front(sizeof("cpu=") - 1);
15328 else
15329 assert(VersionStr == "default");
15330 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15331 } else {
15332 std::vector<std::string> Features;
15333 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15334 if (VersionStr.starts_with("arch="))
15335 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
15336 else if (VersionStr != "default")
15337 Features.push_back((StringRef{"+"} + VersionStr).str());
15338 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15339 }
15340 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
15341 std::vector<std::string> Features;
15342 if (Target->getTriple().isRISCV()) {
15343 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TV->getName());
15344 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
15345 ParsedAttr.Features.end());
15346 } else {
15347 assert(Target->getTriple().isAArch64());
15349 TV->getFeatures(Feats);
15350 Features = getFMVBackendFeaturesFor(Feats);
15351 }
15352 Features.insert(Features.begin(),
15353 Target->getTargetOpts().FeaturesAsWritten.begin(),
15354 Target->getTargetOpts().FeaturesAsWritten.end());
15355 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15356 } else {
15357 FeatureMap = Target->getTargetOpts().FeatureMap;
15358 }
15359}
15360
15362 CanQualType KernelNameType,
15363 const FunctionDecl *FD) {
15364 // Host and device compilation may use different ABIs and different ABIs
15365 // may allocate name mangling discriminators differently. A discriminator
15366 // override is used to ensure consistent discriminator allocation across
15367 // host and device compilation.
15368 auto DeviceDiscriminatorOverrider =
15369 [](ASTContext &Ctx, const NamedDecl *ND) -> UnsignedOrNone {
15370 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
15371 if (RD->isLambda())
15372 return RD->getDeviceLambdaManglingNumber();
15373 return std::nullopt;
15374 };
15375 std::unique_ptr<MangleContext> MC{ItaniumMangleContext::create(
15376 Context, Context.getDiagnostics(), DeviceDiscriminatorOverrider)};
15377
15378 // Construct a mangled name for the SYCL kernel caller offload entry point.
15379 // FIXME: The Itanium typeinfo mangling (_ZTS<type>) is currently used to
15380 // name the SYCL kernel caller offload entry point function. This mangling
15381 // does not suffice to clearly identify symbols that correspond to SYCL
15382 // kernel caller functions, nor is this mangling natural for targets that
15383 // use a non-Itanium ABI.
15384 std::string Buffer;
15385 Buffer.reserve(128);
15386 llvm::raw_string_ostream Out(Buffer);
15387 MC->mangleCanonicalTypeName(KernelNameType, Out);
15388 std::string KernelName = Out.str();
15389
15390 return {KernelNameType, FD, KernelName};
15391}
15392
15394 // If the function declaration to register is invalid or dependent, the
15395 // registration attempt is ignored.
15396 if (FD->isInvalidDecl() || FD->isTemplated())
15397 return;
15398
15399 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
15400 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
15401
15402 // Be tolerant of multiple registration attempts so long as each attempt
15403 // is for the same entity. Callers are obligated to detect and diagnose
15404 // conflicting kernel names prior to calling this function.
15405 CanQualType KernelNameType = getCanonicalType(SKEPAttr->getKernelName());
15406 auto IT = SYCLKernels.find(KernelNameType);
15407 assert((IT == SYCLKernels.end() ||
15408 declaresSameEntity(FD, IT->second.getKernelEntryPointDecl())) &&
15409 "SYCL kernel name conflict");
15410 (void)IT;
15411 SYCLKernels.insert(std::make_pair(
15412 KernelNameType, BuildSYCLKernelInfo(*this, KernelNameType, FD)));
15413}
15414
15416 CanQualType KernelNameType = getCanonicalType(T);
15417 return SYCLKernels.at(KernelNameType);
15418}
15419
15421 CanQualType KernelNameType = getCanonicalType(T);
15422 auto IT = SYCLKernels.find(KernelNameType);
15423 if (IT != SYCLKernels.end())
15424 return &IT->second;
15425 return nullptr;
15426}
15427
15429 OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
15430 return *OMPTraitInfoVector.back();
15431}
15432
15435 const ASTContext::SectionInfo &Section) {
15436 if (Section.Decl)
15437 return DB << Section.Decl;
15438 return DB << "a prior #pragma section";
15439}
15440
15441bool ASTContext::mayExternalize(const Decl *D) const {
15442 bool IsInternalVar =
15443 isa<VarDecl>(D) &&
15445 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
15446 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
15447 (D->hasAttr<CUDAConstantAttr>() &&
15448 !D->getAttr<CUDAConstantAttr>()->isImplicit());
15449 // CUDA/HIP: managed variables need to be externalized since it is
15450 // a declaration in IR, therefore cannot have internal linkage. Kernels in
15451 // anonymous name space needs to be externalized to avoid duplicate symbols.
15452 return (IsInternalVar &&
15453 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
15454 (D->hasAttr<CUDAGlobalAttr>() &&
15456 GVA_Internal);
15457}
15458
15460 return mayExternalize(D) &&
15461 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
15463}
15464
15465StringRef ASTContext::getCUIDHash() const {
15466 if (!CUIDHash.empty())
15467 return CUIDHash;
15468 if (LangOpts.CUID.empty())
15469 return StringRef();
15470 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
15471 return CUIDHash;
15472}
15473
15474const CXXRecordDecl *
15476 assert(ThisClass);
15477 assert(ThisClass->isPolymorphic());
15478 const CXXRecordDecl *PrimaryBase = ThisClass;
15479 while (1) {
15480 assert(PrimaryBase);
15481 assert(PrimaryBase->isPolymorphic());
15482 auto &Layout = getASTRecordLayout(PrimaryBase);
15483 auto Base = Layout.getPrimaryBase();
15484 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
15485 break;
15486 PrimaryBase = Base;
15487 }
15488 return PrimaryBase;
15489}
15490
15492 StringRef MangledName) {
15493 auto *Method = cast<CXXMethodDecl>(VirtualMethodDecl.getDecl());
15494 assert(Method->isVirtual());
15495 bool DefaultIncludesPointerAuth =
15496 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics;
15497
15498 if (!DefaultIncludesPointerAuth)
15499 return true;
15500
15501 auto Existing = ThunksToBeAbbreviated.find(VirtualMethodDecl);
15502 if (Existing != ThunksToBeAbbreviated.end())
15503 return Existing->second.contains(MangledName.str());
15504
15505 std::unique_ptr<MangleContext> Mangler(createMangleContext());
15506 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks;
15507 auto VtableContext = getVTableContext();
15508 if (const auto *ThunkInfos = VtableContext->getThunkInfo(VirtualMethodDecl)) {
15509 auto *Destructor = dyn_cast<CXXDestructorDecl>(Method);
15510 for (const auto &Thunk : *ThunkInfos) {
15511 SmallString<256> ElidedName;
15512 llvm::raw_svector_ostream ElidedNameStream(ElidedName);
15513 if (Destructor)
15514 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15515 Thunk, /* elideOverrideInfo */ true,
15516 ElidedNameStream);
15517 else
15518 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ true,
15519 ElidedNameStream);
15520 SmallString<256> MangledName;
15521 llvm::raw_svector_ostream mangledNameStream(MangledName);
15522 if (Destructor)
15523 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15524 Thunk, /* elideOverrideInfo */ false,
15525 mangledNameStream);
15526 else
15527 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ false,
15528 mangledNameStream);
15529
15530 Thunks[ElidedName].push_back(std::string(MangledName));
15531 }
15532 }
15533 llvm::StringSet<> SimplifiedThunkNames;
15534 for (auto &ThunkList : Thunks) {
15535 llvm::sort(ThunkList.second);
15536 SimplifiedThunkNames.insert(ThunkList.second[0]);
15537 }
15538 bool Result = SimplifiedThunkNames.contains(MangledName);
15539 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames);
15540 return Result;
15541}
15542
15544 // Check for trivially-destructible here because non-trivially-destructible
15545 // types will always cause the type and any types derived from it to be
15546 // considered non-trivially-copyable. The same cannot be said for
15547 // trivially-copyable because deleting special members of a type derived from
15548 // a non-trivially-copyable type can cause the derived type to be considered
15549 // trivially copyable.
15550 if (getLangOpts().PointerFieldProtectionTagged)
15551 return !isa<CXXRecordDecl>(RD) ||
15552 cast<CXXRecordDecl>(RD)->hasTrivialDestructor();
15553 return true;
15554}
15555
15556static void findPFPFields(const ASTContext &Ctx, QualType Ty, CharUnits Offset,
15557 std::vector<PFPField> &Fields, bool IncludeVBases) {
15558 if (auto *AT = Ctx.getAsConstantArrayType(Ty)) {
15559 if (auto *ElemDecl = AT->getElementType()->getAsCXXRecordDecl()) {
15560 const ASTRecordLayout &ElemRL = Ctx.getASTRecordLayout(ElemDecl);
15561 for (unsigned i = 0; i != AT->getSize(); ++i)
15562 findPFPFields(Ctx, AT->getElementType(), Offset + i * ElemRL.getSize(),
15563 Fields, true);
15564 }
15565 }
15566 auto *Decl = Ty->getAsCXXRecordDecl();
15567 // isPFPType() is inherited from bases and members (including via arrays), so
15568 // we can early exit if it is false. Unions are excluded per the API
15569 // documentation.
15570 if (!Decl || !Decl->isPFPType() || Decl->isUnion())
15571 return;
15572 const ASTRecordLayout &RL = Ctx.getASTRecordLayout(Decl);
15573 for (FieldDecl *Field : Decl->fields()) {
15574 CharUnits FieldOffset =
15575 Offset +
15576 Ctx.toCharUnitsFromBits(RL.getFieldOffset(Field->getFieldIndex()));
15577 if (Ctx.isPFPField(Field))
15578 Fields.push_back({FieldOffset, Field});
15579 findPFPFields(Ctx, Field->getType(), FieldOffset, Fields,
15580 /*IncludeVBases=*/true);
15581 }
15582 // Pass false for IncludeVBases below because vbases are only included in
15583 // layout for top-level types, i.e. not bases or vbases.
15584 for (CXXBaseSpecifier &Base : Decl->bases()) {
15585 if (Base.isVirtual())
15586 continue;
15587 CharUnits BaseOffset =
15588 Offset + RL.getBaseClassOffset(Base.getType()->getAsCXXRecordDecl());
15589 findPFPFields(Ctx, Base.getType(), BaseOffset, Fields,
15590 /*IncludeVBases=*/false);
15591 }
15592 if (IncludeVBases) {
15593 for (CXXBaseSpecifier &Base : Decl->vbases()) {
15594 CharUnits BaseOffset =
15595 Offset + RL.getVBaseClassOffset(Base.getType()->getAsCXXRecordDecl());
15596 findPFPFields(Ctx, Base.getType(), BaseOffset, Fields,
15597 /*IncludeVBases=*/false);
15598 }
15599 }
15600}
15601
15602std::vector<PFPField> ASTContext::findPFPFields(QualType Ty) const {
15603 std::vector<PFPField> PFPFields;
15604 ::findPFPFields(*this, Ty, CharUnits::Zero(), PFPFields, true);
15605 return PFPFields;
15606}
15607
15609 return !findPFPFields(Ty).empty();
15610}
15611
15612bool ASTContext::isPFPField(const FieldDecl *FD) const {
15613 if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getParent()))
15614 return RD->isPFPType() && FD->getType()->isPointerType() &&
15615 !FD->hasAttr<NoFieldProtectionAttr>();
15616 return false;
15617}
15618
15620 auto *FD = dyn_cast<FieldDecl>(VD);
15621 if (!FD)
15622 FD = cast<FieldDecl>(cast<IndirectFieldDecl>(VD)->chain().back());
15623 if (isPFPField(FD))
15625}
15626
15628 if (E->getNumComponents() == 0)
15629 return;
15630 OffsetOfNode Comp = E->getComponent(E->getNumComponents() - 1);
15631 if (Comp.getKind() != OffsetOfNode::Field)
15632 return;
15633 if (FieldDecl *FD = Comp.getField(); isPFPField(FD))
15635}
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 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:477
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:2848
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.
__device__ __2f16 float c
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:1105
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1098
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition APValue.cpp:1112
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:229
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:811
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
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:812
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:807
Builtin::Context & BuiltinInfo
Definition ASTContext.h:809
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:961
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:808
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.
Definition ASTContext.h:996
bool isSameDefaultTemplateArgument(const NamedDecl *X, const NamedDecl *Y) const
Determine whether two default template arguments are similar enough that they may be used in declarat...
QualType applyObjCProtocolQualifiers(QualType type, ArrayRef< ObjCProtocolDecl * > protocols, bool &hasError, bool allowOnPointerType=false) const
Apply Objective-C protocol qualifiers to the given type.
QualType getMacroQualifiedType(QualType UnderlyingTy, const IdentifierInfo *MacroII) const
QualType removePtrSizeAddrSpace(QualType T) const
Remove the existing address space on the type if it is a pointer size address space and return the ty...
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
CanQualType SatShortFractTy
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:927
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:585
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:810
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.
Definition ASTContext.h:999
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.
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:230
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:813
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:860
void ResetObjCLayout(const ObjCInterfaceDecl *D)
ArrayRef< Module * > getModulesWithMergedDefinition(const NamedDecl *Def)
Get the additional modules in which the definition Def has been merged.
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:577
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:881
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:926
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)
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:3551
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3572
Represents a loop initializing the elements of an array.
Definition Expr.h:5968
llvm::APInt getArraySize() const
Definition Expr.h:5990
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:5988
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition TypeBase.h:3954
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3784
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3798
Qualifiers getIndexTypeQualifiers() const
Definition TypeBase.h:3802
QualType getElementType() const
Definition TypeBase.h:3796
unsigned getIndexTypeCVRQualifiers() const
Definition TypeBase.h:3806
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:6928
Expr * getPtr() const
Definition Expr.h:6959
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8249
Attr - This represents one attribute.
Definition Attr.h:46
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8297
void Profile(llvm::FoldingSetNodeID &ID) const
Definition TypeBase.h:8314
unsigned getNumBits() const
Definition TypeBase.h:8309
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4694
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6672
Pointer to a block type.
Definition TypeBase.h:3604
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3621
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:3226
Kind getKind() const
Definition TypeBase.h:3274
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:2620
Represents a C++ destructor within a class.
Definition DeclCXX.h:2882
CXXDestructorDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2930
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2132
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2241
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:132
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:1214
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:1186
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:3337
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3352
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:3822
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition TypeBase.h:3918
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3878
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition TypeBase.h:3937
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3898
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4449
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4468
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4514
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4465
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition TypeBase.h:3498
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3534
Represents a pointer type decayed from an array or function type.
Definition TypeBase.h:3587
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1462
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2122
bool isFileContext() const
Definition DeclBase.h:2193
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2138
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:2115
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1273
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:341
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:547
void addAttr(Attr *A)
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition DeclBase.cpp:561
bool isUnconditionallyVisible() const
Determine whether this declaration is definitely visible to name lookup, independent of whether the o...
Definition DeclBase.h:867
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:997
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:850
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:1062
DeclContext * getDeclContext()
Definition DeclBase.h:456
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition DeclBase.cpp:382
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:931
bool hasAttr() const
Definition DeclBase.h:585
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:991
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:4123
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4145
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:8342
Represents an array type in C++ whose size is a value-dependent expression.
Definition TypeBase.h:4073
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4102
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4163
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4188
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4535
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4555
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:6314
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:6319
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4289
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4314
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:233
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
A dynamically typed AST node container.
Represents an enum.
Definition Decl.h:4033
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4251
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4265
EnumDecl * getDefinitionOrSelf() const
Definition Decl.h:4149
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4206
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:3102
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:4236
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:834
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:3077
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition Expr.cpp:4075
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:1732
void Profile(llvm::FoldingSetNodeID &ID) const
Definition TypeBase.h:1779
ExtVectorType - Extended vector type.
Definition TypeBase.h:4329
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:5542
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:3182
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3285
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4746
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3267
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3418
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:4694
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:2018
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2707
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3736
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2939
bool isMSExternInline() const
The combination of the extern and inline keywords under MSVC forces the function to be required.
Definition Decl.cpp:3865
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3721
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4391
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition Decl.h:2428
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:4052
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5337
static FunctionEffectSet getIntersection(FunctionEffectsRef LHS, FunctionEffectsRef RHS)
Definition Type.cpp:5830
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition Type.cpp:5868
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5169
ArrayRef< EffectConditionExpr > conditions() const
Definition TypeBase.h:5203
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:4947
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4963
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5369
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5873
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5676
unsigned getNumParams() const
Definition TypeBase.h:5647
QualType getParamType(unsigned i) const
Definition TypeBase.h:5649
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition Type.cpp:4078
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5682
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5773
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5658
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5654
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition TypeBase.h:5842
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition TypeBase.h:5838
Declaration of a template function.
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4676
CallingConv getCC() const
Definition TypeBase.h:4735
unsigned getRegParm() const
Definition TypeBase.h:4728
bool getNoCallerSavedRegs() const
Definition TypeBase.h:4724
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4747
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition TypeBase.h:4591
ExtParameterInfo withIsNoEscape(bool NoEscape) const
Definition TypeBase.h:4631
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4565
ExtInfo getExtInfo() const
Definition TypeBase.h:4921
QualType getReturnType() const
Definition TypeBase.h:4905
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:5075
Represents a C array with an unspecified size.
Definition TypeBase.h:3971
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3988
static ItaniumMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3679
@ 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
A global _GUID constant.
Definition DeclCXX.h:4403
static void Profile(llvm::FoldingSetNodeID &ID, Parts P)
Definition DeclCXX.h:4440
MSGuidDeclParts Parts
Definition DeclCXX.h:4405
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition TypeBase.h:6248
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:4420
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4413
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3715
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3758
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:3362
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:8007
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:8063
bool isObjCQualifiedClassType() const
True if this is equivalent to 'Class.
Definition TypeBase.h:8144
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:8138
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8220
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8100
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:8121
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8075
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:8115
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:8182
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition TypeBase.h:8127
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:2530
const OffsetOfNode & getComponent(unsigned Idx) const
Definition Expr.h:2577
unsigned getNumComponents() const
Definition Expr.h:2585
Helper class for OffsetOfExpr.
Definition Expr.h:2424
@ Field
A field.
Definition Expr.h:2431
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:4363
Sugar for parentheses used when specifying types.
Definition TypeBase.h:3364
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3378
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:1808
ObjCDeclQualifier getObjCDeclQualifier() const
Definition Decl.h:1872
QualType getOriginalType() const
Definition Decl.cpp:2940
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8280
Pointer-authentication qualifiers.
Definition TypeBase.h:152
static PointerAuthQualifier Create(unsigned Key, bool IsAddressDiscriminated, unsigned ExtraDiscriminator, PointerAuthenticationMode AuthenticationMode, bool IsIsaPointer, bool AuthenticatesNullValues)
Definition TypeBase.h:239
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:301
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3390
QualType getPointeeType() const
Definition TypeBase.h:3400
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3405
PredefinedSugarKind Kind
Definition TypeBase.h:8356
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
A (possibly-)qualified type.
Definition TypeBase.h:937
bool hasAddressDiscriminatedPointerAuth() const
Definition TypeBase.h:1472
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8529
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2962
Qualifiers::GC getObjCGCAttr() const
Returns gc attribute of this type.
Definition TypeBase.h:8576
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8534
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition TypeBase.h:1311
QualType withConst() const
Definition TypeBase.h:1174
bool hasLocalQualifiers() const
Determine whether this particular QualType instance has any qualifiers, without looking through any t...
Definition TypeBase.h:1064
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8445
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8571
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8485
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1453
QualType getCanonicalType() const
Definition TypeBase.h:8497
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8539
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition TypeBase.h:8466
QualType getNonPackExpansionType() const
Remove an outer pack expansion type (if any) from this type.
Definition Type.cpp:3671
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8518
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1560
bool isCanonical() const
Definition TypeBase.h:8502
const Type * getTypePtrOrNull() const
Definition TypeBase.h:8449
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1347
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:3105
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8477
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:8385
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8392
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
unsigned getCVRQualifiers() const
Definition TypeBase.h:488
void removeCVRQualifiers(unsigned mask)
Definition TypeBase.h:495
GC getObjCGCAttr() const
Definition TypeBase.h:519
void addAddressSpace(LangAS space)
Definition TypeBase.h:597
static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R)
Returns the common set of qualifiers while removing them from the given sets.
Definition TypeBase.h:384
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:354
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:350
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:364
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:367
void removeObjCLifetime()
Definition TypeBase.h:551
bool hasNonFastQualifiers() const
Return true if the set contains any qualifiers which require an ExtQuals node to be allocated.
Definition TypeBase.h:638
void addConsistentQualifiers(Qualifiers qs)
Add the qualifiers from the given set to this set, given that they don't conflict.
Definition TypeBase.h:689
void removeFastQualifiers(unsigned mask)
Definition TypeBase.h:624
bool hasUnaligned() const
Definition TypeBase.h:511
bool hasAddressSpace() const
Definition TypeBase.h:570
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:708
unsigned getFastQualifiers() const
Definition TypeBase.h:619
void removeAddressSpace()
Definition TypeBase.h:596
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:603
bool hasObjCGCAttr() const
Definition TypeBase.h:518
uint64_t getAsOpaqueValue() const
Definition TypeBase.h:455
bool hasObjCLifetime() const
Definition TypeBase.h:544
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:545
bool empty() const
Definition TypeBase.h:647
void addObjCGCAttr(GC type)
Definition TypeBase.h:524
LangAS getAddressSpace() const
Definition TypeBase.h:571
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3697
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:4347
bool isLambda() const
Determine whether this record is a class describing a lambda function object.
Definition Decl.cpp:5240
bool hasFlexibleArrayMember() const
Definition Decl.h:4380
field_range fields() const
Definition Decl.h:4550
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition Decl.cpp:5226
RecordDecl * getMostRecentDecl()
Definition Decl.h:4373
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition Decl.cpp:5285
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4531
bool field_empty() const
Definition Decl.h:4558
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:3635
QualType getPointeeType() const
Definition TypeBase.h:3653
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3661
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:1802
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:1193
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:3739
TagTypeKind TagKind
Definition Decl.h:3744
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition Decl.h:3976
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4900
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4893
bool isUnion() const
Definition Decl.h:3950
TagKind getTagKind() const
Definition Decl.h:3939
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:859
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:752
BuiltinVaListKind
The different kinds of __builtin_va_list types defined by the target implementation.
Definition TargetInfo.h:334
@ AArch64ABIBuiltinVaList
__builtin_va_list as defined by the AArch64 ABI http://infocenter.arm.com/help/topic/com....
Definition TargetInfo.h:343
@ PowerABIBuiltinVaList
__builtin_va_list as defined by the Power ABI: https://www.power.org /resources/downloads/Power-Arch-...
Definition TargetInfo.h:348
@ AAPCSABIBuiltinVaList
__builtin_va_list as defined by ARM AAPCS ABI http://infocenter.arm.com
Definition TargetInfo.h:357
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition TargetInfo.h:336
@ VoidPtrBuiltinVaList
typedef void* __builtin_va_list;
Definition TargetInfo.h:339
@ X86_64ABIBuiltinVaList
__builtin_va_list as defined by the x86-64 ABI: http://refspecs.linuxbase.org/elf/x86_64-abi-0....
Definition TargetInfo.h:352
virtual uint64_t getNullPointerValue(LangAS AddrSpace) const
Get integer value for null pointer.
Definition TargetInfo.h:506
static bool isTypeSigned(IntType T)
Returns true if the type is signed; false otherwise.
IntType getPtrDiffType(LangAS AddrSpace) const
Definition TargetInfo.h:408
IntType getSizeType() const
Definition TargetInfo.h:389
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:979
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:760
unsigned getTargetAddressSpace(LangAS AS) const
IntType getSignedSizeType() const
Definition TargetInfo.h:390
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:3535
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:6280
A container of type source information.
Definition TypeBase.h:8416
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:1875
bool isBlockPointerType() const
Definition TypeBase.h:8702
bool isVoidType() const
Definition TypeBase.h:9048
bool isObjCBuiltinType() const
Definition TypeBase.h:8912
QualType getRVVEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an RVV builtin type.
Definition Type.cpp:2771
bool isIncompleteArrayType() const
Definition TypeBase.h:8789
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2266
bool isFloat16Type() const
Definition TypeBase.h:9057
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:8785
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:2517
bool isArrayType() const
Definition TypeBase.h:8781
bool isCharType() const
Definition Type.cpp:2193
QualType getLocallyUnqualifiedSingleStepDesugaredType() const
Pull a single level of sugar off of this locally-unqualified type.
Definition Type.cpp:558
bool isPointerType() const
Definition TypeBase.h:8682
TagDecl * castAsTagDecl() const
Definition Type.h:69
bool isArrayParameterType() const
Definition TypeBase.h:8797
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9092
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9342
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:9136
bool isEnumeralType() const
Definition TypeBase.h:8813
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8882
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:9170
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2961
bool isBitIntType() const
Definition TypeBase.h:8957
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8805
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2844
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9108
bool isHalfType() const
Definition TypeBase.h:9052
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9124
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2465
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3181
@ PtrdiffT
The "ptrdiff_t" type.
Definition TypeBase.h:2340
@ SizeT
The "size_t" type.
Definition TypeBase.h:2334
@ SignedSizeT
The signed integer type corresponding to "size_t".
Definition TypeBase.h:2337
bool isObjCIdType() const
Definition TypeBase.h:8894
bool isOverflowBehaviorType() const
Definition TypeBase.h:8853
EnumDecl * castAsEnumDecl() const
Definition Type.h:59
bool isUnsaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9132
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9328
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:2527
bool isFunctionType() const
Definition TypeBase.h:8678
bool isObjCObjectPointerType() const
Definition TypeBase.h:8861
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:9150
bool isVectorType() const
Definition TypeBase.h:8821
bool isObjCClassType() const
Definition TypeBase.h:8900
bool isRVVVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'riscv_rvv_vector_bits' type attribute,...
Definition Type.cpp:2753
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2688
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2983
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:2332
bool isAnyPointerType() const
Definition TypeBase.h:8690
TypeClass getTypeClass() const
Definition TypeBase.h:2445
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2471
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9275
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:9085
bool isRecordType() const
Definition TypeBase.h:8809
bool isObjCRetainableType() const
Definition Type.cpp:5417
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5148
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3689
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5760
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3584
QualType getUnderlyingType() const
Definition Decl.h:3639
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType Underlying)
Definition TypeBase.h:6224
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2247
Opcode getOpcode() const
Definition Expr.h:2283
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition DeclCXX.h:4460
static void Profile(llvm::FoldingSetNodeID &ID, QualType Ty, const APValue &APVal)
Definition DeclCXX.h:4488
The iterator over UnresolvedSets.
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition TypeBase.h:6085
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UnresolvedUsingTypenameDecl *D)
Definition TypeBase.h:6122
Represents a dependent using declaration which was marked with typename.
Definition DeclCXX.h:4042
UnresolvedUsingTypenameDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this declaration.
Definition DeclCXX.h:4107
Represents a C++ using-enum-declaration.
Definition DeclCXX.h:3797
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3404
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3468
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition DeclCXX.cpp:3475
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UsingShadowDecl *D, QualType UnderlyingType)
Definition TypeBase.h:6162
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:5575
void clear()
Definition Value.cpp:216
Represents a variable declaration or definition.
Definition Decl.h:924
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2768
bool hasInit() const
Definition Decl.cpp:2377
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:2440
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1296
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:1206
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1564
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1308
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2354
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:2737
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4028
Expr * getSizeExpr() const
Definition TypeBase.h:4042
Represents a GCC generic vector type.
Definition TypeBase.h:4237
unsigned getNumElements() const
Definition TypeBase.h:4252
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4261
VectorKind getVectorKind() const
Definition TypeBase.h:4257
QualType getElementType() const
Definition TypeBase.h:4251
A full comment attached to a declaration, contains block content.
Definition Comment.h:1106
ArrayRef< BlockContentComment * > getBlocks() const
Definition Comment.h:1144
const DeclInfo * getDeclInfo() const LLVM_READONLY
Definition Comment.h:1138
const Decl * getDecl() const LLVM_READONLY
Definition Comment.h:1134
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:1834
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:8580
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:918
@ 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:905
@ TypeAlignment
Definition TypeBase.h:76
ArraySizeModifier
Capture whether this is a normal array (e.g.
Definition TypeBase.h:3781
OptionalUnsigned< unsigned > UnsignedOrNone
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
@ Template
We are parsing a template declaration.
Definition Parser.h:81
@ Interface
The "__interface" keyword.
Definition TypeBase.h:5998
@ Struct
The "struct" keyword.
Definition TypeBase.h:5995
@ Class
The "class" keyword.
Definition TypeBase.h:6004
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:1807
@ Deduced
The normal deduced case.
Definition TypeBase.h:1814
@ Undeduced
Not deduced yet. This is for example an 'auto' which was just parsed.
Definition TypeBase.h:1809
@ DeducedAsPack
Same as above, but additionally this represents a case where the deduced entity itself is a pack.
Definition TypeBase.h:1830
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:1301
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:4207
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4216
@ AltiVecPixel
is AltiVec 'vector Pixel'
Definition TypeBase.h:4204
@ Generic
not a target-specific vector type
Definition TypeBase.h:4198
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
Definition TypeBase.h:4222
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
Definition TypeBase.h:4225
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4219
U cast(CodeGen::Address addr)
Definition Address.h:327
LangAS getLangASFromTargetAS(unsigned TargetAS)
AlignRequirementKind
Definition ASTContext.h:180
@ None
The alignment was not explicit in code.
Definition ASTContext.h:182
@ RequiredByEnum
The alignment comes from an alignment attribute on a enum type.
Definition ASTContext.h:191
@ RequiredByTypedef
The alignment comes from an alignment attribute on a typedef.
Definition ASTContext.h:185
@ RequiredByRecord
The alignment comes from an alignment attribute on a record type.
Definition ASTContext.h:188
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:5968
@ Interface
The "__interface" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5973
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5989
@ Struct
The "struct" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5970
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5979
@ Union
The "union" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5976
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5982
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:5986
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:6718
Expr * getCopyExpr() const
Definition Expr.h:6725
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:5426
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5428
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition TypeBase.h:5431
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition TypeBase.h:5434
Extra information about a function prototype.
Definition TypeBase.h:5454
bool requiresFunctionProtoTypeArmAttributes() const
Definition TypeBase.h:5500
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5459
bool requiresFunctionProtoTypeExtraAttributeInfo() const
Definition TypeBase.h:5504
bool requiresFunctionProtoTypeExtraBitfields() const
Definition TypeBase.h:5493
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:3381
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:870
const Type * Ty
The locally-unqualified type.
Definition TypeBase.h:872
Qualifiers Quals
The local qualifiers.
Definition TypeBase.h:875
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:211
bool isAlignRequired()
Definition ASTContext.h:203
AlignRequirementKind AlignRequirement
Definition ASTContext.h:197
Information about the declaration, useful to clients of FullComment.
Definition Comment.h:983
const TemplateParameterList * TemplateParameters
Template parameters that can be referenced by \tparam if CommentDecl is a template (IsTemplateDecl or...
Definition Comment.h:1009
const Decl * CommentDecl
Declaration the comment is actually attached to (in the source).
Definition Comment.h:986