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 AttributedTypes(this_()), DependentBitIntTypes(this_()),
941 SubstTemplateTemplateParmPacks(this_()), DeducedTemplates(this_()),
942 ArrayParameterTypes(this_()), CanonTemplateTemplateParms(this_()),
943 SourceMgr(SM), LangOpts(LOpts),
944 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
945 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
946 LangOpts.XRayNeverInstrumentFiles,
947 LangOpts.XRayAttrListFiles, SM)),
948 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
949 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
950 BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this),
951 Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
952 CompCategories(this_()), LastSDM(nullptr, 0) {
954}
955
957 // Release the DenseMaps associated with DeclContext objects.
958 // FIXME: Is this the ideal solution?
959 ReleaseDeclContextMaps();
960
961 // Call all of the deallocation functions on all of their targets.
962 for (auto &Pair : Deallocations)
963 (Pair.first)(Pair.second);
964 Deallocations.clear();
965
966 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
967 // because they can contain DenseMaps.
968 for (llvm::DenseMap<const ObjCInterfaceDecl *,
970 I = ObjCLayouts.begin(),
971 E = ObjCLayouts.end();
972 I != E;)
973 // Increment in loop to prevent using deallocated memory.
974 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
975 R->Destroy(*this);
976 ObjCLayouts.clear();
977
978 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
979 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
980 // Increment in loop to prevent using deallocated memory.
981 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
982 R->Destroy(*this);
983 }
984 ASTRecordLayouts.clear();
985
986 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
987 AEnd = DeclAttrs.end();
988 A != AEnd; ++A)
989 A->second->~AttrVec();
990 DeclAttrs.clear();
991
992 CtorClosureDefaultArgs.clear();
993
994 for (const auto &Value : ModuleInitializers)
995 Value.second->~PerModuleInitializers();
996 ModuleInitializers.clear();
997
998 TUDecl = nullptr;
999 XRayFilter.reset();
1000 NoSanitizeL.reset();
1001}
1002
1004
1005void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
1006 TraversalScope = TopLevelDecls;
1008}
1009
1010void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
1011 Deallocations.push_back({Callback, Data});
1012}
1013
1014void
1018
1020 llvm::errs() << "\n*** AST Context Stats:\n";
1021 llvm::errs() << " " << Types.size() << " types total.\n";
1022
1023 unsigned counts[] = {
1024#define TYPE(Name, Parent) 0,
1025#define ABSTRACT_TYPE(Name, Parent)
1026#include "clang/AST/TypeNodes.inc"
1027 0 // Extra
1028 };
1029
1030 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1031 Type *T = Types[i];
1032 counts[(unsigned)T->getTypeClass()]++;
1033 }
1034
1035 unsigned Idx = 0;
1036 unsigned TotalBytes = 0;
1037#define TYPE(Name, Parent) \
1038 if (counts[Idx]) \
1039 llvm::errs() << " " << counts[Idx] << " " << #Name \
1040 << " types, " << sizeof(Name##Type) << " each " \
1041 << "(" << counts[Idx] * sizeof(Name##Type) \
1042 << " bytes)\n"; \
1043 TotalBytes += counts[Idx] * sizeof(Name##Type); \
1044 ++Idx;
1045#define ABSTRACT_TYPE(Name, Parent)
1046#include "clang/AST/TypeNodes.inc"
1047
1048 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1049
1050 // Implicit special member functions.
1051 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1053 << " implicit default constructors created\n";
1054 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1056 << " implicit copy constructors created\n";
1057 if (getLangOpts().CPlusPlus)
1058 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1060 << " implicit move constructors created\n";
1061 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1063 << " implicit copy assignment operators created\n";
1064 if (getLangOpts().CPlusPlus)
1065 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1067 << " implicit move assignment operators created\n";
1068 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1070 << " implicit destructors created\n";
1071
1072 if (ExternalSource) {
1073 llvm::errs() << "\n";
1074 ExternalSource->PrintStats();
1075 }
1076
1077 BumpAlloc.PrintStats();
1078}
1079
1081 bool NotifyListeners) {
1082 if (NotifyListeners)
1083 if (auto *Listener = getASTMutationListener();
1085 Listener->RedefinedHiddenDefinition(ND, M);
1086
1087 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1088}
1089
1091 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1092 if (It == MergedDefModules.end())
1093 return;
1094
1095 auto &Merged = It->second;
1096 llvm::DenseSet<Module*> Found;
1097 for (Module *&M : Merged)
1098 if (!Found.insert(M).second)
1099 M = nullptr;
1100 llvm::erase(Merged, nullptr);
1101}
1102
1105 auto MergedIt =
1106 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1107 if (MergedIt == MergedDefModules.end())
1108 return {};
1109 return MergedIt->second;
1110}
1111
1112void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1113 if (LazyInitializers.empty())
1114 return;
1115
1116 auto *Source = Ctx.getExternalSource();
1117 assert(Source && "lazy initializers but no external source");
1118
1119 auto LazyInits = std::move(LazyInitializers);
1120 LazyInitializers.clear();
1121
1122 for (auto ID : LazyInits)
1123 Initializers.push_back(Source->GetExternalDecl(ID));
1124
1125 assert(LazyInitializers.empty() &&
1126 "GetExternalDecl for lazy module initializer added more inits");
1127}
1128
1130 // One special case: if we add a module initializer that imports another
1131 // module, and that module's only initializer is an ImportDecl, simplify.
1132 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1133 auto It = ModuleInitializers.find(ID->getImportedModule());
1134
1135 // Maybe the ImportDecl does nothing at all. (Common case.)
1136 if (It == ModuleInitializers.end())
1137 return;
1138
1139 // Maybe the ImportDecl only imports another ImportDecl.
1140 auto &Imported = *It->second;
1141 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1142 Imported.resolve(*this);
1143 auto *OnlyDecl = Imported.Initializers.front();
1144 if (isa<ImportDecl>(OnlyDecl))
1145 D = OnlyDecl;
1146 }
1147 }
1148
1149 auto *&Inits = ModuleInitializers[M];
1150 if (!Inits)
1151 Inits = new (*this) PerModuleInitializers;
1152 Inits->Initializers.push_back(D);
1153}
1154
1157 auto *&Inits = ModuleInitializers[M];
1158 if (!Inits)
1159 Inits = new (*this) PerModuleInitializers;
1160 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1161 IDs.begin(), IDs.end());
1162}
1163
1165 auto It = ModuleInitializers.find(M);
1166 if (It == ModuleInitializers.end())
1167 return {};
1168
1169 auto *Inits = It->second;
1170 Inits->resolve(*this);
1171 return Inits->Initializers;
1172}
1173
1175 assert(M->isNamedModule());
1176 assert(!CurrentCXXNamedModule &&
1177 "We should set named module for ASTContext for only once");
1178 CurrentCXXNamedModule = M;
1179}
1180
1181bool ASTContext::isInSameModule(const Module *M1, const Module *M2) const {
1182 if (!M1 != !M2)
1183 return false;
1184
1185 /// Get the representative module for M. The representative module is the
1186 /// first module unit for a specific primary module name. So that the module
1187 /// units have the same representative module belongs to the same module.
1188 ///
1189 /// The process is helpful to reduce the expensive string operations.
1190 auto GetRepresentativeModule = [this](const Module *M) {
1191 auto Iter = SameModuleLookupSet.find(M);
1192 if (Iter != SameModuleLookupSet.end())
1193 return Iter->second;
1194
1195 const Module *RepresentativeModule =
1196 PrimaryModuleNameMap.try_emplace(M->getPrimaryModuleInterfaceName(), M)
1197 .first->second;
1198 SameModuleLookupSet[M] = RepresentativeModule;
1199 return RepresentativeModule;
1200 };
1201
1202 assert(M1 && "Shouldn't call `isInSameModule` if both M1 and M2 are none.");
1203 return GetRepresentativeModule(M1) == GetRepresentativeModule(M2);
1204}
1205
1207 if (!ExternCContext)
1208 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1209
1210 return ExternCContext;
1211}
1212
1223
1224#define BuiltinTemplate(BTName) \
1225 BuiltinTemplateDecl *ASTContext::get##BTName##Decl() const { \
1226 if (!Decl##BTName) \
1227 Decl##BTName = \
1228 buildBuiltinTemplateDecl(BTK##BTName, get##BTName##Name()); \
1229 return Decl##BTName; \
1230 }
1231#include "clang/Basic/BuiltinTemplates.inc"
1232
1234 RecordDecl::TagKind TK) const {
1235 SourceLocation Loc;
1236 RecordDecl *NewDecl;
1237 if (getLangOpts().CPlusPlus)
1238 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1239 Loc, &Idents.get(Name));
1240 else
1241 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1242 &Idents.get(Name));
1243 NewDecl->setImplicit();
1244 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1245 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1246 return NewDecl;
1247}
1248
1250 StringRef Name) const {
1253 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1254 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1255 NewDecl->setImplicit();
1256 return NewDecl;
1257}
1258
1260 if (!Int128Decl)
1261 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1262 return Int128Decl;
1263}
1264
1266 if (!UInt128Decl)
1267 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1268 return UInt128Decl;
1269}
1270
1271void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1272 auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K);
1274 Types.push_back(Ty);
1275}
1276
1278 const TargetInfo *AuxTarget) {
1279 assert((!this->Target || this->Target == &Target) &&
1280 "Incorrect target reinitialization");
1281 assert(VoidTy.isNull() && "Context reinitialized?");
1282
1283 this->Target = &Target;
1284 this->AuxTarget = AuxTarget;
1285
1286 ABI.reset(createCXXABI(Target));
1287 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1288
1289 // C99 6.2.5p19.
1290 InitBuiltinType(VoidTy, BuiltinType::Void);
1291
1292 // C99 6.2.5p2.
1293 InitBuiltinType(BoolTy, BuiltinType::Bool);
1294 // C99 6.2.5p3.
1295 if (LangOpts.CharIsSigned)
1296 InitBuiltinType(CharTy, BuiltinType::Char_S);
1297 else
1298 InitBuiltinType(CharTy, BuiltinType::Char_U);
1299 // C99 6.2.5p4.
1300 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1301 InitBuiltinType(ShortTy, BuiltinType::Short);
1302 InitBuiltinType(IntTy, BuiltinType::Int);
1303 InitBuiltinType(LongTy, BuiltinType::Long);
1304 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1305
1306 // C99 6.2.5p6.
1307 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1308 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1309 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1310 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1311 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1312
1313 // C99 6.2.5p10.
1314 InitBuiltinType(FloatTy, BuiltinType::Float);
1315 InitBuiltinType(DoubleTy, BuiltinType::Double);
1316 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1317
1318 // GNU extension, __float128 for IEEE quadruple precision
1319 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1320
1321 // __ibm128 for IBM extended precision
1322 InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128);
1323
1324 // C11 extension ISO/IEC TS 18661-3
1325 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1326
1327 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1328 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1329 InitBuiltinType(AccumTy, BuiltinType::Accum);
1330 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1331 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1332 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1333 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1334 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1335 InitBuiltinType(FractTy, BuiltinType::Fract);
1336 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1337 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1338 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1339 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1340 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1341 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1342 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1343 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1344 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1345 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1346 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1347 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1348 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1349 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1350 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1351 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
1352
1353 // GNU extension, 128-bit integers.
1354 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1355 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1356
1357 // C++ 3.9.1p5
1358 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1359 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1360 else // -fshort-wchar makes wchar_t be unsigned.
1361 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1362 if (LangOpts.CPlusPlus && LangOpts.WChar)
1364 else {
1365 // C99 (or C++ using -fno-wchar).
1366 WideCharTy = getFromTargetType(Target.getWCharType());
1367 }
1368
1369 WIntTy = getFromTargetType(Target.getWIntType());
1370
1371 // C++20 (proposed)
1372 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1373
1374 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1375 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1376 else // C99
1377 Char16Ty = getFromTargetType(Target.getChar16Type());
1378
1379 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1380 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1381 else // C99
1382 Char32Ty = getFromTargetType(Target.getChar32Type());
1383
1384 // Placeholder type for type-dependent expressions whose type is
1385 // completely unknown. No code should ever check a type against
1386 // DependentTy and users should never see it; however, it is here to
1387 // help diagnose failures to properly check for type-dependent
1388 // expressions.
1389 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1390
1391 // Placeholder type for functions.
1392 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1393
1394 // Placeholder type for bound members.
1395 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1396
1397 // Placeholder type for unresolved templates.
1398 InitBuiltinType(UnresolvedTemplateTy, BuiltinType::UnresolvedTemplate);
1399
1400 // Placeholder type for pseudo-objects.
1401 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1402
1403 // "any" type; useful for debugger-like clients.
1404 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1405
1406 // Placeholder type for unbridged ARC casts.
1407 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1408
1409 // Placeholder type for builtin functions.
1410 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1411
1412 // Placeholder type for OMP array sections.
1413 if (LangOpts.OpenMP) {
1414 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1415 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1416 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1417 }
1418 // Placeholder type for OpenACC array sections, if we are ALSO in OMP mode,
1419 // don't bother, as we're just using the same type as OMP.
1420 if (LangOpts.OpenACC && !LangOpts.OpenMP) {
1421 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1422 }
1423 if (LangOpts.MatrixTypes)
1424 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1425
1426 // Builtin types for 'id', 'Class', and 'SEL'.
1427 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1428 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1429 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1430
1431 if (LangOpts.OpenCL) {
1432#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1433 InitBuiltinType(SingletonId, BuiltinType::Id);
1434#include "clang/Basic/OpenCLImageTypes.def"
1435
1436 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1437 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1438 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1439 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1440 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1441
1442#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1443 InitBuiltinType(Id##Ty, BuiltinType::Id);
1444#include "clang/Basic/OpenCLExtensionTypes.def"
1445 }
1446
1447 if (LangOpts.HLSL) {
1448#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1449 InitBuiltinType(SingletonId, BuiltinType::Id);
1450#include "clang/Basic/HLSLIntangibleTypes.def"
1451 }
1452
1453 if (Target.hasAArch64ACLETypes() ||
1454 (AuxTarget && AuxTarget->hasAArch64ACLETypes())) {
1455#define SVE_TYPE(Name, Id, SingletonId) \
1456 InitBuiltinType(SingletonId, BuiltinType::Id);
1457#include "clang/Basic/AArch64ACLETypes.def"
1458 }
1459
1460 if (Target.getTriple().isPPC64()) {
1461#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1462 InitBuiltinType(Id##Ty, BuiltinType::Id);
1463#include "clang/Basic/PPCTypes.def"
1464#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1465 InitBuiltinType(Id##Ty, BuiltinType::Id);
1466#include "clang/Basic/PPCTypes.def"
1467 }
1468
1469 if (Target.hasRISCVVTypes()) {
1470#define RVV_TYPE(Name, Id, SingletonId) \
1471 InitBuiltinType(SingletonId, BuiltinType::Id);
1472#include "clang/Basic/RISCVVTypes.def"
1473 }
1474
1475 if (Target.getTriple().isWasm() && Target.hasFeature("reference-types")) {
1476#define WASM_TYPE(Name, Id, SingletonId) \
1477 InitBuiltinType(SingletonId, BuiltinType::Id);
1478#include "clang/Basic/WebAssemblyReferenceTypes.def"
1479 }
1480
1481 if (Target.getTriple().isAMDGPU() ||
1482 (Target.getTriple().isSPIRV() &&
1483 Target.getTriple().getVendor() == llvm::Triple::AMD) ||
1484 (AuxTarget &&
1485 (AuxTarget->getTriple().isAMDGPU() ||
1486 ((AuxTarget->getTriple().isSPIRV() &&
1487 AuxTarget->getTriple().getVendor() == llvm::Triple::AMD))))) {
1488#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
1489 InitBuiltinType(SingletonId, BuiltinType::Id);
1490#include "clang/Basic/AMDGPUTypes.def"
1491 }
1492
1493 // Builtin type for __objc_yes and __objc_no
1494 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1496
1497 ObjCConstantStringType = QualType();
1498
1499 ObjCSuperType = QualType();
1500
1501 // void * type
1502 if (LangOpts.OpenCLGenericAddressSpace) {
1503 auto Q = VoidTy.getQualifiers();
1504 Q.setAddressSpace(LangAS::opencl_generic);
1506 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1507 } else {
1509 }
1510
1511 // nullptr type (C++0x 2.14.7)
1512 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1513
1514 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1515 InitBuiltinType(HalfTy, BuiltinType::Half);
1516
1517 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1518
1519 // Builtin type used to help define __builtin_va_list.
1520 VaListTagDecl = nullptr;
1521
1522 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1523 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1526 }
1527}
1528
1530 return SourceMgr.getDiagnostics();
1531}
1532
1534 AttrVec *&Result = DeclAttrs[D];
1535 if (!Result) {
1536 void *Mem = Allocate(sizeof(AttrVec));
1537 Result = new (Mem) AttrVec;
1538 }
1539
1540 return *Result;
1541}
1542
1543/// Erase the attributes corresponding to the given declaration.
1545 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1546 if (Pos != DeclAttrs.end()) {
1547 Pos->second->~AttrVec();
1548 DeclAttrs.erase(Pos);
1549 }
1550}
1551
1554 return CtorClosureDefaultArgs.lookup(CD);
1555}
1556
1559 assert(!CtorClosureDefaultArgs.contains(CD));
1560 CtorClosureDefaultArgs[CD] = Args;
1561}
1562
1565 auto It =
1566 ExplicitInstantiations.find(cast<NamedDecl>(Spec->getCanonicalDecl()));
1567 if (It != ExplicitInstantiations.end())
1568 return It->second;
1569 return {};
1570}
1571
1574 ExplicitInstantiations[cast<NamedDecl>(Spec->getCanonicalDecl())].push_back(
1575 EID);
1576}
1577
1578// FIXME: Remove ?
1581 assert(Var->isStaticDataMember() && "Not a static data member");
1583 .dyn_cast<MemberSpecializationInfo *>();
1584}
1585
1588 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1589 TemplateOrInstantiation.find(Var);
1590 if (Pos == TemplateOrInstantiation.end())
1591 return {};
1592
1593 return Pos->second;
1594}
1595
1596void
1599 SourceLocation PointOfInstantiation) {
1600 assert(Inst->isStaticDataMember() && "Not a static data member");
1601 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1603 Tmpl, TSK, PointOfInstantiation));
1604}
1605
1606void
1609 assert(!TemplateOrInstantiation[Inst] &&
1610 "Already noted what the variable was instantiated from");
1611 TemplateOrInstantiation[Inst] = TSI;
1612}
1613
1614NamedDecl *
1616 return InstantiatedFromUsingDecl.lookup(UUD);
1617}
1618
1619void
1621 assert((isa<UsingDecl>(Pattern) ||
1624 "pattern decl is not a using decl");
1625 assert((isa<UsingDecl>(Inst) ||
1628 "instantiation did not produce a using decl");
1629 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1630 InstantiatedFromUsingDecl[Inst] = Pattern;
1631}
1632
1635 return InstantiatedFromUsingEnumDecl.lookup(UUD);
1636}
1637
1639 UsingEnumDecl *Pattern) {
1640 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1641 InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1642}
1643
1646 return InstantiatedFromUsingShadowDecl.lookup(Inst);
1647}
1648
1649void
1651 UsingShadowDecl *Pattern) {
1652 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1653 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1654}
1655
1656FieldDecl *
1658 return InstantiatedFromUnnamedFieldDecl.lookup(Field);
1659}
1660
1662 FieldDecl *Tmpl) {
1663 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1664 "Instantiated field decl is not unnamed");
1665 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1666 "Template field decl is not unnamed");
1667 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1668 "Already noted what unnamed field was instantiated from");
1669
1670 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1671}
1672
1677
1682
1683unsigned
1685 auto Range = overridden_methods(Method);
1686 return Range.end() - Range.begin();
1687}
1688
1691 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1692 OverriddenMethods.find(Method->getCanonicalDecl());
1693 if (Pos == OverriddenMethods.end())
1694 return overridden_method_range(nullptr, nullptr);
1695 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1696}
1697
1699 const CXXMethodDecl *Overridden) {
1700 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1701 OverriddenMethods[Method].push_back(Overridden);
1702}
1703
1705 const NamedDecl *D,
1706 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1707 assert(D);
1708
1709 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1710 Overridden.append(overridden_methods_begin(CXXMethod),
1711 overridden_methods_end(CXXMethod));
1712 return;
1713 }
1714
1715 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1716 if (!Method)
1717 return;
1718
1720 Method->getOverriddenMethods(OverDecls);
1721 Overridden.append(OverDecls.begin(), OverDecls.end());
1722}
1723
1724std::optional<ASTContext::CXXRecordDeclRelocationInfo>
1726 assert(RD);
1727 CXXRecordDecl *D = RD->getDefinition();
1728 auto it = RelocatableClasses.find(D);
1729 if (it != RelocatableClasses.end())
1730 return it->getSecond();
1731 return std::nullopt;
1732}
1733
1736 assert(RD);
1737 CXXRecordDecl *D = RD->getDefinition();
1738 assert(RelocatableClasses.find(D) == RelocatableClasses.end());
1739 RelocatableClasses.insert({D, Info});
1740}
1741
1743 const ASTContext &Context, const CXXRecordDecl *Class) {
1744 if (!Class->isPolymorphic())
1745 return false;
1746 const CXXRecordDecl *BaseType = Context.baseForVTableAuthentication(Class);
1747 using AuthAttr = VTablePointerAuthenticationAttr;
1748 const AuthAttr *ExplicitAuth = BaseType->getAttr<AuthAttr>();
1749 if (!ExplicitAuth)
1750 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1751 AuthAttr::AddressDiscriminationMode AddressDiscrimination =
1752 ExplicitAuth->getAddressDiscrimination();
1753 if (AddressDiscrimination == AuthAttr::DefaultAddressDiscrimination)
1754 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1755 return AddressDiscrimination == AuthAttr::AddressDiscrimination;
1756}
1757
1758ASTContext::PointerAuthContent
1759ASTContext::findPointerAuthContent(QualType T) const {
1760 assert(isPointerAuthenticationAvailable());
1761
1762 T = T.getCanonicalType();
1763 if (T->isDependentType())
1764 return PointerAuthContent::None;
1765
1767 return PointerAuthContent::AddressDiscriminatedData;
1768 const RecordDecl *RD = T->getAsRecordDecl();
1769 if (!RD)
1770 return PointerAuthContent::None;
1771
1772 if (RD->isInvalidDecl())
1773 return PointerAuthContent::None;
1774
1775 if (auto Existing = RecordContainsAddressDiscriminatedPointerAuth.find(RD);
1776 Existing != RecordContainsAddressDiscriminatedPointerAuth.end())
1777 return Existing->second;
1778
1779 PointerAuthContent Result = PointerAuthContent::None;
1780
1781 auto SaveResultAndReturn = [&]() -> PointerAuthContent {
1782 auto [ResultIter, DidAdd] =
1783 RecordContainsAddressDiscriminatedPointerAuth.try_emplace(RD, Result);
1784 (void)ResultIter;
1785 (void)DidAdd;
1786 assert(DidAdd);
1787 return Result;
1788 };
1789 auto ShouldContinueAfterUpdate = [&](PointerAuthContent NewResult) {
1790 static_assert(PointerAuthContent::None <
1791 PointerAuthContent::AddressDiscriminatedVTable);
1792 static_assert(PointerAuthContent::AddressDiscriminatedVTable <
1793 PointerAuthContent::AddressDiscriminatedData);
1794 if (NewResult > Result)
1795 Result = NewResult;
1796 return Result != PointerAuthContent::AddressDiscriminatedData;
1797 };
1798 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1800 !ShouldContinueAfterUpdate(
1801 PointerAuthContent::AddressDiscriminatedVTable))
1802 return SaveResultAndReturn();
1803 for (auto Base : CXXRD->bases()) {
1804 if (!ShouldContinueAfterUpdate(findPointerAuthContent(Base.getType())))
1805 return SaveResultAndReturn();
1806 }
1807 }
1808 for (auto *FieldDecl : RD->fields()) {
1809 if (!ShouldContinueAfterUpdate(
1810 findPointerAuthContent(FieldDecl->getType())))
1811 return SaveResultAndReturn();
1812 }
1813 return SaveResultAndReturn();
1814}
1815
1817 assert(!Import->getNextLocalImport() &&
1818 "Import declaration already in the chain");
1819 assert(!Import->isFromASTFile() && "Non-local import declaration");
1820 if (!FirstLocalImport) {
1821 FirstLocalImport = Import;
1822 LastLocalImport = Import;
1823 return;
1824 }
1825
1826 LastLocalImport->setNextLocalImport(Import);
1827 LastLocalImport = Import;
1828}
1829
1830//===----------------------------------------------------------------------===//
1831// Type Sizing and Analysis
1832//===----------------------------------------------------------------------===//
1833
1834/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1835/// scalar floating point type.
1836const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1837 switch (T->castAs<BuiltinType>()->getKind()) {
1838 default:
1839 llvm_unreachable("Not a floating point type!");
1840 case BuiltinType::BFloat16:
1841 return Target->getBFloat16Format();
1842 case BuiltinType::Float16:
1843 return Target->getHalfFormat();
1844 case BuiltinType::Half:
1845 return Target->getHalfFormat();
1846 case BuiltinType::Float: return Target->getFloatFormat();
1847 case BuiltinType::Double: return Target->getDoubleFormat();
1848 case BuiltinType::Ibm128:
1849 return Target->getIbm128Format();
1850 case BuiltinType::LongDouble:
1851 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1852 return AuxTarget->getLongDoubleFormat();
1853 return Target->getLongDoubleFormat();
1854 case BuiltinType::Float128:
1855 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1856 return AuxTarget->getFloat128Format();
1857 return Target->getFloat128Format();
1858 }
1859}
1860
1861CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1862 unsigned Align = Target->getCharWidth();
1863
1864 const unsigned AlignFromAttr = D->getMaxAlignment();
1865 if (AlignFromAttr)
1866 Align = AlignFromAttr;
1867
1868 // __attribute__((aligned)) can increase or decrease alignment
1869 // *except* on a struct or struct member, where it only increases
1870 // alignment unless 'packed' is also specified.
1871 //
1872 // It is an error for alignas to decrease alignment, so we can
1873 // ignore that possibility; Sema should diagnose it.
1874 bool UseAlignAttrOnly;
1875 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D))
1876 UseAlignAttrOnly =
1877 FD->hasAttr<PackedAttr>() || FD->getParent()->hasAttr<PackedAttr>();
1878 else
1879 UseAlignAttrOnly = AlignFromAttr != 0;
1880 // If we're using the align attribute only, just ignore everything
1881 // else about the declaration and its type.
1882 if (UseAlignAttrOnly) {
1883 // do nothing
1884 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1885 QualType T = VD->getType();
1886 if (const auto *RT = T->getAs<ReferenceType>()) {
1887 if (ForAlignof)
1888 T = RT->getPointeeType();
1889 else
1890 T = getPointerType(RT->getPointeeType());
1891 }
1892 QualType BaseT = getBaseElementType(T);
1893 if (T->isFunctionType())
1894 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1895 else if (!BaseT->isIncompleteType()) {
1896 // Adjust alignments of declarations with array type by the
1897 // large-array alignment on the target.
1898 if (const ArrayType *arrayType = getAsArrayType(T)) {
1899 unsigned MinWidth = Target->getLargeArrayMinWidth();
1900 if (!ForAlignof && MinWidth) {
1902 Align = std::max(Align, Target->getLargeArrayAlign());
1905 Align = std::max(Align, Target->getLargeArrayAlign());
1906 }
1907 }
1908 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1909 if (BaseT.getQualifiers().hasUnaligned())
1910 Align = Target->getCharWidth();
1911 }
1912
1913 // Ensure minimum alignment for global variables.
1914 if (const auto *VD = dyn_cast<VarDecl>(D))
1915 if (VD->hasGlobalStorage() && !ForAlignof) {
1916 uint64_t TypeSize =
1917 !BaseT->isIncompleteType() ? getTypeSize(T.getTypePtr()) : 0;
1918 Align = std::max(Align, getMinGlobalAlignOfVar(TypeSize, VD));
1919 }
1920
1921 // Fields can be subject to extra alignment constraints, like if
1922 // the field is packed, the struct is packed, or the struct has a
1923 // a max-field-alignment constraint (#pragma pack). So calculate
1924 // the actual alignment of the field within the struct, and then
1925 // (as we're expected to) constrain that by the alignment of the type.
1926 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1927 const RecordDecl *Parent = Field->getParent();
1928 // We can only produce a sensible answer if the record is valid.
1929 if (!Parent->isInvalidDecl()) {
1930 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1931
1932 // Start with the record's overall alignment.
1933 unsigned FieldAlign = toBits(Layout.getAlignment());
1934
1935 // Use the GCD of that and the offset within the record.
1936 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1937 if (Offset > 0) {
1938 // Alignment is always a power of 2, so the GCD will be a power of 2,
1939 // which means we get to do this crazy thing instead of Euclid's.
1940 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1941 if (LowBitOfOffset < FieldAlign)
1942 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1943 }
1944
1945 Align = std::min(Align, FieldAlign);
1946 }
1947 }
1948 }
1949
1950 // Some targets have hard limitation on the maximum requestable alignment in
1951 // aligned attribute for static variables.
1952 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1953 const auto *VD = dyn_cast<VarDecl>(D);
1954 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1955 Align = std::min(Align, MaxAlignedAttr);
1956
1957 return toCharUnitsFromBits(Align);
1958}
1959
1961 return toCharUnitsFromBits(Target->getExnObjectAlignment());
1962}
1963
1964// getTypeInfoDataSizeInChars - Return the size of a type, in
1965// chars. If the type is a record, its data size is returned. This is
1966// the size of the memcpy that's performed when assigning this type
1967// using a trivial copy/move assignment operator.
1970
1971 // In C++, objects can sometimes be allocated into the tail padding
1972 // of a base-class subobject. We decide whether that's possible
1973 // during class layout, so here we can just trust the layout results.
1974 if (getLangOpts().CPlusPlus) {
1975 if (const auto *RD = T->getAsCXXRecordDecl(); RD && !RD->isInvalidDecl()) {
1976 const ASTRecordLayout &layout = getASTRecordLayout(RD);
1977 Info.Width = layout.getDataSize();
1978 }
1979 }
1980
1981 return Info;
1982}
1983
1984/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1985/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1988 const ConstantArrayType *CAT) {
1989 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1990 uint64_t Size = CAT->getZExtSize();
1991 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1992 (uint64_t)(-1)/Size) &&
1993 "Overflow in array type char size evaluation");
1994 uint64_t Width = EltInfo.Width.getQuantity() * Size;
1995 unsigned Align = EltInfo.Align.getQuantity();
1996 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1997 Context.getTargetInfo().getPointerWidth(LangAS::Default) == 64)
1998 Width = llvm::alignTo(Width, Align);
2001 EltInfo.AlignRequirement);
2002}
2003
2005 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
2006 return getConstantArrayInfoInChars(*this, CAT);
2007 TypeInfo Info = getTypeInfo(T);
2010}
2011
2013 return getTypeInfoInChars(T.getTypePtr());
2014}
2015
2017 // HLSL doesn't promote all small integer types to int, it
2018 // just uses the rank-based promotion rules for all types.
2019 if (getLangOpts().HLSL)
2020 return false;
2021
2022 if (const auto *BT = T->getAs<BuiltinType>())
2023 switch (BT->getKind()) {
2024 case BuiltinType::Bool:
2025 case BuiltinType::Char_S:
2026 case BuiltinType::Char_U:
2027 case BuiltinType::SChar:
2028 case BuiltinType::UChar:
2029 case BuiltinType::Short:
2030 case BuiltinType::UShort:
2031 case BuiltinType::WChar_S:
2032 case BuiltinType::WChar_U:
2033 case BuiltinType::Char8:
2034 case BuiltinType::Char16:
2035 case BuiltinType::Char32:
2036 return true;
2037 default:
2038 return false;
2039 }
2040
2041 // Enumerated types are promotable to their compatible integer types
2042 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
2043 if (const auto *ED = T->getAsEnumDecl()) {
2044 if (T->isDependentType() || ED->getPromotionType().isNull() ||
2045 ED->isScoped())
2046 return false;
2047
2048 return true;
2049 }
2050
2051 // OverflowBehaviorTypes are promotable if their underlying type is promotable
2052 if (const auto *OBT = T->getAs<OverflowBehaviorType>()) {
2053 return isPromotableIntegerType(OBT->getUnderlyingType());
2054 }
2055
2056 return false;
2057}
2058
2062
2064 return isAlignmentRequired(T.getTypePtr());
2065}
2066
2068 bool NeedsPreferredAlignment) const {
2069 // An alignment on a typedef overrides anything else.
2070 if (const auto *TT = T->getAs<TypedefType>())
2071 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2072 return Align;
2073
2074 // If we have an (array of) complete type, we're done.
2075 T = getBaseElementType(T);
2076 if (!T->isIncompleteType())
2077 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
2078
2079 // If we had an array type, its element type might be a typedef
2080 // type with an alignment attribute.
2081 if (const auto *TT = T->getAs<TypedefType>())
2082 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2083 return Align;
2084
2085 // Otherwise, see if the declaration of the type had an attribute.
2086 if (const auto *TD = T->getAsTagDecl())
2087 return TD->getMaxAlignment();
2088
2089 return 0;
2090}
2091
2093 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
2094 if (I != MemoizedTypeInfo.end())
2095 return I->second;
2096
2097 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
2098 TypeInfo TI = getTypeInfoImpl(T);
2099 MemoizedTypeInfo[T] = TI;
2100 return TI;
2101}
2102
2103/// getTypeInfoImpl - Return the size of the specified type, in bits. This
2104/// method does not work on incomplete types.
2105///
2106/// FIXME: Pointers into different addr spaces could have different sizes and
2107/// alignment requirements: getPointerInfo should take an AddrSpace, this
2108/// should take a QualType, &c.
2109TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
2110 uint64_t Width = 0;
2111 unsigned Align = 8;
2114 switch (T->getTypeClass()) {
2115#define TYPE(Class, Base)
2116#define ABSTRACT_TYPE(Class, Base)
2117#define NON_CANONICAL_TYPE(Class, Base)
2118#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2119#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
2120 case Type::Class: \
2121 assert(!T->isDependentType() && "should not see dependent types here"); \
2122 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
2123#include "clang/AST/TypeNodes.inc"
2124 llvm_unreachable("Should not see dependent types");
2125
2126 case Type::FunctionNoProto:
2127 case Type::FunctionProto:
2128 // GCC extension: alignof(function) = 32 bits
2129 Width = 0;
2130 Align = 32;
2131 break;
2132
2133 case Type::IncompleteArray:
2134 case Type::VariableArray:
2135 case Type::ConstantArray:
2136 case Type::ArrayParameter: {
2137 // Model non-constant sized arrays as size zero, but track the alignment.
2138 uint64_t Size = 0;
2139 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
2140 Size = CAT->getZExtSize();
2141
2142 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
2143 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
2144 "Overflow in array type bit size evaluation");
2145 Width = EltInfo.Width * Size;
2146 Align = EltInfo.Align;
2147 AlignRequirement = EltInfo.AlignRequirement;
2148 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
2149 getTargetInfo().getPointerWidth(LangAS::Default) == 64)
2150 Width = llvm::alignTo(Width, Align);
2151 break;
2152 }
2153
2154 case Type::ExtVector:
2155 case Type::Vector: {
2156 const auto *VT = cast<VectorType>(T);
2157 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
2158 Width = VT->isPackedVectorBoolType(*this)
2159 ? VT->getNumElements()
2160 : EltInfo.Width * VT->getNumElements();
2161 // Enforce at least byte size and alignment.
2162 Width = std::max<unsigned>(8, Width);
2163 Align = std::max<unsigned>(
2164 8, Target->vectorsAreElementAligned() ? EltInfo.Width : Width);
2165
2166 // If the alignment is not a power of 2, round up to the next power of 2.
2167 // This happens for non-power-of-2 length vectors.
2168 if (Align & (Align-1)) {
2169 Align = llvm::bit_ceil(Align);
2170 Width = llvm::alignTo(Width, Align);
2171 }
2172 // Adjust the alignment based on the target max.
2173 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
2174 if (TargetVectorAlign && TargetVectorAlign < Align)
2175 Align = TargetVectorAlign;
2176 if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
2177 // Adjust the alignment for fixed-length SVE vectors. This is important
2178 // for non-power-of-2 vector lengths.
2179 Align = 128;
2180 else if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
2181 // Adjust the alignment for fixed-length SVE predicates.
2182 Align = 16;
2183 else if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
2184 VT->getVectorKind() == VectorKind::RVVFixedLengthMask ||
2185 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
2186 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
2187 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4)
2188 // Adjust the alignment for fixed-length RVV vectors.
2189 Align = std::min<unsigned>(64, Width);
2190 break;
2191 }
2192
2193 case Type::ConstantMatrix: {
2194 const auto *MT = cast<ConstantMatrixType>(T);
2195 TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
2196 // The internal layout of a matrix value is implementation defined.
2197 // Initially be ABI compatible with arrays with respect to alignment and
2198 // size.
2199 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
2200 Align = ElementInfo.Align;
2201 break;
2202 }
2203
2204 case Type::Builtin:
2205 switch (cast<BuiltinType>(T)->getKind()) {
2206 default: llvm_unreachable("Unknown builtin type!");
2207 case BuiltinType::Void:
2208 // GCC extension: alignof(void) = 8 bits.
2209 Width = 0;
2210 Align = 8;
2211 break;
2212 case BuiltinType::Bool:
2213 Width = Target->getBoolWidth();
2214 Align = Target->getBoolAlign();
2215 break;
2216 case BuiltinType::Char_S:
2217 case BuiltinType::Char_U:
2218 case BuiltinType::UChar:
2219 case BuiltinType::SChar:
2220 case BuiltinType::Char8:
2221 Width = Target->getCharWidth();
2222 Align = Target->getCharAlign();
2223 break;
2224 case BuiltinType::WChar_S:
2225 case BuiltinType::WChar_U:
2226 Width = Target->getWCharWidth();
2227 Align = Target->getWCharAlign();
2228 break;
2229 case BuiltinType::Char16:
2230 Width = Target->getChar16Width();
2231 Align = Target->getChar16Align();
2232 break;
2233 case BuiltinType::Char32:
2234 Width = Target->getChar32Width();
2235 Align = Target->getChar32Align();
2236 break;
2237 case BuiltinType::UShort:
2238 case BuiltinType::Short:
2239 Width = Target->getShortWidth();
2240 Align = Target->getShortAlign();
2241 break;
2242 case BuiltinType::UInt:
2243 case BuiltinType::Int:
2244 Width = Target->getIntWidth();
2245 Align = Target->getIntAlign();
2246 break;
2247 case BuiltinType::ULong:
2248 case BuiltinType::Long:
2249 Width = Target->getLongWidth();
2250 Align = Target->getLongAlign();
2251 break;
2252 case BuiltinType::ULongLong:
2253 case BuiltinType::LongLong:
2254 Width = Target->getLongLongWidth();
2255 Align = Target->getLongLongAlign();
2256 break;
2257 case BuiltinType::Int128:
2258 case BuiltinType::UInt128:
2259 Width = 128;
2260 Align = Target->getInt128Align();
2261 break;
2262 case BuiltinType::ShortAccum:
2263 case BuiltinType::UShortAccum:
2264 case BuiltinType::SatShortAccum:
2265 case BuiltinType::SatUShortAccum:
2266 Width = Target->getShortAccumWidth();
2267 Align = Target->getShortAccumAlign();
2268 break;
2269 case BuiltinType::Accum:
2270 case BuiltinType::UAccum:
2271 case BuiltinType::SatAccum:
2272 case BuiltinType::SatUAccum:
2273 Width = Target->getAccumWidth();
2274 Align = Target->getAccumAlign();
2275 break;
2276 case BuiltinType::LongAccum:
2277 case BuiltinType::ULongAccum:
2278 case BuiltinType::SatLongAccum:
2279 case BuiltinType::SatULongAccum:
2280 Width = Target->getLongAccumWidth();
2281 Align = Target->getLongAccumAlign();
2282 break;
2283 case BuiltinType::ShortFract:
2284 case BuiltinType::UShortFract:
2285 case BuiltinType::SatShortFract:
2286 case BuiltinType::SatUShortFract:
2287 Width = Target->getShortFractWidth();
2288 Align = Target->getShortFractAlign();
2289 break;
2290 case BuiltinType::Fract:
2291 case BuiltinType::UFract:
2292 case BuiltinType::SatFract:
2293 case BuiltinType::SatUFract:
2294 Width = Target->getFractWidth();
2295 Align = Target->getFractAlign();
2296 break;
2297 case BuiltinType::LongFract:
2298 case BuiltinType::ULongFract:
2299 case BuiltinType::SatLongFract:
2300 case BuiltinType::SatULongFract:
2301 Width = Target->getLongFractWidth();
2302 Align = Target->getLongFractAlign();
2303 break;
2304 case BuiltinType::BFloat16:
2305 if (Target->hasBFloat16Type()) {
2306 Width = Target->getBFloat16Width();
2307 Align = Target->getBFloat16Align();
2308 } else if ((getLangOpts().SYCLIsDevice ||
2309 (getLangOpts().OpenMP &&
2310 getLangOpts().OpenMPIsTargetDevice)) &&
2311 AuxTarget->hasBFloat16Type()) {
2312 Width = AuxTarget->getBFloat16Width();
2313 Align = AuxTarget->getBFloat16Align();
2314 }
2315 break;
2316 case BuiltinType::Float16:
2317 case BuiltinType::Half:
2318 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2319 !getLangOpts().OpenMPIsTargetDevice) {
2320 Width = Target->getHalfWidth();
2321 Align = Target->getHalfAlign();
2322 } else {
2323 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2324 "Expected OpenMP device compilation.");
2325 Width = AuxTarget->getHalfWidth();
2326 Align = AuxTarget->getHalfAlign();
2327 }
2328 break;
2329 case BuiltinType::Float:
2330 Width = Target->getFloatWidth();
2331 Align = Target->getFloatAlign();
2332 break;
2333 case BuiltinType::Double:
2334 Width = Target->getDoubleWidth();
2335 Align = Target->getDoubleAlign();
2336 break;
2337 case BuiltinType::Ibm128:
2338 Width = Target->getIbm128Width();
2339 Align = Target->getIbm128Align();
2340 break;
2341 case BuiltinType::LongDouble:
2342 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2343 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2344 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2345 Width = AuxTarget->getLongDoubleWidth();
2346 Align = AuxTarget->getLongDoubleAlign();
2347 } else {
2348 Width = Target->getLongDoubleWidth();
2349 Align = Target->getLongDoubleAlign();
2350 }
2351 break;
2352 case BuiltinType::Float128:
2353 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2354 !getLangOpts().OpenMPIsTargetDevice) {
2355 Width = Target->getFloat128Width();
2356 Align = Target->getFloat128Align();
2357 } else {
2358 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2359 "Expected OpenMP device compilation.");
2360 Width = AuxTarget->getFloat128Width();
2361 Align = AuxTarget->getFloat128Align();
2362 }
2363 break;
2364 case BuiltinType::NullPtr:
2365 // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
2366 Width = Target->getPointerWidth(LangAS::Default);
2367 Align = Target->getPointerAlign(LangAS::Default);
2368 break;
2369 case BuiltinType::ObjCId:
2370 case BuiltinType::ObjCClass:
2371 case BuiltinType::ObjCSel:
2372 Width = Target->getPointerWidth(LangAS::Default);
2373 Align = Target->getPointerAlign(LangAS::Default);
2374 break;
2375 case BuiltinType::OCLSampler:
2376 case BuiltinType::OCLEvent:
2377 case BuiltinType::OCLClkEvent:
2378 case BuiltinType::OCLQueue:
2379 case BuiltinType::OCLReserveID:
2380#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2381 case BuiltinType::Id:
2382#include "clang/Basic/OpenCLImageTypes.def"
2383#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2384 case BuiltinType::Id:
2385#include "clang/Basic/OpenCLExtensionTypes.def"
2386 AS = Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
2387 Width = Target->getPointerWidth(AS);
2388 Align = Target->getPointerAlign(AS);
2389 break;
2390 // The SVE types are effectively target-specific. The length of an
2391 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2392 // of 128 bits. There is one predicate bit for each vector byte, so the
2393 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2394 //
2395 // Because the length is only known at runtime, we use a dummy value
2396 // of 0 for the static length. The alignment values are those defined
2397 // by the Procedure Call Standard for the Arm Architecture.
2398#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
2399 case BuiltinType::Id: \
2400 Width = 0; \
2401 Align = 128; \
2402 break;
2403#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
2404 case BuiltinType::Id: \
2405 Width = 0; \
2406 Align = 16; \
2407 break;
2408#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
2409 case BuiltinType::Id: \
2410 Width = 0; \
2411 Align = 16; \
2412 break;
2413#define SVE_SCALAR_TYPE(Name, MangledName, Id, SingletonId, Bits) \
2414 case BuiltinType::Id: \
2415 Width = Bits; \
2416 Align = Bits; \
2417 break;
2418#include "clang/Basic/AArch64ACLETypes.def"
2419#define PPC_VECTOR_TYPE(Name, Id, Size) \
2420 case BuiltinType::Id: \
2421 Width = Size; \
2422 Align = Size; \
2423 break;
2424#include "clang/Basic/PPCTypes.def"
2425#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
2426 IsFP, IsBF) \
2427 case BuiltinType::Id: \
2428 Width = 0; \
2429 Align = ElBits; \
2430 break;
2431#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2432 case BuiltinType::Id: \
2433 Width = 0; \
2434 Align = 8; \
2435 break;
2436#include "clang/Basic/RISCVVTypes.def"
2437#define WASM_TYPE(Name, Id, SingletonId) \
2438 case BuiltinType::Id: \
2439 Width = 0; \
2440 Align = 8; \
2441 break;
2442#include "clang/Basic/WebAssemblyReferenceTypes.def"
2443#define AMDGPU_TYPE(NAME, ID, SINGLETONID, WIDTH, ALIGN) \
2444 case BuiltinType::ID: \
2445 Width = WIDTH; \
2446 Align = ALIGN; \
2447 break;
2448#include "clang/Basic/AMDGPUTypes.def"
2449#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2450#include "clang/Basic/HLSLIntangibleTypes.def"
2451 Width = Target->getPointerWidth(LangAS::Default);
2452 Align = Target->getPointerAlign(LangAS::Default);
2453 break;
2454 }
2455 break;
2456 case Type::ObjCObjectPointer:
2457 Width = Target->getPointerWidth(LangAS::Default);
2458 Align = Target->getPointerAlign(LangAS::Default);
2459 break;
2460 case Type::BlockPointer:
2461 AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
2462 Width = Target->getPointerWidth(AS);
2463 Align = Target->getPointerAlign(AS);
2464 break;
2465 case Type::LValueReference:
2466 case Type::RValueReference:
2467 // alignof and sizeof should never enter this code path here, so we go
2468 // the pointer route.
2469 AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
2470 Width = Target->getPointerWidth(AS);
2471 Align = Target->getPointerAlign(AS);
2472 break;
2473 case Type::Pointer:
2474 AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
2475 Width = Target->getPointerWidth(AS);
2476 Align = Target->getPointerAlign(AS);
2477 break;
2478 case Type::MemberPointer: {
2479 const auto *MPT = cast<MemberPointerType>(T);
2480 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2481 Width = MPI.Width;
2482 Align = MPI.Align;
2483 break;
2484 }
2485 case Type::Complex: {
2486 // Complex types have the same alignment as their elements, but twice the
2487 // size.
2488 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2489 Width = EltInfo.Width * 2;
2490 Align = EltInfo.Align;
2491 break;
2492 }
2493 case Type::ObjCObject:
2494 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2495 case Type::Adjusted:
2496 case Type::Decayed:
2497 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2498 case Type::ObjCInterface: {
2499 const auto *ObjCI = cast<ObjCInterfaceType>(T);
2500 if (ObjCI->getDecl()->isInvalidDecl()) {
2501 Width = 8;
2502 Align = 8;
2503 break;
2504 }
2505 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2506 Width = toBits(Layout.getSize());
2507 Align = toBits(Layout.getAlignment());
2508 break;
2509 }
2510 case Type::BitInt: {
2511 const auto *EIT = cast<BitIntType>(T);
2512 Align = Target->getBitIntAlign(EIT->getNumBits());
2513 Width = Target->getBitIntWidth(EIT->getNumBits());
2514 break;
2515 }
2516 case Type::Record:
2517 case Type::Enum: {
2518 const auto *TT = cast<TagType>(T);
2519 const TagDecl *TD = TT->getDecl()->getDefinitionOrSelf();
2520
2521 if (TD->isInvalidDecl()) {
2522 Width = 8;
2523 Align = 8;
2524 break;
2525 }
2526
2527 if (isa<EnumType>(TT)) {
2528 const EnumDecl *ED = cast<EnumDecl>(TD);
2529 TypeInfo Info =
2531 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2532 Info.Align = AttrAlign;
2534 }
2535 return Info;
2536 }
2537
2538 const auto *RD = cast<RecordDecl>(TD);
2539 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2540 Width = toBits(Layout.getSize());
2541 Align = toBits(Layout.getAlignment());
2542 AlignRequirement = RD->hasAttr<AlignedAttr>()
2544 : AlignRequirementKind::None;
2545 break;
2546 }
2547
2548 case Type::SubstTemplateTypeParm:
2550 getReplacementType().getTypePtr());
2551
2552 case Type::Auto:
2553 case Type::DeducedTemplateSpecialization: {
2554 const auto *A = cast<DeducedType>(T);
2555 assert(!A->getDeducedType().isNull() &&
2556 "cannot request the size of an undeduced or dependent auto type");
2557 return getTypeInfo(A->getDeducedType().getTypePtr());
2558 }
2559
2560 case Type::Paren:
2561 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2562
2563 case Type::MacroQualified:
2564 return getTypeInfo(
2565 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2566
2567 case Type::ObjCTypeParam:
2568 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2569
2570 case Type::Using:
2571 return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr());
2572
2573 case Type::Typedef: {
2574 const auto *TT = cast<TypedefType>(T);
2575 TypeInfo Info = getTypeInfo(TT->desugar().getTypePtr());
2576 // If the typedef has an aligned attribute on it, it overrides any computed
2577 // alignment we have. This violates the GCC documentation (which says that
2578 // attribute(aligned) can only round up) but matches its implementation.
2579 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2580 Align = AttrAlign;
2581 AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2582 } else {
2583 Align = Info.Align;
2584 AlignRequirement = Info.AlignRequirement;
2585 }
2586 Width = Info.Width;
2587 break;
2588 }
2589
2590 case Type::Attributed:
2591 return getTypeInfo(
2592 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2593
2594 case Type::CountAttributed:
2595 return getTypeInfo(cast<CountAttributedType>(T)->desugar().getTypePtr());
2596
2597 case Type::BTFTagAttributed:
2598 return getTypeInfo(
2599 cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr());
2600
2601 case Type::OverflowBehavior:
2602 return getTypeInfo(
2604
2605 case Type::HLSLAttributedResource:
2606 return getTypeInfo(
2607 cast<HLSLAttributedResourceType>(T)->getWrappedType().getTypePtr());
2608
2609 case Type::HLSLInlineSpirv: {
2610 const auto *ST = cast<HLSLInlineSpirvType>(T);
2611 // Size is specified in bytes, convert to bits
2612 Width = ST->getSize() * 8;
2613 Align = ST->getAlignment();
2614 if (Width == 0 && Align == 0) {
2615 // We are defaulting to laying out opaque SPIR-V types as 32-bit ints.
2616 Width = 32;
2617 Align = 32;
2618 }
2619 break;
2620 }
2621
2622 case Type::Atomic: {
2623 // Start with the base type information.
2624 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2625 Width = Info.Width;
2626 Align = Info.Align;
2627
2628 if (!Width) {
2629 // An otherwise zero-sized type should still generate an
2630 // atomic operation.
2631 Width = Target->getCharWidth();
2632 assert(Align);
2633 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2634 // If the size of the type doesn't exceed the platform's max
2635 // atomic promotion width, make the size and alignment more
2636 // favorable to atomic operations:
2637
2638 // Round the size up to a power of 2.
2639 Width = llvm::bit_ceil(Width);
2640
2641 // Set the alignment equal to the size.
2642 Align = static_cast<unsigned>(Width);
2643 }
2644 }
2645 break;
2646
2647 case Type::PredefinedSugar:
2648 return getTypeInfo(cast<PredefinedSugarType>(T)->desugar().getTypePtr());
2649
2650 case Type::Pipe:
2651 Width = Target->getPointerWidth(LangAS::opencl_global);
2652 Align = Target->getPointerAlign(LangAS::opencl_global);
2653 break;
2654 }
2655
2656 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2657 return TypeInfo(Width, Align, AlignRequirement);
2658}
2659
2661 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2662 if (I != MemoizedUnadjustedAlign.end())
2663 return I->second;
2664
2665 unsigned UnadjustedAlign;
2666 if (const auto *RT = T->getAsCanonical<RecordType>()) {
2667 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
2668 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2669 } else if (const auto *ObjCI = T->getAsCanonical<ObjCInterfaceType>()) {
2670 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2671 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2672 } else {
2673 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2674 }
2675
2676 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2677 return UnadjustedAlign;
2678}
2679
2681 unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign(
2682 getTargetInfo().getTriple(), Target->getTargetOpts().FeatureMap);
2683 return SimdAlign;
2684}
2685
2686/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2688 return CharUnits::fromQuantity(BitSize / getCharWidth());
2689}
2690
2691/// toBits - Convert a size in characters to a size in characters.
2692int64_t ASTContext::toBits(CharUnits CharSize) const {
2693 return CharSize.getQuantity() * getCharWidth();
2694}
2695
2696/// getTypeSizeInChars - Return the size of the specified type, in characters.
2697/// This method does not work on incomplete types.
2704
2705/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2706/// characters. This method does not work on incomplete types.
2713
2714/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2715/// type, in characters, before alignment adjustments. This method does
2716/// not work on incomplete types.
2723
2724/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2725/// type for the current target in bits. This can be different than the ABI
2726/// alignment in cases where it is beneficial for performance or backwards
2727/// compatibility preserving to overalign a data type. (Note: despite the name,
2728/// the preferred alignment is ABI-impacting, and not an optimization.)
2729unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
2730 TypeInfo TI = getTypeInfo(T);
2731 unsigned ABIAlign = TI.Align;
2732
2733 T = T->getBaseElementTypeUnsafe();
2734
2735 // The preferred alignment of member pointers is that of a pointer.
2736 if (T->isMemberPointerType())
2737 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2738
2739 if (!Target->allowsLargerPreferedTypeAlignment())
2740 return ABIAlign;
2741
2742 if (const auto *RD = T->getAsRecordDecl()) {
2743 // When used as part of a typedef, or together with a 'packed' attribute,
2744 // the 'aligned' attribute can be used to decrease alignment. Note that the
2745 // 'packed' case is already taken into consideration when computing the
2746 // alignment, we only need to handle the typedef case here.
2748 RD->isInvalidDecl())
2749 return ABIAlign;
2750
2751 unsigned PreferredAlign = static_cast<unsigned>(
2752 toBits(getASTRecordLayout(RD).PreferredAlignment));
2753 assert(PreferredAlign >= ABIAlign &&
2754 "PreferredAlign should be at least as large as ABIAlign.");
2755 return PreferredAlign;
2756 }
2757
2758 // Double (and, for targets supporting AIX `power` alignment, long double) and
2759 // long long should be naturally aligned (despite requiring less alignment) if
2760 // possible.
2761 if (const auto *CT = T->getAs<ComplexType>())
2762 T = CT->getElementType().getTypePtr();
2763 if (const auto *ED = T->getAsEnumDecl())
2764 T = ED->getIntegerType().getTypePtr();
2765 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2766 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2767 T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2768 (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2769 Target->defaultsToAIXPowerAlignment()))
2770 // Don't increase the alignment if an alignment attribute was specified on a
2771 // typedef declaration.
2772 if (!TI.isAlignRequired())
2773 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2774
2775 return ABIAlign;
2776}
2777
2778/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2779/// for __attribute__((aligned)) on this target, to be used if no alignment
2780/// value is specified.
2784
2785/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2786/// to a global variable of the specified type.
2788 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2789 return std::max(getPreferredTypeAlign(T),
2790 getMinGlobalAlignOfVar(TypeSize, VD));
2791}
2792
2793/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2794/// should be given to a global variable of the specified type.
2799
2801 const VarDecl *VD) const {
2802 // Make the default handling as that of a non-weak definition in the
2803 // current translation unit.
2804 bool HasNonWeakDef = !VD || (VD->hasDefinition() && !VD->isWeak());
2805 return getTargetInfo().getMinGlobalAlign(Size, HasNonWeakDef);
2806}
2807
2809 CharUnits Offset = CharUnits::Zero();
2810 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2811 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2812 Offset += Layout->getBaseClassOffset(Base);
2813 Layout = &getASTRecordLayout(Base);
2814 }
2815 return Offset;
2816}
2817
2819 const ValueDecl *MPD = MP.getMemberPointerDecl();
2822 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2824 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2825 const CXXRecordDecl *Base = RD;
2826 const CXXRecordDecl *Derived = Path[I];
2827 if (DerivedMember)
2828 std::swap(Base, Derived);
2830 RD = Path[I];
2831 }
2832 if (DerivedMember)
2834 return ThisAdjustment;
2835}
2836
2837/// DeepCollectObjCIvars -
2838/// This routine first collects all declared, but not synthesized, ivars in
2839/// super class and then collects all ivars, including those synthesized for
2840/// current class. This routine is used for implementation of current class
2841/// when all ivars, declared and synthesized are known.
2843 bool leafClass,
2845 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2846 DeepCollectObjCIvars(SuperClass, false, Ivars);
2847 if (!leafClass) {
2848 llvm::append_range(Ivars, OI->ivars());
2849 } else {
2850 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2851 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2852 Iv= Iv->getNextIvar())
2853 Ivars.push_back(Iv);
2854 }
2855}
2856
2857/// CollectInheritedProtocols - Collect all protocols in current class and
2858/// those inherited by it.
2861 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2862 // We can use protocol_iterator here instead of
2863 // all_referenced_protocol_iterator since we are walking all categories.
2864 for (auto *Proto : OI->all_referenced_protocols()) {
2865 CollectInheritedProtocols(Proto, Protocols);
2866 }
2867
2868 // Categories of this Interface.
2869 for (const auto *Cat : OI->visible_categories())
2870 CollectInheritedProtocols(Cat, Protocols);
2871
2872 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2873 while (SD) {
2874 CollectInheritedProtocols(SD, Protocols);
2875 SD = SD->getSuperClass();
2876 }
2877 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2878 for (auto *Proto : OC->protocols()) {
2879 CollectInheritedProtocols(Proto, Protocols);
2880 }
2881 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2882 // Insert the protocol.
2883 if (!Protocols.insert(
2884 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2885 return;
2886
2887 for (auto *Proto : OP->protocols())
2888 CollectInheritedProtocols(Proto, Protocols);
2889 }
2890}
2891
2893 const RecordDecl *RD,
2894 bool CheckIfTriviallyCopyable) {
2895 assert(RD->isUnion() && "Must be union type");
2896 CharUnits UnionSize =
2897 Context.getTypeSizeInChars(Context.getCanonicalTagType(RD));
2898
2899 for (const auto *Field : RD->fields()) {
2900 if (!Context.hasUniqueObjectRepresentations(Field->getType(),
2901 CheckIfTriviallyCopyable))
2902 return false;
2903 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2904 if (FieldSize != UnionSize)
2905 return false;
2906 }
2907 return !RD->field_empty();
2908}
2909
2910static int64_t getSubobjectOffset(const FieldDecl *Field,
2911 const ASTContext &Context,
2912 const clang::ASTRecordLayout & /*Layout*/) {
2913 return Context.getFieldOffset(Field);
2914}
2915
2916static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2917 const ASTContext &Context,
2918 const clang::ASTRecordLayout &Layout) {
2919 return Context.toBits(Layout.getBaseClassOffset(RD));
2920}
2921
2922static std::optional<int64_t>
2924 const RecordDecl *RD,
2925 bool CheckIfTriviallyCopyable);
2926
2927static std::optional<int64_t>
2928getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context,
2929 bool CheckIfTriviallyCopyable) {
2930 if (const auto *RD = Field->getType()->getAsRecordDecl();
2931 RD && !RD->isUnion())
2932 return structHasUniqueObjectRepresentations(Context, RD,
2933 CheckIfTriviallyCopyable);
2934
2935 // A _BitInt type may not be unique if it has padding bits
2936 // but if it is a bitfield the padding bits are not used.
2937 bool IsBitIntType = Field->getType()->isBitIntType();
2938 if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2939 !Context.hasUniqueObjectRepresentations(Field->getType(),
2940 CheckIfTriviallyCopyable))
2941 return std::nullopt;
2942
2943 int64_t FieldSizeInBits =
2944 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2945 if (Field->isBitField()) {
2946 // If we have explicit padding bits, they don't contribute bits
2947 // to the actual object representation, so return 0.
2948 if (Field->isUnnamedBitField())
2949 return 0;
2950
2951 int64_t BitfieldSize = Field->getBitWidthValue();
2952 if (IsBitIntType) {
2953 if ((unsigned)BitfieldSize >
2954 cast<BitIntType>(Field->getType())->getNumBits())
2955 return std::nullopt;
2956 } else if (BitfieldSize > FieldSizeInBits) {
2957 return std::nullopt;
2958 }
2959 FieldSizeInBits = BitfieldSize;
2960 } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations(
2961 Field->getType(), CheckIfTriviallyCopyable)) {
2962 return std::nullopt;
2963 }
2964 return FieldSizeInBits;
2965}
2966
2967static std::optional<int64_t>
2969 bool CheckIfTriviallyCopyable) {
2970 return structHasUniqueObjectRepresentations(Context, RD,
2971 CheckIfTriviallyCopyable);
2972}
2973
2974template <typename RangeT>
2976 const RangeT &Subobjects, int64_t CurOffsetInBits,
2977 const ASTContext &Context, const clang::ASTRecordLayout &Layout,
2978 bool CheckIfTriviallyCopyable) {
2979 for (const auto *Subobject : Subobjects) {
2980 std::optional<int64_t> SizeInBits =
2981 getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable);
2982 if (!SizeInBits)
2983 return std::nullopt;
2984 if (*SizeInBits != 0) {
2985 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2986 if (Offset != CurOffsetInBits)
2987 return std::nullopt;
2988 CurOffsetInBits += *SizeInBits;
2989 }
2990 }
2991 return CurOffsetInBits;
2992}
2993
2994static std::optional<int64_t>
2996 const RecordDecl *RD,
2997 bool CheckIfTriviallyCopyable) {
2998 assert(!RD->isUnion() && "Must be struct/class type");
2999 const auto &Layout = Context.getASTRecordLayout(RD);
3000
3001 int64_t CurOffsetInBits = 0;
3002 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
3003 if (ClassDecl->isDynamicClass())
3004 return std::nullopt;
3005
3007 for (const auto &Base : ClassDecl->bases()) {
3008 // Empty types can be inherited from, and non-empty types can potentially
3009 // have tail padding, so just make sure there isn't an error.
3010 Bases.emplace_back(Base.getType()->getAsCXXRecordDecl());
3011 }
3012
3013 llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
3014 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
3015 });
3016
3017 std::optional<int64_t> OffsetAfterBases =
3019 Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable);
3020 if (!OffsetAfterBases)
3021 return std::nullopt;
3022 CurOffsetInBits = *OffsetAfterBases;
3023 }
3024
3025 std::optional<int64_t> OffsetAfterFields =
3027 RD->fields(), CurOffsetInBits, Context, Layout,
3028 CheckIfTriviallyCopyable);
3029 if (!OffsetAfterFields)
3030 return std::nullopt;
3031 CurOffsetInBits = *OffsetAfterFields;
3032
3033 return CurOffsetInBits;
3034}
3035
3037 QualType Ty, bool CheckIfTriviallyCopyable) const {
3038 // C++17 [meta.unary.prop]:
3039 // The predicate condition for a template specialization
3040 // has_unique_object_representations<T> shall be satisfied if and only if:
3041 // (9.1) - T is trivially copyable, and
3042 // (9.2) - any two objects of type T with the same value have the same
3043 // object representation, where:
3044 // - two objects of array or non-union class type are considered to have
3045 // the same value if their respective sequences of direct subobjects
3046 // have the same values, and
3047 // - two objects of union type are considered to have the same value if
3048 // they have the same active member and the corresponding members have
3049 // the same value.
3050 // The set of scalar types for which this condition holds is
3051 // implementation-defined. [ Note: If a type has padding bits, the condition
3052 // does not hold; otherwise, the condition holds true for unsigned integral
3053 // types. -- end note ]
3054 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
3055
3056 // Arrays are unique only if their element type is unique.
3057 if (Ty->isArrayType())
3059 CheckIfTriviallyCopyable);
3060
3061 assert((Ty->isVoidType() || !Ty->isIncompleteType()) &&
3062 "hasUniqueObjectRepresentations should not be called with an "
3063 "incomplete type");
3064
3065 // (9.1) - T is trivially copyable...
3066 if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(*this))
3067 return false;
3068
3069 // All integrals and enums are unique.
3070 if (Ty->isIntegralOrEnumerationType()) {
3071 // Address discriminated integer types are not unique.
3073 return false;
3074 // Except _BitInt types that have padding bits.
3075 if (const auto *BIT = Ty->getAs<BitIntType>())
3076 return getTypeSize(BIT) == BIT->getNumBits();
3077
3078 return true;
3079 }
3080
3081 // All other pointers are unique.
3082 if (Ty->isPointerType())
3084
3085 if (const auto *MPT = Ty->getAs<MemberPointerType>())
3086 return !ABI->getMemberPointerInfo(MPT).HasPadding;
3087
3088 if (const auto *Record = Ty->getAsRecordDecl()) {
3089 if (Record->isInvalidDecl())
3090 return false;
3091
3092 if (Record->isUnion())
3094 CheckIfTriviallyCopyable);
3095
3096 std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(
3097 *this, Record, CheckIfTriviallyCopyable);
3098
3099 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(Ty));
3100 }
3101
3102 // FIXME: More cases to handle here (list by rsmith):
3103 // vectors (careful about, eg, vector of 3 foo)
3104 // _Complex int and friends
3105 // _Atomic T
3106 // Obj-C block pointers
3107 // Obj-C object pointers
3108 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
3109 // clk_event_t, queue_t, reserve_id_t)
3110 // There're also Obj-C class types and the Obj-C selector type, but I think it
3111 // makes sense for those to return false here.
3112
3113 return false;
3114}
3115
3117 unsigned count = 0;
3118 // Count ivars declared in class extension.
3119 for (const auto *Ext : OI->known_extensions())
3120 count += Ext->ivar_size();
3121
3122 // Count ivar defined in this class's implementation. This
3123 // includes synthesized ivars.
3124 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
3125 count += ImplDecl->ivar_size();
3126
3127 return count;
3128}
3129
3131 if (!E)
3132 return false;
3133
3134 // nullptr_t is always treated as null.
3135 if (E->getType()->isNullPtrType()) return true;
3136
3137 if (E->getType()->isAnyPointerType() &&
3140 return true;
3141
3142 // Unfortunately, __null has type 'int'.
3143 if (isa<GNUNullExpr>(E)) return true;
3144
3145 return false;
3146}
3147
3148/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
3149/// exists.
3151 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3152 I = ObjCImpls.find(D);
3153 if (I != ObjCImpls.end())
3154 return cast<ObjCImplementationDecl>(I->second);
3155 return nullptr;
3156}
3157
3158/// Get the implementation of ObjCCategoryDecl, or nullptr if none
3159/// exists.
3161 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3162 I = ObjCImpls.find(D);
3163 if (I != ObjCImpls.end())
3164 return cast<ObjCCategoryImplDecl>(I->second);
3165 return nullptr;
3166}
3167
3168/// Set the implementation of ObjCInterfaceDecl.
3170 ObjCImplementationDecl *ImplD) {
3171 assert(IFaceD && ImplD && "Passed null params");
3172 ObjCImpls[IFaceD] = ImplD;
3173}
3174
3175/// Set the implementation of ObjCCategoryDecl.
3177 ObjCCategoryImplDecl *ImplD) {
3178 assert(CatD && ImplD && "Passed null params");
3179 ObjCImpls[CatD] = ImplD;
3180}
3181
3182const ObjCMethodDecl *
3184 return ObjCMethodRedecls.lookup(MD);
3185}
3186
3188 const ObjCMethodDecl *Redecl) {
3189 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
3190 ObjCMethodRedecls[MD] = Redecl;
3191}
3192
3194 const NamedDecl *ND) const {
3195 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
3196 return ID;
3197 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
3198 return CD->getClassInterface();
3199 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
3200 return IMD->getClassInterface();
3201
3202 return nullptr;
3203}
3204
3205/// Get the copy initialization expression of VarDecl, or nullptr if
3206/// none exists.
3208 assert(VD && "Passed null params");
3209 assert(VD->hasAttr<BlocksAttr>() &&
3210 "getBlockVarCopyInits - not __block var");
3211 auto I = BlockVarCopyInits.find(VD);
3212 if (I != BlockVarCopyInits.end())
3213 return I->second;
3214 return {nullptr, false};
3215}
3216
3217/// Set the copy initialization expression of a block var decl.
3219 bool CanThrow) {
3220 assert(VD && CopyExpr && "Passed null params");
3221 assert(VD->hasAttr<BlocksAttr>() &&
3222 "setBlockVarCopyInits - not __block var");
3223 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
3224}
3225
3227 unsigned DataSize) const {
3228 if (!DataSize)
3229 DataSize = TypeLoc::getFullDataSizeForType(T);
3230 else
3231 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
3232 "incorrect data size provided to CreateTypeSourceInfo!");
3233
3234 auto *TInfo =
3235 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
3236 new (TInfo) TypeSourceInfo(T, DataSize);
3237 return TInfo;
3238}
3239
3241 SourceLocation L) const {
3243 TSI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
3244 return TSI;
3245}
3246
3247const ASTRecordLayout &
3249 return getObjCLayout(D);
3250}
3251
3254 bool &AnyNonCanonArgs) {
3255 SmallVector<TemplateArgument, 16> CanonArgs(Args);
3256 AnyNonCanonArgs |= C.canonicalizeTemplateArguments(CanonArgs);
3257 return CanonArgs;
3258}
3259
3262 bool AnyNonCanonArgs = false;
3263 for (auto &Arg : Args) {
3264 TemplateArgument OrigArg = Arg;
3266 AnyNonCanonArgs |= !Arg.structurallyEquals(OrigArg);
3267 }
3268 return AnyNonCanonArgs;
3269}
3270
3271//===----------------------------------------------------------------------===//
3272// Type creation/memoization methods
3273//===----------------------------------------------------------------------===//
3274
3276ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3277 unsigned fastQuals = quals.getFastQualifiers();
3278 quals.removeFastQualifiers();
3279
3280 // Check if we've already instantiated this type.
3281 llvm::FoldingSetNodeID ID;
3282 ExtQuals::Profile(ID, baseType, quals);
3283 void *insertPos = nullptr;
3284 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
3285 assert(eq->getQualifiers() == quals);
3286 return QualType(eq, fastQuals);
3287 }
3288
3289 // If the base type is not canonical, make the appropriate canonical type.
3290 QualType canon;
3291 if (!baseType->isCanonicalUnqualified()) {
3292 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3293 canonSplit.Quals.addConsistentQualifiers(quals);
3294 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
3295
3296 // Re-find the insert position.
3297 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
3298 }
3299
3300 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3301 ExtQualNodes.InsertNode(eq, insertPos);
3302 return QualType(eq, fastQuals);
3303}
3304
3306 LangAS AddressSpace) const {
3307 QualType CanT = getCanonicalType(T);
3308 if (CanT.getAddressSpace() == AddressSpace)
3309 return T;
3310
3311 // If we are composing extended qualifiers together, merge together
3312 // into one ExtQuals node.
3313 QualifierCollector Quals;
3314 const Type *TypeNode = Quals.strip(T);
3315
3316 // If this type already has an address space specified, it cannot get
3317 // another one.
3318 assert(!Quals.hasAddressSpace() &&
3319 "Type cannot be in multiple addr spaces!");
3320 Quals.addAddressSpace(AddressSpace);
3321
3322 return getExtQualType(TypeNode, Quals);
3323}
3324
3326 // If the type is not qualified with an address space, just return it
3327 // immediately.
3328 if (!T.hasAddressSpace())
3329 return T;
3330
3331 QualifierCollector Quals;
3332 const Type *TypeNode;
3333 // For arrays, strip the qualifier off the element type, then reconstruct the
3334 // array type
3335 if (T.getTypePtr()->isArrayType()) {
3336 T = getUnqualifiedArrayType(T, Quals);
3337 TypeNode = T.getTypePtr();
3338 } else {
3339 // If we are composing extended qualifiers together, merge together
3340 // into one ExtQuals node.
3341 while (T.hasAddressSpace()) {
3342 TypeNode = Quals.strip(T);
3343
3344 // If the type no longer has an address space after stripping qualifiers,
3345 // jump out.
3346 if (!QualType(TypeNode, 0).hasAddressSpace())
3347 break;
3348
3349 // There might be sugar in the way. Strip it and try again.
3350 T = T.getSingleStepDesugaredType(*this);
3351 }
3352 }
3353
3354 Quals.removeAddressSpace();
3355
3356 // Removal of the address space can mean there are no longer any
3357 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3358 // or required.
3359 if (Quals.hasNonFastQualifiers())
3360 return getExtQualType(TypeNode, Quals);
3361 else
3362 return QualType(TypeNode, Quals.getFastQualifiers());
3363}
3364
3365uint16_t
3367 assert(RD->isPolymorphic() &&
3368 "Attempted to get vtable pointer discriminator on a monomorphic type");
3369 std::unique_ptr<MangleContext> MC(createMangleContext());
3370 SmallString<256> Str;
3371 llvm::raw_svector_ostream Out(Str);
3372 MC->mangleCXXVTable(RD, Out);
3373 return llvm::getPointerAuthStableSipHash(Str);
3374}
3375
3376/// Encode a function type for use in the discriminator of a function pointer
3377/// type. We can't use the itanium scheme for this since C has quite permissive
3378/// rules for type compatibility that we need to be compatible with.
3379///
3380/// Formally, this function associates every function pointer type T with an
3381/// encoded string E(T). Let the equivalence relation T1 ~ T2 be defined as
3382/// E(T1) == E(T2). E(T) is part of the ABI of values of type T. C type
3383/// compatibility requires equivalent treatment under the ABI, so
3384/// CCompatible(T1, T2) must imply E(T1) == E(T2), that is, CCompatible must be
3385/// a subset of ~. Crucially, however, it must be a proper subset because
3386/// CCompatible is not an equivalence relation: for example, int[] is compatible
3387/// with both int[1] and int[2], but the latter are not compatible with each
3388/// other. Therefore this encoding function must be careful to only distinguish
3389/// types if there is no third type with which they are both required to be
3390/// compatible.
3392 raw_ostream &OS, QualType QT) {
3393 // FIXME: Consider address space qualifiers.
3394 const Type *T = QT.getCanonicalType().getTypePtr();
3395
3396 // FIXME: Consider using the C++ type mangling when we encounter a construct
3397 // that is incompatible with C.
3398
3399 switch (T->getTypeClass()) {
3400 case Type::Atomic:
3402 Ctx, OS, cast<AtomicType>(T)->getValueType());
3403
3404 case Type::LValueReference:
3405 OS << "R";
3408 return;
3409 case Type::RValueReference:
3410 OS << "O";
3413 return;
3414
3415 case Type::Pointer:
3416 // C11 6.7.6.1p2:
3417 // For two pointer types to be compatible, both shall be identically
3418 // qualified and both shall be pointers to compatible types.
3419 // FIXME: we should also consider pointee types.
3420 OS << "P";
3421 return;
3422
3423 case Type::ObjCObjectPointer:
3424 case Type::BlockPointer:
3425 OS << "P";
3426 return;
3427
3428 case Type::Complex:
3429 OS << "C";
3431 Ctx, OS, cast<ComplexType>(T)->getElementType());
3432
3433 case Type::VariableArray:
3434 case Type::ConstantArray:
3435 case Type::IncompleteArray:
3436 case Type::ArrayParameter:
3437 // C11 6.7.6.2p6:
3438 // For two array types to be compatible, both shall have compatible
3439 // element types, and if both size specifiers are present, and are integer
3440 // constant expressions, then both size specifiers shall have the same
3441 // constant value [...]
3442 //
3443 // So since ElemType[N] has to be compatible ElemType[], we can't encode the
3444 // width of the array.
3445 OS << "A";
3447 Ctx, OS, cast<ArrayType>(T)->getElementType());
3448
3449 case Type::ObjCInterface:
3450 case Type::ObjCObject:
3451 OS << "<objc_object>";
3452 return;
3453
3454 case Type::Enum: {
3455 // C11 6.7.2.2p4:
3456 // Each enumerated type shall be compatible with char, a signed integer
3457 // type, or an unsigned integer type.
3458 //
3459 // So we have to treat enum types as integers.
3460 QualType UnderlyingType = T->castAsEnumDecl()->getIntegerType();
3462 Ctx, OS, UnderlyingType.isNull() ? Ctx.IntTy : UnderlyingType);
3463 }
3464
3465 case Type::FunctionNoProto:
3466 case Type::FunctionProto: {
3467 // C11 6.7.6.3p15:
3468 // For two function types to be compatible, both shall specify compatible
3469 // return types. Moreover, the parameter type lists, if both are present,
3470 // shall agree in the number of parameters and in the use of the ellipsis
3471 // terminator; corresponding parameters shall have compatible types.
3472 //
3473 // That paragraph goes on to describe how unprototyped functions are to be
3474 // handled, which we ignore here. Unprototyped function pointers are hashed
3475 // as though they were prototyped nullary functions since thats probably
3476 // what the user meant. This behavior is non-conforming.
3477 // FIXME: If we add a "custom discriminator" function type attribute we
3478 // should encode functions as their discriminators.
3479 OS << "F";
3480 const auto *FuncType = cast<FunctionType>(T);
3481 encodeTypeForFunctionPointerAuth(Ctx, OS, FuncType->getReturnType());
3482 if (const auto *FPT = dyn_cast<FunctionProtoType>(FuncType)) {
3483 for (QualType Param : FPT->param_types()) {
3484 Param = Ctx.getSignatureParameterType(Param);
3485 encodeTypeForFunctionPointerAuth(Ctx, OS, Param);
3486 }
3487 if (FPT->isVariadic())
3488 OS << "z";
3489 }
3490 OS << "E";
3491 return;
3492 }
3493
3494 case Type::MemberPointer: {
3495 OS << "M";
3496 const auto *MPT = T->castAs<MemberPointerType>();
3498 Ctx, OS, QualType(MPT->getQualifier().getAsType(), 0));
3499 encodeTypeForFunctionPointerAuth(Ctx, OS, MPT->getPointeeType());
3500 return;
3501 }
3502 case Type::ExtVector:
3503 case Type::Vector:
3504 OS << "Dv" << Ctx.getTypeSizeInChars(T).getQuantity();
3505 break;
3506
3507 // Don't bother discriminating based on these types.
3508 case Type::Pipe:
3509 case Type::BitInt:
3510 case Type::ConstantMatrix:
3511 OS << "?";
3512 return;
3513
3514 case Type::Builtin: {
3515 const auto *BTy = T->castAs<BuiltinType>();
3516 switch (BTy->getKind()) {
3517#define SIGNED_TYPE(Id, SingletonId) \
3518 case BuiltinType::Id: \
3519 OS << "i"; \
3520 return;
3521#define UNSIGNED_TYPE(Id, SingletonId) \
3522 case BuiltinType::Id: \
3523 OS << "i"; \
3524 return;
3525#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
3526#define BUILTIN_TYPE(Id, SingletonId)
3527#include "clang/AST/BuiltinTypes.def"
3528 llvm_unreachable("placeholder types should not appear here.");
3529
3530 case BuiltinType::Half:
3531 OS << "Dh";
3532 return;
3533 case BuiltinType::Float:
3534 OS << "f";
3535 return;
3536 case BuiltinType::Double:
3537 OS << "d";
3538 return;
3539 case BuiltinType::LongDouble:
3540 OS << "e";
3541 return;
3542 case BuiltinType::Float16:
3543 OS << "DF16_";
3544 return;
3545 case BuiltinType::Float128:
3546 OS << "g";
3547 return;
3548
3549 case BuiltinType::Void:
3550 OS << "v";
3551 return;
3552
3553 case BuiltinType::ObjCId:
3554 case BuiltinType::ObjCClass:
3555 case BuiltinType::ObjCSel:
3556 case BuiltinType::NullPtr:
3557 OS << "P";
3558 return;
3559
3560 // Don't bother discriminating based on OpenCL types.
3561 case BuiltinType::OCLSampler:
3562 case BuiltinType::OCLEvent:
3563 case BuiltinType::OCLClkEvent:
3564 case BuiltinType::OCLQueue:
3565 case BuiltinType::OCLReserveID:
3566 case BuiltinType::BFloat16:
3567 case BuiltinType::VectorQuad:
3568 case BuiltinType::VectorPair:
3569 case BuiltinType::DMR1024:
3570 case BuiltinType::DMR2048:
3571 OS << "?";
3572 return;
3573
3574 // Don't bother discriminating based on these seldom-used types.
3575 case BuiltinType::Ibm128:
3576 return;
3577#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3578 case BuiltinType::Id: \
3579 return;
3580#include "clang/Basic/OpenCLImageTypes.def"
3581#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3582 case BuiltinType::Id: \
3583 return;
3584#include "clang/Basic/OpenCLExtensionTypes.def"
3585#define SVE_TYPE(Name, Id, SingletonId) \
3586 case BuiltinType::Id: \
3587 return;
3588#include "clang/Basic/AArch64ACLETypes.def"
3589#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3590 case BuiltinType::Id: \
3591 return;
3592#include "clang/Basic/HLSLIntangibleTypes.def"
3593 case BuiltinType::Dependent:
3594 llvm_unreachable("should never get here");
3595#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
3596#include "clang/Basic/AMDGPUTypes.def"
3597 case BuiltinType::WasmExternRef:
3598#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3599#include "clang/Basic/RISCVVTypes.def"
3600 llvm_unreachable("not yet implemented");
3601 }
3602 llvm_unreachable("should never get here");
3603 }
3604 case Type::Record: {
3605 const RecordDecl *RD = T->castAsCanonical<RecordType>()->getDecl();
3606 const IdentifierInfo *II = RD->getIdentifier();
3607
3608 // In C++, an immediate typedef of an anonymous struct or union
3609 // is considered to name it for ODR purposes, but C's specification
3610 // of type compatibility does not have a similar rule. Using the typedef
3611 // name in function type discriminators anyway, as we do here,
3612 // therefore technically violates the C standard: two function pointer
3613 // types defined in terms of two typedef'd anonymous structs with
3614 // different names are formally still compatible, but we are assigning
3615 // them different discriminators and therefore incompatible ABIs.
3616 //
3617 // This is a relatively minor violation that significantly improves
3618 // discrimination in some cases and has not caused problems in
3619 // practice. Regardless, it is now part of the ABI in places where
3620 // function type discrimination is used, and it can no longer be
3621 // changed except on new platforms.
3622
3623 if (!II)
3624 if (const TypedefNameDecl *Typedef = RD->getTypedefNameForAnonDecl())
3625 II = Typedef->getDeclName().getAsIdentifierInfo();
3626
3627 if (!II) {
3628 OS << "<anonymous_record>";
3629 return;
3630 }
3631 OS << II->getLength() << II->getName();
3632 return;
3633 }
3634 case Type::HLSLAttributedResource:
3635 case Type::HLSLInlineSpirv:
3636 llvm_unreachable("should never get here");
3637 break;
3638 case Type::OverflowBehavior:
3639 llvm_unreachable("should never get here");
3640 break;
3641 case Type::DeducedTemplateSpecialization:
3642 case Type::Auto:
3643#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3644#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3645#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3646#define ABSTRACT_TYPE(Class, Base)
3647#define TYPE(Class, Base)
3648#include "clang/AST/TypeNodes.inc"
3649 llvm_unreachable("unexpected non-canonical or dependent type!");
3650 return;
3651 }
3652}
3653
3655 assert(!T->isDependentType() &&
3656 "cannot compute type discriminator of a dependent type");
3657 SmallString<256> Str;
3658 llvm::raw_svector_ostream Out(Str);
3659
3660 if (T->isFunctionPointerType() || T->isFunctionReferenceType())
3661 T = T->getPointeeType();
3662
3663 if (T->isFunctionType()) {
3664 encodeTypeForFunctionPointerAuth(*this, Out, T);
3665 } else {
3666 T = T.getUnqualifiedType();
3667 // Calls to member function pointers don't need to worry about
3668 // language interop or the laxness of the C type compatibility rules.
3669 // We just mangle the member pointer type directly, which is
3670 // implicitly much stricter about type matching. However, we do
3671 // strip any top-level exception specification before this mangling.
3672 // C++23 requires calls to work when the function type is convertible
3673 // to the pointer type by a function pointer conversion, which can
3674 // change the exception specification. This does not technically
3675 // require the exception specification to not affect representation,
3676 // because the function pointer conversion is still always a direct
3677 // value conversion and therefore an opportunity to resign the
3678 // pointer. (This is in contrast to e.g. qualification conversions,
3679 // which can be applied in nested pointer positions, effectively
3680 // requiring qualified and unqualified representations to match.)
3681 // However, it is pragmatic to ignore exception specifications
3682 // because it allows a certain amount of `noexcept` mismatching
3683 // to not become a visible ODR problem. This also leaves some
3684 // room for the committee to add laxness to function pointer
3685 // conversions in future standards.
3686 if (auto *MPT = T->getAs<MemberPointerType>())
3687 if (MPT->isMemberFunctionPointer()) {
3688 QualType PointeeType = MPT->getPointeeType();
3689 if (PointeeType->castAs<FunctionProtoType>()->getExceptionSpecType() !=
3690 EST_None) {
3692 T = getMemberPointerType(FT, MPT->getQualifier(),
3693 MPT->getMostRecentCXXRecordDecl());
3694 }
3695 }
3696 std::unique_ptr<MangleContext> MC(createMangleContext());
3697 MC->mangleCanonicalTypeName(T, Out);
3698 }
3699
3700 return llvm::getPointerAuthStableSipHash(Str);
3701}
3702
3704 Qualifiers::GC GCAttr) const {
3705 QualType CanT = getCanonicalType(T);
3706 if (CanT.getObjCGCAttr() == GCAttr)
3707 return T;
3708
3709 if (const auto *ptr = T->getAs<PointerType>()) {
3710 QualType Pointee = ptr->getPointeeType();
3711 if (Pointee->isAnyPointerType()) {
3712 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
3713 return getPointerType(ResultType);
3714 }
3715 }
3716
3717 // If we are composing extended qualifiers together, merge together
3718 // into one ExtQuals node.
3719 QualifierCollector Quals;
3720 const Type *TypeNode = Quals.strip(T);
3721
3722 // If this type already has an ObjCGC specified, it cannot get
3723 // another one.
3724 assert(!Quals.hasObjCGCAttr() &&
3725 "Type cannot have multiple ObjCGCs!");
3726 Quals.addObjCGCAttr(GCAttr);
3727
3728 return getExtQualType(TypeNode, Quals);
3729}
3730
3732 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3733 QualType Pointee = Ptr->getPointeeType();
3734 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3735 return getPointerType(removeAddrSpaceQualType(Pointee));
3736 }
3737 }
3738 return T;
3739}
3740
3742 QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull,
3743 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3744 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3745
3746 llvm::FoldingSetNodeID ID;
3747 CountAttributedType::Profile(ID, WrappedTy, CountExpr, CountInBytes, OrNull);
3748
3749 void *InsertPos = nullptr;
3750 CountAttributedType *CATy =
3751 CountAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
3752 if (CATy)
3753 return QualType(CATy, 0);
3754
3755 QualType CanonTy = getCanonicalType(WrappedTy);
3756 size_t Size = CountAttributedType::totalSizeToAlloc<TypeCoupledDeclRefInfo>(
3757 DependentDecls.size());
3759 new (CATy) CountAttributedType(WrappedTy, CanonTy, CountExpr, CountInBytes,
3760 OrNull, DependentDecls);
3761 Types.push_back(CATy);
3762 CountAttributedTypes.InsertNode(CATy, InsertPos);
3763
3764 return QualType(CATy, 0);
3765}
3766
3769 llvm::function_ref<QualType(QualType)> Adjust) const {
3770 switch (Orig->getTypeClass()) {
3771 case Type::Attributed: {
3772 const auto *AT = cast<AttributedType>(Orig);
3773 return getAttributedType(AT->getAttrKind(),
3774 adjustType(AT->getModifiedType(), Adjust),
3775 adjustType(AT->getEquivalentType(), Adjust),
3776 AT->getAttr());
3777 }
3778
3779 case Type::BTFTagAttributed: {
3780 const auto *BTFT = dyn_cast<BTFTagAttributedType>(Orig);
3781 return getBTFTagAttributedType(BTFT->getAttr(),
3782 adjustType(BTFT->getWrappedType(), Adjust));
3783 }
3784
3785 case Type::OverflowBehavior: {
3786 const auto *OB = dyn_cast<OverflowBehaviorType>(Orig);
3787 return getOverflowBehaviorType(OB->getBehaviorKind(),
3788 adjustType(OB->getUnderlyingType(), Adjust));
3789 }
3790
3791 case Type::Paren:
3792 return getParenType(
3793 adjustType(cast<ParenType>(Orig)->getInnerType(), Adjust));
3794
3795 case Type::Adjusted: {
3796 const auto *AT = cast<AdjustedType>(Orig);
3797 return getAdjustedType(AT->getOriginalType(),
3798 adjustType(AT->getAdjustedType(), Adjust));
3799 }
3800
3801 case Type::MacroQualified: {
3802 const auto *MQT = cast<MacroQualifiedType>(Orig);
3803 return getMacroQualifiedType(adjustType(MQT->getUnderlyingType(), Adjust),
3804 MQT->getMacroIdentifier());
3805 }
3806
3807 default:
3808 return Adjust(Orig);
3809 }
3810}
3811
3813 FunctionType::ExtInfo Info) {
3814 if (T->getExtInfo() == Info)
3815 return T;
3816
3818 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3819 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3820 } else {
3821 const auto *FPT = cast<FunctionProtoType>(T);
3822 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3823 EPI.ExtInfo = Info;
3824 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3825 }
3826
3827 return cast<FunctionType>(Result.getTypePtr());
3828}
3829
3831 QualType ResultType) {
3832 return adjustType(FunctionType, [&](QualType Orig) {
3833 if (const auto *FNPT = Orig->getAs<FunctionNoProtoType>())
3834 return getFunctionNoProtoType(ResultType, FNPT->getExtInfo());
3835
3836 const auto *FPT = Orig->castAs<FunctionProtoType>();
3837 return getFunctionType(ResultType, FPT->getParamTypes(),
3838 FPT->getExtProtoInfo());
3839 });
3840}
3841
3843 QualType ResultType) {
3844 FD = FD->getMostRecentDecl();
3845 while (true) {
3846 FD->setType(adjustFunctionResultType(FD->getType(), ResultType));
3847 if (FunctionDecl *Next = FD->getPreviousDecl())
3848 FD = Next;
3849 else
3850 break;
3851 }
3853 L->DeducedReturnType(FD, ResultType);
3854}
3855
3856/// Get a function type and produce the equivalent function type with the
3857/// specified exception specification. Type sugar that can be present on a
3858/// declaration of a function with an exception specification is permitted
3859/// and preserved. Other type sugar (for instance, typedefs) is not.
3861 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3862 return adjustType(Orig, [&](QualType Ty) {
3863 const auto *Proto = Ty->castAs<FunctionProtoType>();
3864 return getFunctionType(Proto->getReturnType(), Proto->getParamTypes(),
3865 Proto->getExtProtoInfo().withExceptionSpec(ESI));
3866 });
3867}
3868
3876
3878 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3879 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3880 SmallVector<QualType, 16> Args(Proto->param_types().size());
3881 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3882 Args[i] = removePtrSizeAddrSpace(Proto->param_types()[i]);
3883 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3884 }
3885
3886 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3887 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3888 return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3889 }
3890
3891 return T;
3892}
3893
3899
3901 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3902 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3903 EPI.ExtParameterInfos = nullptr;
3904 return getFunctionType(Proto->getReturnType(), Proto->param_types(), EPI);
3905 }
3906 return T;
3907}
3908
3914
3917 bool AsWritten) {
3918 // Update the type.
3919 QualType Updated =
3921 FD->setType(Updated);
3922
3923 if (!AsWritten)
3924 return;
3925
3926 // Update the type in the type source information too.
3927 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3928 // If the type and the type-as-written differ, we may need to update
3929 // the type-as-written too.
3930 if (TSInfo->getType() != FD->getType())
3931 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3932
3933 // FIXME: When we get proper type location information for exceptions,
3934 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3935 // up the TypeSourceInfo;
3936 assert(TypeLoc::getFullDataSizeForType(Updated) ==
3937 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3938 "TypeLoc size mismatch from updating exception specification");
3939 TSInfo->overrideType(Updated);
3940 }
3941}
3942
3943/// getComplexType - Return the uniqued reference to the type for a complex
3944/// number with the specified element type.
3946 // Unique pointers, to guarantee there is only one pointer of a particular
3947 // structure.
3948 llvm::FoldingSetNodeID ID;
3949 ComplexType::Profile(ID, T);
3950
3951 void *InsertPos = nullptr;
3952 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3953 return QualType(CT, 0);
3954
3955 // If the pointee type isn't canonical, this won't be a canonical type either,
3956 // so fill in the canonical type field.
3957 QualType Canonical;
3958 if (!T.isCanonical()) {
3959 Canonical = getComplexType(getCanonicalType(T));
3960
3961 // Get the new insert position for the node we care about.
3962 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3963 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3964 }
3965 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
3966 Types.push_back(New);
3967 ComplexTypes.InsertNode(New, InsertPos);
3968 return QualType(New, 0);
3969}
3970
3971/// getPointerType - Return the uniqued reference to the type for a pointer to
3972/// the specified type.
3974 // Unique pointers, to guarantee there is only one pointer of a particular
3975 // structure.
3976 llvm::FoldingSetNodeID ID;
3977 PointerType::Profile(ID, T);
3978
3979 void *InsertPos = nullptr;
3980 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3981 return QualType(PT, 0);
3982
3983 // If the pointee type isn't canonical, this won't be a canonical type either,
3984 // so fill in the canonical type field.
3985 QualType Canonical;
3986 if (!T.isCanonical()) {
3987 Canonical = getPointerType(getCanonicalType(T));
3988
3989 // Get the new insert position for the node we care about.
3990 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3991 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3992 }
3993 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
3994 Types.push_back(New);
3995 PointerTypes.InsertNode(New, InsertPos);
3996 return QualType(New, 0);
3997}
3998
4000 llvm::FoldingSetNodeID ID;
4001 AdjustedType::Profile(ID, Orig, New);
4002 void *InsertPos = nullptr;
4003 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
4004 if (AT)
4005 return QualType(AT, 0);
4006
4007 QualType Canonical = getCanonicalType(New);
4008
4009 // Get the new insert position for the node we care about.
4010 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
4011 assert(!AT && "Shouldn't be in the map!");
4012
4013 AT = new (*this, alignof(AdjustedType))
4014 AdjustedType(Type::Adjusted, Orig, New, Canonical);
4015 Types.push_back(AT);
4016 AdjustedTypes.InsertNode(AT, InsertPos);
4017 return QualType(AT, 0);
4018}
4019
4021 llvm::FoldingSetNodeID ID;
4022 AdjustedType::Profile(ID, Orig, Decayed);
4023 void *InsertPos = nullptr;
4024 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
4025 if (AT)
4026 return QualType(AT, 0);
4027
4028 QualType Canonical = getCanonicalType(Decayed);
4029
4030 // Get the new insert position for the node we care about.
4031 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
4032 assert(!AT && "Shouldn't be in the map!");
4033
4034 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
4035 Types.push_back(AT);
4036 AdjustedTypes.InsertNode(AT, InsertPos);
4037 return QualType(AT, 0);
4038}
4039
4041 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
4042
4043 QualType Decayed;
4044
4045 // C99 6.7.5.3p7:
4046 // A declaration of a parameter as "array of type" shall be
4047 // adjusted to "qualified pointer to type", where the type
4048 // qualifiers (if any) are those specified within the [ and ] of
4049 // the array type derivation.
4050 if (T->isArrayType())
4051 Decayed = getArrayDecayedType(T);
4052
4053 // C99 6.7.5.3p8:
4054 // A declaration of a parameter as "function returning type"
4055 // shall be adjusted to "pointer to function returning type", as
4056 // in 6.3.2.1.
4057 if (T->isFunctionType())
4058 Decayed = getPointerType(T);
4059
4060 return getDecayedType(T, Decayed);
4061}
4062
4064 if (Ty->isArrayParameterType())
4065 return Ty;
4066 assert(Ty->isConstantArrayType() && "Ty must be an array type.");
4067 QualType DTy = Ty.getDesugaredType(*this);
4068 const auto *ATy = cast<ConstantArrayType>(DTy);
4069 llvm::FoldingSetNodeID ID;
4070 ATy->Profile(ID, *this, ATy->getElementType(), ATy->getZExtSize(),
4071 ATy->getSizeExpr(), ATy->getSizeModifier(),
4072 ATy->getIndexTypeQualifiers().getAsOpaqueValue());
4073 void *InsertPos = nullptr;
4074 ArrayParameterType *AT =
4075 ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
4076 if (AT)
4077 return QualType(AT, 0);
4078
4079 QualType Canonical;
4080 if (!DTy.isCanonical()) {
4081 Canonical = getArrayParameterType(getCanonicalType(Ty));
4082
4083 // Get the new insert position for the node we care about.
4084 AT = ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
4085 assert(!AT && "Shouldn't be in the map!");
4086 }
4087
4088 AT = new (*this, alignof(ArrayParameterType))
4089 ArrayParameterType(ATy, Canonical);
4090 Types.push_back(AT);
4091 ArrayParameterTypes.InsertNode(AT, InsertPos);
4092 return QualType(AT, 0);
4093}
4094
4095/// getBlockPointerType - Return the uniqued reference to the type for
4096/// a pointer to the specified block.
4098 assert(T->isFunctionType() && "block of function types only");
4099 // Unique pointers, to guarantee there is only one block of a particular
4100 // structure.
4101 llvm::FoldingSetNodeID ID;
4103
4104 void *InsertPos = nullptr;
4105 if (BlockPointerType *PT =
4106 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4107 return QualType(PT, 0);
4108
4109 // If the block pointee type isn't canonical, this won't be a canonical
4110 // type either so fill in the canonical type field.
4111 QualType Canonical;
4112 if (!T.isCanonical()) {
4113 Canonical = getBlockPointerType(getCanonicalType(T));
4114
4115 // Get the new insert position for the node we care about.
4116 BlockPointerType *NewIP =
4117 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4118 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4119 }
4120 auto *New =
4121 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
4122 Types.push_back(New);
4123 BlockPointerTypes.InsertNode(New, InsertPos);
4124 return QualType(New, 0);
4125}
4126
4127/// getLValueReferenceType - Return the uniqued reference to the type for an
4128/// lvalue reference to the specified type.
4130ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
4131 assert((!T->isPlaceholderType() ||
4132 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4133 "Unresolved placeholder type");
4134
4135 // Unique pointers, to guarantee there is only one pointer of a particular
4136 // structure.
4137 llvm::FoldingSetNodeID ID;
4138 ReferenceType::Profile(ID, T, SpelledAsLValue);
4139
4140 void *InsertPos = nullptr;
4141 if (LValueReferenceType *RT =
4142 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4143 return QualType(RT, 0);
4144
4145 const auto *InnerRef = T->getAs<ReferenceType>();
4146
4147 // If the referencee type isn't canonical, this won't be a canonical type
4148 // either, so fill in the canonical type field.
4149 QualType Canonical;
4150 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
4151 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4152 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
4153
4154 // Get the new insert position for the node we care about.
4155 LValueReferenceType *NewIP =
4156 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4157 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4158 }
4159
4160 auto *New = new (*this, alignof(LValueReferenceType))
4161 LValueReferenceType(T, Canonical, SpelledAsLValue);
4162 Types.push_back(New);
4163 LValueReferenceTypes.InsertNode(New, InsertPos);
4164
4165 return QualType(New, 0);
4166}
4167
4168/// getRValueReferenceType - Return the uniqued reference to the type for an
4169/// rvalue reference to the specified type.
4171 assert((!T->isPlaceholderType() ||
4172 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4173 "Unresolved placeholder type");
4174
4175 // Unique pointers, to guarantee there is only one pointer of a particular
4176 // structure.
4177 llvm::FoldingSetNodeID ID;
4178 ReferenceType::Profile(ID, T, false);
4179
4180 void *InsertPos = nullptr;
4181 if (RValueReferenceType *RT =
4182 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4183 return QualType(RT, 0);
4184
4185 const auto *InnerRef = T->getAs<ReferenceType>();
4186
4187 // If the referencee type isn't canonical, this won't be a canonical type
4188 // either, so fill in the canonical type field.
4189 QualType Canonical;
4190 if (InnerRef || !T.isCanonical()) {
4191 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4192 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
4193
4194 // Get the new insert position for the node we care about.
4195 RValueReferenceType *NewIP =
4196 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4197 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4198 }
4199
4200 auto *New = new (*this, alignof(RValueReferenceType))
4201 RValueReferenceType(T, Canonical);
4202 Types.push_back(New);
4203 RValueReferenceTypes.InsertNode(New, InsertPos);
4204 return QualType(New, 0);
4205}
4206
4208 NestedNameSpecifier Qualifier,
4209 const CXXRecordDecl *Cls) const {
4210 if (!Qualifier) {
4211 assert(Cls && "At least one of Qualifier or Cls must be provided");
4212 Qualifier = NestedNameSpecifier(getCanonicalTagType(Cls).getTypePtr());
4213 } else if (!Cls) {
4214 Cls = Qualifier.getAsRecordDecl();
4215 }
4216 // Unique pointers, to guarantee there is only one pointer of a particular
4217 // structure.
4218 llvm::FoldingSetNodeID ID;
4219 MemberPointerType::Profile(ID, T, Qualifier, Cls);
4220
4221 void *InsertPos = nullptr;
4222 if (MemberPointerType *PT =
4223 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4224 return QualType(PT, 0);
4225
4226 NestedNameSpecifier CanonicalQualifier = [&] {
4227 if (!Cls)
4228 return Qualifier.getCanonical();
4229 NestedNameSpecifier R(getCanonicalTagType(Cls).getTypePtr());
4230 assert(R.isCanonical());
4231 return R;
4232 }();
4233 // If the pointee or class type isn't canonical, this won't be a canonical
4234 // type either, so fill in the canonical type field.
4235 QualType Canonical;
4236 if (!T.isCanonical() || Qualifier != CanonicalQualifier) {
4237 Canonical =
4238 getMemberPointerType(getCanonicalType(T), CanonicalQualifier, Cls);
4239 assert(!cast<MemberPointerType>(Canonical)->isSugared());
4240 // Get the new insert position for the node we care about.
4241 [[maybe_unused]] MemberPointerType *NewIP =
4242 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4243 assert(!NewIP && "Shouldn't be in the map!");
4244 }
4245 auto *New = new (*this, alignof(MemberPointerType))
4246 MemberPointerType(T, Qualifier, Canonical);
4247 Types.push_back(New);
4248 MemberPointerTypes.InsertNode(New, InsertPos);
4249 return QualType(New, 0);
4250}
4251
4252/// getConstantArrayType - Return the unique reference to the type for an
4253/// array of the specified element type.
4255 const llvm::APInt &ArySizeIn,
4256 const Expr *SizeExpr,
4258 unsigned IndexTypeQuals) const {
4259 assert((EltTy->isDependentType() ||
4260 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
4261 "Constant array of VLAs is illegal!");
4262
4263 // We only need the size as part of the type if it's instantiation-dependent.
4264 if (SizeExpr && !SizeExpr->isInstantiationDependent())
4265 SizeExpr = nullptr;
4266
4267 // Convert the array size into a canonical width matching the pointer size for
4268 // the target.
4269 llvm::APInt ArySize(ArySizeIn);
4270 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
4271
4272 llvm::FoldingSetNodeID ID;
4273 ConstantArrayType::Profile(ID, *this, EltTy, ArySize.getZExtValue(), SizeExpr,
4274 ASM, IndexTypeQuals);
4275
4276 void *InsertPos = nullptr;
4277 if (ConstantArrayType *ATP =
4278 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
4279 return QualType(ATP, 0);
4280
4281 // If the element type isn't canonical or has qualifiers, or the array bound
4282 // is instantiation-dependent, this won't be a canonical type either, so fill
4283 // in the canonical type field.
4284 QualType Canon;
4285 // FIXME: Check below should look for qualifiers behind sugar.
4286 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
4287 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4288 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
4289 ASM, IndexTypeQuals);
4290 Canon = getQualifiedType(Canon, canonSplit.Quals);
4291
4292 // Get the new insert position for the node we care about.
4293 ConstantArrayType *NewIP =
4294 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
4295 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4296 }
4297
4298 auto *New = ConstantArrayType::Create(*this, EltTy, Canon, ArySize, SizeExpr,
4299 ASM, IndexTypeQuals);
4300 ConstantArrayTypes.InsertNode(New, InsertPos);
4301 Types.push_back(New);
4302 return QualType(New, 0);
4303}
4304
4305/// getVariableArrayDecayedType - Turns the given type, which may be
4306/// variably-modified, into the corresponding type with all the known
4307/// sizes replaced with [*].
4309 // Vastly most common case.
4310 if (!type->isVariablyModifiedType()) return type;
4311
4312 QualType result;
4313
4314 SplitQualType split = type.getSplitDesugaredType();
4315 const Type *ty = split.Ty;
4316 switch (ty->getTypeClass()) {
4317#define TYPE(Class, Base)
4318#define ABSTRACT_TYPE(Class, Base)
4319#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4320#include "clang/AST/TypeNodes.inc"
4321 llvm_unreachable("didn't desugar past all non-canonical types?");
4322
4323 // These types should never be variably-modified.
4324 case Type::Builtin:
4325 case Type::Complex:
4326 case Type::Vector:
4327 case Type::DependentVector:
4328 case Type::ExtVector:
4329 case Type::DependentSizedExtVector:
4330 case Type::ConstantMatrix:
4331 case Type::DependentSizedMatrix:
4332 case Type::DependentAddressSpace:
4333 case Type::ObjCObject:
4334 case Type::ObjCInterface:
4335 case Type::ObjCObjectPointer:
4336 case Type::Record:
4337 case Type::Enum:
4338 case Type::UnresolvedUsing:
4339 case Type::TypeOfExpr:
4340 case Type::TypeOf:
4341 case Type::Decltype:
4342 case Type::UnaryTransform:
4343 case Type::DependentName:
4344 case Type::InjectedClassName:
4345 case Type::TemplateSpecialization:
4346 case Type::TemplateTypeParm:
4347 case Type::SubstTemplateTypeParmPack:
4348 case Type::SubstBuiltinTemplatePack:
4349 case Type::Auto:
4350 case Type::DeducedTemplateSpecialization:
4351 case Type::PackExpansion:
4352 case Type::PackIndexing:
4353 case Type::BitInt:
4354 case Type::DependentBitInt:
4355 case Type::ArrayParameter:
4356 case Type::HLSLAttributedResource:
4357 case Type::HLSLInlineSpirv:
4358 case Type::OverflowBehavior:
4359 llvm_unreachable("type should never be variably-modified");
4360
4361 // These types can be variably-modified but should never need to
4362 // further decay.
4363 case Type::FunctionNoProto:
4364 case Type::FunctionProto:
4365 case Type::BlockPointer:
4366 case Type::MemberPointer:
4367 case Type::Pipe:
4368 return type;
4369
4370 // These types can be variably-modified. All these modifications
4371 // preserve structure except as noted by comments.
4372 // TODO: if we ever care about optimizing VLAs, there are no-op
4373 // optimizations available here.
4374 case Type::Pointer:
4377 break;
4378
4379 case Type::LValueReference: {
4380 const auto *lv = cast<LValueReferenceType>(ty);
4381 result = getLValueReferenceType(
4382 getVariableArrayDecayedType(lv->getPointeeType()),
4383 lv->isSpelledAsLValue());
4384 break;
4385 }
4386
4387 case Type::RValueReference: {
4388 const auto *lv = cast<RValueReferenceType>(ty);
4389 result = getRValueReferenceType(
4390 getVariableArrayDecayedType(lv->getPointeeType()));
4391 break;
4392 }
4393
4394 case Type::Atomic: {
4395 const auto *at = cast<AtomicType>(ty);
4396 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
4397 break;
4398 }
4399
4400 case Type::ConstantArray: {
4401 const auto *cat = cast<ConstantArrayType>(ty);
4402 result = getConstantArrayType(
4403 getVariableArrayDecayedType(cat->getElementType()),
4404 cat->getSize(),
4405 cat->getSizeExpr(),
4406 cat->getSizeModifier(),
4407 cat->getIndexTypeCVRQualifiers());
4408 break;
4409 }
4410
4411 case Type::DependentSizedArray: {
4412 const auto *dat = cast<DependentSizedArrayType>(ty);
4414 getVariableArrayDecayedType(dat->getElementType()), dat->getSizeExpr(),
4415 dat->getSizeModifier(), dat->getIndexTypeCVRQualifiers());
4416 break;
4417 }
4418
4419 // Turn incomplete types into [*] types.
4420 case Type::IncompleteArray: {
4421 const auto *iat = cast<IncompleteArrayType>(ty);
4422 result =
4424 /*size*/ nullptr, ArraySizeModifier::Normal,
4425 iat->getIndexTypeCVRQualifiers());
4426 break;
4427 }
4428
4429 // Turn VLA types into [*] types.
4430 case Type::VariableArray: {
4431 const auto *vat = cast<VariableArrayType>(ty);
4432 result =
4434 /*size*/ nullptr, ArraySizeModifier::Star,
4435 vat->getIndexTypeCVRQualifiers());
4436 break;
4437 }
4438 }
4439
4440 // Apply the top-level qualifiers from the original.
4441 return getQualifiedType(result, split.Quals);
4442}
4443
4444/// getVariableArrayType - Returns a non-unique reference to the type for a
4445/// variable array of the specified element type.
4448 unsigned IndexTypeQuals) const {
4449 // Since we don't unique expressions, it isn't possible to unique VLA's
4450 // that have an expression provided for their size.
4451 QualType Canon;
4452
4453 // Be sure to pull qualifiers off the element type.
4454 // FIXME: Check below should look for qualifiers behind sugar.
4455 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
4456 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4457 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
4458 IndexTypeQuals);
4459 Canon = getQualifiedType(Canon, canonSplit.Quals);
4460 }
4461
4462 auto *New = new (*this, alignof(VariableArrayType))
4463 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals);
4464
4465 VariableArrayTypes.push_back(New);
4466 Types.push_back(New);
4467 return QualType(New, 0);
4468}
4469
4470/// getDependentSizedArrayType - Returns a non-unique reference to
4471/// the type for a dependently-sized array of the specified element
4472/// type.
4476 unsigned elementTypeQuals) const {
4477 assert((!numElements || numElements->isTypeDependent() ||
4478 numElements->isValueDependent()) &&
4479 "Size must be type- or value-dependent!");
4480
4481 SplitQualType canonElementType = getCanonicalType(elementType).split();
4482
4483 void *insertPos = nullptr;
4484 llvm::FoldingSetNodeID ID;
4486 ID, *this, numElements ? QualType(canonElementType.Ty, 0) : elementType,
4487 ASM, elementTypeQuals, numElements);
4488
4489 // Look for an existing type with these properties.
4490 DependentSizedArrayType *canonTy =
4491 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4492
4493 // Dependently-sized array types that do not have a specified number
4494 // of elements will have their sizes deduced from a dependent
4495 // initializer.
4496 if (!numElements) {
4497 if (canonTy)
4498 return QualType(canonTy, 0);
4499
4500 auto *newType = new (*this, alignof(DependentSizedArrayType))
4501 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
4502 elementTypeQuals);
4503 DependentSizedArrayTypes.InsertNode(newType, insertPos);
4504 Types.push_back(newType);
4505 return QualType(newType, 0);
4506 }
4507
4508 // If we don't have one, build one.
4509 if (!canonTy) {
4510 canonTy = new (*this, alignof(DependentSizedArrayType))
4511 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
4512 numElements, ASM, elementTypeQuals);
4513 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
4514 Types.push_back(canonTy);
4515 }
4516
4517 // Apply qualifiers from the element type to the array.
4518 QualType canon = getQualifiedType(QualType(canonTy,0),
4519 canonElementType.Quals);
4520
4521 // If we didn't need extra canonicalization for the element type or the size
4522 // expression, then just use that as our result.
4523 if (QualType(canonElementType.Ty, 0) == elementType &&
4524 canonTy->getSizeExpr() == numElements)
4525 return canon;
4526
4527 // Otherwise, we need to build a type which follows the spelling
4528 // of the element type.
4529 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
4530 DependentSizedArrayType(elementType, canon, numElements, ASM,
4531 elementTypeQuals);
4532 Types.push_back(sugaredType);
4533 return QualType(sugaredType, 0);
4534}
4535
4538 unsigned elementTypeQuals) const {
4539 llvm::FoldingSetNodeID ID;
4540 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
4541
4542 void *insertPos = nullptr;
4543 if (IncompleteArrayType *iat =
4544 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
4545 return QualType(iat, 0);
4546
4547 // If the element type isn't canonical, this won't be a canonical type
4548 // either, so fill in the canonical type field. We also have to pull
4549 // qualifiers off the element type.
4550 QualType canon;
4551
4552 // FIXME: Check below should look for qualifiers behind sugar.
4553 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
4554 SplitQualType canonSplit = getCanonicalType(elementType).split();
4555 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
4556 ASM, elementTypeQuals);
4557 canon = getQualifiedType(canon, canonSplit.Quals);
4558
4559 // Get the new insert position for the node we care about.
4560 IncompleteArrayType *existing =
4561 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4562 assert(!existing && "Shouldn't be in the map!"); (void) existing;
4563 }
4564
4565 auto *newType = new (*this, alignof(IncompleteArrayType))
4566 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
4567
4568 IncompleteArrayTypes.InsertNode(newType, insertPos);
4569 Types.push_back(newType);
4570 return QualType(newType, 0);
4571}
4572
4575#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
4576 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
4577 NUMVECTORS};
4578
4579#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
4580 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
4581
4582 switch (Ty->getKind()) {
4583 default:
4584 llvm_unreachable("Unsupported builtin vector type");
4585
4586#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4587 ElBits, NF, IsSigned) \
4588 case BuiltinType::Id: \
4589 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4590 llvm::ElementCount::getScalable(NumEls), NF};
4591#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4592 ElBits, NF) \
4593 case BuiltinType::Id: \
4594 return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy), \
4595 llvm::ElementCount::getScalable(NumEls), NF};
4596#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4597 ElBits, NF) \
4598 case BuiltinType::Id: \
4599 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4600#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4601 ElBits, NF) \
4602 case BuiltinType::Id: \
4603 return {MFloat8Ty, llvm::ElementCount::getScalable(NumEls), NF};
4604#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4605 case BuiltinType::Id: \
4606 return {BoolTy, llvm::ElementCount::getScalable(NumEls), NF};
4607#include "clang/Basic/AArch64ACLETypes.def"
4608
4609#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4610 IsSigned) \
4611 case BuiltinType::Id: \
4612 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4613 llvm::ElementCount::getScalable(NumEls), NF};
4614#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4615 case BuiltinType::Id: \
4616 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4617 llvm::ElementCount::getScalable(NumEls), NF};
4618#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4619 case BuiltinType::Id: \
4620 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4621#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4622 case BuiltinType::Id: \
4623 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4624#include "clang/Basic/RISCVVTypes.def"
4625 }
4626}
4627
4628/// getExternrefType - Return a WebAssembly externref type, which represents an
4629/// opaque reference to a host value.
4631 if (Target->getTriple().isWasm() && Target->hasFeature("reference-types")) {
4632#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4633 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4634 return SingletonId;
4635#include "clang/Basic/WebAssemblyReferenceTypes.def"
4636 }
4637 llvm_unreachable(
4638 "shouldn't try to generate type externref outside WebAssembly target");
4639}
4640
4641/// getScalableVectorType - Return the unique reference to a scalable vector
4642/// type of the specified element type and size. VectorType must be a built-in
4643/// type.
4645 unsigned NumFields) const {
4646 auto K = llvm::ScalableVecTyKey{EltTy, NumElts, NumFields};
4647 if (auto It = ScalableVecTyMap.find(K); It != ScalableVecTyMap.end())
4648 return It->second;
4649
4650 if (Target->hasAArch64ACLETypes()) {
4651 uint64_t EltTySize = getTypeSize(EltTy);
4652
4653#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4654 ElBits, NF, IsSigned) \
4655 if (EltTy->hasIntegerRepresentation() && !EltTy->isBooleanType() && \
4656 EltTy->hasSignedIntegerRepresentation() == IsSigned && \
4657 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4658 return ScalableVecTyMap[K] = SingletonId; \
4659 }
4660#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4661 ElBits, NF) \
4662 if (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4663 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4664 return ScalableVecTyMap[K] = SingletonId; \
4665 }
4666#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4667 ElBits, NF) \
4668 if (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4669 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4670 return ScalableVecTyMap[K] = SingletonId; \
4671 }
4672#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4673 ElBits, NF) \
4674 if (EltTy->isMFloat8Type() && EltTySize == ElBits && \
4675 NumElts == (NumEls * NF) && NumFields == 1) { \
4676 return ScalableVecTyMap[K] = SingletonId; \
4677 }
4678#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4679 if (EltTy->isBooleanType() && NumElts == (NumEls * NF) && NumFields == 1) \
4680 return ScalableVecTyMap[K] = SingletonId;
4681#include "clang/Basic/AArch64ACLETypes.def"
4682 } else if (Target->hasRISCVVTypes()) {
4683 uint64_t EltTySize = getTypeSize(EltTy);
4684#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4685 IsFP, IsBF) \
4686 if (!EltTy->isBooleanType() && \
4687 ((EltTy->hasIntegerRepresentation() && \
4688 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4689 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4690 IsFP && !IsBF) || \
4691 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4692 IsBF && !IsFP)) && \
4693 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4694 return ScalableVecTyMap[K] = SingletonId;
4695#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4696 if (EltTy->isBooleanType() && NumElts == NumEls) \
4697 return ScalableVecTyMap[K] = SingletonId;
4698#include "clang/Basic/RISCVVTypes.def"
4699 }
4700 return QualType();
4701}
4702
4703/// getVectorType - Return the unique reference to a vector type of
4704/// the specified element type and size. VectorType must be a built-in type.
4706 VectorKind VecKind) const {
4707 assert(vecType->isBuiltinType() ||
4708 (vecType->isBitIntType() &&
4709 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4710 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4711
4712 // Check if we've already instantiated a vector of this type.
4713 llvm::FoldingSetNodeID ID;
4714 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
4715
4716 void *InsertPos = nullptr;
4717 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4718 return QualType(VTP, 0);
4719
4720 // If the element type isn't canonical, this won't be a canonical type either,
4721 // so fill in the canonical type field.
4722 QualType Canonical;
4723 if (!vecType.isCanonical()) {
4724 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4725
4726 // Get the new insert position for the node we care about.
4727 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4728 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4729 }
4730 auto *New = new (*this, alignof(VectorType))
4731 VectorType(vecType, NumElts, Canonical, VecKind);
4732 VectorTypes.InsertNode(New, InsertPos);
4733 Types.push_back(New);
4734 return QualType(New, 0);
4735}
4736
4738 SourceLocation AttrLoc,
4739 VectorKind VecKind) const {
4740 llvm::FoldingSetNodeID ID;
4741 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4742 VecKind);
4743 void *InsertPos = nullptr;
4744 DependentVectorType *Canon =
4745 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4747
4748 if (Canon) {
4749 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4750 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4751 } else {
4752 QualType CanonVecTy = getCanonicalType(VecType);
4753 if (CanonVecTy == VecType) {
4754 New = new (*this, alignof(DependentVectorType))
4755 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4756
4757 DependentVectorType *CanonCheck =
4758 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4759 assert(!CanonCheck &&
4760 "Dependent-sized vector_size canonical type broken");
4761 (void)CanonCheck;
4762 DependentVectorTypes.InsertNode(New, InsertPos);
4763 } else {
4764 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4765 SourceLocation(), VecKind);
4766 New = new (*this, alignof(DependentVectorType))
4767 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4768 }
4769 }
4770
4771 Types.push_back(New);
4772 return QualType(New, 0);
4773}
4774
4775/// getExtVectorType - Return the unique reference to an extended vector type of
4776/// the specified element type and size. VectorType must be a built-in type.
4778 unsigned NumElts) const {
4779 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4780 (vecType->isBitIntType() &&
4781 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4782 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4783
4784 // Check if we've already instantiated a vector of this type.
4785 llvm::FoldingSetNodeID ID;
4786 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4788 void *InsertPos = nullptr;
4789 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4790 return QualType(VTP, 0);
4791
4792 // If the element type isn't canonical, this won't be a canonical type either,
4793 // so fill in the canonical type field.
4794 QualType Canonical;
4795 if (!vecType.isCanonical()) {
4796 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4797
4798 // Get the new insert position for the node we care about.
4799 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4800 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4801 }
4802 auto *New = new (*this, alignof(ExtVectorType))
4803 ExtVectorType(vecType, NumElts, Canonical);
4804 VectorTypes.InsertNode(New, InsertPos);
4805 Types.push_back(New);
4806 return QualType(New, 0);
4807}
4808
4811 Expr *SizeExpr,
4812 SourceLocation AttrLoc) const {
4813 llvm::FoldingSetNodeID ID;
4815 SizeExpr);
4816
4817 void *InsertPos = nullptr;
4819 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4821 if (Canon) {
4822 // We already have a canonical version of this array type; use it as
4823 // the canonical type for a newly-built type.
4824 New = new (*this, alignof(DependentSizedExtVectorType))
4825 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4826 AttrLoc);
4827 } else {
4828 QualType CanonVecTy = getCanonicalType(vecType);
4829 if (CanonVecTy == vecType) {
4830 New = new (*this, alignof(DependentSizedExtVectorType))
4831 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4832
4833 DependentSizedExtVectorType *CanonCheck
4834 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4835 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4836 (void)CanonCheck;
4837 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4838 } else {
4839 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4840 SourceLocation());
4841 New = new (*this, alignof(DependentSizedExtVectorType))
4842 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4843 }
4844 }
4845
4846 Types.push_back(New);
4847 return QualType(New, 0);
4848}
4849
4851 unsigned NumColumns) const {
4852 llvm::FoldingSetNodeID ID;
4853 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4854 Type::ConstantMatrix);
4855
4856 assert(MatrixType::isValidElementType(ElementTy, getLangOpts()) &&
4857 "need a valid element type");
4858 assert(NumRows > 0 && NumRows <= LangOpts.MaxMatrixDimension &&
4859 NumColumns > 0 && NumColumns <= LangOpts.MaxMatrixDimension &&
4860 "need valid matrix dimensions");
4861 void *InsertPos = nullptr;
4862 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4863 return QualType(MTP, 0);
4864
4865 QualType Canonical;
4866 if (!ElementTy.isCanonical()) {
4867 Canonical =
4868 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4869
4870 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4871 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4872 (void)NewIP;
4873 }
4874
4875 auto *New = new (*this, alignof(ConstantMatrixType))
4876 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4877 MatrixTypes.InsertNode(New, InsertPos);
4878 Types.push_back(New);
4879 return QualType(New, 0);
4880}
4881
4883 Expr *RowExpr,
4884 Expr *ColumnExpr,
4885 SourceLocation AttrLoc) const {
4886 QualType CanonElementTy = getCanonicalType(ElementTy);
4887 llvm::FoldingSetNodeID ID;
4888 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4889 ColumnExpr);
4890
4891 void *InsertPos = nullptr;
4893 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4894
4895 if (!Canon) {
4896 Canon = new (*this, alignof(DependentSizedMatrixType))
4897 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4898 ColumnExpr, AttrLoc);
4899#ifndef NDEBUG
4900 DependentSizedMatrixType *CanonCheck =
4901 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4902 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4903#endif
4904 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4905 Types.push_back(Canon);
4906 }
4907
4908 // Already have a canonical version of the matrix type
4909 //
4910 // If it exactly matches the requested type, use it directly.
4911 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4912 Canon->getRowExpr() == ColumnExpr)
4913 return QualType(Canon, 0);
4914
4915 // Use Canon as the canonical type for newly-built type.
4917 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4918 ColumnExpr, AttrLoc);
4919 Types.push_back(New);
4920 return QualType(New, 0);
4921}
4922
4924 Expr *AddrSpaceExpr,
4925 SourceLocation AttrLoc) const {
4926 assert(AddrSpaceExpr->isInstantiationDependent());
4927
4928 QualType canonPointeeType = getCanonicalType(PointeeType);
4929
4930 void *insertPos = nullptr;
4931 llvm::FoldingSetNodeID ID;
4932 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4933 AddrSpaceExpr);
4934
4935 DependentAddressSpaceType *canonTy =
4936 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4937
4938 if (!canonTy) {
4939 canonTy = new (*this, alignof(DependentAddressSpaceType))
4940 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
4941 AttrLoc);
4942 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4943 Types.push_back(canonTy);
4944 }
4945
4946 if (canonPointeeType == PointeeType &&
4947 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4948 return QualType(canonTy, 0);
4949
4950 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
4951 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
4952 AddrSpaceExpr, AttrLoc);
4953 Types.push_back(sugaredType);
4954 return QualType(sugaredType, 0);
4955}
4956
4957/// Determine whether \p T is canonical as the result type of a function.
4959 return T.isCanonical() &&
4960 (T.getObjCLifetime() == Qualifiers::OCL_None ||
4961 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4962}
4963
4964/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4965QualType
4967 const FunctionType::ExtInfo &Info) const {
4968 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
4969 // functionality creates a function without a prototype regardless of
4970 // language mode (so it makes them even in C++). Once the rewriter has been
4971 // fixed, this assertion can be enabled again.
4972 //assert(!LangOpts.requiresStrictPrototypes() &&
4973 // "strict prototypes are disabled");
4974
4975 // Unique functions, to guarantee there is only one function of a particular
4976 // structure.
4977 llvm::FoldingSetNodeID ID;
4978 FunctionNoProtoType::Profile(ID, ResultTy, Info);
4979
4980 void *InsertPos = nullptr;
4981 if (FunctionNoProtoType *FT =
4982 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4983 return QualType(FT, 0);
4984
4985 QualType Canonical;
4986 if (!isCanonicalResultType(ResultTy)) {
4987 Canonical =
4989
4990 // Get the new insert position for the node we care about.
4991 FunctionNoProtoType *NewIP =
4992 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4993 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4994 }
4995
4996 auto *New = new (*this, alignof(FunctionNoProtoType))
4997 FunctionNoProtoType(ResultTy, Canonical, Info);
4998 Types.push_back(New);
4999 FunctionNoProtoTypes.InsertNode(New, InsertPos);
5000 return QualType(New, 0);
5001}
5002
5005 CanQualType CanResultType = getCanonicalType(ResultType);
5006
5007 // Canonical result types do not have ARC lifetime qualifiers.
5008 if (CanResultType.getQualifiers().hasObjCLifetime()) {
5009 Qualifiers Qs = CanResultType.getQualifiers();
5010 Qs.removeObjCLifetime();
5012 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
5013 }
5014
5015 return CanResultType;
5016}
5017
5019 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
5020 if (ESI.Type == EST_None)
5021 return true;
5022 if (!NoexceptInType)
5023 return false;
5024
5025 // C++17 onwards: exception specification is part of the type, as a simple
5026 // boolean "can this function type throw".
5027 if (ESI.Type == EST_BasicNoexcept)
5028 return true;
5029
5030 // A noexcept(expr) specification is (possibly) canonical if expr is
5031 // value-dependent.
5032 if (ESI.Type == EST_DependentNoexcept)
5033 return true;
5034
5035 // A dynamic exception specification is canonical if it only contains pack
5036 // expansions (so we can't tell whether it's non-throwing) and all its
5037 // contained types are canonical.
5038 if (ESI.Type == EST_Dynamic) {
5039 bool AnyPackExpansions = false;
5040 for (QualType ET : ESI.Exceptions) {
5041 if (!ET.isCanonical())
5042 return false;
5043 if (ET->getAs<PackExpansionType>())
5044 AnyPackExpansions = true;
5045 }
5046 return AnyPackExpansions;
5047 }
5048
5049 return false;
5050}
5051
5052QualType ASTContext::getFunctionTypeInternal(
5053 QualType ResultTy, ArrayRef<QualType> ArgArray,
5054 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
5055 size_t NumArgs = ArgArray.size();
5056
5057 // Unique functions, to guarantee there is only one function of a particular
5058 // structure.
5059 llvm::FoldingSetNodeID ID;
5060 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
5061 *this, true);
5062
5063 QualType Canonical;
5064 bool Unique = false;
5065
5066 void *InsertPos = nullptr;
5067 if (FunctionProtoType *FPT =
5068 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
5069 QualType Existing = QualType(FPT, 0);
5070
5071 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
5072 // it so long as our exception specification doesn't contain a dependent
5073 // noexcept expression, or we're just looking for a canonical type.
5074 // Otherwise, we're going to need to create a type
5075 // sugar node to hold the concrete expression.
5076 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
5077 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
5078 return Existing;
5079
5080 // We need a new type sugar node for this one, to hold the new noexcept
5081 // expression. We do no canonicalization here, but that's OK since we don't
5082 // expect to see the same noexcept expression much more than once.
5083 Canonical = getCanonicalType(Existing);
5084 Unique = true;
5085 }
5086
5087 bool NoexceptInType = getLangOpts().CPlusPlus17;
5088 bool IsCanonicalExceptionSpec =
5090
5091 // Determine whether the type being created is already canonical or not.
5092 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
5093 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
5094 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
5095 if (!ArgArray[i].isCanonicalAsParam())
5096 isCanonical = false;
5097
5098 if (OnlyWantCanonical)
5099 assert(isCanonical &&
5100 "given non-canonical parameters constructing canonical type");
5101
5102 // If this type isn't canonical, get the canonical version of it if we don't
5103 // already have it. The exception spec is only partially part of the
5104 // canonical type, and only in C++17 onwards.
5105 if (!isCanonical && Canonical.isNull()) {
5106 SmallVector<QualType, 16> CanonicalArgs;
5107 CanonicalArgs.reserve(NumArgs);
5108 for (unsigned i = 0; i != NumArgs; ++i)
5109 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
5110
5111 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
5112 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
5113 CanonicalEPI.HasTrailingReturn = false;
5114
5115 if (IsCanonicalExceptionSpec) {
5116 // Exception spec is already OK.
5117 } else if (NoexceptInType) {
5118 switch (EPI.ExceptionSpec.Type) {
5120 // We don't know yet. It shouldn't matter what we pick here; no-one
5121 // should ever look at this.
5122 [[fallthrough]];
5123 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
5124 CanonicalEPI.ExceptionSpec.Type = EST_None;
5125 break;
5126
5127 // A dynamic exception specification is almost always "not noexcept",
5128 // with the exception that a pack expansion might expand to no types.
5129 case EST_Dynamic: {
5130 bool AnyPacks = false;
5131 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
5132 if (ET->getAs<PackExpansionType>())
5133 AnyPacks = true;
5134 ExceptionTypeStorage.push_back(getCanonicalType(ET));
5135 }
5136 if (!AnyPacks)
5137 CanonicalEPI.ExceptionSpec.Type = EST_None;
5138 else {
5139 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
5140 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
5141 }
5142 break;
5143 }
5144
5145 case EST_DynamicNone:
5146 case EST_BasicNoexcept:
5147 case EST_NoexceptTrue:
5148 case EST_NoThrow:
5149 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
5150 break;
5151
5153 llvm_unreachable("dependent noexcept is already canonical");
5154 }
5155 } else {
5156 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
5157 }
5158
5159 // Adjust the canonical function result type.
5160 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
5161 Canonical =
5162 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
5163
5164 // Get the new insert position for the node we care about.
5165 FunctionProtoType *NewIP =
5166 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
5167 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5168 }
5169
5170 // Compute the needed size to hold this FunctionProtoType and the
5171 // various trailing objects.
5172 auto ESH = FunctionProtoType::getExceptionSpecSize(
5173 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
5174 size_t Size = FunctionProtoType::totalSizeToAlloc<
5175 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
5176 FunctionType::FunctionTypeExtraAttributeInfo,
5177 FunctionType::FunctionTypeArmAttributes, FunctionType::ExceptionType,
5178 Expr *, FunctionDecl *, FunctionProtoType::ExtParameterInfo, Qualifiers,
5179 FunctionEffect, EffectConditionExpr>(
5182 EPI.requiresFunctionProtoTypeArmAttributes(), ESH.NumExceptionType,
5183 ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
5184 EPI.ExtParameterInfos ? NumArgs : 0,
5186 EPI.FunctionEffects.conditions().size());
5187
5188 auto *FTP = (FunctionProtoType *)Allocate(Size, alignof(FunctionProtoType));
5189 FunctionProtoType::ExtProtoInfo newEPI = EPI;
5190 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
5191 Types.push_back(FTP);
5192 if (!Unique)
5193 FunctionProtoTypes.InsertNode(FTP, InsertPos);
5194 if (!EPI.FunctionEffects.empty())
5195 AnyFunctionEffects = true;
5196 return QualType(FTP, 0);
5197}
5198
5199QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
5200 llvm::FoldingSetNodeID ID;
5201 PipeType::Profile(ID, T, ReadOnly);
5202
5203 void *InsertPos = nullptr;
5204 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
5205 return QualType(PT, 0);
5206
5207 // If the pipe element type isn't canonical, this won't be a canonical type
5208 // either, so fill in the canonical type field.
5209 QualType Canonical;
5210 if (!T.isCanonical()) {
5211 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
5212
5213 // Get the new insert position for the node we care about.
5214 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
5215 assert(!NewIP && "Shouldn't be in the map!");
5216 (void)NewIP;
5217 }
5218 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
5219 Types.push_back(New);
5220 PipeTypes.InsertNode(New, InsertPos);
5221 return QualType(New, 0);
5222}
5223
5225 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
5226 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
5227 : Ty;
5228}
5229
5231 return getPipeType(T, true);
5232}
5233
5235 return getPipeType(T, false);
5236}
5237
5238QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
5239 llvm::FoldingSetNodeID ID;
5240 BitIntType::Profile(ID, IsUnsigned, NumBits);
5241
5242 void *InsertPos = nullptr;
5243 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5244 return QualType(EIT, 0);
5245
5246 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
5247 BitIntTypes.InsertNode(New, InsertPos);
5248 Types.push_back(New);
5249 return QualType(New, 0);
5250}
5251
5253 Expr *NumBitsExpr) const {
5254 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
5255 llvm::FoldingSetNodeID ID;
5256 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
5257
5258 void *InsertPos = nullptr;
5259 if (DependentBitIntType *Existing =
5260 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5261 return QualType(Existing, 0);
5262
5263 auto *New = new (*this, alignof(DependentBitIntType))
5264 DependentBitIntType(IsUnsigned, NumBitsExpr);
5265 DependentBitIntTypes.InsertNode(New, InsertPos);
5266
5267 Types.push_back(New);
5268 return QualType(New, 0);
5269}
5270
5273 using Kind = PredefinedSugarType::Kind;
5274
5275 if (auto *Target = PredefinedSugarTypes[llvm::to_underlying(KD)];
5276 Target != nullptr)
5277 return QualType(Target, 0);
5278
5279 auto getCanonicalType = [](const ASTContext &Ctx, Kind KDI) -> QualType {
5280 switch (KDI) {
5281 // size_t (C99TC3 6.5.3.4), signed size_t (C++23 5.13.2) and
5282 // ptrdiff_t (C99TC3 6.5.6) Although these types are not built-in, they
5283 // are part of the core language and are widely used. Using
5284 // PredefinedSugarType makes these types as named sugar types rather than
5285 // standard integer types, enabling better hints and diagnostics.
5286 case Kind::SizeT:
5287 return Ctx.getFromTargetType(Ctx.Target->getSizeType());
5288 case Kind::SignedSizeT:
5289 return Ctx.getFromTargetType(Ctx.Target->getSignedSizeType());
5290 case Kind::PtrdiffT:
5291 return Ctx.getFromTargetType(Ctx.Target->getPtrDiffType(LangAS::Default));
5292 }
5293 llvm_unreachable("unexpected kind");
5294 };
5295 auto *New = new (*this, alignof(PredefinedSugarType))
5296 PredefinedSugarType(KD, &Idents.get(PredefinedSugarType::getName(KD)),
5297 getCanonicalType(*this, static_cast<Kind>(KD)));
5298 Types.push_back(New);
5299 PredefinedSugarTypes[llvm::to_underlying(KD)] = New;
5300 return QualType(New, 0);
5301}
5302
5304 NestedNameSpecifier Qualifier,
5305 const TypeDecl *Decl) const {
5306 if (auto *Tag = dyn_cast<TagDecl>(Decl))
5307 return getTagType(Keyword, Qualifier, Tag,
5308 /*OwnsTag=*/false);
5309 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
5310 return getTypedefType(Keyword, Qualifier, Typedef);
5311 if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5312 return getUnresolvedUsingType(Keyword, Qualifier, UD);
5313
5315 assert(!Qualifier);
5316 return QualType(Decl->TypeForDecl, 0);
5317}
5318
5320 if (auto *Tag = dyn_cast<TagDecl>(TD))
5321 return getCanonicalTagType(Tag);
5322 if (auto *TN = dyn_cast<TypedefNameDecl>(TD))
5323 return getCanonicalType(TN->getUnderlyingType());
5324 if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD))
5326 assert(TD->TypeForDecl);
5327 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5328}
5329
5331 if (const auto *TD = dyn_cast<TagDecl>(Decl))
5332 return getCanonicalTagType(TD);
5333 if (const auto *TD = dyn_cast<TypedefNameDecl>(Decl);
5334 isa_and_nonnull<TypedefDecl, TypeAliasDecl>(TD))
5336 /*Qualifier=*/std::nullopt, TD);
5337 if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5338 return getCanonicalUnresolvedUsingType(Using);
5339
5340 assert(Decl->TypeForDecl);
5341 return QualType(Decl->TypeForDecl, 0);
5342}
5343
5344/// getTypedefType - Return the unique reference to the type for the
5345/// specified typedef name decl.
5348 NestedNameSpecifier Qualifier,
5349 const TypedefNameDecl *Decl, QualType UnderlyingType,
5350 std::optional<bool> TypeMatchesDeclOrNone) const {
5351 if (!TypeMatchesDeclOrNone) {
5352 QualType DeclUnderlyingType = Decl->getUnderlyingType();
5353 assert(!DeclUnderlyingType.isNull());
5354 if (UnderlyingType.isNull())
5355 UnderlyingType = DeclUnderlyingType;
5356 else
5357 assert(hasSameType(UnderlyingType, DeclUnderlyingType));
5358 TypeMatchesDeclOrNone = UnderlyingType == DeclUnderlyingType;
5359 } else {
5360 // FIXME: This is a workaround for a serialization cycle: assume the decl
5361 // underlying type is not available; don't touch it.
5362 assert(!UnderlyingType.isNull());
5363 }
5364
5365 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier &&
5366 *TypeMatchesDeclOrNone) {
5367 if (Decl->TypeForDecl)
5368 return QualType(Decl->TypeForDecl, 0);
5369
5370 auto *NewType = new (*this, alignof(TypedefType))
5371 TypedefType(Type::Typedef, Keyword, Qualifier, Decl, UnderlyingType,
5372 !*TypeMatchesDeclOrNone);
5373
5374 Types.push_back(NewType);
5375 Decl->TypeForDecl = NewType;
5376 return QualType(NewType, 0);
5377 }
5378
5379 llvm::FoldingSetNodeID ID;
5380 TypedefType::Profile(ID, Keyword, Qualifier, Decl,
5381 *TypeMatchesDeclOrNone ? QualType() : UnderlyingType);
5382
5383 void *InsertPos = nullptr;
5384 if (FoldingSetPlaceholder<TypedefType> *Placeholder =
5385 TypedefTypes.FindNodeOrInsertPos(ID, InsertPos))
5386 return QualType(Placeholder->getType(), 0);
5387
5388 void *Mem =
5389 Allocate(TypedefType::totalSizeToAlloc<FoldingSetPlaceholder<TypedefType>,
5391 1, !!Qualifier, !*TypeMatchesDeclOrNone),
5392 alignof(TypedefType));
5393 auto *NewType =
5394 new (Mem) TypedefType(Type::Typedef, Keyword, Qualifier, Decl,
5395 UnderlyingType, !*TypeMatchesDeclOrNone);
5396 auto *Placeholder = new (NewType->getFoldingSetPlaceholder())
5398 TypedefTypes.InsertNode(Placeholder, InsertPos);
5399 Types.push_back(NewType);
5400 return QualType(NewType, 0);
5401}
5402
5404 NestedNameSpecifier Qualifier,
5405 const UsingShadowDecl *D,
5406 QualType UnderlyingType) const {
5407 // FIXME: This is expensive to compute every time!
5408 if (UnderlyingType.isNull()) {
5409 const auto *UD = cast<UsingDecl>(D->getIntroducer());
5410 UnderlyingType =
5413 UD->getQualifier(), cast<TypeDecl>(D->getTargetDecl()));
5414 }
5415
5416 llvm::FoldingSetNodeID ID;
5417 UsingType::Profile(ID, Keyword, Qualifier, D, UnderlyingType);
5418
5419 void *InsertPos = nullptr;
5420 if (const UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5421 return QualType(T, 0);
5422
5423 assert(!UnderlyingType.hasLocalQualifiers());
5424
5425 assert(
5427 UnderlyingType));
5428
5429 void *Mem =
5430 Allocate(UsingType::totalSizeToAlloc<NestedNameSpecifier>(!!Qualifier),
5431 alignof(UsingType));
5432 UsingType *T = new (Mem) UsingType(Keyword, Qualifier, D, UnderlyingType);
5433 Types.push_back(T);
5434 UsingTypes.InsertNode(T, InsertPos);
5435 return QualType(T, 0);
5436}
5437
5438TagType *ASTContext::getTagTypeInternal(ElaboratedTypeKeyword Keyword,
5439 NestedNameSpecifier Qualifier,
5440 const TagDecl *TD, bool OwnsTag,
5441 bool IsInjected,
5442 const Type *CanonicalType,
5443 bool WithFoldingSetNode) const {
5444 auto [TC, Size] = [&] {
5445 switch (TD->getDeclKind()) {
5446 case Decl::Enum:
5447 static_assert(alignof(EnumType) == alignof(TagType));
5448 return std::make_tuple(Type::Enum, sizeof(EnumType));
5449 case Decl::ClassTemplatePartialSpecialization:
5450 case Decl::ClassTemplateSpecialization:
5451 case Decl::CXXRecord:
5452 static_assert(alignof(RecordType) == alignof(TagType));
5453 static_assert(alignof(InjectedClassNameType) == alignof(TagType));
5454 if (cast<CXXRecordDecl>(TD)->hasInjectedClassType())
5455 return std::make_tuple(Type::InjectedClassName,
5456 sizeof(InjectedClassNameType));
5457 [[fallthrough]];
5458 case Decl::Record:
5459 return std::make_tuple(Type::Record, sizeof(RecordType));
5460 default:
5461 llvm_unreachable("unexpected decl kind");
5462 }
5463 }();
5464
5465 if (Qualifier) {
5466 static_assert(alignof(NestedNameSpecifier) <= alignof(TagType));
5467 Size = llvm::alignTo(Size, alignof(NestedNameSpecifier)) +
5468 sizeof(NestedNameSpecifier);
5469 }
5470 void *Mem;
5471 if (WithFoldingSetNode) {
5472 // FIXME: It would be more profitable to tail allocate the folding set node
5473 // from the type, instead of the other way around, due to the greater
5474 // alignment requirements of the type. But this makes it harder to deal with
5475 // the different type node sizes. This would require either uniquing from
5476 // different folding sets, or having the folding setaccept a
5477 // contextual parameter which is not fixed at construction.
5478 Mem = Allocate(
5479 sizeof(TagTypeFoldingSetPlaceholder) +
5480 TagTypeFoldingSetPlaceholder::getOffset() + Size,
5481 std::max(alignof(TagTypeFoldingSetPlaceholder), alignof(TagType)));
5482 auto *T = new (Mem) TagTypeFoldingSetPlaceholder();
5483 Mem = T->getTagType();
5484 } else {
5485 Mem = Allocate(Size, alignof(TagType));
5486 }
5487
5488 auto *T = [&, TC = TC]() -> TagType * {
5489 switch (TC) {
5490 case Type::Enum: {
5491 assert(isa<EnumDecl>(TD));
5492 auto *T = new (Mem) EnumType(TC, Keyword, Qualifier, TD, OwnsTag,
5493 IsInjected, CanonicalType);
5494 assert(reinterpret_cast<void *>(T) ==
5495 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5496 "TagType must be the first base of EnumType");
5497 return T;
5498 }
5499 case Type::Record: {
5500 assert(isa<RecordDecl>(TD));
5501 auto *T = new (Mem) RecordType(TC, Keyword, Qualifier, TD, OwnsTag,
5502 IsInjected, CanonicalType);
5503 assert(reinterpret_cast<void *>(T) ==
5504 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5505 "TagType must be the first base of RecordType");
5506 return T;
5507 }
5508 case Type::InjectedClassName: {
5509 auto *T = new (Mem) InjectedClassNameType(Keyword, Qualifier, TD,
5510 IsInjected, CanonicalType);
5511 assert(reinterpret_cast<void *>(T) ==
5512 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5513 "TagType must be the first base of InjectedClassNameType");
5514 return T;
5515 }
5516 default:
5517 llvm_unreachable("unexpected type class");
5518 }
5519 }();
5520 assert(T->getKeyword() == Keyword);
5521 assert(T->getQualifier() == Qualifier);
5522 assert(T->getDecl() == TD);
5523 assert(T->isInjected() == IsInjected);
5524 assert(T->isTagOwned() == OwnsTag);
5525 assert((T->isCanonicalUnqualified()
5526 ? QualType()
5527 : T->getCanonicalTypeInternal()) == QualType(CanonicalType, 0));
5528 Types.push_back(T);
5529 return T;
5530}
5531
5532static const TagDecl *getNonInjectedClassName(const TagDecl *TD) {
5533 if (const auto *RD = dyn_cast<CXXRecordDecl>(TD);
5534 RD && RD->isInjectedClassName())
5535 return cast<TagDecl>(RD->getDeclContext());
5536 return TD;
5537}
5538
5541 if (TD->TypeForDecl)
5542 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5543
5544 const Type *CanonicalType = getTagTypeInternal(
5546 /*Qualifier=*/std::nullopt, TD,
5547 /*OwnsTag=*/false, /*IsInjected=*/false, /*CanonicalType=*/nullptr,
5548 /*WithFoldingSetNode=*/false);
5549 TD->TypeForDecl = CanonicalType;
5550 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5551}
5552
5554 NestedNameSpecifier Qualifier,
5555 const TagDecl *TD, bool OwnsTag) const {
5556
5557 const TagDecl *NonInjectedTD = ::getNonInjectedClassName(TD);
5558 bool IsInjected = TD != NonInjectedTD;
5559
5560 ElaboratedTypeKeyword PreferredKeyword =
5563 NonInjectedTD->getTagKind());
5564
5565 if (Keyword == PreferredKeyword && !Qualifier && !OwnsTag) {
5566 if (const Type *T = TD->TypeForDecl; T && !T->isCanonicalUnqualified())
5567 return QualType(T, 0);
5568
5569 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5570 const Type *T =
5571 getTagTypeInternal(Keyword,
5572 /*Qualifier=*/std::nullopt, NonInjectedTD,
5573 /*OwnsTag=*/false, IsInjected, CanonicalType,
5574 /*WithFoldingSetNode=*/false);
5575 TD->TypeForDecl = T;
5576 return QualType(T, 0);
5577 }
5578
5579 llvm::FoldingSetNodeID ID;
5580 TagTypeFoldingSetPlaceholder::Profile(ID, Keyword, Qualifier, NonInjectedTD,
5581 OwnsTag, IsInjected);
5582
5583 void *InsertPos = nullptr;
5584 if (TagTypeFoldingSetPlaceholder *T =
5585 TagTypes.FindNodeOrInsertPos(ID, InsertPos))
5586 return QualType(T->getTagType(), 0);
5587
5588 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5589 TagType *T =
5590 getTagTypeInternal(Keyword, Qualifier, NonInjectedTD, OwnsTag, IsInjected,
5591 CanonicalType, /*WithFoldingSetNode=*/true);
5592 TagTypes.InsertNode(TagTypeFoldingSetPlaceholder::fromTagType(T), InsertPos);
5593 return QualType(T, 0);
5594}
5595
5596bool ASTContext::computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits,
5597 unsigned NumPositiveBits,
5598 QualType &BestType,
5599 QualType &BestPromotionType) {
5600 unsigned IntWidth = Target->getIntWidth();
5601 unsigned CharWidth = Target->getCharWidth();
5602 unsigned ShortWidth = Target->getShortWidth();
5603 bool EnumTooLarge = false;
5604 unsigned BestWidth;
5605 if (NumNegativeBits) {
5606 // If there is a negative value, figure out the smallest integer type (of
5607 // int/long/longlong) that fits.
5608 // If it's packed, check also if it fits a char or a short.
5609 if (IsPacked && NumNegativeBits <= CharWidth &&
5610 NumPositiveBits < CharWidth) {
5611 BestType = SignedCharTy;
5612 BestWidth = CharWidth;
5613 } else if (IsPacked && NumNegativeBits <= ShortWidth &&
5614 NumPositiveBits < ShortWidth) {
5615 BestType = ShortTy;
5616 BestWidth = ShortWidth;
5617 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5618 BestType = IntTy;
5619 BestWidth = IntWidth;
5620 } else {
5621 BestWidth = Target->getLongWidth();
5622
5623 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
5624 BestType = LongTy;
5625 } else {
5626 BestWidth = Target->getLongLongWidth();
5627
5628 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5629 EnumTooLarge = true;
5630 BestType = LongLongTy;
5631 }
5632 }
5633 BestPromotionType = (BestWidth <= IntWidth ? IntTy : BestType);
5634 } else {
5635 // If there is no negative value, figure out the smallest type that fits
5636 // all of the enumerator values.
5637 // If it's packed, check also if it fits a char or a short.
5638 if (IsPacked && NumPositiveBits <= CharWidth) {
5639 BestType = UnsignedCharTy;
5640 BestPromotionType = IntTy;
5641 BestWidth = CharWidth;
5642 } else if (IsPacked && NumPositiveBits <= ShortWidth) {
5643 BestType = UnsignedShortTy;
5644 BestPromotionType = IntTy;
5645 BestWidth = ShortWidth;
5646 } else if (NumPositiveBits <= IntWidth) {
5647 BestType = UnsignedIntTy;
5648 BestWidth = IntWidth;
5649 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5651 : IntTy;
5652 } else if (NumPositiveBits <= (BestWidth = Target->getLongWidth())) {
5653 BestType = UnsignedLongTy;
5654 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5656 : LongTy;
5657 } else {
5658 BestWidth = Target->getLongLongWidth();
5659 if (NumPositiveBits > BestWidth) {
5660 // This can happen with bit-precise integer types, but those are not
5661 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
5662 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
5663 // a 128-bit integer, we should consider doing the same.
5664 EnumTooLarge = true;
5665 }
5666 BestType = UnsignedLongLongTy;
5667 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5669 : LongLongTy;
5670 }
5671 }
5672 return EnumTooLarge;
5673}
5674
5676 assert((T->isIntegralType(*this) || T->isEnumeralType()) &&
5677 "Integral type required!");
5678 unsigned BitWidth = getIntWidth(T);
5679
5680 if (Value.isUnsigned() || Value.isNonNegative()) {
5681 if (T->isSignedIntegerOrEnumerationType())
5682 --BitWidth;
5683 return Value.getActiveBits() <= BitWidth;
5684 }
5685 return Value.getSignificantBits() <= BitWidth;
5686}
5687
5688UnresolvedUsingType *ASTContext::getUnresolvedUsingTypeInternal(
5690 const UnresolvedUsingTypenameDecl *D, void *InsertPos,
5691 const Type *CanonicalType) const {
5692 void *Mem = Allocate(
5693 UnresolvedUsingType::totalSizeToAlloc<
5695 !!InsertPos, !!Qualifier),
5696 alignof(UnresolvedUsingType));
5697 auto *T = new (Mem) UnresolvedUsingType(Keyword, Qualifier, D, CanonicalType);
5698 if (InsertPos) {
5699 auto *Placeholder = new (T->getFoldingSetPlaceholder())
5701 TypedefTypes.InsertNode(Placeholder, InsertPos);
5702 }
5703 Types.push_back(T);
5704 return T;
5705}
5706
5708 const UnresolvedUsingTypenameDecl *D) const {
5709 D = D->getCanonicalDecl();
5710 if (D->TypeForDecl)
5711 return D->TypeForDecl->getCanonicalTypeUnqualified();
5712
5713 const Type *CanonicalType = getUnresolvedUsingTypeInternal(
5715 /*Qualifier=*/std::nullopt, D,
5716 /*InsertPos=*/nullptr, /*CanonicalType=*/nullptr);
5717 D->TypeForDecl = CanonicalType;
5718 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5719}
5720
5723 NestedNameSpecifier Qualifier,
5724 const UnresolvedUsingTypenameDecl *D) const {
5725 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier) {
5726 if (const Type *T = D->TypeForDecl; T && !T->isCanonicalUnqualified())
5727 return QualType(T, 0);
5728
5729 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5730 const Type *T =
5731 getUnresolvedUsingTypeInternal(ElaboratedTypeKeyword::None,
5732 /*Qualifier=*/std::nullopt, D,
5733 /*InsertPos=*/nullptr, CanonicalType);
5734 D->TypeForDecl = T;
5735 return QualType(T, 0);
5736 }
5737
5738 llvm::FoldingSetNodeID ID;
5739 UnresolvedUsingType::Profile(ID, Keyword, Qualifier, D);
5740
5741 void *InsertPos = nullptr;
5743 UnresolvedUsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5744 return QualType(Placeholder->getType(), 0);
5745 assert(InsertPos);
5746
5747 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5748 const Type *T = getUnresolvedUsingTypeInternal(Keyword, Qualifier, D,
5749 InsertPos, CanonicalType);
5750 return QualType(T, 0);
5751}
5752
5754 QualType modifiedType,
5755 QualType equivalentType,
5756 const Attr *attr) const {
5757 llvm::FoldingSetNodeID id;
5758 AttributedType::Profile(id, *this, attrKind, modifiedType, equivalentType,
5759 attr);
5760
5761 void *insertPos = nullptr;
5762 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
5763 if (type) return QualType(type, 0);
5764
5765 assert(!attr || attr->getKind() == attrKind);
5766
5767 QualType canon = getCanonicalType(equivalentType);
5768 type = new (*this, alignof(AttributedType))
5769 AttributedType(canon, attrKind, attr, modifiedType, equivalentType);
5770
5771 Types.push_back(type);
5772 AttributedTypes.InsertNode(type, insertPos);
5773
5774 return QualType(type, 0);
5775}
5776
5778 QualType equivalentType) const {
5779 return getAttributedType(attr->getKind(), modifiedType, equivalentType, attr);
5780}
5781
5783 QualType modifiedType,
5784 QualType equivalentType) {
5785 switch (nullability) {
5787 return getAttributedType(attr::TypeNonNull, modifiedType, equivalentType);
5788
5790 return getAttributedType(attr::TypeNullable, modifiedType, equivalentType);
5791
5793 return getAttributedType(attr::TypeNullableResult, modifiedType,
5794 equivalentType);
5795
5797 return getAttributedType(attr::TypeNullUnspecified, modifiedType,
5798 equivalentType);
5799 }
5800
5801 llvm_unreachable("Unknown nullability kind");
5802}
5803
5804QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
5805 QualType Wrapped) const {
5806 llvm::FoldingSetNodeID ID;
5807 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
5808
5809 void *InsertPos = nullptr;
5810 BTFTagAttributedType *Ty =
5811 BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
5812 if (Ty)
5813 return QualType(Ty, 0);
5814
5815 QualType Canon = getCanonicalType(Wrapped);
5816 Ty = new (*this, alignof(BTFTagAttributedType))
5817 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
5818
5819 Types.push_back(Ty);
5820 BTFTagAttributedTypes.InsertNode(Ty, InsertPos);
5821
5822 return QualType(Ty, 0);
5823}
5824
5826 QualType Underlying) const {
5827 const IdentifierInfo *II = Attr->getBehaviorKind();
5828 StringRef IdentName = II->getName();
5829 OverflowBehaviorType::OverflowBehaviorKind Kind;
5830 if (IdentName == "wrap") {
5831 Kind = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
5832 } else if (IdentName == "trap") {
5833 Kind = OverflowBehaviorType::OverflowBehaviorKind::Trap;
5834 } else {
5835 return Underlying;
5836 }
5837
5838 return getOverflowBehaviorType(Kind, Underlying);
5839}
5840
5842 OverflowBehaviorType::OverflowBehaviorKind Kind,
5843 QualType Underlying) const {
5844 assert(!Underlying->isOverflowBehaviorType() &&
5845 "Cannot have underlying types that are themselves OBTs");
5846 llvm::FoldingSetNodeID ID;
5847 OverflowBehaviorType::Profile(ID, Underlying, Kind);
5848 void *InsertPos = nullptr;
5849
5850 if (OverflowBehaviorType *OBT =
5851 OverflowBehaviorTypes.FindNodeOrInsertPos(ID, InsertPos)) {
5852 return QualType(OBT, 0);
5853 }
5854
5855 QualType Canonical;
5856 if (!Underlying.isCanonical() || Underlying.hasLocalQualifiers()) {
5857 SplitQualType canonSplit = getCanonicalType(Underlying).split();
5858 Canonical = getOverflowBehaviorType(Kind, QualType(canonSplit.Ty, 0));
5859 Canonical = getQualifiedType(Canonical, canonSplit.Quals);
5860 assert(!OverflowBehaviorTypes.FindNodeOrInsertPos(ID, InsertPos) &&
5861 "Shouldn't be in the map");
5862 }
5863
5864 OverflowBehaviorType *Ty = new (*this, alignof(OverflowBehaviorType))
5865 OverflowBehaviorType(Canonical, Underlying, Kind);
5866
5867 Types.push_back(Ty);
5868 OverflowBehaviorTypes.InsertNode(Ty, InsertPos);
5869 return QualType(Ty, 0);
5870}
5871
5873 QualType Wrapped, QualType Contained,
5874 const HLSLAttributedResourceType::Attributes &Attrs) {
5875
5876 llvm::FoldingSetNodeID ID;
5877 HLSLAttributedResourceType::Profile(ID, Wrapped, Contained, Attrs);
5878
5879 void *InsertPos = nullptr;
5880 HLSLAttributedResourceType *Ty =
5881 HLSLAttributedResourceTypes.FindNodeOrInsertPos(ID, InsertPos);
5882 if (Ty)
5883 return QualType(Ty, 0);
5884
5885 Ty = new (*this, alignof(HLSLAttributedResourceType))
5886 HLSLAttributedResourceType(Wrapped, Contained, Attrs);
5887
5888 Types.push_back(Ty);
5889 HLSLAttributedResourceTypes.InsertNode(Ty, InsertPos);
5890
5891 return QualType(Ty, 0);
5892}
5893
5894QualType ASTContext::getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size,
5895 uint32_t Alignment,
5896 ArrayRef<SpirvOperand> Operands) {
5897 llvm::FoldingSetNodeID ID;
5898 HLSLInlineSpirvType::Profile(ID, Opcode, Size, Alignment, Operands);
5899
5900 void *InsertPos = nullptr;
5901 HLSLInlineSpirvType *Ty =
5902 HLSLInlineSpirvTypes.FindNodeOrInsertPos(ID, InsertPos);
5903 if (Ty)
5904 return QualType(Ty, 0);
5905
5906 void *Mem = Allocate(
5907 HLSLInlineSpirvType::totalSizeToAlloc<SpirvOperand>(Operands.size()),
5908 alignof(HLSLInlineSpirvType));
5909
5910 Ty = new (Mem) HLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
5911
5912 Types.push_back(Ty);
5913 HLSLInlineSpirvTypes.InsertNode(Ty, InsertPos);
5914
5915 return QualType(Ty, 0);
5916}
5917
5918/// Retrieve a substitution-result type.
5920 Decl *AssociatedDecl,
5921 unsigned Index,
5923 bool Final) const {
5924 llvm::FoldingSetNodeID ID;
5925 SubstTemplateTypeParmType::Profile(ID, Replacement, AssociatedDecl, Index,
5926 PackIndex, Final);
5927 void *InsertPos = nullptr;
5928 SubstTemplateTypeParmType *SubstParm =
5929 SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5930
5931 if (!SubstParm) {
5932 void *Mem = Allocate(SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
5933 !Replacement.isCanonical()),
5934 alignof(SubstTemplateTypeParmType));
5935 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
5936 Index, PackIndex, Final);
5937 Types.push_back(SubstParm);
5938 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
5939 }
5940
5941 return QualType(SubstParm, 0);
5942}
5943
5946 unsigned Index, bool Final,
5947 const TemplateArgument &ArgPack) {
5948#ifndef NDEBUG
5949 for (const auto &P : ArgPack.pack_elements())
5950 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
5951#endif
5952
5953 llvm::FoldingSetNodeID ID;
5954 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
5955 ArgPack);
5956 void *InsertPos = nullptr;
5957 if (SubstTemplateTypeParmPackType *SubstParm =
5958 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
5959 return QualType(SubstParm, 0);
5960
5961 QualType Canon;
5962 {
5963 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5964 if (!AssociatedDecl->isCanonicalDecl() ||
5965 !CanonArgPack.structurallyEquals(ArgPack)) {
5967 AssociatedDecl->getCanonicalDecl(), Index, Final, CanonArgPack);
5968 [[maybe_unused]] const auto *Nothing =
5969 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
5970 assert(!Nothing);
5971 }
5972 }
5973
5974 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
5975 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
5976 ArgPack);
5977 Types.push_back(SubstParm);
5978 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
5979 return QualType(SubstParm, 0);
5980}
5981
5984 assert(llvm::all_of(ArgPack.pack_elements(),
5985 [](const auto &P) {
5986 return P.getKind() == TemplateArgument::Type;
5987 }) &&
5988 "Pack contains a non-type");
5989
5990 llvm::FoldingSetNodeID ID;
5991 SubstBuiltinTemplatePackType::Profile(ID, ArgPack);
5992
5993 void *InsertPos = nullptr;
5994 if (auto *T =
5995 SubstBuiltinTemplatePackTypes.FindNodeOrInsertPos(ID, InsertPos))
5996 return QualType(T, 0);
5997
5998 QualType Canon;
5999 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
6000 if (!CanonArgPack.structurallyEquals(ArgPack)) {
6001 Canon = getSubstBuiltinTemplatePack(CanonArgPack);
6002 // Refresh InsertPos, in case the recursive call above caused rehashing,
6003 // which would invalidate the bucket pointer.
6004 [[maybe_unused]] const auto *Nothing =
6005 SubstBuiltinTemplatePackTypes.FindNodeOrInsertPos(ID, InsertPos);
6006 assert(!Nothing);
6007 }
6008
6009 auto *PackType = new (*this, alignof(SubstBuiltinTemplatePackType))
6010 SubstBuiltinTemplatePackType(Canon, ArgPack);
6011 Types.push_back(PackType);
6012 SubstBuiltinTemplatePackTypes.InsertNode(PackType, InsertPos);
6013 return QualType(PackType, 0);
6014}
6015
6016/// Retrieve the template type parameter type for a template
6017/// parameter or parameter pack with the given depth, index, and (optionally)
6018/// name.
6020ASTContext::getTemplateTypeParmType(int Depth, int Index, bool ParameterPack,
6021 TemplateTypeParmDecl *TTPDecl) const {
6022 assert(Depth >= 0 && "Depth must be non-negative");
6023 assert(Index >= 0 && "Index must be non-negative");
6024
6025 llvm::FoldingSetNodeID ID;
6026 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
6027 void *InsertPos = nullptr;
6028 TemplateTypeParmType *TypeParm
6029 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
6030
6031 if (TypeParm)
6032 return QualType(TypeParm, 0);
6033
6034 if (TTPDecl) {
6035 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
6036 TypeParm = new (*this, alignof(TemplateTypeParmType))
6037 TemplateTypeParmType(Depth, Index, ParameterPack, TTPDecl, Canon);
6038
6039 TemplateTypeParmType *TypeCheck
6040 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
6041 assert(!TypeCheck && "Template type parameter canonical type broken");
6042 (void)TypeCheck;
6043 } else
6044 TypeParm = new (*this, alignof(TemplateTypeParmType)) TemplateTypeParmType(
6045 Depth, Index, ParameterPack, /*TTPDecl=*/nullptr, /*Canon=*/QualType());
6046
6047 Types.push_back(TypeParm);
6048 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
6049
6050 return QualType(TypeParm, 0);
6051}
6052
6055 switch (Keyword) {
6056 // These are just themselves.
6062 return Keyword;
6063
6064 // These are equivalent.
6067
6068 // These are functionally equivalent, so relying on their equivalence is
6069 // IFNDR. By making them equivalent, we disallow overloading, which at least
6070 // can produce a diagnostic.
6073 }
6074 llvm_unreachable("unexpected keyword kind");
6075}
6076
6078 ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc,
6079 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc,
6080 TemplateName Name, SourceLocation NameLoc,
6081 const TemplateArgumentListInfo &SpecifiedArgs,
6082 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6084 Keyword, Name, SpecifiedArgs.arguments(), CanonicalArgs, Underlying);
6085
6088 ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
6089 SpecifiedArgs);
6090 return TSI;
6091}
6092
6095 ArrayRef<TemplateArgumentLoc> SpecifiedArgs,
6096 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6097 SmallVector<TemplateArgument, 4> SpecifiedArgVec;
6098 SpecifiedArgVec.reserve(SpecifiedArgs.size());
6099 for (const TemplateArgumentLoc &Arg : SpecifiedArgs)
6100 SpecifiedArgVec.push_back(Arg.getArgument());
6101
6102 return getTemplateSpecializationType(Keyword, Template, SpecifiedArgVec,
6103 CanonicalArgs, Underlying);
6104}
6105
6106[[maybe_unused]] static bool
6108 for (const TemplateArgument &Arg : Args)
6109 if (Arg.isPackExpansion())
6110 return true;
6111 return false;
6112}
6113
6116 ArrayRef<TemplateArgument> Args) const {
6117 assert(Template ==
6118 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true));
6120 Template.getAsDependentTemplateName()));
6121#ifndef NDEBUG
6122 for (const auto &Arg : Args)
6123 assert(Arg.structurallyEquals(getCanonicalTemplateArgument(Arg)));
6124#endif
6125
6126 llvm::FoldingSetNodeID ID;
6127 TemplateSpecializationType::Profile(ID, Keyword, Template, Args, QualType(),
6128 *this);
6129 void *InsertPos = nullptr;
6130 if (auto *T = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6131 return QualType(T, 0);
6132
6133 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
6134 sizeof(TemplateArgument) * Args.size(),
6135 alignof(TemplateSpecializationType));
6136 auto *Spec =
6137 new (Mem) TemplateSpecializationType(Keyword, Template,
6138 /*IsAlias=*/false, Args, QualType());
6139 assert(Spec->isDependentType() &&
6140 "canonical template specialization must be dependent");
6141 Types.push_back(Spec);
6142 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
6143 return QualType(Spec, 0);
6144}
6145
6148 ArrayRef<TemplateArgument> SpecifiedArgs,
6149 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6150 const auto *TD = Template.getAsTemplateDecl(/*IgnoreDeduced=*/true);
6151 bool IsTypeAlias = TD && TD->isTypeAlias();
6152 if (Underlying.isNull()) {
6153 TemplateName CanonTemplate =
6154 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true);
6155 ElaboratedTypeKeyword CanonKeyword =
6156 CanonTemplate.getAsDependentTemplateName()
6159 bool NonCanonical = Template != CanonTemplate || Keyword != CanonKeyword;
6161 if (CanonicalArgs.empty()) {
6162 CanonArgsVec = SmallVector<TemplateArgument, 4>(SpecifiedArgs);
6163 NonCanonical |= canonicalizeTemplateArguments(CanonArgsVec);
6164 CanonicalArgs = CanonArgsVec;
6165 } else {
6166 NonCanonical |= !llvm::equal(
6167 SpecifiedArgs, CanonicalArgs,
6168 [](const TemplateArgument &A, const TemplateArgument &B) {
6169 return A.structurallyEquals(B);
6170 });
6171 }
6172
6173 // We can get here with an alias template when the specialization
6174 // contains a pack expansion that does not match up with a parameter
6175 // pack, or a builtin template which cannot be resolved due to dependency.
6176 assert((!isa_and_nonnull<TypeAliasTemplateDecl>(TD) ||
6177 hasAnyPackExpansions(CanonicalArgs)) &&
6178 "Caller must compute aliased type");
6179 IsTypeAlias = false;
6180
6182 CanonKeyword, CanonTemplate, CanonicalArgs);
6183 if (!NonCanonical)
6184 return Underlying;
6185 }
6186 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
6187 sizeof(TemplateArgument) * SpecifiedArgs.size() +
6188 (IsTypeAlias ? sizeof(QualType) : 0),
6189 alignof(TemplateSpecializationType));
6190 auto *Spec = new (Mem) TemplateSpecializationType(
6191 Keyword, Template, IsTypeAlias, SpecifiedArgs, Underlying);
6192 Types.push_back(Spec);
6193 return QualType(Spec, 0);
6194}
6195
6198 llvm::FoldingSetNodeID ID;
6199 ParenType::Profile(ID, InnerType);
6200
6201 void *InsertPos = nullptr;
6202 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6203 if (T)
6204 return QualType(T, 0);
6205
6206 QualType Canon = InnerType;
6207 if (!Canon.isCanonical()) {
6208 Canon = getCanonicalType(InnerType);
6209 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6210 assert(!CheckT && "Paren canonical type broken");
6211 (void)CheckT;
6212 }
6213
6214 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
6215 Types.push_back(T);
6216 ParenTypes.InsertNode(T, InsertPos);
6217 return QualType(T, 0);
6218}
6219
6222 const IdentifierInfo *MacroII) const {
6223 QualType Canon = UnderlyingTy;
6224 if (!Canon.isCanonical())
6225 Canon = getCanonicalType(UnderlyingTy);
6226
6227 auto *newType = new (*this, alignof(MacroQualifiedType))
6228 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
6229 Types.push_back(newType);
6230 return QualType(newType, 0);
6231}
6232
6235 const IdentifierInfo *Name) const {
6236 llvm::FoldingSetNodeID ID;
6237 DependentNameType::Profile(ID, Keyword, NNS, Name);
6238
6239 void *InsertPos = nullptr;
6240 if (DependentNameType *T =
6241 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos))
6242 return QualType(T, 0);
6243
6244 ElaboratedTypeKeyword CanonKeyword =
6246 NestedNameSpecifier CanonNNS = NNS.getCanonical();
6247
6248 QualType Canon;
6249 if (CanonKeyword != Keyword || CanonNNS != NNS) {
6250 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
6251 [[maybe_unused]] DependentNameType *T =
6252 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
6253 assert(!T && "broken canonicalization");
6254 assert(Canon.isCanonical());
6255 }
6256
6257 DependentNameType *T = new (*this, alignof(DependentNameType))
6258 DependentNameType(Keyword, NNS, Name, Canon);
6259 Types.push_back(T);
6260 DependentNameTypes.InsertNode(T, InsertPos);
6261 return QualType(T, 0);
6262}
6263
6265 TemplateArgument Arg;
6266 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6268 if (TTP->isParameterPack())
6269 ArgType = getPackExpansionType(ArgType, std::nullopt);
6270
6272 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6273 QualType T =
6274 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
6275 // For class NTTPs, ensure we include the 'const' so the type matches that
6276 // of a real template argument.
6277 // FIXME: It would be more faithful to model this as something like an
6278 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
6280 if (T->isRecordType()) {
6281 // C++ [temp.param]p8: An id-expression naming a non-type
6282 // template-parameter of class type T denotes a static storage duration
6283 // object of type const T.
6284 T.addConst();
6285 VK = VK_LValue;
6286 } else {
6287 VK = Expr::getValueKindForType(NTTP->getType());
6288 }
6289 Expr *E = new (*this)
6290 DeclRefExpr(*this, NTTP, /*RefersToEnclosingVariableOrCapture=*/false,
6291 T, VK, NTTP->getLocation());
6292
6293 if (NTTP->isParameterPack())
6294 E = new (*this) PackExpansionExpr(E, NTTP->getLocation(), std::nullopt);
6295 Arg = TemplateArgument(E, /*IsCanonical=*/false);
6296 } else {
6297 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
6299 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
6300 TemplateName(TTP));
6301 if (TTP->isParameterPack())
6302 Arg = TemplateArgument(Name, /*NumExpansions=*/std::nullopt);
6303 else
6304 Arg = TemplateArgument(Name);
6305 }
6306
6307 if (Param->isTemplateParameterPack())
6308 Arg =
6309 TemplateArgument::CreatePackCopy(const_cast<ASTContext &>(*this), Arg);
6310
6311 return Arg;
6312}
6313
6315 UnsignedOrNone NumExpansions,
6316 bool ExpectPackInType) const {
6317 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
6318 "Pack expansions must expand one or more parameter packs");
6319
6320 llvm::FoldingSetNodeID ID;
6321 PackExpansionType::Profile(ID, Pattern, NumExpansions);
6322
6323 void *InsertPos = nullptr;
6324 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6325 if (T)
6326 return QualType(T, 0);
6327
6328 QualType Canon;
6329 if (!Pattern.isCanonical()) {
6330 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
6331 /*ExpectPackInType=*/false);
6332
6333 // Find the insert position again, in case we inserted an element into
6334 // PackExpansionTypes and invalidated our insert position.
6335 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6336 }
6337
6338 T = new (*this, alignof(PackExpansionType))
6339 PackExpansionType(Pattern, Canon, NumExpansions);
6340 Types.push_back(T);
6341 PackExpansionTypes.InsertNode(T, InsertPos);
6342 return QualType(T, 0);
6343}
6344
6345/// CmpProtocolNames - Comparison predicate for sorting protocols
6346/// alphabetically.
6347static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
6348 ObjCProtocolDecl *const *RHS) {
6349 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
6350}
6351
6353 if (Protocols.empty()) return true;
6354
6355 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
6356 return false;
6357
6358 for (unsigned i = 1; i != Protocols.size(); ++i)
6359 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
6360 Protocols[i]->getCanonicalDecl() != Protocols[i])
6361 return false;
6362 return true;
6363}
6364
6365static void
6367 // Sort protocols, keyed by name.
6368 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
6369
6370 // Canonicalize.
6371 for (ObjCProtocolDecl *&P : Protocols)
6372 P = P->getCanonicalDecl();
6373
6374 // Remove duplicates.
6375 auto ProtocolsEnd = llvm::unique(Protocols);
6376 Protocols.erase(ProtocolsEnd, Protocols.end());
6377}
6378
6380 ObjCProtocolDecl * const *Protocols,
6381 unsigned NumProtocols) const {
6382 return getObjCObjectType(BaseType, {}, ArrayRef(Protocols, NumProtocols),
6383 /*isKindOf=*/false);
6384}
6385
6387 QualType baseType,
6388 ArrayRef<QualType> typeArgs,
6390 bool isKindOf) const {
6391 // If the base type is an interface and there aren't any protocols or
6392 // type arguments to add, then the interface type will do just fine.
6393 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
6394 isa<ObjCInterfaceType>(baseType))
6395 return baseType;
6396
6397 // Look in the folding set for an existing type.
6398 llvm::FoldingSetNodeID ID;
6399 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
6400 void *InsertPos = nullptr;
6401 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
6402 return QualType(QT, 0);
6403
6404 // Determine the type arguments to be used for canonicalization,
6405 // which may be explicitly specified here or written on the base
6406 // type.
6407 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
6408 if (effectiveTypeArgs.empty()) {
6409 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
6410 effectiveTypeArgs = baseObject->getTypeArgs();
6411 }
6412
6413 // Build the canonical type, which has the canonical base type and a
6414 // sorted-and-uniqued list of protocols and the type arguments
6415 // canonicalized.
6416 QualType canonical;
6417 bool typeArgsAreCanonical = llvm::all_of(
6418 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
6419 bool protocolsSorted = areSortedAndUniqued(protocols);
6420 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
6421 // Determine the canonical type arguments.
6422 ArrayRef<QualType> canonTypeArgs;
6423 SmallVector<QualType, 4> canonTypeArgsVec;
6424 if (!typeArgsAreCanonical) {
6425 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
6426 for (auto typeArg : effectiveTypeArgs)
6427 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
6428 canonTypeArgs = canonTypeArgsVec;
6429 } else {
6430 canonTypeArgs = effectiveTypeArgs;
6431 }
6432
6433 ArrayRef<ObjCProtocolDecl *> canonProtocols;
6434 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
6435 if (!protocolsSorted) {
6436 canonProtocolsVec.append(protocols.begin(), protocols.end());
6437 SortAndUniqueProtocols(canonProtocolsVec);
6438 canonProtocols = canonProtocolsVec;
6439 } else {
6440 canonProtocols = protocols;
6441 }
6442
6443 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
6444 canonProtocols, isKindOf);
6445
6446 // Regenerate InsertPos.
6447 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
6448 }
6449
6450 unsigned size = sizeof(ObjCObjectTypeImpl);
6451 size += typeArgs.size() * sizeof(QualType);
6452 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6453 void *mem = Allocate(size, alignof(ObjCObjectTypeImpl));
6454 auto *T =
6455 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
6456 isKindOf);
6457
6458 Types.push_back(T);
6459 ObjCObjectTypes.InsertNode(T, InsertPos);
6460 return QualType(T, 0);
6461}
6462
6463/// Apply Objective-C protocol qualifiers to the given type.
6464/// If this is for the canonical type of a type parameter, we can apply
6465/// protocol qualifiers on the ObjCObjectPointerType.
6468 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
6469 bool allowOnPointerType) const {
6470 hasError = false;
6471
6472 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
6473 return getObjCTypeParamType(objT->getDecl(), protocols);
6474 }
6475
6476 // Apply protocol qualifiers to ObjCObjectPointerType.
6477 if (allowOnPointerType) {
6478 if (const auto *objPtr =
6479 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
6480 const ObjCObjectType *objT = objPtr->getObjectType();
6481 // Merge protocol lists and construct ObjCObjectType.
6483 protocolsVec.append(objT->qual_begin(),
6484 objT->qual_end());
6485 protocolsVec.append(protocols.begin(), protocols.end());
6486 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
6488 objT->getBaseType(),
6489 objT->getTypeArgsAsWritten(),
6490 protocols,
6491 objT->isKindOfTypeAsWritten());
6493 }
6494 }
6495
6496 // Apply protocol qualifiers to ObjCObjectType.
6497 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
6498 // FIXME: Check for protocols to which the class type is already
6499 // known to conform.
6500
6501 return getObjCObjectType(objT->getBaseType(),
6502 objT->getTypeArgsAsWritten(),
6503 protocols,
6504 objT->isKindOfTypeAsWritten());
6505 }
6506
6507 // If the canonical type is ObjCObjectType, ...
6508 if (type->isObjCObjectType()) {
6509 // Silently overwrite any existing protocol qualifiers.
6510 // TODO: determine whether that's the right thing to do.
6511
6512 // FIXME: Check for protocols to which the class type is already
6513 // known to conform.
6514 return getObjCObjectType(type, {}, protocols, false);
6515 }
6516
6517 // id<protocol-list>
6518 if (type->isObjCIdType()) {
6519 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6520 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
6521 objPtr->isKindOfType());
6523 }
6524
6525 // Class<protocol-list>
6526 if (type->isObjCClassType()) {
6527 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6528 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
6529 objPtr->isKindOfType());
6531 }
6532
6533 hasError = true;
6534 return type;
6535}
6536
6539 ArrayRef<ObjCProtocolDecl *> protocols) const {
6540 // Look in the folding set for an existing type.
6541 llvm::FoldingSetNodeID ID;
6542 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
6543 void *InsertPos = nullptr;
6544 if (ObjCTypeParamType *TypeParam =
6545 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
6546 return QualType(TypeParam, 0);
6547
6548 // We canonicalize to the underlying type.
6549 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
6550 if (!protocols.empty()) {
6551 // Apply the protocol qualifers.
6552 bool hasError;
6554 Canonical, protocols, hasError, true /*allowOnPointerType*/));
6555 assert(!hasError && "Error when apply protocol qualifier to bound type");
6556 }
6557
6558 unsigned size = sizeof(ObjCTypeParamType);
6559 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6560 void *mem = Allocate(size, alignof(ObjCTypeParamType));
6561 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
6562
6563 Types.push_back(newType);
6564 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
6565 return QualType(newType, 0);
6566}
6567
6569 ObjCTypeParamDecl *New) const {
6570 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
6571 // Update TypeForDecl after updating TypeSourceInfo.
6572 auto *NewTypeParamTy = cast<ObjCTypeParamType>(New->TypeForDecl);
6574 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
6575 QualType UpdatedTy = getObjCTypeParamType(New, protocols);
6576 New->TypeForDecl = UpdatedTy.getTypePtr();
6577}
6578
6579/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
6580/// protocol list adopt all protocols in QT's qualified-id protocol
6581/// list.
6583 ObjCInterfaceDecl *IC) {
6584 if (!QT->isObjCQualifiedIdType())
6585 return false;
6586
6587 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
6588 // If both the right and left sides have qualifiers.
6589 for (auto *Proto : OPT->quals()) {
6590 if (!IC->ClassImplementsProtocol(Proto, false))
6591 return false;
6592 }
6593 return true;
6594 }
6595 return false;
6596}
6597
6598/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
6599/// QT's qualified-id protocol list adopt all protocols in IDecl's list
6600/// of protocols.
6602 ObjCInterfaceDecl *IDecl) {
6603 if (!QT->isObjCQualifiedIdType())
6604 return false;
6605 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
6606 if (!OPT)
6607 return false;
6608 if (!IDecl->hasDefinition())
6609 return false;
6611 CollectInheritedProtocols(IDecl, InheritedProtocols);
6612 if (InheritedProtocols.empty())
6613 return false;
6614 // Check that if every protocol in list of id<plist> conforms to a protocol
6615 // of IDecl's, then bridge casting is ok.
6616 bool Conforms = false;
6617 for (auto *Proto : OPT->quals()) {
6618 Conforms = false;
6619 for (auto *PI : InheritedProtocols) {
6620 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
6621 Conforms = true;
6622 break;
6623 }
6624 }
6625 if (!Conforms)
6626 break;
6627 }
6628 if (Conforms)
6629 return true;
6630
6631 for (auto *PI : InheritedProtocols) {
6632 // If both the right and left sides have qualifiers.
6633 bool Adopts = false;
6634 for (auto *Proto : OPT->quals()) {
6635 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
6636 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
6637 break;
6638 }
6639 if (!Adopts)
6640 return false;
6641 }
6642 return true;
6643}
6644
6645/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
6646/// the given object type.
6648 llvm::FoldingSetNodeID ID;
6649 ObjCObjectPointerType::Profile(ID, ObjectT);
6650
6651 void *InsertPos = nullptr;
6652 if (ObjCObjectPointerType *QT =
6653 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
6654 return QualType(QT, 0);
6655
6656 // Find the canonical object type.
6657 QualType Canonical;
6658 if (!ObjectT.isCanonical()) {
6659 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
6660
6661 // Regenerate InsertPos.
6662 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
6663 }
6664
6665 // No match.
6666 void *Mem =
6668 auto *QType =
6669 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
6670
6671 Types.push_back(QType);
6672 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
6673 return QualType(QType, 0);
6674}
6675
6676/// getObjCInterfaceType - Return the unique reference to the type for the
6677/// specified ObjC interface decl. The list of protocols is optional.
6679 ObjCInterfaceDecl *PrevDecl) const {
6680 if (Decl->TypeForDecl)
6681 return QualType(Decl->TypeForDecl, 0);
6682
6683 if (PrevDecl) {
6684 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
6685 Decl->TypeForDecl = PrevDecl->TypeForDecl;
6686 return QualType(PrevDecl->TypeForDecl, 0);
6687 }
6688
6689 // Prefer the definition, if there is one.
6690 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
6691 Decl = Def;
6692
6693 void *Mem = Allocate(sizeof(ObjCInterfaceType), alignof(ObjCInterfaceType));
6694 auto *T = new (Mem) ObjCInterfaceType(Decl);
6695 Decl->TypeForDecl = T;
6696 Types.push_back(T);
6697 return QualType(T, 0);
6698}
6699
6700/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
6701/// TypeOfExprType AST's (since expression's are never shared). For example,
6702/// multiple declarations that refer to "typeof(x)" all contain different
6703/// DeclRefExpr's. This doesn't effect the type checker, since it operates
6704/// on canonical type's (which are always unique).
6706 TypeOfExprType *toe;
6707 if (tofExpr->isTypeDependent()) {
6708 llvm::FoldingSetNodeID ID;
6709 DependentTypeOfExprType::Profile(ID, *this, tofExpr,
6710 Kind == TypeOfKind::Unqualified);
6711
6712 void *InsertPos = nullptr;
6714 DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
6715 if (Canon) {
6716 // We already have a "canonical" version of an identical, dependent
6717 // typeof(expr) type. Use that as our canonical type.
6718 toe = new (*this, alignof(TypeOfExprType)) TypeOfExprType(
6719 *this, tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
6720 } else {
6721 // Build a new, canonical typeof(expr) type.
6722 Canon = new (*this, alignof(DependentTypeOfExprType))
6723 DependentTypeOfExprType(*this, tofExpr, Kind);
6724 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
6725 toe = Canon;
6726 }
6727 } else {
6728 QualType Canonical = getCanonicalType(tofExpr->getType());
6729 toe = new (*this, alignof(TypeOfExprType))
6730 TypeOfExprType(*this, tofExpr, Kind, Canonical);
6731 }
6732 Types.push_back(toe);
6733 return QualType(toe, 0);
6734}
6735
6736/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
6737/// TypeOfType nodes. The only motivation to unique these nodes would be
6738/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
6739/// an issue. This doesn't affect the type checker, since it operates
6740/// on canonical types (which are always unique).
6742 QualType Canonical = getCanonicalType(tofType);
6743 auto *tot = new (*this, alignof(TypeOfType))
6744 TypeOfType(*this, tofType, Canonical, Kind);
6745 Types.push_back(tot);
6746 return QualType(tot, 0);
6747}
6748
6749/// getReferenceQualifiedType - Given an expr, will return the type for
6750/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
6751/// and class member access into account.
6753 // C++11 [dcl.type.simple]p4:
6754 // [...]
6755 QualType T = E->getType();
6756 switch (E->getValueKind()) {
6757 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6758 // type of e;
6759 case VK_XValue:
6760 return getRValueReferenceType(T);
6761 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6762 // type of e;
6763 case VK_LValue:
6764 return getLValueReferenceType(T);
6765 // - otherwise, decltype(e) is the type of e.
6766 case VK_PRValue:
6767 return T;
6768 }
6769 llvm_unreachable("Unknown value kind");
6770}
6771
6772/// Unlike many "get<Type>" functions, we don't unique DecltypeType
6773/// nodes. This would never be helpful, since each such type has its own
6774/// expression, and would not give a significant memory saving, since there
6775/// is an Expr tree under each such type.
6777 // C++11 [temp.type]p2:
6778 // If an expression e involves a template parameter, decltype(e) denotes a
6779 // unique dependent type. Two such decltype-specifiers refer to the same
6780 // type only if their expressions are equivalent (14.5.6.1).
6781 QualType CanonType;
6782 if (!E->isInstantiationDependent()) {
6783 CanonType = getCanonicalType(UnderlyingType);
6784 } else if (!UnderlyingType.isNull()) {
6785 CanonType = getDecltypeType(E, QualType());
6786 } else {
6787 llvm::FoldingSetNodeID ID;
6788 DependentDecltypeType::Profile(ID, *this, E);
6789
6790 void *InsertPos = nullptr;
6791 if (DependentDecltypeType *Canon =
6792 DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos))
6793 return QualType(Canon, 0);
6794
6795 // Build a new, canonical decltype(expr) type.
6796 auto *DT =
6797 new (*this, alignof(DependentDecltypeType)) DependentDecltypeType(E);
6798 DependentDecltypeTypes.InsertNode(DT, InsertPos);
6799 Types.push_back(DT);
6800 return QualType(DT, 0);
6801 }
6802 auto *DT = new (*this, alignof(DecltypeType))
6803 DecltypeType(E, UnderlyingType, CanonType);
6804 Types.push_back(DT);
6805 return QualType(DT, 0);
6806}
6807
6809 bool FullySubstituted,
6810 ArrayRef<QualType> Expansions,
6811 UnsignedOrNone Index) const {
6812 QualType Canonical;
6813 if (FullySubstituted && Index) {
6814 Canonical = getCanonicalType(Expansions[*Index]);
6815 } else {
6816 llvm::FoldingSetNodeID ID;
6817 PackIndexingType::Profile(ID, *this, Pattern.getCanonicalType(), IndexExpr,
6818 FullySubstituted, Expansions);
6819 void *InsertPos = nullptr;
6820 PackIndexingType *Canon =
6821 DependentPackIndexingTypes.FindNodeOrInsertPos(ID, InsertPos);
6822 if (!Canon) {
6823 void *Mem = Allocate(
6824 PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6826 Canon =
6827 new (Mem) PackIndexingType(QualType(), Pattern.getCanonicalType(),
6828 IndexExpr, FullySubstituted, Expansions);
6829 DependentPackIndexingTypes.InsertNode(Canon, InsertPos);
6830 }
6831 Canonical = QualType(Canon, 0);
6832 }
6833
6834 void *Mem =
6835 Allocate(PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6837 auto *T = new (Mem) PackIndexingType(Canonical, Pattern, IndexExpr,
6838 FullySubstituted, Expansions);
6839 Types.push_back(T);
6840 return QualType(T, 0);
6841}
6842
6843/// getUnaryTransformationType - We don't unique these, since the memory
6844/// savings are minimal and these are rare.
6847 UnaryTransformType::UTTKind Kind) const {
6848
6849 llvm::FoldingSetNodeID ID;
6850 UnaryTransformType::Profile(ID, BaseType, UnderlyingType, Kind);
6851
6852 void *InsertPos = nullptr;
6853 if (UnaryTransformType *UT =
6854 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos))
6855 return QualType(UT, 0);
6856
6857 QualType CanonType;
6858 if (!BaseType->isDependentType()) {
6859 CanonType = UnderlyingType.getCanonicalType();
6860 } else {
6861 assert(UnderlyingType.isNull() || BaseType == UnderlyingType);
6862 UnderlyingType = QualType();
6863 if (QualType CanonBase = BaseType.getCanonicalType();
6864 BaseType != CanonBase) {
6865 CanonType = getUnaryTransformType(CanonBase, QualType(), Kind);
6866 assert(CanonType.isCanonical());
6867
6868 // Find the insertion position again.
6869 [[maybe_unused]] UnaryTransformType *UT =
6870 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
6871 assert(!UT && "broken canonicalization");
6872 }
6873 }
6874
6875 auto *UT = new (*this, alignof(UnaryTransformType))
6876 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
6877 UnaryTransformTypes.InsertNode(UT, InsertPos);
6878 Types.push_back(UT);
6879 return QualType(UT, 0);
6880}
6881
6882/// getAutoType - Return the uniqued reference to the 'auto' type which has been
6883/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
6884/// canonical deduced-but-dependent 'auto' type.
6888 TemplateDecl *TypeConstraintConcept,
6889 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
6891 !TypeConstraintConcept) {
6892 assert(DeducedAsType.isNull() && "");
6893 assert(TypeConstraintArgs.empty() && "");
6894 return getAutoDeductType();
6895 }
6896
6897 // Look in the folding set for an existing type.
6898 llvm::FoldingSetNodeID ID;
6899 AutoType::Profile(ID, *this, DK, DeducedAsType, Keyword,
6900 TypeConstraintConcept, TypeConstraintArgs);
6901 if (auto const AT_iter = AutoTypes.find(ID); AT_iter != AutoTypes.end())
6902 return QualType(AT_iter->getSecond(), 0);
6903
6904 if (DK == DeducedKind::Deduced) {
6905 assert(!DeducedAsType.isNull() && "deduced type must be provided");
6906 } else {
6907 assert(DeducedAsType.isNull() && "deduced type must not be provided");
6908 if (TypeConstraintConcept) {
6909 bool AnyNonCanonArgs = false;
6910 auto *CanonicalConcept =
6911 cast<TemplateDecl>(TypeConstraintConcept->getCanonicalDecl());
6912 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
6913 *this, TypeConstraintArgs, AnyNonCanonArgs);
6914 if (TypeConstraintConcept != CanonicalConcept || AnyNonCanonArgs)
6915 DeducedAsType = getAutoType(DK, QualType(), Keyword, CanonicalConcept,
6916 CanonicalConceptArgs);
6917 }
6918 }
6919
6920 void *Mem = Allocate(sizeof(AutoType) +
6921 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
6922 alignof(AutoType));
6923 auto *AT = new (Mem) AutoType(DK, DeducedAsType, Keyword,
6924 TypeConstraintConcept, TypeConstraintArgs);
6925#ifndef NDEBUG
6926 llvm::FoldingSetNodeID InsertedID;
6927 AT->Profile(InsertedID, *this);
6928 assert(InsertedID == ID && "ID does not match");
6929#endif
6930 Types.push_back(AT);
6931 AutoTypes.try_emplace(ID, AT);
6932 return QualType(AT, 0);
6933}
6934
6937
6938 // Remove a type-constraint from a top-level auto or decltype(auto).
6939 if (auto *AT = CanonT->getAs<AutoType>()) {
6940 if (!AT->isConstrained())
6941 return T;
6942 return getQualifiedType(
6943 getAutoType(AT->getDeducedKind(), QualType(), AT->getKeyword()),
6944 T.getQualifiers());
6945 }
6946
6947 // FIXME: We only support constrained auto at the top level in the type of a
6948 // non-type template parameter at the moment. Once we lift that restriction,
6949 // we'll need to recursively build types containing auto here.
6950 assert(!CanonT->getContainedAutoType() ||
6951 !CanonT->getContainedAutoType()->isConstrained());
6952 return T;
6953}
6954
6955/// Return the uniqued reference to the deduced template specialization type
6956/// which has been deduced to the given type, or to the canonical undeduced
6957/// such type, or the canonical deduced-but-dependent such type.
6960 TemplateName Template) const {
6961 // Look in the folding set for an existing type.
6962 void *InsertPos = nullptr;
6963 llvm::FoldingSetNodeID ID;
6964 DeducedTemplateSpecializationType::Profile(ID, DK, DeducedAsType, Keyword,
6965 Template);
6966 if (DeducedTemplateSpecializationType *DTST =
6967 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6968 return QualType(DTST, 0);
6969
6970 if (DK == DeducedKind::Deduced) {
6971 assert(!DeducedAsType.isNull() && "deduced type must be provided");
6972 } else {
6973 assert(DeducedAsType.isNull() && "deduced type must not be provided");
6974 TemplateName CanonTemplateName = getCanonicalTemplateName(Template);
6975 // FIXME: Can this be formed from a DependentTemplateName, such that the
6976 // keyword should be part of the canonical type?
6978 Template != CanonTemplateName) {
6980 DK, QualType(), ElaboratedTypeKeyword::None, CanonTemplateName);
6981 // Find the insertion position again.
6982 [[maybe_unused]] DeducedTemplateSpecializationType *DTST =
6983 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
6984 assert(!DTST && "broken canonicalization");
6985 }
6986 }
6987
6988 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
6989 DeducedTemplateSpecializationType(DK, DeducedAsType, Keyword, Template);
6990
6991#ifndef NDEBUG
6992 llvm::FoldingSetNodeID TempID;
6993 DTST->Profile(TempID);
6994 assert(ID == TempID && "ID does not match");
6995#endif
6996 Types.push_back(DTST);
6997 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
6998 return QualType(DTST, 0);
6999}
7000
7001/// getAtomicType - Return the uniqued reference to the atomic type for
7002/// the given value type.
7004 // Unique pointers, to guarantee there is only one pointer of a particular
7005 // structure.
7006 llvm::FoldingSetNodeID ID;
7007 AtomicType::Profile(ID, T);
7008
7009 void *InsertPos = nullptr;
7010 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
7011 return QualType(AT, 0);
7012
7013 // If the atomic value type isn't canonical, this won't be a canonical type
7014 // either, so fill in the canonical type field.
7015 QualType Canonical;
7016 if (!T.isCanonical()) {
7017 Canonical = getAtomicType(getCanonicalType(T));
7018
7019 // Get the new insert position for the node we care about.
7020 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
7021 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
7022 }
7023 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
7024 Types.push_back(New);
7025 AtomicTypes.InsertNode(New, InsertPos);
7026 return QualType(New, 0);
7027}
7028
7029/// getAutoDeductType - Get type pattern for deducing against 'auto'.
7031 if (AutoDeductTy.isNull())
7032 AutoDeductTy = QualType(new (*this, alignof(AutoType))
7033 AutoType(DeducedKind::Undeduced, QualType(),
7035 /*TypeConstraintConcept=*/nullptr,
7036 /*TypeConstraintArgs=*/{}),
7037 0);
7038 return AutoDeductTy;
7039}
7040
7041/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
7043 if (AutoRRefDeductTy.isNull())
7045 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
7046 return AutoRRefDeductTy;
7047}
7048
7049/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
7050/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
7051/// needs to agree with the definition in <stddef.h>.
7055
7057 return getFromTargetType(Target->getSizeType());
7058}
7059
7060/// Return the unique signed counterpart of the integer type
7061/// corresponding to size_t.
7065
7066/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
7067/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
7071
7072/// Return the unique unsigned counterpart of "ptrdiff_t"
7073/// integer type. The standard (C11 7.21.6.1p7) refers to this type
7074/// in the definition of %tu format specifier.
7076 return getFromTargetType(Target->getUnsignedPtrDiffType(LangAS::Default));
7077}
7078
7079/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
7081 return getFromTargetType(Target->getIntMaxType());
7082}
7083
7084/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
7086 return getFromTargetType(Target->getUIntMaxType());
7087}
7088
7089/// getSignedWCharType - Return the type of "signed wchar_t".
7090/// Used when in C++, as a GCC extension.
7092 // FIXME: derive from "Target" ?
7093 return WCharTy;
7094}
7095
7096/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
7097/// Used when in C++, as a GCC extension.
7099 // FIXME: derive from "Target" ?
7100 return UnsignedIntTy;
7101}
7102
7104 return getFromTargetType(Target->getIntPtrType());
7105}
7106
7110
7111/// Return the unique type for "pid_t" defined in
7112/// <sys/types.h>. We need this to compute the correct type for vfork().
7114 return getFromTargetType(Target->getProcessIDType());
7115}
7116
7117//===----------------------------------------------------------------------===//
7118// Type Operators
7119//===----------------------------------------------------------------------===//
7120
7122 // Push qualifiers into arrays, and then discard any remaining
7123 // qualifiers.
7124 T = getCanonicalType(T);
7126 const Type *Ty = T.getTypePtr();
7130 } else if (isa<ArrayType>(Ty)) {
7132 } else if (isa<FunctionType>(Ty)) {
7133 Result = getPointerType(QualType(Ty, 0));
7134 } else {
7135 Result = QualType(Ty, 0);
7136 }
7137
7139}
7140
7142 Qualifiers &quals) const {
7143 SplitQualType splitType = type.getSplitUnqualifiedType();
7144
7145 // FIXME: getSplitUnqualifiedType() actually walks all the way to
7146 // the unqualified desugared type and then drops it on the floor.
7147 // We then have to strip that sugar back off with
7148 // getUnqualifiedDesugaredType(), which is silly.
7149 const auto *AT =
7150 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
7151
7152 // If we don't have an array, just use the results in splitType.
7153 if (!AT) {
7154 quals = splitType.Quals;
7155 return QualType(splitType.Ty, 0);
7156 }
7157
7158 // Otherwise, recurse on the array's element type.
7159 QualType elementType = AT->getElementType();
7160 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
7161
7162 // If that didn't change the element type, AT has no qualifiers, so we
7163 // can just use the results in splitType.
7164 if (elementType == unqualElementType) {
7165 assert(quals.empty()); // from the recursive call
7166 quals = splitType.Quals;
7167 return QualType(splitType.Ty, 0);
7168 }
7169
7170 // Otherwise, add in the qualifiers from the outermost type, then
7171 // build the type back up.
7172 quals.addConsistentQualifiers(splitType.Quals);
7173
7174 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
7175 return getConstantArrayType(unqualElementType, CAT->getSize(),
7176 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
7177 }
7178
7179 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
7180 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
7181 }
7182
7183 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
7184 return getVariableArrayType(unqualElementType, VAT->getSizeExpr(),
7185 VAT->getSizeModifier(),
7186 VAT->getIndexTypeCVRQualifiers());
7187 }
7188
7189 const auto *DSAT = cast<DependentSizedArrayType>(AT);
7190 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
7191 DSAT->getSizeModifier(), 0);
7192}
7193
7194/// Attempt to unwrap two types that may both be array types with the same bound
7195/// (or both be array types of unknown bound) for the purpose of comparing the
7196/// cv-decomposition of two types per C++ [conv.qual].
7197///
7198/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7199/// C++20 [conv.qual], if permitted by the current language mode.
7201 bool AllowPiMismatch) const {
7202 while (true) {
7203 auto *AT1 = getAsArrayType(T1);
7204 if (!AT1)
7205 return;
7206
7207 auto *AT2 = getAsArrayType(T2);
7208 if (!AT2)
7209 return;
7210
7211 // If we don't have two array types with the same constant bound nor two
7212 // incomplete array types, we've unwrapped everything we can.
7213 // C++20 also permits one type to be a constant array type and the other
7214 // to be an incomplete array type.
7215 // FIXME: Consider also unwrapping array of unknown bound and VLA.
7216 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
7217 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
7218 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
7219 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7221 return;
7222 } else if (isa<IncompleteArrayType>(AT1)) {
7223 if (!(isa<IncompleteArrayType>(AT2) ||
7224 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7226 return;
7227 } else {
7228 return;
7229 }
7230
7231 T1 = AT1->getElementType();
7232 T2 = AT2->getElementType();
7233 }
7234}
7235
7236/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
7237///
7238/// If T1 and T2 are both pointer types of the same kind, or both array types
7239/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
7240/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
7241///
7242/// This function will typically be called in a loop that successively
7243/// "unwraps" pointer and pointer-to-member types to compare them at each
7244/// level.
7245///
7246/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7247/// C++20 [conv.qual], if permitted by the current language mode.
7248///
7249/// \return \c true if a pointer type was unwrapped, \c false if we reached a
7250/// pair of types that can't be unwrapped further.
7252 bool AllowPiMismatch) const {
7253 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
7254
7255 const auto *T1PtrType = T1->getAs<PointerType>();
7256 const auto *T2PtrType = T2->getAs<PointerType>();
7257 if (T1PtrType && T2PtrType) {
7258 T1 = T1PtrType->getPointeeType();
7259 T2 = T2PtrType->getPointeeType();
7260 return true;
7261 }
7262
7263 if (const auto *T1MPType = T1->getAsCanonical<MemberPointerType>(),
7264 *T2MPType = T2->getAsCanonical<MemberPointerType>();
7265 T1MPType && T2MPType) {
7266 // Compare the qualifiers of the canonical type, as the non-canonical type
7267 // may have qualifiers pointing to a base or derived class.
7268 if (T1MPType->getQualifier() != T2MPType->getQualifier())
7269 return false;
7270 // Get the pointee types of the non-canonical type, in order to preserve
7271 // their sugar.
7272 T1 = T1->getAs<MemberPointerType>()->getPointeeType();
7273 T2 = T2->getAs<MemberPointerType>()->getPointeeType();
7274 return true;
7275 }
7276
7277 if (getLangOpts().ObjC) {
7278 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
7279 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
7280 if (T1OPType && T2OPType) {
7281 T1 = T1OPType->getPointeeType();
7282 T2 = T2OPType->getPointeeType();
7283 return true;
7284 }
7285 }
7286
7287 // FIXME: Block pointers, too?
7288
7289 return false;
7290}
7291
7293 while (true) {
7294 Qualifiers Quals;
7295 T1 = getUnqualifiedArrayType(T1, Quals);
7296 T2 = getUnqualifiedArrayType(T2, Quals);
7297 if (hasSameType(T1, T2))
7298 return true;
7299 if (!UnwrapSimilarTypes(T1, T2))
7300 return false;
7301 }
7302}
7303
7305 while (true) {
7306 Qualifiers Quals1, Quals2;
7307 T1 = getUnqualifiedArrayType(T1, Quals1);
7308 T2 = getUnqualifiedArrayType(T2, Quals2);
7309
7310 Quals1.removeCVRQualifiers();
7311 Quals2.removeCVRQualifiers();
7312 if (Quals1 != Quals2)
7313 return false;
7314
7315 if (hasSameType(T1, T2))
7316 return true;
7317
7318 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
7319 return false;
7320 }
7321}
7322
7325 SourceLocation NameLoc) const {
7326 switch (Name.getKind()) {
7329 // DNInfo work in progress: CHECKME: what about DNLoc?
7331 NameLoc);
7332
7335 // DNInfo work in progress: CHECKME: what about DNLoc?
7336 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
7337 }
7338
7341 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
7342 }
7343
7347 DeclarationName DName;
7348 if (const IdentifierInfo *II = TN.getIdentifier()) {
7349 DName = DeclarationNames.getIdentifier(II);
7350 return DeclarationNameInfo(DName, NameLoc);
7351 } else {
7352 DName = DeclarationNames.getCXXOperatorName(TN.getOperator());
7353 // DNInfo work in progress: FIXME: source locations?
7354 DeclarationNameLoc DNLoc =
7356 return DeclarationNameInfo(DName, NameLoc, DNLoc);
7357 }
7358 }
7359
7363 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
7364 NameLoc);
7365 }
7366
7371 NameLoc);
7372 }
7375 NameLoc);
7378 return getNameForTemplate(DTS->getUnderlying(), NameLoc);
7379 }
7380 }
7381
7382 llvm_unreachable("bad template name kind!");
7383}
7384
7385const TemplateArgument *
7387 auto handleParam = [](auto *TP) -> const TemplateArgument * {
7388 if (!TP->hasDefaultArgument())
7389 return nullptr;
7390 return &TP->getDefaultArgument().getArgument();
7391 };
7392 switch (P->getKind()) {
7393 case NamedDecl::TemplateTypeParm:
7394 return handleParam(cast<TemplateTypeParmDecl>(P));
7395 case NamedDecl::NonTypeTemplateParm:
7396 return handleParam(cast<NonTypeTemplateParmDecl>(P));
7397 case NamedDecl::TemplateTemplateParm:
7398 return handleParam(cast<TemplateTemplateParmDecl>(P));
7399 default:
7400 llvm_unreachable("Unexpected template parameter kind");
7401 }
7402}
7403
7405 bool IgnoreDeduced) const {
7406 while (std::optional<TemplateName> UnderlyingOrNone =
7407 Name.desugar(IgnoreDeduced))
7408 Name = *UnderlyingOrNone;
7409
7410 switch (Name.getKind()) {
7413 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
7415
7416 // The canonical template name is the canonical template declaration.
7417 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
7418 }
7419
7421 // An assumed template is just a name, so it is already canonical.
7422 return Name;
7423
7425 llvm_unreachable("cannot canonicalize overloaded template");
7426
7429 assert(DTN && "Non-dependent template names must refer to template decls.");
7430 NestedNameSpecifier Qualifier = DTN->getQualifier();
7431 NestedNameSpecifier CanonQualifier = Qualifier.getCanonical();
7432 if (Qualifier != CanonQualifier || !DTN->hasTemplateKeyword())
7433 return getDependentTemplateName({CanonQualifier, DTN->getName(),
7434 /*HasTemplateKeyword=*/true});
7435 return Name;
7436 }
7437
7441 TemplateArgument canonArgPack =
7444 canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
7445 subst->getIndex(), subst->getFinal());
7446 }
7448 assert(IgnoreDeduced == false);
7450 DefaultArguments DefArgs = DTS->getDefaultArguments();
7451 TemplateName Underlying = DTS->getUnderlying();
7452
7453 TemplateName CanonUnderlying =
7454 getCanonicalTemplateName(Underlying, /*IgnoreDeduced=*/true);
7455 bool NonCanonical = CanonUnderlying != Underlying;
7456 auto CanonArgs =
7457 getCanonicalTemplateArguments(*this, DefArgs.Args, NonCanonical);
7458
7459 ArrayRef<NamedDecl *> Params =
7460 CanonUnderlying.getAsTemplateDecl()->getTemplateParameters()->asArray();
7461 assert(CanonArgs.size() <= Params.size());
7462 // A deduced template name which deduces the same default arguments already
7463 // declared in the underlying template is the same template as the
7464 // underlying template. We need need to note any arguments which differ from
7465 // the corresponding declaration. If any argument differs, we must build a
7466 // deduced template name.
7467 for (int I = CanonArgs.size() - 1; I >= 0; --I) {
7469 if (!A)
7470 break;
7471 auto CanonParamDefArg = getCanonicalTemplateArgument(*A);
7472 TemplateArgument &CanonDefArg = CanonArgs[I];
7473 if (CanonDefArg.structurallyEquals(CanonParamDefArg))
7474 continue;
7475 // Keep popping from the back any deault arguments which are the same.
7476 if (I == int(CanonArgs.size() - 1))
7477 CanonArgs.pop_back();
7478 NonCanonical = true;
7479 }
7480 return NonCanonical ? getDeducedTemplateName(
7481 CanonUnderlying,
7482 /*DefaultArgs=*/{DefArgs.StartPos, CanonArgs})
7483 : Name;
7484 }
7488 llvm_unreachable("always sugar node");
7489 }
7490
7491 llvm_unreachable("bad template name!");
7492}
7493
7495 const TemplateName &Y,
7496 bool IgnoreDeduced) const {
7497 return getCanonicalTemplateName(X, IgnoreDeduced) ==
7498 getCanonicalTemplateName(Y, IgnoreDeduced);
7499}
7500
7502 const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const {
7503 if (ACX.ArgPackSubstIndex != ACY.ArgPackSubstIndex)
7504 return false;
7506 return false;
7507 return true;
7508}
7509
7510bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
7511 if (!XCE != !YCE)
7512 return false;
7513
7514 if (!XCE)
7515 return true;
7516
7517 llvm::FoldingSetNodeID XCEID, YCEID;
7518 XCE->Profile(XCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7519 YCE->Profile(YCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7520 return XCEID == YCEID;
7521}
7522
7524 const TypeConstraint *YTC) const {
7525 if (!XTC != !YTC)
7526 return false;
7527
7528 if (!XTC)
7529 return true;
7530
7531 auto *NCX = XTC->getNamedConcept();
7532 auto *NCY = YTC->getNamedConcept();
7533 if (!NCX || !NCY || !isSameEntity(NCX, NCY))
7534 return false;
7537 return false;
7539 if (XTC->getConceptReference()
7541 ->NumTemplateArgs !=
7543 return false;
7544
7545 // Compare slowly by profiling.
7546 //
7547 // We couldn't compare the profiling result for the template
7548 // args here. Consider the following example in different modules:
7549 //
7550 // template <__integer_like _Tp, C<_Tp> Sentinel>
7551 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
7552 // return __t;
7553 // }
7554 //
7555 // When we compare the profiling result for `C<_Tp>` in different
7556 // modules, it will compare the type of `_Tp` in different modules.
7557 // However, the type of `_Tp` in different modules refer to different
7558 // types here naturally. So we couldn't compare the profiling result
7559 // for the template args directly.
7562}
7563
7565 const NamedDecl *Y) const {
7566 if (X->getKind() != Y->getKind())
7567 return false;
7568
7569 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
7570 auto *TY = cast<TemplateTypeParmDecl>(Y);
7571 if (TX->isParameterPack() != TY->isParameterPack())
7572 return false;
7573 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
7574 return false;
7575 return isSameTypeConstraint(TX->getTypeConstraint(),
7576 TY->getTypeConstraint());
7577 }
7578
7579 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7580 auto *TY = cast<NonTypeTemplateParmDecl>(Y);
7581 return TX->isParameterPack() == TY->isParameterPack() &&
7582 TX->getASTContext().hasSameType(TX->getType(), TY->getType()) &&
7583 isSameConstraintExpr(TX->getPlaceholderTypeConstraint(),
7584 TY->getPlaceholderTypeConstraint());
7585 }
7586
7588 auto *TY = cast<TemplateTemplateParmDecl>(Y);
7589 return TX->isParameterPack() == TY->isParameterPack() &&
7590 isSameTemplateParameterList(TX->getTemplateParameters(),
7591 TY->getTemplateParameters());
7592}
7593
7595 const TemplateParameterList *X, const TemplateParameterList *Y) const {
7596 if (X->size() != Y->size())
7597 return false;
7598
7599 for (unsigned I = 0, N = X->size(); I != N; ++I)
7600 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
7601 return false;
7602
7603 return isSameConstraintExpr(X->getRequiresClause(), Y->getRequiresClause());
7604}
7605
7607 const NamedDecl *Y) const {
7608 // If the type parameter isn't the same already, we don't need to check the
7609 // default argument further.
7610 if (!isSameTemplateParameter(X, Y))
7611 return false;
7612
7613 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(X)) {
7614 auto *TTPY = cast<TemplateTypeParmDecl>(Y);
7615 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7616 return false;
7617
7618 return hasSameType(TTPX->getDefaultArgument().getArgument().getAsType(),
7619 TTPY->getDefaultArgument().getArgument().getAsType());
7620 }
7621
7622 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7623 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Y);
7624 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
7625 return false;
7626
7627 Expr *DefaultArgumentX =
7628 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7629 Expr *DefaultArgumentY =
7630 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7631 llvm::FoldingSetNodeID XID, YID;
7632 DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true);
7633 DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true);
7634 return XID == YID;
7635 }
7636
7637 auto *TTPX = cast<TemplateTemplateParmDecl>(X);
7638 auto *TTPY = cast<TemplateTemplateParmDecl>(Y);
7639
7640 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7641 return false;
7642
7643 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
7644 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
7645 return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate());
7646}
7647
7649 const NestedNameSpecifier Y) {
7650 if (X == Y)
7651 return true;
7652 if (!X || !Y)
7653 return false;
7654
7655 auto Kind = X.getKind();
7656 if (Kind != Y.getKind())
7657 return false;
7658
7659 // FIXME: For namespaces and types, we're permitted to check that the entity
7660 // is named via the same tokens. We should probably do so.
7661 switch (Kind) {
7663 auto [NamespaceX, PrefixX] = X.getAsNamespaceAndPrefix();
7664 auto [NamespaceY, PrefixY] = Y.getAsNamespaceAndPrefix();
7665 if (!declaresSameEntity(NamespaceX->getNamespace(),
7666 NamespaceY->getNamespace()))
7667 return false;
7668 return isSameQualifier(PrefixX, PrefixY);
7669 }
7671 const auto *TX = X.getAsType(), *TY = Y.getAsType();
7672 if (TX->getCanonicalTypeInternal() != TY->getCanonicalTypeInternal())
7673 return false;
7674 return isSameQualifier(TX->getPrefix(), TY->getPrefix());
7675 }
7679 return true;
7680 }
7681 llvm_unreachable("unhandled qualifier kind");
7682}
7683
7684static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B) {
7685 if (!A->getASTContext().getLangOpts().CUDA)
7686 return true; // Target attributes are overloadable in CUDA compilation only.
7687 if (A->hasAttr<CUDADeviceAttr>() != B->hasAttr<CUDADeviceAttr>())
7688 return false;
7689 if (A->hasAttr<CUDADeviceAttr>() && B->hasAttr<CUDADeviceAttr>())
7690 return A->hasAttr<CUDAHostAttr>() == B->hasAttr<CUDAHostAttr>();
7691 return true; // unattributed and __host__ functions are the same.
7692}
7693
7694/// Determine whether the attributes we can overload on are identical for A and
7695/// B. Will ignore any overloadable attrs represented in the type of A and B.
7697 const FunctionDecl *B) {
7698 // Note that pass_object_size attributes are represented in the function's
7699 // ExtParameterInfo, so we don't need to check them here.
7700
7701 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
7702 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
7703 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
7704
7705 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
7706 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
7707 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
7708
7709 // Return false if the number of enable_if attributes is different.
7710 if (!Cand1A || !Cand2A)
7711 return false;
7712
7713 Cand1ID.clear();
7714 Cand2ID.clear();
7715
7716 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
7717 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
7718
7719 // Return false if any of the enable_if expressions of A and B are
7720 // different.
7721 if (Cand1ID != Cand2ID)
7722 return false;
7723 }
7724 return hasSameCudaAttrs(A, B);
7725}
7726
7727bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
7728 // Caution: this function is called by the AST reader during deserialization,
7729 // so it cannot rely on AST invariants being met. Non-trivial accessors
7730 // should be avoided, along with any traversal of redeclaration chains.
7731
7732 if (X == Y)
7733 return true;
7734
7735 if (X->getDeclName() != Y->getDeclName())
7736 return false;
7737
7738 // Must be in the same context.
7739 //
7740 // Note that we can't use DeclContext::Equals here, because the DeclContexts
7741 // could be two different declarations of the same function. (We will fix the
7742 // semantic DC to refer to the primary definition after merging.)
7743 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
7745 return false;
7746
7747 // If either X or Y are local to the owning module, they are only possible to
7748 // be the same entity if they are in the same module.
7749 if (X->isModuleLocal() || Y->isModuleLocal())
7750 if (!isInSameModule(X->getOwningModule(), Y->getOwningModule()))
7751 return false;
7752
7753 // Two typedefs refer to the same entity if they have the same underlying
7754 // type.
7755 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
7756 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
7757 return hasSameType(TypedefX->getUnderlyingType(),
7758 TypedefY->getUnderlyingType());
7759
7760 // Must have the same kind.
7761 if (X->getKind() != Y->getKind())
7762 return false;
7763
7764 // Objective-C classes and protocols with the same name always match.
7766 return true;
7767
7769 // No need to handle these here: we merge them when adding them to the
7770 // template.
7771 return false;
7772 }
7773
7774 // Compatible tags match.
7775 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
7776 const auto *TagY = cast<TagDecl>(Y);
7777 return (TagX->getTagKind() == TagY->getTagKind()) ||
7778 ((TagX->getTagKind() == TagTypeKind::Struct ||
7779 TagX->getTagKind() == TagTypeKind::Class ||
7780 TagX->getTagKind() == TagTypeKind::Interface) &&
7781 (TagY->getTagKind() == TagTypeKind::Struct ||
7782 TagY->getTagKind() == TagTypeKind::Class ||
7783 TagY->getTagKind() == TagTypeKind::Interface));
7784 }
7785
7786 // Functions with the same type and linkage match.
7787 // FIXME: This needs to cope with merging of prototyped/non-prototyped
7788 // functions, etc.
7789 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
7790 const auto *FuncY = cast<FunctionDecl>(Y);
7791 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
7792 const auto *CtorY = cast<CXXConstructorDecl>(Y);
7793 if (CtorX->getInheritedConstructor() &&
7794 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
7795 CtorY->getInheritedConstructor().getConstructor()))
7796 return false;
7797 }
7798
7799 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
7800 return false;
7801
7802 // Multiversioned functions with different feature strings are represented
7803 // as separate declarations.
7804 if (FuncX->isMultiVersion()) {
7805 const auto *TAX = FuncX->getAttr<TargetAttr>();
7806 const auto *TAY = FuncY->getAttr<TargetAttr>();
7807 assert(TAX && TAY && "Multiversion Function without target attribute");
7808
7809 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
7810 return false;
7811 }
7812
7813 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
7814 // not the same entity if they are constrained.
7815 if ((FuncX->isMemberLikeConstrainedFriend() ||
7816 FuncY->isMemberLikeConstrainedFriend()) &&
7817 !FuncX->getLexicalDeclContext()->Equals(
7818 FuncY->getLexicalDeclContext())) {
7819 return false;
7820 }
7821
7822 if (!isSameAssociatedConstraint(FuncX->getTrailingRequiresClause(),
7823 FuncY->getTrailingRequiresClause()))
7824 return false;
7825
7826 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
7827 // Map to the first declaration that we've already merged into this one.
7828 // The TSI of redeclarations might not match (due to calling conventions
7829 // being inherited onto the type but not the TSI), but the TSI type of
7830 // the first declaration of the function should match across modules.
7831 FD = FD->getCanonicalDecl();
7832 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
7833 : FD->getType();
7834 };
7835 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
7836 if (!hasSameType(XT, YT)) {
7837 // We can get functions with different types on the redecl chain in C++17
7838 // if they have differing exception specifications and at least one of
7839 // the excpetion specs is unresolved.
7840 auto *XFPT = XT->getAs<FunctionProtoType>();
7841 auto *YFPT = YT->getAs<FunctionProtoType>();
7842 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
7843 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
7846 return true;
7847 return false;
7848 }
7849
7850 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
7851 hasSameOverloadableAttrs(FuncX, FuncY);
7852 }
7853
7854 // Variables with the same type and linkage match.
7855 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
7856 const auto *VarY = cast<VarDecl>(Y);
7857 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
7858 // During deserialization, we might compare variables before we load
7859 // their types. Assume the types will end up being the same.
7860 if (VarX->getType().isNull() || VarY->getType().isNull())
7861 return true;
7862
7863 if (hasSameType(VarX->getType(), VarY->getType()))
7864 return true;
7865
7866 // We can get decls with different types on the redecl chain. Eg.
7867 // template <typename T> struct S { static T Var[]; }; // #1
7868 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
7869 // Only? happens when completing an incomplete array type. In this case
7870 // when comparing #1 and #2 we should go through their element type.
7871 const ArrayType *VarXTy = getAsArrayType(VarX->getType());
7872 const ArrayType *VarYTy = getAsArrayType(VarY->getType());
7873 if (!VarXTy || !VarYTy)
7874 return false;
7875 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
7876 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
7877 }
7878 return false;
7879 }
7880
7881 // Namespaces with the same name and inlinedness match.
7882 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
7883 const auto *NamespaceY = cast<NamespaceDecl>(Y);
7884 return NamespaceX->isInline() == NamespaceY->isInline();
7885 }
7886
7887 // Identical template names and kinds match if their template parameter lists
7888 // and patterns match.
7889 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
7890 const auto *TemplateY = cast<TemplateDecl>(Y);
7891
7892 // ConceptDecl wouldn't be the same if their constraint expression differs.
7893 if (const auto *ConceptX = dyn_cast<ConceptDecl>(X)) {
7894 const auto *ConceptY = cast<ConceptDecl>(Y);
7895 if (!isSameConstraintExpr(ConceptX->getConstraintExpr(),
7896 ConceptY->getConstraintExpr()))
7897 return false;
7898 }
7899
7900 return isSameEntity(TemplateX->getTemplatedDecl(),
7901 TemplateY->getTemplatedDecl()) &&
7902 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
7903 TemplateY->getTemplateParameters());
7904 }
7905
7906 // Fields with the same name and the same type match.
7907 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
7908 const auto *FDY = cast<FieldDecl>(Y);
7909 // FIXME: Also check the bitwidth is odr-equivalent, if any.
7910 return hasSameType(FDX->getType(), FDY->getType());
7911 }
7912
7913 // Indirect fields with the same target field match.
7914 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
7915 const auto *IFDY = cast<IndirectFieldDecl>(Y);
7916 return IFDX->getAnonField()->getCanonicalDecl() ==
7917 IFDY->getAnonField()->getCanonicalDecl();
7918 }
7919
7920 // Enumerators with the same name match.
7922 // FIXME: Also check the value is odr-equivalent.
7923 return true;
7924
7925 // Using shadow declarations with the same target match.
7926 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
7927 const auto *USY = cast<UsingShadowDecl>(Y);
7928 return declaresSameEntity(USX->getTargetDecl(), USY->getTargetDecl());
7929 }
7930
7931 // Using declarations with the same qualifier match. (We already know that
7932 // the name matches.)
7933 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
7934 const auto *UY = cast<UsingDecl>(Y);
7935 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7936 UX->hasTypename() == UY->hasTypename() &&
7937 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7938 }
7939 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
7940 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
7941 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7942 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7943 }
7944 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
7945 return isSameQualifier(
7946 UX->getQualifier(),
7947 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
7948 }
7949
7950 // Using-pack declarations are only created by instantiation, and match if
7951 // they're instantiated from matching UnresolvedUsing...Decls.
7952 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
7953 return declaresSameEntity(
7954 UX->getInstantiatedFromUsingDecl(),
7955 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
7956 }
7957
7958 // Namespace alias definitions with the same target match.
7959 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
7960 const auto *NAY = cast<NamespaceAliasDecl>(Y);
7961 return NAX->getNamespace()->Equals(NAY->getNamespace());
7962 }
7963
7964 if (const auto *UX = dyn_cast<UsingEnumDecl>(X)) {
7965 const auto *UY = cast<UsingEnumDecl>(Y);
7966 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7967 declaresSameEntity(UX->getEnumDecl(), UY->getEnumDecl());
7968 }
7969
7970 return false;
7971}
7972
7975 switch (Arg.getKind()) {
7977 return Arg;
7978
7980 return TemplateArgument(Arg.getAsExpr(), /*IsCanonical=*/true,
7981 Arg.getIsDefaulted());
7982
7984 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
7986 Arg.getIsDefaulted());
7987 }
7988
7991 /*isNullPtr*/ true, Arg.getIsDefaulted());
7992
7995 Arg.getIsDefaulted());
7996
7998 return TemplateArgument(
8001
8004
8006 return TemplateArgument(*this,
8009
8012 /*isNullPtr*/ false, Arg.getIsDefaulted());
8013
8015 bool AnyNonCanonArgs = false;
8016 auto CanonArgs = ::getCanonicalTemplateArguments(
8017 *this, Arg.pack_elements(), AnyNonCanonArgs);
8018 if (!AnyNonCanonArgs)
8019 return Arg;
8021 const_cast<ASTContext &>(*this), CanonArgs);
8022 NewArg.setIsDefaulted(Arg.getIsDefaulted());
8023 return NewArg;
8024 }
8025 }
8026
8027 // Silence GCC warning
8028 llvm_unreachable("Unhandled template argument kind");
8029}
8030
8032 const TemplateArgument &Arg2) const {
8033 if (Arg1.getKind() != Arg2.getKind())
8034 return false;
8035
8036 switch (Arg1.getKind()) {
8038 llvm_unreachable("Comparing NULL template argument");
8039
8041 return hasSameType(Arg1.getAsType(), Arg2.getAsType());
8042
8044 return Arg1.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl() ==
8046
8048 return hasSameType(Arg1.getNullPtrType(), Arg2.getNullPtrType());
8049
8054
8056 return llvm::APSInt::isSameValue(Arg1.getAsIntegral(),
8057 Arg2.getAsIntegral());
8058
8060 return Arg1.structurallyEquals(Arg2);
8061
8063 llvm::FoldingSetNodeID ID1, ID2;
8064 Arg1.getAsExpr()->Profile(ID1, *this, /*Canonical=*/true);
8065 Arg2.getAsExpr()->Profile(ID2, *this, /*Canonical=*/true);
8066 return ID1 == ID2;
8067 }
8068
8070 return llvm::equal(
8071 Arg1.getPackAsArray(), Arg2.getPackAsArray(),
8072 [&](const TemplateArgument &Arg1, const TemplateArgument &Arg2) {
8073 return isSameTemplateArgument(Arg1, Arg2);
8074 });
8075 }
8076
8077 llvm_unreachable("Unhandled template argument kind");
8078}
8079
8081 // Handle the non-qualified case efficiently.
8082 if (!T.hasLocalQualifiers()) {
8083 // Handle the common positive case fast.
8084 if (const auto *AT = dyn_cast<ArrayType>(T))
8085 return AT;
8086 }
8087
8088 // Handle the common negative case fast.
8089 if (!isa<ArrayType>(T.getCanonicalType()))
8090 return nullptr;
8091
8092 // Apply any qualifiers from the array type to the element type. This
8093 // implements C99 6.7.3p8: "If the specification of an array type includes
8094 // any type qualifiers, the element type is so qualified, not the array type."
8095
8096 // If we get here, we either have type qualifiers on the type, or we have
8097 // sugar such as a typedef in the way. If we have type qualifiers on the type
8098 // we must propagate them down into the element type.
8099
8100 SplitQualType split = T.getSplitDesugaredType();
8101 Qualifiers qs = split.Quals;
8102
8103 // If we have a simple case, just return now.
8104 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
8105 if (!ATy || qs.empty())
8106 return ATy;
8107
8108 // Otherwise, we have an array and we have qualifiers on it. Push the
8109 // qualifiers into the array element type and return a new array type.
8110 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
8111
8112 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
8113 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
8114 CAT->getSizeExpr(),
8115 CAT->getSizeModifier(),
8116 CAT->getIndexTypeCVRQualifiers()));
8117 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
8119 IAT->getSizeModifier(),
8120 IAT->getIndexTypeCVRQualifiers()));
8121
8122 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
8124 NewEltTy, DSAT->getSizeExpr(), DSAT->getSizeModifier(),
8125 DSAT->getIndexTypeCVRQualifiers()));
8126
8127 const auto *VAT = cast<VariableArrayType>(ATy);
8128 return cast<ArrayType>(
8129 getVariableArrayType(NewEltTy, VAT->getSizeExpr(), VAT->getSizeModifier(),
8130 VAT->getIndexTypeCVRQualifiers()));
8131}
8132
8134 if (getLangOpts().HLSL && T.getAddressSpace() == LangAS::hlsl_groupshared)
8135 return getLValueReferenceType(T);
8136 if (getLangOpts().HLSL && T->isConstantArrayType())
8137 return getArrayParameterType(T);
8138 if (T->isArrayType() || T->isFunctionType())
8139 return getDecayedType(T);
8140 return T;
8141}
8142
8146 return T.getUnqualifiedType();
8147}
8148
8150 // C++ [except.throw]p3:
8151 // A throw-expression initializes a temporary object, called the exception
8152 // object, the type of which is determined by removing any top-level
8153 // cv-qualifiers from the static type of the operand of throw and adjusting
8154 // the type from "array of T" or "function returning T" to "pointer to T"
8155 // or "pointer to function returning T", [...]
8157 if (T->isArrayType() || T->isFunctionType())
8158 T = getDecayedType(T);
8159 return T.getUnqualifiedType();
8160}
8161
8162/// getArrayDecayedType - Return the properly qualified result of decaying the
8163/// specified array type to a pointer. This operation is non-trivial when
8164/// handling typedefs etc. The canonical type of "T" must be an array type,
8165/// this returns a pointer to a properly qualified element of the array.
8166///
8167/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
8169 // Get the element type with 'getAsArrayType' so that we don't lose any
8170 // typedefs in the element type of the array. This also handles propagation
8171 // of type qualifiers from the array type into the element type if present
8172 // (C99 6.7.3p8).
8173 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
8174 assert(PrettyArrayType && "Not an array type!");
8175
8176 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
8177
8178 // int x[restrict 4] -> int *restrict
8180 PrettyArrayType->getIndexTypeQualifiers());
8181
8182 // int x[_Nullable] -> int * _Nullable
8183 if (auto Nullability = Ty->getNullability()) {
8184 Result = const_cast<ASTContext *>(this)->getAttributedType(*Nullability,
8185 Result, Result);
8186 }
8187 return Result;
8188}
8189
8191 return getBaseElementType(array->getElementType());
8192}
8193
8195 Qualifiers qs;
8196 while (true) {
8197 SplitQualType split = type.getSplitDesugaredType();
8198 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
8199 if (!array) break;
8200
8201 type = array->getElementType();
8203 }
8204
8205 return getQualifiedType(type, qs);
8206}
8207
8208/// getConstantArrayElementCount - Returns number of constant array elements.
8209uint64_t
8211 uint64_t ElementCount = 1;
8212 do {
8213 ElementCount *= CA->getZExtSize();
8214 CA = dyn_cast_or_null<ConstantArrayType>(
8216 } while (CA);
8217 return ElementCount;
8218}
8219
8221 const ArrayInitLoopExpr *AILE) const {
8222 if (!AILE)
8223 return 0;
8224
8225 uint64_t ElementCount = 1;
8226
8227 do {
8228 ElementCount *= AILE->getArraySize().getZExtValue();
8229 AILE = dyn_cast<ArrayInitLoopExpr>(AILE->getSubExpr());
8230 } while (AILE);
8231
8232 return ElementCount;
8233}
8234
8235/// getFloatingRank - Return a relative rank for floating point types.
8236/// This routine will assert if passed a built-in type that isn't a float.
8238 if (const auto *CT = T->getAs<ComplexType>())
8239 return getFloatingRank(CT->getElementType());
8240
8241 switch (T->castAs<BuiltinType>()->getKind()) {
8242 default: llvm_unreachable("getFloatingRank(): not a floating type");
8243 case BuiltinType::Float16: return Float16Rank;
8244 case BuiltinType::Half: return HalfRank;
8245 case BuiltinType::Float: return FloatRank;
8246 case BuiltinType::Double: return DoubleRank;
8247 case BuiltinType::LongDouble: return LongDoubleRank;
8248 case BuiltinType::Float128: return Float128Rank;
8249 case BuiltinType::BFloat16: return BFloat16Rank;
8250 case BuiltinType::Ibm128: return Ibm128Rank;
8251 }
8252}
8253
8254/// getFloatingTypeOrder - Compare the rank of the two specified floating
8255/// point types, ignoring the domain of the type (i.e. 'double' ==
8256/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
8257/// LHS < RHS, return -1.
8259 FloatingRank LHSR = getFloatingRank(LHS);
8260 FloatingRank RHSR = getFloatingRank(RHS);
8261
8262 if (LHSR == RHSR)
8263 return 0;
8264 if (LHSR > RHSR)
8265 return 1;
8266 return -1;
8267}
8268
8271 return 0;
8272 return getFloatingTypeOrder(LHS, RHS);
8273}
8274
8275/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
8276/// routine will assert if passed a built-in type that isn't an integer or enum,
8277/// or if it is not canonicalized.
8278unsigned ASTContext::getIntegerRank(const Type *T) const {
8279 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
8280
8281 // Results in this 'losing' to any type of the same size, but winning if
8282 // larger.
8283 if (const auto *EIT = dyn_cast<BitIntType>(T))
8284 return 0 + (EIT->getNumBits() << 3);
8285
8286 if (const auto *OBT = dyn_cast<OverflowBehaviorType>(T))
8287 return getIntegerRank(OBT->getUnderlyingType().getTypePtr());
8288
8289 switch (cast<BuiltinType>(T)->getKind()) {
8290 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
8291 case BuiltinType::Bool:
8292 return 1 + (getIntWidth(BoolTy) << 3);
8293 case BuiltinType::Char_S:
8294 case BuiltinType::Char_U:
8295 case BuiltinType::SChar:
8296 case BuiltinType::UChar:
8297 return 2 + (getIntWidth(CharTy) << 3);
8298 case BuiltinType::Short:
8299 case BuiltinType::UShort:
8300 return 3 + (getIntWidth(ShortTy) << 3);
8301 case BuiltinType::Int:
8302 case BuiltinType::UInt:
8303 return 4 + (getIntWidth(IntTy) << 3);
8304 case BuiltinType::Long:
8305 case BuiltinType::ULong:
8306 return 5 + (getIntWidth(LongTy) << 3);
8307 case BuiltinType::LongLong:
8308 case BuiltinType::ULongLong:
8309 return 6 + (getIntWidth(LongLongTy) << 3);
8310 case BuiltinType::Int128:
8311 case BuiltinType::UInt128:
8312 return 7 + (getIntWidth(Int128Ty) << 3);
8313
8314 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
8315 // their underlying types" [c++20 conv.rank]
8316 case BuiltinType::Char8:
8317 return getIntegerRank(UnsignedCharTy.getTypePtr());
8318 case BuiltinType::Char16:
8319 return getIntegerRank(
8320 getFromTargetType(Target->getChar16Type()).getTypePtr());
8321 case BuiltinType::Char32:
8322 return getIntegerRank(
8323 getFromTargetType(Target->getChar32Type()).getTypePtr());
8324 case BuiltinType::WChar_S:
8325 case BuiltinType::WChar_U:
8326 return getIntegerRank(
8327 getFromTargetType(Target->getWCharType()).getTypePtr());
8328 }
8329}
8330
8331/// Whether this is a promotable bitfield reference according
8332/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
8333///
8334/// \returns the type this bit-field will promote to, or NULL if no
8335/// promotion occurs.
8337 if (E->isTypeDependent() || E->isValueDependent())
8338 return {};
8339
8340 // C++ [conv.prom]p5:
8341 // If the bit-field has an enumerated type, it is treated as any other
8342 // value of that type for promotion purposes.
8344 return {};
8345
8346 // FIXME: We should not do this unless E->refersToBitField() is true. This
8347 // matters in C where getSourceBitField() will find bit-fields for various
8348 // cases where the source expression is not a bit-field designator.
8349
8350 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
8351 if (!Field)
8352 return {};
8353
8354 QualType FT = Field->getType();
8355
8356 uint64_t BitWidth = Field->getBitWidthValue();
8357 uint64_t IntSize = getTypeSize(IntTy);
8358 // C++ [conv.prom]p5:
8359 // A prvalue for an integral bit-field can be converted to a prvalue of type
8360 // int if int can represent all the values of the bit-field; otherwise, it
8361 // can be converted to unsigned int if unsigned int can represent all the
8362 // values of the bit-field. If the bit-field is larger yet, no integral
8363 // promotion applies to it.
8364 // C11 6.3.1.1/2:
8365 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
8366 // If an int can represent all values of the original type (as restricted by
8367 // the width, for a bit-field), the value is converted to an int; otherwise,
8368 // it is converted to an unsigned int.
8369 //
8370 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
8371 // We perform that promotion here to match GCC and C++.
8372 // FIXME: C does not permit promotion of an enum bit-field whose rank is
8373 // greater than that of 'int'. We perform that promotion to match GCC.
8374 //
8375 // C23 6.3.1.1p2:
8376 // The value from a bit-field of a bit-precise integer type is converted to
8377 // the corresponding bit-precise integer type. (The rest is the same as in
8378 // C11.)
8379 if (QualType QT = Field->getType(); QT->isBitIntType())
8380 return QT;
8381
8382 if (BitWidth < IntSize)
8383 return IntTy;
8384
8385 if (BitWidth == IntSize)
8386 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
8387
8388 // Bit-fields wider than int are not subject to promotions, and therefore act
8389 // like the base type. GCC has some weird bugs in this area that we
8390 // deliberately do not follow (GCC follows a pre-standard resolution to
8391 // C's DR315 which treats bit-width as being part of the type, and this leaks
8392 // into their semantics in some cases).
8393 return {};
8394}
8395
8396/// getPromotedIntegerType - Returns the type that Promotable will
8397/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
8398/// integer type.
8400 assert(!Promotable.isNull());
8401 assert(isPromotableIntegerType(Promotable));
8402 if (const auto *ED = Promotable->getAsEnumDecl())
8403 return ED->getPromotionType();
8404
8405 // OverflowBehaviorTypes promote their underlying type and preserve OBT
8406 // qualifier.
8407 if (const auto *OBT = Promotable->getAs<OverflowBehaviorType>()) {
8408 QualType PromotedUnderlying =
8409 getPromotedIntegerType(OBT->getUnderlyingType());
8410 return getOverflowBehaviorType(OBT->getBehaviorKind(), PromotedUnderlying);
8411 }
8412
8413 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
8414 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
8415 // (3.9.1) can be converted to a prvalue of the first of the following
8416 // types that can represent all the values of its underlying type:
8417 // int, unsigned int, long int, unsigned long int, long long int, or
8418 // unsigned long long int [...]
8419 // FIXME: Is there some better way to compute this?
8420 if (BT->getKind() == BuiltinType::WChar_S ||
8421 BT->getKind() == BuiltinType::WChar_U ||
8422 BT->getKind() == BuiltinType::Char8 ||
8423 BT->getKind() == BuiltinType::Char16 ||
8424 BT->getKind() == BuiltinType::Char32) {
8425 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
8426 uint64_t FromSize = getTypeSize(BT);
8427 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
8429 for (const auto &PT : PromoteTypes) {
8430 uint64_t ToSize = getTypeSize(PT);
8431 if (FromSize < ToSize ||
8432 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
8433 return PT;
8434 }
8435 llvm_unreachable("char type should fit into long long");
8436 }
8437 }
8438
8439 // At this point, we should have a signed or unsigned integer type.
8440 if (Promotable->isSignedIntegerType())
8441 return IntTy;
8442 uint64_t PromotableSize = getIntWidth(Promotable);
8443 uint64_t IntSize = getIntWidth(IntTy);
8444 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
8445 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
8446}
8447
8448/// Recurses in pointer/array types until it finds an objc retainable
8449/// type and returns its ownership.
8451 while (!T.isNull()) {
8452 if (T.getObjCLifetime() != Qualifiers::OCL_None)
8453 return T.getObjCLifetime();
8454 if (T->isArrayType())
8455 T = getBaseElementType(T);
8456 else if (const auto *PT = T->getAs<PointerType>())
8457 T = PT->getPointeeType();
8458 else if (const auto *RT = T->getAs<ReferenceType>())
8459 T = RT->getPointeeType();
8460 else
8461 break;
8462 }
8463
8464 return Qualifiers::OCL_None;
8465}
8466
8467static const Type *getIntegerTypeForEnum(const EnumType *ET) {
8468 // Incomplete enum types are not treated as integer types.
8469 // FIXME: In C++, enum types are never integer types.
8470 const EnumDecl *ED = ET->getDecl()->getDefinitionOrSelf();
8471 if (ED->isComplete() && !ED->isScoped())
8472 return ED->getIntegerType().getTypePtr();
8473 return nullptr;
8474}
8475
8476/// getIntegerTypeOrder - Returns the highest ranked integer type:
8477/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
8478/// LHS < RHS, return -1.
8480 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
8481 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
8482
8483 // Unwrap enums to their underlying type.
8484 if (const auto *ET = dyn_cast<EnumType>(LHSC))
8485 LHSC = getIntegerTypeForEnum(ET);
8486 if (const auto *ET = dyn_cast<EnumType>(RHSC))
8487 RHSC = getIntegerTypeForEnum(ET);
8488
8489 if (LHSC == RHSC) return 0;
8490
8491 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
8492 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
8493
8494 unsigned LHSRank = getIntegerRank(LHSC);
8495 unsigned RHSRank = getIntegerRank(RHSC);
8496
8497 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
8498 if (LHSRank == RHSRank) return 0;
8499 return LHSRank > RHSRank ? 1 : -1;
8500 }
8501
8502 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
8503 if (LHSUnsigned) {
8504 // If the unsigned [LHS] type is larger, return it.
8505 if (LHSRank >= RHSRank)
8506 return 1;
8507
8508 // If the signed type can represent all values of the unsigned type, it
8509 // wins. Because we are dealing with 2's complement and types that are
8510 // powers of two larger than each other, this is always safe.
8511 return -1;
8512 }
8513
8514 // If the unsigned [RHS] type is larger, return it.
8515 if (RHSRank >= LHSRank)
8516 return -1;
8517
8518 // If the signed type can represent all values of the unsigned type, it
8519 // wins. Because we are dealing with 2's complement and types that are
8520 // powers of two larger than each other, this is always safe.
8521 return 1;
8522}
8523
8525 if (CFConstantStringTypeDecl)
8526 return CFConstantStringTypeDecl;
8527
8528 assert(!CFConstantStringTagDecl &&
8529 "tag and typedef should be initialized together");
8530 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
8531 CFConstantStringTagDecl->startDefinition();
8532
8533 struct {
8534 QualType Type;
8535 const char *Name;
8536 } Fields[5];
8537 unsigned Count = 0;
8538
8539 /// Objective-C ABI
8540 ///
8541 /// typedef struct __NSConstantString_tag {
8542 /// const int *isa;
8543 /// int flags;
8544 /// const char *str;
8545 /// long length;
8546 /// } __NSConstantString;
8547 ///
8548 /// Swift ABI (4.1, 4.2)
8549 ///
8550 /// typedef struct __NSConstantString_tag {
8551 /// uintptr_t _cfisa;
8552 /// uintptr_t _swift_rc;
8553 /// _Atomic(uint64_t) _cfinfoa;
8554 /// const char *_ptr;
8555 /// uint32_t _length;
8556 /// } __NSConstantString;
8557 ///
8558 /// Swift ABI (5.0)
8559 ///
8560 /// typedef struct __NSConstantString_tag {
8561 /// uintptr_t _cfisa;
8562 /// uintptr_t _swift_rc;
8563 /// _Atomic(uint64_t) _cfinfoa;
8564 /// const char *_ptr;
8565 /// uintptr_t _length;
8566 /// } __NSConstantString;
8567
8568 const auto CFRuntime = getLangOpts().CFRuntime;
8569 if (static_cast<unsigned>(CFRuntime) <
8570 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
8571 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
8572 Fields[Count++] = { IntTy, "flags" };
8573 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
8574 Fields[Count++] = { LongTy, "length" };
8575 } else {
8576 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
8577 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
8578 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
8579 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
8582 Fields[Count++] = { IntTy, "_ptr" };
8583 else
8584 Fields[Count++] = { getUIntPtrType(), "_ptr" };
8585 }
8586
8587 // Create fields
8588 for (unsigned i = 0; i < Count; ++i) {
8589 FieldDecl *Field =
8590 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
8591 SourceLocation(), &Idents.get(Fields[i].Name),
8592 Fields[i].Type, /*TInfo=*/nullptr,
8593 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8594 Field->setAccess(AS_public);
8595 CFConstantStringTagDecl->addDecl(Field);
8596 }
8597
8598 CFConstantStringTagDecl->completeDefinition();
8599 // This type is designed to be compatible with NSConstantString, but cannot
8600 // use the same name, since NSConstantString is an interface.
8601 CanQualType tagType = getCanonicalTagType(CFConstantStringTagDecl);
8602 CFConstantStringTypeDecl =
8603 buildImplicitTypedef(tagType, "__NSConstantString");
8604
8605 return CFConstantStringTypeDecl;
8606}
8607
8609 if (!CFConstantStringTagDecl)
8610 getCFConstantStringDecl(); // Build the tag and the typedef.
8611 return CFConstantStringTagDecl;
8612}
8613
8614// getCFConstantStringType - Return the type used for constant CFStrings.
8619
8621 if (ObjCSuperType.isNull()) {
8622 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
8623 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
8624 ObjCSuperType = getCanonicalTagType(ObjCSuperTypeDecl);
8625 }
8626 return ObjCSuperType;
8627}
8628
8630 const auto *TT = T->castAs<TypedefType>();
8631 CFConstantStringTypeDecl = cast<TypedefDecl>(TT->getDecl());
8632 CFConstantStringTagDecl = TT->castAsRecordDecl();
8633}
8634
8636 if (BlockDescriptorType)
8637 return getCanonicalTagType(BlockDescriptorType);
8638
8639 RecordDecl *RD;
8640 // FIXME: Needs the FlagAppleBlock bit.
8641 RD = buildImplicitRecord("__block_descriptor");
8642 RD->startDefinition();
8643
8644 QualType FieldTypes[] = {
8647 };
8648
8649 static const char *const FieldNames[] = {
8650 "reserved",
8651 "Size"
8652 };
8653
8654 for (size_t i = 0; i < 2; ++i) {
8656 *this, RD, SourceLocation(), SourceLocation(),
8657 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8658 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8659 Field->setAccess(AS_public);
8660 RD->addDecl(Field);
8661 }
8662
8663 RD->completeDefinition();
8664
8665 BlockDescriptorType = RD;
8666
8667 return getCanonicalTagType(BlockDescriptorType);
8668}
8669
8671 if (BlockDescriptorExtendedType)
8672 return getCanonicalTagType(BlockDescriptorExtendedType);
8673
8674 RecordDecl *RD;
8675 // FIXME: Needs the FlagAppleBlock bit.
8676 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
8677 RD->startDefinition();
8678
8679 QualType FieldTypes[] = {
8684 };
8685
8686 static const char *const FieldNames[] = {
8687 "reserved",
8688 "Size",
8689 "CopyFuncPtr",
8690 "DestroyFuncPtr"
8691 };
8692
8693 for (size_t i = 0; i < 4; ++i) {
8695 *this, RD, SourceLocation(), SourceLocation(),
8696 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8697 /*BitWidth=*/nullptr,
8698 /*Mutable=*/false, ICIS_NoInit);
8699 Field->setAccess(AS_public);
8700 RD->addDecl(Field);
8701 }
8702
8703 RD->completeDefinition();
8704
8705 BlockDescriptorExtendedType = RD;
8706 return getCanonicalTagType(BlockDescriptorExtendedType);
8707}
8708
8710 const auto *BT = dyn_cast<BuiltinType>(T);
8711
8712 if (!BT) {
8713 if (isa<PipeType>(T))
8714 return OCLTK_Pipe;
8715
8716 return OCLTK_Default;
8717 }
8718
8719 switch (BT->getKind()) {
8720#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8721 case BuiltinType::Id: \
8722 return OCLTK_Image;
8723#include "clang/Basic/OpenCLImageTypes.def"
8724
8725 case BuiltinType::OCLClkEvent:
8726 return OCLTK_ClkEvent;
8727
8728 case BuiltinType::OCLEvent:
8729 return OCLTK_Event;
8730
8731 case BuiltinType::OCLQueue:
8732 return OCLTK_Queue;
8733
8734 case BuiltinType::OCLReserveID:
8735 return OCLTK_ReserveID;
8736
8737 case BuiltinType::OCLSampler:
8738 return OCLTK_Sampler;
8739
8740 default:
8741 return OCLTK_Default;
8742 }
8743}
8744
8746 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
8747}
8748
8749/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
8750/// requires copy/dispose. Note that this must match the logic
8751/// in buildByrefHelpers.
8753 const VarDecl *D) {
8754 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
8755 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
8756 if (!copyExpr && record->hasTrivialDestructor()) return false;
8757
8758 return true;
8759 }
8760
8762 return true;
8763
8764 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
8765 // move or destroy.
8767 return true;
8768
8769 if (!Ty->isObjCRetainableType()) return false;
8770
8771 Qualifiers qs = Ty.getQualifiers();
8772
8773 // If we have lifetime, that dominates.
8774 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
8775 switch (lifetime) {
8776 case Qualifiers::OCL_None: llvm_unreachable("impossible");
8777
8778 // These are just bits as far as the runtime is concerned.
8781 return false;
8782
8783 // These cases should have been taken care of when checking the type's
8784 // non-triviality.
8787 llvm_unreachable("impossible");
8788 }
8789 llvm_unreachable("fell out of lifetime switch!");
8790 }
8791 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
8793}
8794
8796 Qualifiers::ObjCLifetime &LifeTime,
8797 bool &HasByrefExtendedLayout) const {
8798 if (!getLangOpts().ObjC ||
8799 getLangOpts().getGC() != LangOptions::NonGC)
8800 return false;
8801
8802 HasByrefExtendedLayout = false;
8803 if (Ty->isRecordType()) {
8804 HasByrefExtendedLayout = true;
8805 LifeTime = Qualifiers::OCL_None;
8806 } else if ((LifeTime = Ty.getObjCLifetime())) {
8807 // Honor the ARC qualifiers.
8808 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
8809 // The MRR rule.
8811 } else {
8812 LifeTime = Qualifiers::OCL_None;
8813 }
8814 return true;
8815}
8816
8818 assert(Target && "Expected target to be initialized");
8819 const llvm::Triple &T = Target->getTriple();
8820 // Windows is LLP64 rather than LP64
8821 if (T.isOSWindows() && T.isArch64Bit())
8822 return UnsignedLongLongTy;
8823 return UnsignedLongTy;
8824}
8825
8827 assert(Target && "Expected target to be initialized");
8828 const llvm::Triple &T = Target->getTriple();
8829 // Windows is LLP64 rather than LP64
8830 if (T.isOSWindows() && T.isArch64Bit())
8831 return LongLongTy;
8832 return LongTy;
8833}
8834
8836 if (!ObjCInstanceTypeDecl)
8837 ObjCInstanceTypeDecl =
8838 buildImplicitTypedef(getObjCIdType(), "instancetype");
8839 return ObjCInstanceTypeDecl;
8840}
8841
8842// This returns true if a type has been typedefed to BOOL:
8843// typedef <type> BOOL;
8845 if (const auto *TT = dyn_cast<TypedefType>(T))
8846 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
8847 return II->isStr("BOOL");
8848
8849 return false;
8850}
8851
8852/// getObjCEncodingTypeSize returns size of type for objective-c encoding
8853/// purpose.
8855 if (!type->isIncompleteArrayType() && type->isIncompleteType())
8856 return CharUnits::Zero();
8857
8859
8860 // Make all integer and enum types at least as large as an int
8861 if (sz.isPositive() && type->isIntegralOrEnumerationType())
8862 sz = std::max(sz, getTypeSizeInChars(IntTy));
8863 // Treat arrays as pointers, since that's how they're passed in.
8864 else if (type->isArrayType())
8866 return sz;
8867}
8868
8875
8878 if (!VD->isInline())
8880
8881 // In almost all cases, it's a weak definition.
8882 auto *First = VD->getFirstDecl();
8883 if (First->isInlineSpecified() || !First->isStaticDataMember())
8885
8886 // If there's a file-context declaration in this translation unit, it's a
8887 // non-discardable definition.
8888 for (auto *D : VD->redecls())
8890 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
8892
8893 // If we've not seen one yet, we don't know.
8895}
8896
8897static std::string charUnitsToString(const CharUnits &CU) {
8898 return llvm::itostr(CU.getQuantity());
8899}
8900
8901/// getObjCEncodingForBlock - Return the encoded type for this block
8902/// declaration.
8904 std::string S;
8905
8906 const BlockDecl *Decl = Expr->getBlockDecl();
8907 QualType BlockTy =
8909 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
8910 // Encode result type.
8911 if (getLangOpts().EncodeExtendedBlockSig)
8913 true /*Extended*/);
8914 else
8915 getObjCEncodingForType(BlockReturnTy, S);
8916 // Compute size of all parameters.
8917 // Start with computing size of a pointer in number of bytes.
8918 // FIXME: There might(should) be a better way of doing this computation!
8920 CharUnits ParmOffset = PtrSize;
8921 for (auto *PI : Decl->parameters()) {
8922 QualType PType = PI->getType();
8924 if (sz.isZero())
8925 continue;
8926 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
8927 ParmOffset += sz;
8928 }
8929 // Size of the argument frame
8930 S += charUnitsToString(ParmOffset);
8931 // Block pointer and offset.
8932 S += "@?0";
8933
8934 // Argument types.
8935 ParmOffset = PtrSize;
8936 for (auto *PVDecl : Decl->parameters()) {
8937 QualType PType = PVDecl->getOriginalType();
8938 if (const auto *AT =
8939 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8940 // Use array's original type only if it has known number of
8941 // elements.
8942 if (!isa<ConstantArrayType>(AT))
8943 PType = PVDecl->getType();
8944 } else if (PType->isFunctionType())
8945 PType = PVDecl->getType();
8946 if (getLangOpts().EncodeExtendedBlockSig)
8948 S, true /*Extended*/);
8949 else
8950 getObjCEncodingForType(PType, S);
8951 S += charUnitsToString(ParmOffset);
8952 ParmOffset += getObjCEncodingTypeSize(PType);
8953 }
8954
8955 return S;
8956}
8957
8958std::string
8960 std::string S;
8961 // Encode result type.
8962 getObjCEncodingForType(Decl->getReturnType(), S);
8963 CharUnits ParmOffset;
8964 // Compute size of all parameters.
8965 for (auto *PI : Decl->parameters()) {
8966 QualType PType = PI->getType();
8968 if (sz.isZero())
8969 continue;
8970
8971 assert(sz.isPositive() &&
8972 "getObjCEncodingForFunctionDecl - Incomplete param type");
8973 ParmOffset += sz;
8974 }
8975 S += charUnitsToString(ParmOffset);
8976 ParmOffset = CharUnits::Zero();
8977
8978 // Argument types.
8979 for (auto *PVDecl : Decl->parameters()) {
8980 QualType PType = PVDecl->getOriginalType();
8981 if (const auto *AT =
8982 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8983 // Use array's original type only if it has known number of
8984 // elements.
8985 if (!isa<ConstantArrayType>(AT))
8986 PType = PVDecl->getType();
8987 } else if (PType->isFunctionType())
8988 PType = PVDecl->getType();
8989 getObjCEncodingForType(PType, S);
8990 S += charUnitsToString(ParmOffset);
8991 ParmOffset += getObjCEncodingTypeSize(PType);
8992 }
8993
8994 return S;
8995}
8996
8997/// getObjCEncodingForMethodParameter - Return the encoded type for a single
8998/// method parameter or return type. If Extended, include class names and
8999/// block object types.
9001 QualType T, std::string& S,
9002 bool Extended) const {
9003 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
9005 // Encode parameter type.
9006 ObjCEncOptions Options = ObjCEncOptions()
9007 .setExpandPointedToStructures()
9008 .setExpandStructures()
9009 .setIsOutermostType();
9010 if (Extended)
9011 Options.setEncodeBlockParameters().setEncodeClassNames();
9012 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
9013}
9014
9015/// getObjCEncodingForMethodDecl - Return the encoded type for this method
9016/// declaration.
9018 bool Extended) const {
9019 // FIXME: This is not very efficient.
9020 // Encode return type.
9021 std::string S;
9022 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
9023 Decl->getReturnType(), S, Extended);
9024 // Compute size of all parameters.
9025 // Start with computing size of a pointer in number of bytes.
9026 // FIXME: There might(should) be a better way of doing this computation!
9028 // The first two arguments (self and _cmd) are pointers; account for
9029 // their size.
9030 CharUnits ParmOffset = 2 * PtrSize;
9031 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
9032 E = Decl->sel_param_end(); PI != E; ++PI) {
9033 QualType PType = (*PI)->getType();
9035 if (sz.isZero())
9036 continue;
9037
9038 assert(sz.isPositive() &&
9039 "getObjCEncodingForMethodDecl - Incomplete param type");
9040 ParmOffset += sz;
9041 }
9042 S += charUnitsToString(ParmOffset);
9043 S += "@0:";
9044 S += charUnitsToString(PtrSize);
9045
9046 // Argument types.
9047 ParmOffset = 2 * PtrSize;
9048 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
9049 E = Decl->sel_param_end(); PI != E; ++PI) {
9050 const ParmVarDecl *PVDecl = *PI;
9051 QualType PType = PVDecl->getOriginalType();
9052 if (const auto *AT =
9053 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
9054 // Use array's original type only if it has known number of
9055 // elements.
9056 if (!isa<ConstantArrayType>(AT))
9057 PType = PVDecl->getType();
9058 } else if (PType->isFunctionType())
9059 PType = PVDecl->getType();
9061 PType, S, Extended);
9062 S += charUnitsToString(ParmOffset);
9063 ParmOffset += getObjCEncodingTypeSize(PType);
9064 }
9065
9066 return S;
9067}
9068
9071 const ObjCPropertyDecl *PD,
9072 const Decl *Container) const {
9073 if (!Container)
9074 return nullptr;
9075 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
9076 for (auto *PID : CID->property_impls())
9077 if (PID->getPropertyDecl() == PD)
9078 return PID;
9079 } else {
9080 const auto *OID = cast<ObjCImplementationDecl>(Container);
9081 for (auto *PID : OID->property_impls())
9082 if (PID->getPropertyDecl() == PD)
9083 return PID;
9084 }
9085 return nullptr;
9086}
9087
9088/// getObjCEncodingForPropertyDecl - Return the encoded type for this
9089/// property declaration. If non-NULL, Container must be either an
9090/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
9091/// NULL when getting encodings for protocol properties.
9092/// Property attributes are stored as a comma-delimited C string. The simple
9093/// attributes readonly and bycopy are encoded as single characters. The
9094/// parametrized attributes, getter=name, setter=name, and ivar=name, are
9095/// encoded as single characters, followed by an identifier. Property types
9096/// are also encoded as a parametrized attribute. The characters used to encode
9097/// these attributes are defined by the following enumeration:
9098/// @code
9099/// enum PropertyAttributes {
9100/// kPropertyReadOnly = 'R', // property is read-only.
9101/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
9102/// kPropertyByref = '&', // property is a reference to the value last assigned
9103/// kPropertyDynamic = 'D', // property is dynamic
9104/// kPropertyGetter = 'G', // followed by getter selector name
9105/// kPropertySetter = 'S', // followed by setter selector name
9106/// kPropertyInstanceVariable = 'V' // followed by instance variable name
9107/// kPropertyType = 'T' // followed by old-style type encoding.
9108/// kPropertyWeak = 'W' // 'weak' property
9109/// kPropertyStrong = 'P' // property GC'able
9110/// kPropertyNonAtomic = 'N' // property non-atomic
9111/// kPropertyOptional = '?' // property optional
9112/// };
9113/// @endcode
9114std::string
9116 const Decl *Container) const {
9117 // Collect information from the property implementation decl(s).
9118 bool Dynamic = false;
9119 ObjCPropertyImplDecl *SynthesizePID = nullptr;
9120
9121 if (ObjCPropertyImplDecl *PropertyImpDecl =
9123 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
9124 Dynamic = true;
9125 else
9126 SynthesizePID = PropertyImpDecl;
9127 }
9128
9129 // FIXME: This is not very efficient.
9130 std::string S = "T";
9131
9132 // Encode result type.
9133 // GCC has some special rules regarding encoding of properties which
9134 // closely resembles encoding of ivars.
9136
9137 if (PD->isOptional())
9138 S += ",?";
9139
9140 if (PD->isReadOnly()) {
9141 S += ",R";
9143 S += ",C";
9145 S += ",&";
9147 S += ",W";
9148 } else {
9149 switch (PD->getSetterKind()) {
9150 case ObjCPropertyDecl::Assign: break;
9151 case ObjCPropertyDecl::Copy: S += ",C"; break;
9152 case ObjCPropertyDecl::Retain: S += ",&"; break;
9153 case ObjCPropertyDecl::Weak: S += ",W"; break;
9154 }
9155 }
9156
9157 // It really isn't clear at all what this means, since properties
9158 // are "dynamic by default".
9159 if (Dynamic)
9160 S += ",D";
9161
9163 S += ",N";
9164
9166 S += ",G";
9167 S += PD->getGetterName().getAsString();
9168 }
9169
9171 S += ",S";
9172 S += PD->getSetterName().getAsString();
9173 }
9174
9175 if (SynthesizePID) {
9176 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
9177 S += ",V";
9178 S += OID->getNameAsString();
9179 }
9180
9181 // FIXME: OBJCGC: weak & strong
9182 return S;
9183}
9184
9185/// getLegacyIntegralTypeEncoding -
9186/// Another legacy compatibility encoding: 32-bit longs are encoded as
9187/// 'l' or 'L' , but not always. For typedefs, we need to use
9188/// 'i' or 'I' instead if encoding a struct field, or a pointer!
9190 if (PointeeTy->getAs<TypedefType>()) {
9191 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
9192 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
9193 PointeeTy = UnsignedIntTy;
9194 else
9195 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
9196 PointeeTy = IntTy;
9197 }
9198 }
9199}
9200
9202 const FieldDecl *Field,
9203 QualType *NotEncodedT) const {
9204 // We follow the behavior of gcc, expanding structures which are
9205 // directly pointed to, and expanding embedded structures. Note that
9206 // these rules are sufficient to prevent recursive encoding of the
9207 // same type.
9208 getObjCEncodingForTypeImpl(T, S,
9209 ObjCEncOptions()
9210 .setExpandPointedToStructures()
9211 .setExpandStructures()
9212 .setIsOutermostType(),
9213 Field, NotEncodedT);
9214}
9215
9217 std::string& S) const {
9218 // Encode result type.
9219 // GCC has some special rules regarding encoding of properties which
9220 // closely resembles encoding of ivars.
9221 getObjCEncodingForTypeImpl(T, S,
9222 ObjCEncOptions()
9223 .setExpandPointedToStructures()
9224 .setExpandStructures()
9225 .setIsOutermostType()
9226 .setEncodingProperty(),
9227 /*Field=*/nullptr);
9228}
9229
9231 const BuiltinType *BT) {
9233 switch (kind) {
9234 case BuiltinType::Void: return 'v';
9235 case BuiltinType::Bool: return 'B';
9236 case BuiltinType::Char8:
9237 case BuiltinType::Char_U:
9238 case BuiltinType::UChar: return 'C';
9239 case BuiltinType::Char16:
9240 case BuiltinType::UShort: return 'S';
9241 case BuiltinType::Char32:
9242 case BuiltinType::UInt: return 'I';
9243 case BuiltinType::ULong:
9244 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
9245 case BuiltinType::UInt128: return 'T';
9246 case BuiltinType::ULongLong: return 'Q';
9247 case BuiltinType::Char_S:
9248 case BuiltinType::SChar: return 'c';
9249 case BuiltinType::Short: return 's';
9250 case BuiltinType::WChar_S:
9251 case BuiltinType::WChar_U:
9252 case BuiltinType::Int: return 'i';
9253 case BuiltinType::Long:
9254 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
9255 case BuiltinType::LongLong: return 'q';
9256 case BuiltinType::Int128: return 't';
9257 case BuiltinType::Float: return 'f';
9258 case BuiltinType::Double: return 'd';
9259 case BuiltinType::LongDouble: return 'D';
9260 case BuiltinType::NullPtr: return '*'; // like char*
9261
9262 case BuiltinType::BFloat16:
9263 case BuiltinType::Float16:
9264 case BuiltinType::Float128:
9265 case BuiltinType::Ibm128:
9266 case BuiltinType::Half:
9267 case BuiltinType::ShortAccum:
9268 case BuiltinType::Accum:
9269 case BuiltinType::LongAccum:
9270 case BuiltinType::UShortAccum:
9271 case BuiltinType::UAccum:
9272 case BuiltinType::ULongAccum:
9273 case BuiltinType::ShortFract:
9274 case BuiltinType::Fract:
9275 case BuiltinType::LongFract:
9276 case BuiltinType::UShortFract:
9277 case BuiltinType::UFract:
9278 case BuiltinType::ULongFract:
9279 case BuiltinType::SatShortAccum:
9280 case BuiltinType::SatAccum:
9281 case BuiltinType::SatLongAccum:
9282 case BuiltinType::SatUShortAccum:
9283 case BuiltinType::SatUAccum:
9284 case BuiltinType::SatULongAccum:
9285 case BuiltinType::SatShortFract:
9286 case BuiltinType::SatFract:
9287 case BuiltinType::SatLongFract:
9288 case BuiltinType::SatUShortFract:
9289 case BuiltinType::SatUFract:
9290 case BuiltinType::SatULongFract:
9291 // FIXME: potentially need @encodes for these!
9292 return ' ';
9293
9294#define SVE_TYPE(Name, Id, SingletonId) \
9295 case BuiltinType::Id:
9296#include "clang/Basic/AArch64ACLETypes.def"
9297#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9298#include "clang/Basic/RISCVVTypes.def"
9299#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9300#include "clang/Basic/WebAssemblyReferenceTypes.def"
9301#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
9302#include "clang/Basic/AMDGPUTypes.def"
9303 {
9304 DiagnosticsEngine &Diags = C->getDiagnostics();
9305 Diags.Report(diag::err_unsupported_objc_primitive_encoding)
9306 << QualType(BT, 0);
9307 return ' ';
9308 }
9309
9310 case BuiltinType::ObjCId:
9311 case BuiltinType::ObjCClass:
9312 case BuiltinType::ObjCSel:
9313 llvm_unreachable("@encoding ObjC primitive type");
9314
9315 // OpenCL and placeholder types don't need @encodings.
9316#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
9317 case BuiltinType::Id:
9318#include "clang/Basic/OpenCLImageTypes.def"
9319#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9320 case BuiltinType::Id:
9321#include "clang/Basic/OpenCLExtensionTypes.def"
9322 case BuiltinType::OCLEvent:
9323 case BuiltinType::OCLClkEvent:
9324 case BuiltinType::OCLQueue:
9325 case BuiltinType::OCLReserveID:
9326 case BuiltinType::OCLSampler:
9327 case BuiltinType::Dependent:
9328#define PPC_VECTOR_TYPE(Name, Id, Size) \
9329 case BuiltinType::Id:
9330#include "clang/Basic/PPCTypes.def"
9331#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9332#include "clang/Basic/HLSLIntangibleTypes.def"
9333#define BUILTIN_TYPE(KIND, ID)
9334#define PLACEHOLDER_TYPE(KIND, ID) \
9335 case BuiltinType::KIND:
9336#include "clang/AST/BuiltinTypes.def"
9337 llvm_unreachable("invalid builtin type for @encode");
9338 }
9339 llvm_unreachable("invalid BuiltinType::Kind value");
9340}
9341
9342static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED) {
9344
9345 // The encoding of an non-fixed enum type is always 'i', regardless of size.
9346 if (!Enum->isFixed())
9347 return 'i';
9348
9349 // The encoding of a fixed enum type matches its fixed underlying type.
9350 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
9352}
9353
9354static void EncodeBitField(const ASTContext *Ctx, std::string& S,
9355 QualType T, const FieldDecl *FD) {
9356 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
9357 S += 'b';
9358 // The NeXT runtime encodes bit fields as b followed by the number of bits.
9359 // The GNU runtime requires more information; bitfields are encoded as b,
9360 // then the offset (in bits) of the first element, then the type of the
9361 // bitfield, then the size in bits. For example, in this structure:
9362 //
9363 // struct
9364 // {
9365 // int integer;
9366 // int flags:2;
9367 // };
9368 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
9369 // runtime, but b32i2 for the GNU runtime. The reason for this extra
9370 // information is not especially sensible, but we're stuck with it for
9371 // compatibility with GCC, although providing it breaks anything that
9372 // actually uses runtime introspection and wants to work on both runtimes...
9373 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
9374 uint64_t Offset;
9375
9376 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
9377 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), IVD);
9378 } else {
9379 const RecordDecl *RD = FD->getParent();
9380 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
9381 Offset = RL.getFieldOffset(FD->getFieldIndex());
9382 }
9383
9384 S += llvm::utostr(Offset);
9385
9386 if (const auto *ET = T->getAsCanonical<EnumType>())
9387 S += ObjCEncodingForEnumDecl(Ctx, ET->getDecl());
9388 else {
9389 const auto *BT = T->castAs<BuiltinType>();
9390 S += getObjCEncodingForPrimitiveType(Ctx, BT);
9391 }
9392 }
9393 S += llvm::utostr(FD->getBitWidthValue());
9394}
9395
9396// Helper function for determining whether the encoded type string would include
9397// a template specialization type.
9399 bool VisitBasesAndFields) {
9400 T = T->getBaseElementTypeUnsafe();
9401
9402 if (auto *PT = T->getAs<PointerType>())
9404 PT->getPointeeType().getTypePtr(), false);
9405
9406 auto *CXXRD = T->getAsCXXRecordDecl();
9407
9408 if (!CXXRD)
9409 return false;
9410
9412 return true;
9413
9414 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
9415 return false;
9416
9417 for (const auto &B : CXXRD->bases())
9418 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
9419 true))
9420 return true;
9421
9422 for (auto *FD : CXXRD->fields())
9423 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
9424 true))
9425 return true;
9426
9427 return false;
9428}
9429
9430// FIXME: Use SmallString for accumulating string.
9431void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
9432 const ObjCEncOptions Options,
9433 const FieldDecl *FD,
9434 QualType *NotEncodedT) const {
9436 switch (CT->getTypeClass()) {
9437 case Type::Builtin:
9438 case Type::Enum:
9439 if (FD && FD->isBitField())
9440 return EncodeBitField(this, S, T, FD);
9441 if (const auto *BT = dyn_cast<BuiltinType>(CT))
9442 S += getObjCEncodingForPrimitiveType(this, BT);
9443 else
9444 S += ObjCEncodingForEnumDecl(this, cast<EnumType>(CT)->getDecl());
9445 return;
9446
9447 case Type::Complex:
9448 S += 'j';
9449 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
9450 ObjCEncOptions(),
9451 /*Field=*/nullptr);
9452 return;
9453
9454 case Type::Atomic:
9455 S += 'A';
9456 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
9457 ObjCEncOptions(),
9458 /*Field=*/nullptr);
9459 return;
9460
9461 // encoding for pointer or reference types.
9462 case Type::Pointer:
9463 case Type::LValueReference:
9464 case Type::RValueReference: {
9465 QualType PointeeTy;
9466 if (isa<PointerType>(CT)) {
9467 const auto *PT = T->castAs<PointerType>();
9468 if (PT->isObjCSelType()) {
9469 S += ':';
9470 return;
9471 }
9472 PointeeTy = PT->getPointeeType();
9473 } else {
9474 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
9475 }
9476
9477 bool isReadOnly = false;
9478 // For historical/compatibility reasons, the read-only qualifier of the
9479 // pointee gets emitted _before_ the '^'. The read-only qualifier of
9480 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
9481 // Also, do not emit the 'r' for anything but the outermost type!
9482 if (T->getAs<TypedefType>()) {
9483 if (Options.IsOutermostType() && T.isConstQualified()) {
9484 isReadOnly = true;
9485 S += 'r';
9486 }
9487 } else if (Options.IsOutermostType()) {
9488 QualType P = PointeeTy;
9489 while (auto PT = P->getAs<PointerType>())
9490 P = PT->getPointeeType();
9491 if (P.isConstQualified()) {
9492 isReadOnly = true;
9493 S += 'r';
9494 }
9495 }
9496 if (isReadOnly) {
9497 // Another legacy compatibility encoding. Some ObjC qualifier and type
9498 // combinations need to be rearranged.
9499 // Rewrite "in const" from "nr" to "rn"
9500 if (StringRef(S).ends_with("nr"))
9501 S.replace(S.end()-2, S.end(), "rn");
9502 }
9503
9504 if (PointeeTy->isCharType()) {
9505 // char pointer types should be encoded as '*' unless it is a
9506 // type that has been typedef'd to 'BOOL'.
9507 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
9508 S += '*';
9509 return;
9510 }
9511 } else if (const auto *RTy = PointeeTy->getAsCanonical<RecordType>()) {
9512 const IdentifierInfo *II = RTy->getDecl()->getIdentifier();
9513 // GCC binary compat: Need to convert "struct objc_class *" to "#".
9514 if (II == &Idents.get("objc_class")) {
9515 S += '#';
9516 return;
9517 }
9518 // GCC binary compat: Need to convert "struct objc_object *" to "@".
9519 if (II == &Idents.get("objc_object")) {
9520 S += '@';
9521 return;
9522 }
9523 // If the encoded string for the class includes template names, just emit
9524 // "^v" for pointers to the class.
9525 if (getLangOpts().CPlusPlus &&
9526 (!getLangOpts().EncodeCXXClassTemplateSpec &&
9528 RTy, Options.ExpandPointedToStructures()))) {
9529 S += "^v";
9530 return;
9531 }
9532 // fall through...
9533 }
9534 S += '^';
9536
9537 ObjCEncOptions NewOptions;
9538 if (Options.ExpandPointedToStructures())
9539 NewOptions.setExpandStructures();
9540 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
9541 /*Field=*/nullptr, NotEncodedT);
9542 return;
9543 }
9544
9545 case Type::ConstantArray:
9546 case Type::IncompleteArray:
9547 case Type::VariableArray: {
9548 const auto *AT = cast<ArrayType>(CT);
9549
9550 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
9551 // Incomplete arrays are encoded as a pointer to the array element.
9552 S += '^';
9553
9554 getObjCEncodingForTypeImpl(
9555 AT->getElementType(), S,
9556 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
9557 } else {
9558 S += '[';
9559
9560 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
9561 S += llvm::utostr(CAT->getZExtSize());
9562 else {
9563 //Variable length arrays are encoded as a regular array with 0 elements.
9565 "Unknown array type!");
9566 S += '0';
9567 }
9568
9569 getObjCEncodingForTypeImpl(
9570 AT->getElementType(), S,
9571 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
9572 NotEncodedT);
9573 S += ']';
9574 }
9575 return;
9576 }
9577
9578 case Type::FunctionNoProto:
9579 case Type::FunctionProto:
9580 S += '?';
9581 return;
9582
9583 case Type::Record: {
9584 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
9585 S += RDecl->isUnion() ? '(' : '{';
9586 // Anonymous structures print as '?'
9587 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
9588 S += II->getName();
9589 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
9590 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
9591 llvm::raw_string_ostream OS(S);
9592 printTemplateArgumentList(OS, TemplateArgs.asArray(),
9594 }
9595 } else {
9596 S += '?';
9597 }
9598 if (Options.ExpandStructures()) {
9599 S += '=';
9600 if (!RDecl->isUnion()) {
9601 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
9602 } else {
9603 for (const auto *Field : RDecl->fields()) {
9604 if (FD) {
9605 S += '"';
9606 S += Field->getNameAsString();
9607 S += '"';
9608 }
9609
9610 // Special case bit-fields.
9611 if (Field->isBitField()) {
9612 getObjCEncodingForTypeImpl(Field->getType(), S,
9613 ObjCEncOptions().setExpandStructures(),
9614 Field);
9615 } else {
9616 QualType qt = Field->getType();
9618 getObjCEncodingForTypeImpl(
9619 qt, S,
9620 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
9621 NotEncodedT);
9622 }
9623 }
9624 }
9625 }
9626 S += RDecl->isUnion() ? ')' : '}';
9627 return;
9628 }
9629
9630 case Type::BlockPointer: {
9631 const auto *BT = T->castAs<BlockPointerType>();
9632 S += "@?"; // Unlike a pointer-to-function, which is "^?".
9633 if (Options.EncodeBlockParameters()) {
9634 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
9635
9636 S += '<';
9637 // Block return type
9638 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
9639 Options.forComponentType(), FD, NotEncodedT);
9640 // Block self
9641 S += "@?";
9642 // Block parameters
9643 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
9644 for (const auto &I : FPT->param_types())
9645 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
9646 NotEncodedT);
9647 }
9648 S += '>';
9649 }
9650 return;
9651 }
9652
9653 case Type::ObjCObject: {
9654 // hack to match legacy encoding of *id and *Class
9655 QualType Ty = getObjCObjectPointerType(CT);
9656 if (Ty->isObjCIdType()) {
9657 S += "{objc_object=}";
9658 return;
9659 }
9660 else if (Ty->isObjCClassType()) {
9661 S += "{objc_class=}";
9662 return;
9663 }
9664 // TODO: Double check to make sure this intentionally falls through.
9665 [[fallthrough]];
9666 }
9667
9668 case Type::ObjCInterface: {
9669 // Ignore protocol qualifiers when mangling at this level.
9670 // @encode(class_name)
9671 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
9672 S += '{';
9673 S += OI->getObjCRuntimeNameAsString();
9674 if (Options.ExpandStructures()) {
9675 S += '=';
9676 SmallVector<const ObjCIvarDecl*, 32> Ivars;
9677 DeepCollectObjCIvars(OI, true, Ivars);
9678 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
9679 const FieldDecl *Field = Ivars[i];
9680 if (Field->isBitField())
9681 getObjCEncodingForTypeImpl(Field->getType(), S,
9682 ObjCEncOptions().setExpandStructures(),
9683 Field);
9684 else
9685 getObjCEncodingForTypeImpl(Field->getType(), S,
9686 ObjCEncOptions().setExpandStructures(), FD,
9687 NotEncodedT);
9688 }
9689 }
9690 S += '}';
9691 return;
9692 }
9693
9694 case Type::ObjCObjectPointer: {
9695 const auto *OPT = T->castAs<ObjCObjectPointerType>();
9696 if (OPT->isObjCIdType()) {
9697 S += '@';
9698 return;
9699 }
9700
9701 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
9702 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
9703 // Since this is a binary compatibility issue, need to consult with
9704 // runtime folks. Fortunately, this is a *very* obscure construct.
9705 S += '#';
9706 return;
9707 }
9708
9709 if (OPT->isObjCQualifiedIdType()) {
9710 getObjCEncodingForTypeImpl(
9711 getObjCIdType(), S,
9712 Options.keepingOnly(ObjCEncOptions()
9713 .setExpandPointedToStructures()
9714 .setExpandStructures()),
9715 FD);
9716 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
9717 // Note that we do extended encoding of protocol qualifier list
9718 // Only when doing ivar or property encoding.
9719 S += '"';
9720 for (const auto *I : OPT->quals()) {
9721 S += '<';
9722 S += I->getObjCRuntimeNameAsString();
9723 S += '>';
9724 }
9725 S += '"';
9726 }
9727 return;
9728 }
9729
9730 S += '@';
9731 if (OPT->getInterfaceDecl() &&
9732 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
9733 S += '"';
9734 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
9735 for (const auto *I : OPT->quals()) {
9736 S += '<';
9737 S += I->getObjCRuntimeNameAsString();
9738 S += '>';
9739 }
9740 S += '"';
9741 }
9742 return;
9743 }
9744
9745 // gcc just blithely ignores member pointers.
9746 // FIXME: we should do better than that. 'M' is available.
9747 case Type::MemberPointer:
9748 // This matches gcc's encoding, even though technically it is insufficient.
9749 //FIXME. We should do a better job than gcc.
9750 case Type::Vector:
9751 case Type::ExtVector:
9752 // Until we have a coherent encoding of these three types, issue warning.
9753 if (NotEncodedT)
9754 *NotEncodedT = T;
9755 return;
9756
9757 case Type::ConstantMatrix:
9758 if (NotEncodedT)
9759 *NotEncodedT = T;
9760 return;
9761
9762 case Type::BitInt:
9763 if (NotEncodedT)
9764 *NotEncodedT = T;
9765 return;
9766
9767 // We could see an undeduced auto type here during error recovery.
9768 // Just ignore it.
9769 case Type::Auto:
9770 case Type::DeducedTemplateSpecialization:
9771 return;
9772
9773 case Type::HLSLAttributedResource:
9774 case Type::HLSLInlineSpirv:
9775 case Type::OverflowBehavior:
9776 llvm_unreachable("unexpected type");
9777
9778 case Type::ArrayParameter:
9779 case Type::Pipe:
9780#define ABSTRACT_TYPE(KIND, BASE)
9781#define TYPE(KIND, BASE)
9782#define DEPENDENT_TYPE(KIND, BASE) \
9783 case Type::KIND:
9784#define NON_CANONICAL_TYPE(KIND, BASE) \
9785 case Type::KIND:
9786#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
9787 case Type::KIND:
9788#include "clang/AST/TypeNodes.inc"
9789 llvm_unreachable("@encode for dependent type!");
9790 }
9791 llvm_unreachable("bad type kind!");
9792}
9793
9794void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
9795 std::string &S,
9796 const FieldDecl *FD,
9797 bool includeVBases,
9798 QualType *NotEncodedT) const {
9799 assert(RDecl && "Expected non-null RecordDecl");
9800 assert(!RDecl->isUnion() && "Should not be called for unions");
9801 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
9802 return;
9803
9804 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
9805 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
9806 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
9807
9808 if (CXXRec) {
9809 for (const auto &BI : CXXRec->bases()) {
9810 if (!BI.isVirtual()) {
9811 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9812 if (base->isEmpty())
9813 continue;
9814 uint64_t offs = toBits(layout.getBaseClassOffset(base));
9815 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9816 std::make_pair(offs, base));
9817 }
9818 }
9819 }
9820
9821 for (FieldDecl *Field : RDecl->fields()) {
9822 if (!Field->isZeroLengthBitField() && Field->isZeroSize(*this))
9823 continue;
9824 uint64_t offs = layout.getFieldOffset(Field->getFieldIndex());
9825 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9826 std::make_pair(offs, Field));
9827 }
9828
9829 if (CXXRec && includeVBases) {
9830 for (const auto &BI : CXXRec->vbases()) {
9831 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9832 if (base->isEmpty())
9833 continue;
9834 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
9835 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
9836 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
9837 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
9838 std::make_pair(offs, base));
9839 }
9840 }
9841
9842 CharUnits size;
9843 if (CXXRec) {
9844 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
9845 } else {
9846 size = layout.getSize();
9847 }
9848
9849#ifndef NDEBUG
9850 uint64_t CurOffs = 0;
9851#endif
9852 std::multimap<uint64_t, NamedDecl *>::iterator
9853 CurLayObj = FieldOrBaseOffsets.begin();
9854
9855 if (CXXRec && CXXRec->isDynamicClass() &&
9856 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
9857 if (FD) {
9858 S += "\"_vptr$";
9859 std::string recname = CXXRec->getNameAsString();
9860 if (recname.empty()) recname = "?";
9861 S += recname;
9862 S += '"';
9863 }
9864 S += "^^?";
9865#ifndef NDEBUG
9866 CurOffs += getTypeSize(VoidPtrTy);
9867#endif
9868 }
9869
9870 if (!RDecl->hasFlexibleArrayMember()) {
9871 // Mark the end of the structure.
9872 uint64_t offs = toBits(size);
9873 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9874 std::make_pair(offs, nullptr));
9875 }
9876
9877 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
9878#ifndef NDEBUG
9879 assert(CurOffs <= CurLayObj->first);
9880 if (CurOffs < CurLayObj->first) {
9881 uint64_t padding = CurLayObj->first - CurOffs;
9882 // FIXME: There doesn't seem to be a way to indicate in the encoding that
9883 // packing/alignment of members is different that normal, in which case
9884 // the encoding will be out-of-sync with the real layout.
9885 // If the runtime switches to just consider the size of types without
9886 // taking into account alignment, we could make padding explicit in the
9887 // encoding (e.g. using arrays of chars). The encoding strings would be
9888 // longer then though.
9889 CurOffs += padding;
9890 }
9891#endif
9892
9893 NamedDecl *dcl = CurLayObj->second;
9894 if (!dcl)
9895 break; // reached end of structure.
9896
9897 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
9898 // We expand the bases without their virtual bases since those are going
9899 // in the initial structure. Note that this differs from gcc which
9900 // expands virtual bases each time one is encountered in the hierarchy,
9901 // making the encoding type bigger than it really is.
9902 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
9903 NotEncodedT);
9904 assert(!base->isEmpty());
9905#ifndef NDEBUG
9906 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
9907#endif
9908 } else {
9909 const auto *field = cast<FieldDecl>(dcl);
9910 if (FD) {
9911 S += '"';
9912 S += field->getNameAsString();
9913 S += '"';
9914 }
9915
9916 if (field->isBitField()) {
9917 EncodeBitField(this, S, field->getType(), field);
9918#ifndef NDEBUG
9919 CurOffs += field->getBitWidthValue();
9920#endif
9921 } else {
9922 QualType qt = field->getType();
9924 getObjCEncodingForTypeImpl(
9925 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
9926 FD, NotEncodedT);
9927#ifndef NDEBUG
9928 CurOffs += getTypeSize(field->getType());
9929#endif
9930 }
9931 }
9932 }
9933}
9934
9936 std::string& S) const {
9937 if (QT & Decl::OBJC_TQ_In)
9938 S += 'n';
9939 if (QT & Decl::OBJC_TQ_Inout)
9940 S += 'N';
9941 if (QT & Decl::OBJC_TQ_Out)
9942 S += 'o';
9943 if (QT & Decl::OBJC_TQ_Bycopy)
9944 S += 'O';
9945 if (QT & Decl::OBJC_TQ_Byref)
9946 S += 'R';
9947 if (QT & Decl::OBJC_TQ_Oneway)
9948 S += 'V';
9949}
9950
9952 if (!ObjCIdDecl) {
9955 ObjCIdDecl = buildImplicitTypedef(T, "id");
9956 }
9957 return ObjCIdDecl;
9958}
9959
9961 if (!ObjCSelDecl) {
9963 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
9964 }
9965 return ObjCSelDecl;
9966}
9967
9969 if (!ObjCClassDecl) {
9972 ObjCClassDecl = buildImplicitTypedef(T, "Class");
9973 }
9974 return ObjCClassDecl;
9975}
9976
9978 if (!ObjCProtocolClassDecl) {
9979 ObjCProtocolClassDecl
9982 &Idents.get("Protocol"),
9983 /*typeParamList=*/nullptr,
9984 /*PrevDecl=*/nullptr,
9985 SourceLocation(), true);
9986 }
9987
9988 return ObjCProtocolClassDecl;
9989}
9990
9992 if (!getLangOpts().PointerAuthObjcInterfaceSel)
9993 return PointerAuthQualifier();
9995 getLangOpts().PointerAuthObjcInterfaceSelKey,
9996 /*isAddressDiscriminated=*/true, SelPointerConstantDiscriminator,
9998 /*isIsaPointer=*/false,
9999 /*authenticatesNullValues=*/false);
10000}
10001
10002//===----------------------------------------------------------------------===//
10003// __builtin_va_list Construction Functions
10004//===----------------------------------------------------------------------===//
10005
10007 StringRef Name) {
10008 // typedef char* __builtin[_ms]_va_list;
10009 QualType T = Context->getPointerType(Context->CharTy);
10010 return Context->buildImplicitTypedef(T, Name);
10011}
10012
10014 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
10015}
10016
10018 // typedef char *__builtin_zos_va_list[2];
10019 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 2);
10020 QualType T = Context->getPointerType(Context->CharTy);
10021 QualType ArrayType = Context->getConstantArrayType(
10022 T, Size, nullptr, ArraySizeModifier::Normal, 0);
10023 return Context->buildImplicitTypedef(ArrayType, "__builtin_zos_va_list");
10024}
10025
10027 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
10028}
10029
10031 // typedef void* __builtin_va_list;
10032 QualType T = Context->getPointerType(Context->VoidTy);
10033 return Context->buildImplicitTypedef(T, "__builtin_va_list");
10034}
10035
10036static TypedefDecl *
10038 // struct __va_list
10039 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
10040 if (Context->getLangOpts().CPlusPlus) {
10041 // namespace std { struct __va_list {
10042 auto *NS = NamespaceDecl::Create(
10043 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
10044 /*Inline=*/false, SourceLocation(), SourceLocation(),
10045 &Context->Idents.get("std"),
10046 /*PrevDecl=*/nullptr, /*Nested=*/false);
10047 NS->setImplicit();
10049 }
10050
10051 VaListTagDecl->startDefinition();
10052
10053 const size_t NumFields = 5;
10054 QualType FieldTypes[NumFields];
10055 const char *FieldNames[NumFields];
10056
10057 // void *__stack;
10058 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
10059 FieldNames[0] = "__stack";
10060
10061 // void *__gr_top;
10062 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
10063 FieldNames[1] = "__gr_top";
10064
10065 // void *__vr_top;
10066 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10067 FieldNames[2] = "__vr_top";
10068
10069 // int __gr_offs;
10070 FieldTypes[3] = Context->IntTy;
10071 FieldNames[3] = "__gr_offs";
10072
10073 // int __vr_offs;
10074 FieldTypes[4] = Context->IntTy;
10075 FieldNames[4] = "__vr_offs";
10076
10077 // Create fields
10078 for (unsigned i = 0; i < NumFields; ++i) {
10079 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10083 &Context->Idents.get(FieldNames[i]),
10084 FieldTypes[i], /*TInfo=*/nullptr,
10085 /*BitWidth=*/nullptr,
10086 /*Mutable=*/false,
10087 ICIS_NoInit);
10088 Field->setAccess(AS_public);
10089 VaListTagDecl->addDecl(Field);
10090 }
10091 VaListTagDecl->completeDefinition();
10092 Context->VaListTagDecl = VaListTagDecl;
10093 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10094
10095 // } __builtin_va_list;
10096 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10097}
10098
10100 // typedef struct __va_list_tag {
10102
10103 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10104 VaListTagDecl->startDefinition();
10105
10106 const size_t NumFields = 5;
10107 QualType FieldTypes[NumFields];
10108 const char *FieldNames[NumFields];
10109
10110 // unsigned char gpr;
10111 FieldTypes[0] = Context->UnsignedCharTy;
10112 FieldNames[0] = "gpr";
10113
10114 // unsigned char fpr;
10115 FieldTypes[1] = Context->UnsignedCharTy;
10116 FieldNames[1] = "fpr";
10117
10118 // unsigned short reserved;
10119 FieldTypes[2] = Context->UnsignedShortTy;
10120 FieldNames[2] = "reserved";
10121
10122 // void* overflow_arg_area;
10123 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10124 FieldNames[3] = "overflow_arg_area";
10125
10126 // void* reg_save_area;
10127 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
10128 FieldNames[4] = "reg_save_area";
10129
10130 // Create fields
10131 for (unsigned i = 0; i < NumFields; ++i) {
10132 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
10135 &Context->Idents.get(FieldNames[i]),
10136 FieldTypes[i], /*TInfo=*/nullptr,
10137 /*BitWidth=*/nullptr,
10138 /*Mutable=*/false,
10139 ICIS_NoInit);
10140 Field->setAccess(AS_public);
10141 VaListTagDecl->addDecl(Field);
10142 }
10143 VaListTagDecl->completeDefinition();
10144 Context->VaListTagDecl = VaListTagDecl;
10145 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10146
10147 // } __va_list_tag;
10148 TypedefDecl *VaListTagTypedefDecl =
10149 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10150
10151 QualType VaListTagTypedefType =
10152 Context->getTypedefType(ElaboratedTypeKeyword::None,
10153 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10154
10155 // typedef __va_list_tag __builtin_va_list[1];
10156 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10157 QualType VaListTagArrayType = Context->getConstantArrayType(
10158 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10159 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10160}
10161
10162static TypedefDecl *
10164 // struct __va_list_tag {
10166 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10167 VaListTagDecl->startDefinition();
10168
10169 const size_t NumFields = 4;
10170 QualType FieldTypes[NumFields];
10171 const char *FieldNames[NumFields];
10172
10173 // unsigned gp_offset;
10174 FieldTypes[0] = Context->UnsignedIntTy;
10175 FieldNames[0] = "gp_offset";
10176
10177 // unsigned fp_offset;
10178 FieldTypes[1] = Context->UnsignedIntTy;
10179 FieldNames[1] = "fp_offset";
10180
10181 // void* overflow_arg_area;
10182 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10183 FieldNames[2] = "overflow_arg_area";
10184
10185 // void* reg_save_area;
10186 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10187 FieldNames[3] = "reg_save_area";
10188
10189 // Create fields
10190 for (unsigned i = 0; i < NumFields; ++i) {
10191 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10195 &Context->Idents.get(FieldNames[i]),
10196 FieldTypes[i], /*TInfo=*/nullptr,
10197 /*BitWidth=*/nullptr,
10198 /*Mutable=*/false,
10199 ICIS_NoInit);
10200 Field->setAccess(AS_public);
10201 VaListTagDecl->addDecl(Field);
10202 }
10203 VaListTagDecl->completeDefinition();
10204 Context->VaListTagDecl = VaListTagDecl;
10205 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10206
10207 // };
10208
10209 // typedef struct __va_list_tag __builtin_va_list[1];
10210 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10211 QualType VaListTagArrayType = Context->getConstantArrayType(
10212 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10213 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10214}
10215
10216static TypedefDecl *
10218 // struct __va_list
10219 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
10220 if (Context->getLangOpts().CPlusPlus) {
10221 // namespace std { struct __va_list {
10222 NamespaceDecl *NS;
10223 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
10224 Context->getTranslationUnitDecl(),
10225 /*Inline=*/false, SourceLocation(),
10226 SourceLocation(), &Context->Idents.get("std"),
10227 /*PrevDecl=*/nullptr, /*Nested=*/false);
10228 NS->setImplicit();
10229 VaListDecl->setDeclContext(NS);
10230 }
10231
10232 VaListDecl->startDefinition();
10233
10234 // void * __ap;
10235 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10236 VaListDecl,
10239 &Context->Idents.get("__ap"),
10240 Context->getPointerType(Context->VoidTy),
10241 /*TInfo=*/nullptr,
10242 /*BitWidth=*/nullptr,
10243 /*Mutable=*/false,
10244 ICIS_NoInit);
10245 Field->setAccess(AS_public);
10246 VaListDecl->addDecl(Field);
10247
10248 // };
10249 VaListDecl->completeDefinition();
10250 Context->VaListTagDecl = VaListDecl;
10251
10252 // typedef struct __va_list __builtin_va_list;
10253 CanQualType T = Context->getCanonicalTagType(VaListDecl);
10254 return Context->buildImplicitTypedef(T, "__builtin_va_list");
10255}
10256
10257static TypedefDecl *
10259 // struct __va_list_tag {
10261 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10262 VaListTagDecl->startDefinition();
10263
10264 const size_t NumFields = 4;
10265 QualType FieldTypes[NumFields];
10266 const char *FieldNames[NumFields];
10267
10268 // long __gpr;
10269 FieldTypes[0] = Context->LongTy;
10270 FieldNames[0] = "__gpr";
10271
10272 // long __fpr;
10273 FieldTypes[1] = Context->LongTy;
10274 FieldNames[1] = "__fpr";
10275
10276 // void *__overflow_arg_area;
10277 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10278 FieldNames[2] = "__overflow_arg_area";
10279
10280 // void *__reg_save_area;
10281 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10282 FieldNames[3] = "__reg_save_area";
10283
10284 // Create fields
10285 for (unsigned i = 0; i < NumFields; ++i) {
10286 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10290 &Context->Idents.get(FieldNames[i]),
10291 FieldTypes[i], /*TInfo=*/nullptr,
10292 /*BitWidth=*/nullptr,
10293 /*Mutable=*/false,
10294 ICIS_NoInit);
10295 Field->setAccess(AS_public);
10296 VaListTagDecl->addDecl(Field);
10297 }
10298 VaListTagDecl->completeDefinition();
10299 Context->VaListTagDecl = VaListTagDecl;
10300 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10301
10302 // };
10303
10304 // typedef __va_list_tag __builtin_va_list[1];
10305 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10306 QualType VaListTagArrayType = Context->getConstantArrayType(
10307 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10308
10309 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10310}
10311
10313 // typedef struct __va_list_tag {
10315 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10316 VaListTagDecl->startDefinition();
10317
10318 const size_t NumFields = 3;
10319 QualType FieldTypes[NumFields];
10320 const char *FieldNames[NumFields];
10321
10322 // void *CurrentSavedRegisterArea;
10323 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
10324 FieldNames[0] = "__current_saved_reg_area_pointer";
10325
10326 // void *SavedRegAreaEnd;
10327 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
10328 FieldNames[1] = "__saved_reg_area_end_pointer";
10329
10330 // void *OverflowArea;
10331 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10332 FieldNames[2] = "__overflow_area_pointer";
10333
10334 // Create fields
10335 for (unsigned i = 0; i < NumFields; ++i) {
10337 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
10338 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
10339 /*TInfo=*/nullptr,
10340 /*BitWidth=*/nullptr,
10341 /*Mutable=*/false, ICIS_NoInit);
10342 Field->setAccess(AS_public);
10343 VaListTagDecl->addDecl(Field);
10344 }
10345 VaListTagDecl->completeDefinition();
10346 Context->VaListTagDecl = VaListTagDecl;
10347 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10348
10349 // } __va_list_tag;
10350 TypedefDecl *VaListTagTypedefDecl =
10351 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10352
10353 QualType VaListTagTypedefType =
10354 Context->getTypedefType(ElaboratedTypeKeyword::None,
10355 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10356
10357 // typedef __va_list_tag __builtin_va_list[1];
10358 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10359 QualType VaListTagArrayType = Context->getConstantArrayType(
10360 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10361
10362 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10363}
10364
10365static TypedefDecl *
10367 // typedef struct __va_list_tag {
10368 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10369
10370 VaListTagDecl->startDefinition();
10371
10372 // int* __va_stk;
10373 // int* __va_reg;
10374 // int __va_ndx;
10375 constexpr size_t NumFields = 3;
10376 QualType FieldTypes[NumFields] = {Context->getPointerType(Context->IntTy),
10377 Context->getPointerType(Context->IntTy),
10378 Context->IntTy};
10379 const char *FieldNames[NumFields] = {"__va_stk", "__va_reg", "__va_ndx"};
10380
10381 // Create fields
10382 for (unsigned i = 0; i < NumFields; ++i) {
10385 &Context->Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
10386 /*BitWidth=*/nullptr,
10387 /*Mutable=*/false, ICIS_NoInit);
10388 Field->setAccess(AS_public);
10389 VaListTagDecl->addDecl(Field);
10390 }
10391 VaListTagDecl->completeDefinition();
10392 Context->VaListTagDecl = VaListTagDecl;
10393 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10394
10395 // } __va_list_tag;
10396 TypedefDecl *VaListTagTypedefDecl =
10397 Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10398
10399 return VaListTagTypedefDecl;
10400}
10401
10404 switch (Kind) {
10406 return CreateCharPtrBuiltinVaListDecl(Context);
10408 return CreateVoidPtrBuiltinVaListDecl(Context);
10410 return CreateAArch64ABIBuiltinVaListDecl(Context);
10412 return CreatePowerABIBuiltinVaListDecl(Context);
10414 return CreateX86_64ABIBuiltinVaListDecl(Context);
10416 return CreateAAPCSABIBuiltinVaListDecl(Context);
10418 return CreateSystemZBuiltinVaListDecl(Context);
10420 return CreateHexagonBuiltinVaListDecl(Context);
10422 return CreateXtensaABIBuiltinVaListDecl(Context);
10423 }
10424
10425 llvm_unreachable("Unhandled __builtin_va_list type kind");
10426}
10427
10429 if (!BuiltinVaListDecl) {
10430 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
10431 assert(BuiltinVaListDecl->isImplicit());
10432 }
10433
10434 return BuiltinVaListDecl;
10435}
10436
10438 // Force the creation of VaListTagDecl by building the __builtin_va_list
10439 // declaration.
10440 if (!VaListTagDecl)
10441 (void)getBuiltinVaListDecl();
10442
10443 return VaListTagDecl;
10444}
10445
10447 if (!BuiltinMSVaListDecl)
10448 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
10449
10450 return BuiltinMSVaListDecl;
10451}
10452
10454 if (!BuiltinZOSVaListDecl)
10455 BuiltinZOSVaListDecl = CreateZOSVaListDecl(this);
10456
10457 return BuiltinZOSVaListDecl;
10458}
10459
10461 // Allow redecl custom type checking builtin for HLSL.
10462 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
10463 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10464 return true;
10465 // Allow redecl custom type checking builtin for SPIR-V.
10466 if (getTargetInfo().getTriple().isSPIROrSPIRV() &&
10467 BuiltinInfo.isTSBuiltin(FD->getBuiltinID()) &&
10468 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10469 return true;
10470 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
10471}
10472
10474 assert(ObjCConstantStringType.isNull() &&
10475 "'NSConstantString' type already set!");
10476
10477 ObjCConstantStringType = getObjCInterfaceType(Decl);
10478}
10479
10480/// Retrieve the template name that corresponds to a non-empty
10481/// lookup.
10484 UnresolvedSetIterator End) const {
10485 unsigned size = End - Begin;
10486 assert(size > 1 && "set is not overloaded!");
10487
10488 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
10489 size * sizeof(FunctionTemplateDecl*));
10490 auto *OT = new (memory) OverloadedTemplateStorage(size);
10491
10492 NamedDecl **Storage = OT->getStorage();
10493 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
10494 NamedDecl *D = *I;
10495 assert(isa<FunctionTemplateDecl>(D) ||
10499 *Storage++ = D;
10500 }
10501
10502 return TemplateName(OT);
10503}
10504
10505/// Retrieve a template name representing an unqualified-id that has been
10506/// assumed to name a template for ADL purposes.
10508 auto *OT = new (*this) AssumedTemplateStorage(Name);
10509 return TemplateName(OT);
10510}
10511
10512/// Retrieve the template name that represents a qualified
10513/// template name such as \c std::vector.
10515 bool TemplateKeyword,
10516 TemplateName Template) const {
10517 assert(Template.getKind() == TemplateName::Template ||
10519
10520 if (Template.getAsTemplateDecl()->getKind() == Decl::TemplateTemplateParm) {
10521 assert(!Qualifier && "unexpected qualified template template parameter");
10522 assert(TemplateKeyword == false);
10523 return Template;
10524 }
10525
10526 // FIXME: Canonicalization?
10527 llvm::FoldingSetNodeID ID;
10528 QualifiedTemplateName::Profile(ID, Qualifier, TemplateKeyword, Template);
10529
10530 void *InsertPos = nullptr;
10532 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
10533 if (!QTN) {
10534 QTN = new (*this, alignof(QualifiedTemplateName))
10535 QualifiedTemplateName(Qualifier, TemplateKeyword, Template);
10536 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
10537 }
10538
10539 return TemplateName(QTN);
10540}
10541
10542/// Retrieve the template name that represents a dependent
10543/// template name such as \c MetaFun::template operator+.
10546 llvm::FoldingSetNodeID ID;
10547 S.Profile(ID);
10548
10549 void *InsertPos = nullptr;
10550 if (DependentTemplateName *QTN =
10551 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos))
10552 return TemplateName(QTN);
10553
10555 new (*this, alignof(DependentTemplateName)) DependentTemplateName(S);
10556 DependentTemplateNames.InsertNode(QTN, InsertPos);
10557 return TemplateName(QTN);
10558}
10559
10561 Decl *AssociatedDecl,
10562 unsigned Index,
10564 bool Final) const {
10565 llvm::FoldingSetNodeID ID;
10566 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
10567 Index, PackIndex, Final);
10568
10569 void *insertPos = nullptr;
10571 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
10572
10573 if (!subst) {
10574 subst = new (*this) SubstTemplateTemplateParmStorage(
10575 Replacement, AssociatedDecl, Index, PackIndex, Final);
10576 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
10577 }
10578
10579 return TemplateName(subst);
10580}
10581
10584 Decl *AssociatedDecl,
10585 unsigned Index, bool Final) const {
10586 auto &Self = const_cast<ASTContext &>(*this);
10587 llvm::FoldingSetNodeID ID;
10589 AssociatedDecl, Index, Final);
10590
10591 void *InsertPos = nullptr;
10593 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
10594
10595 if (!Subst) {
10596 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
10597 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
10598 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
10599 }
10600
10601 return TemplateName(Subst);
10602}
10603
10604/// Retrieve the template name that represents a template name
10605/// deduced from a specialization.
10608 DefaultArguments DefaultArgs) const {
10609 if (!DefaultArgs)
10610 return Underlying;
10611
10612 llvm::FoldingSetNodeID ID;
10613 DeducedTemplateStorage::Profile(ID, *this, Underlying, DefaultArgs);
10614
10615 void *InsertPos = nullptr;
10617 DeducedTemplates.FindNodeOrInsertPos(ID, InsertPos);
10618 if (!DTS) {
10619 void *Mem = Allocate(sizeof(DeducedTemplateStorage) +
10620 sizeof(TemplateArgument) * DefaultArgs.Args.size(),
10621 alignof(DeducedTemplateStorage));
10622 DTS = new (Mem) DeducedTemplateStorage(Underlying, DefaultArgs);
10623 DeducedTemplates.InsertNode(DTS, InsertPos);
10624 }
10625 return TemplateName(DTS);
10626}
10627
10628/// getFromTargetType - Given one of the integer types provided by
10629/// TargetInfo, produce the corresponding type. The unsigned @p Type
10630/// is actually a value of type @c TargetInfo::IntType.
10631CanQualType ASTContext::getFromTargetType(unsigned Type) const {
10632 switch (Type) {
10633 case TargetInfo::NoInt: return {};
10636 case TargetInfo::SignedShort: return ShortTy;
10638 case TargetInfo::SignedInt: return IntTy;
10640 case TargetInfo::SignedLong: return LongTy;
10644 }
10645
10646 llvm_unreachable("Unhandled TargetInfo::IntType value");
10647}
10648
10649//===----------------------------------------------------------------------===//
10650// Type Predicates.
10651//===----------------------------------------------------------------------===//
10652
10653/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
10654/// garbage collection attribute.
10655///
10657 if (getLangOpts().getGC() == LangOptions::NonGC)
10658 return Qualifiers::GCNone;
10659
10660 assert(getLangOpts().ObjC);
10661 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
10662
10663 // Default behaviour under objective-C's gc is for ObjC pointers
10664 // (or pointers to them) be treated as though they were declared
10665 // as __strong.
10666 if (GCAttrs == Qualifiers::GCNone) {
10668 return Qualifiers::Strong;
10669 else if (Ty->isPointerType())
10671 } else {
10672 // It's not valid to set GC attributes on anything that isn't a
10673 // pointer.
10674#ifndef NDEBUG
10676 while (const auto *AT = dyn_cast<ArrayType>(CT))
10677 CT = AT->getElementType();
10678 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
10679#endif
10680 }
10681 return GCAttrs;
10682}
10683
10684//===----------------------------------------------------------------------===//
10685// Type Compatibility Testing
10686//===----------------------------------------------------------------------===//
10687
10688/// areCompatVectorTypes - Return true if the two specified vector types are
10689/// compatible.
10690static bool areCompatVectorTypes(const VectorType *LHS,
10691 const VectorType *RHS) {
10692 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10693 return LHS->getElementType() == RHS->getElementType() &&
10694 LHS->getNumElements() == RHS->getNumElements();
10695}
10696
10697/// areCompatMatrixTypes - Return true if the two specified matrix types are
10698/// compatible.
10700 const ConstantMatrixType *RHS) {
10701 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10702 return LHS->getElementType() == RHS->getElementType() &&
10703 LHS->getNumRows() == RHS->getNumRows() &&
10704 LHS->getNumColumns() == RHS->getNumColumns();
10705}
10706
10708 QualType SecondVec) {
10709 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
10710 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
10711
10712 if (hasSameUnqualifiedType(FirstVec, SecondVec))
10713 return true;
10714
10715 // Treat Neon vector types and most AltiVec vector types as if they are the
10716 // equivalent GCC vector types.
10717 const auto *First = FirstVec->castAs<VectorType>();
10718 const auto *Second = SecondVec->castAs<VectorType>();
10719 if (First->getNumElements() == Second->getNumElements() &&
10720 hasSameType(First->getElementType(), Second->getElementType()) &&
10721 First->getVectorKind() != VectorKind::AltiVecPixel &&
10722 First->getVectorKind() != VectorKind::AltiVecBool &&
10725 First->getVectorKind() != VectorKind::SveFixedLengthData &&
10726 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10729 First->getVectorKind() != VectorKind::RVVFixedLengthData &&
10731 First->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10733 First->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10735 First->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10737 First->getVectorKind() != VectorKind::RVVFixedLengthMask_4 &&
10739 return true;
10740
10741 // In OpenCL, treat half and _Float16 vector types as compatible.
10742 if (getLangOpts().OpenCL &&
10743 First->getNumElements() == Second->getNumElements()) {
10744 QualType FirstElt = First->getElementType();
10745 QualType SecondElt = Second->getElementType();
10746
10747 if ((FirstElt->isFloat16Type() && SecondElt->isHalfType()) ||
10748 (FirstElt->isHalfType() && SecondElt->isFloat16Type())) {
10749 if (First->getVectorKind() != VectorKind::AltiVecPixel &&
10750 First->getVectorKind() != VectorKind::AltiVecBool &&
10753 return true;
10754 }
10755 }
10756 return false;
10757}
10758
10764
10767 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
10768 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
10769
10770 if (!LHSOBT && !RHSOBT)
10772
10773 if (LHSOBT && RHSOBT) {
10774 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
10777 }
10778
10779 QualType LHSUnderlying = LHSOBT ? LHSOBT->desugar() : LHS;
10780 QualType RHSUnderlying = RHSOBT ? RHSOBT->desugar() : RHS;
10781
10782 if (RHSOBT && !LHSOBT) {
10783 if (LHSUnderlying->isIntegerType() && RHSUnderlying->isIntegerType())
10785 }
10786
10788}
10789
10790/// getRVVTypeSize - Return RVV vector register size.
10791static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
10792 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
10793 auto VScale = Context.getTargetInfo().getVScaleRange(
10794 Context.getLangOpts(), TargetInfo::ArmStreamingKind::NotStreaming);
10795 if (!VScale)
10796 return 0;
10797
10798 ASTContext::BuiltinVectorTypeInfo Info = Context.getBuiltinVectorTypeInfo(Ty);
10799
10800 uint64_t EltSize = Context.getTypeSize(Info.ElementType);
10801 if (Info.ElementType == Context.BoolTy)
10802 EltSize = 1;
10803
10804 uint64_t MinElts = Info.EC.getKnownMinValue();
10805 return VScale->first * MinElts * EltSize;
10806}
10807
10809 QualType SecondType) {
10810 assert(
10811 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10812 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10813 "Expected RVV builtin type and vector type!");
10814
10815 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10816 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10817 if (const auto *VT = SecondType->getAs<VectorType>()) {
10818 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10820 return FirstType->isRVVVLSBuiltinType() &&
10821 Info.ElementType == BoolTy &&
10822 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)));
10823 }
10824 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1) {
10826 return FirstType->isRVVVLSBuiltinType() &&
10827 Info.ElementType == BoolTy &&
10828 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT) * 8));
10829 }
10830 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2) {
10832 return FirstType->isRVVVLSBuiltinType() &&
10833 Info.ElementType == BoolTy &&
10834 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 4);
10835 }
10836 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10838 return FirstType->isRVVVLSBuiltinType() &&
10839 Info.ElementType == BoolTy &&
10840 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 2);
10841 }
10842 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
10843 VT->getVectorKind() == VectorKind::Generic)
10844 return FirstType->isRVVVLSBuiltinType() &&
10845 getTypeSize(SecondType) == getRVVTypeSize(*this, BT) &&
10846 hasSameType(VT->getElementType(),
10847 getBuiltinVectorTypeInfo(BT).ElementType);
10848 }
10849 }
10850 return false;
10851 };
10852
10853 return IsValidCast(FirstType, SecondType) ||
10854 IsValidCast(SecondType, FirstType);
10855}
10856
10858 QualType SecondType) {
10859 assert(
10860 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10861 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10862 "Expected RVV builtin type and vector type!");
10863
10864 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10865 const auto *BT = FirstType->getAs<BuiltinType>();
10866 if (!BT)
10867 return false;
10868
10869 if (!BT->isRVVVLSBuiltinType())
10870 return false;
10871
10872 const auto *VecTy = SecondType->getAs<VectorType>();
10873 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
10875 getLangOpts().getLaxVectorConversions();
10876
10877 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
10878 if (getTypeSize(SecondType) != getRVVTypeSize(*this, BT))
10879 return false;
10880
10881 // If -flax-vector-conversions=all is specified, the types are
10882 // certainly compatible.
10884 return true;
10885
10886 // If -flax-vector-conversions=integer is specified, the types are
10887 // compatible if the elements are integer types.
10889 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10890 FirstType->getRVVEltType(*this)->isIntegerType();
10891 }
10892
10893 return false;
10894 };
10895
10896 return IsLaxCompatible(FirstType, SecondType) ||
10897 IsLaxCompatible(SecondType, FirstType);
10898}
10899
10901 while (true) {
10902 // __strong id
10903 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
10904 if (Attr->getAttrKind() == attr::ObjCOwnership)
10905 return true;
10906
10907 Ty = Attr->getModifiedType();
10908
10909 // X *__strong (...)
10910 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
10911 Ty = Paren->getInnerType();
10912
10913 // We do not want to look through typedefs, typeof(expr),
10914 // typeof(type), or any other way that the type is somehow
10915 // abstracted.
10916 } else {
10917 return false;
10918 }
10919 }
10920}
10921
10922//===----------------------------------------------------------------------===//
10923// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
10924//===----------------------------------------------------------------------===//
10925
10926/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
10927/// inheritance hierarchy of 'rProto'.
10928bool
10930 ObjCProtocolDecl *rProto) const {
10931 if (declaresSameEntity(lProto, rProto))
10932 return true;
10933 for (auto *PI : rProto->protocols())
10934 if (ProtocolCompatibleWithProtocol(lProto, PI))
10935 return true;
10936 return false;
10937}
10938
10939/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
10940/// Class<pr1, ...>.
10942 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
10943 for (auto *lhsProto : lhs->quals()) {
10944 bool match = false;
10945 for (auto *rhsProto : rhs->quals()) {
10946 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
10947 match = true;
10948 break;
10949 }
10950 }
10951 if (!match)
10952 return false;
10953 }
10954 return true;
10955}
10956
10957/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
10958/// ObjCQualifiedIDType.
10960 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
10961 bool compare) {
10962 // Allow id<P..> and an 'id' in all cases.
10963 if (lhs->isObjCIdType() || rhs->isObjCIdType())
10964 return true;
10965
10966 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
10967 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
10969 return false;
10970
10971 if (lhs->isObjCQualifiedIdType()) {
10972 if (rhs->qual_empty()) {
10973 // If the RHS is a unqualified interface pointer "NSString*",
10974 // make sure we check the class hierarchy.
10975 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10976 for (auto *I : lhs->quals()) {
10977 // when comparing an id<P> on lhs with a static type on rhs,
10978 // see if static class implements all of id's protocols, directly or
10979 // through its super class and categories.
10980 if (!rhsID->ClassImplementsProtocol(I, true))
10981 return false;
10982 }
10983 }
10984 // If there are no qualifiers and no interface, we have an 'id'.
10985 return true;
10986 }
10987 // Both the right and left sides have qualifiers.
10988 for (auto *lhsProto : lhs->quals()) {
10989 bool match = false;
10990
10991 // when comparing an id<P> on lhs with a static type on rhs,
10992 // see if static class implements all of id's protocols, directly or
10993 // through its super class and categories.
10994 for (auto *rhsProto : rhs->quals()) {
10995 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10996 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10997 match = true;
10998 break;
10999 }
11000 }
11001 // If the RHS is a qualified interface pointer "NSString<P>*",
11002 // make sure we check the class hierarchy.
11003 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
11004 for (auto *I : lhs->quals()) {
11005 // when comparing an id<P> on lhs with a static type on rhs,
11006 // see if static class implements all of id's protocols, directly or
11007 // through its super class and categories.
11008 if (rhsID->ClassImplementsProtocol(I, true)) {
11009 match = true;
11010 break;
11011 }
11012 }
11013 }
11014 if (!match)
11015 return false;
11016 }
11017
11018 return true;
11019 }
11020
11021 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
11022
11023 if (lhs->getInterfaceType()) {
11024 // If both the right and left sides have qualifiers.
11025 for (auto *lhsProto : lhs->quals()) {
11026 bool match = false;
11027
11028 // when comparing an id<P> on rhs with a static type on lhs,
11029 // see if static class implements all of id's protocols, directly or
11030 // through its super class and categories.
11031 // First, lhs protocols in the qualifier list must be found, direct
11032 // or indirect in rhs's qualifier list or it is a mismatch.
11033 for (auto *rhsProto : rhs->quals()) {
11034 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
11035 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
11036 match = true;
11037 break;
11038 }
11039 }
11040 if (!match)
11041 return false;
11042 }
11043
11044 // Static class's protocols, or its super class or category protocols
11045 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
11046 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
11047 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
11048 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
11049 // This is rather dubious but matches gcc's behavior. If lhs has
11050 // no type qualifier and its class has no static protocol(s)
11051 // assume that it is mismatch.
11052 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
11053 return false;
11054 for (auto *lhsProto : LHSInheritedProtocols) {
11055 bool match = false;
11056 for (auto *rhsProto : rhs->quals()) {
11057 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
11058 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
11059 match = true;
11060 break;
11061 }
11062 }
11063 if (!match)
11064 return false;
11065 }
11066 }
11067 return true;
11068 }
11069 return false;
11070}
11071
11072/// canAssignObjCInterfaces - Return true if the two interface types are
11073/// compatible for assignment from RHS to LHS. This handles validation of any
11074/// protocol qualifiers on the LHS or RHS.
11076 const ObjCObjectPointerType *RHSOPT) {
11077 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11078 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11079
11080 // If either type represents the built-in 'id' type, return true.
11081 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
11082 return true;
11083
11084 // Function object that propagates a successful result or handles
11085 // __kindof types.
11086 auto finish = [&](bool succeeded) -> bool {
11087 if (succeeded)
11088 return true;
11089
11090 if (!RHS->isKindOfType())
11091 return false;
11092
11093 // Strip off __kindof and protocol qualifiers, then check whether
11094 // we can assign the other way.
11096 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
11097 };
11098
11099 // Casts from or to id<P> are allowed when the other side has compatible
11100 // protocols.
11101 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
11102 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
11103 }
11104
11105 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
11106 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
11107 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
11108 }
11109
11110 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
11111 if (LHS->isObjCClass() && RHS->isObjCClass()) {
11112 return true;
11113 }
11114
11115 // If we have 2 user-defined types, fall into that path.
11116 if (LHS->getInterface() && RHS->getInterface()) {
11117 return finish(canAssignObjCInterfaces(LHS, RHS));
11118 }
11119
11120 return false;
11121}
11122
11123/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
11124/// for providing type-safety for objective-c pointers used to pass/return
11125/// arguments in block literals. When passed as arguments, passing 'A*' where
11126/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
11127/// not OK. For the return type, the opposite is not OK.
11129 const ObjCObjectPointerType *LHSOPT,
11130 const ObjCObjectPointerType *RHSOPT,
11131 bool BlockReturnType) {
11132
11133 // Function object that propagates a successful result or handles
11134 // __kindof types.
11135 auto finish = [&](bool succeeded) -> bool {
11136 if (succeeded)
11137 return true;
11138
11139 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
11140 if (!Expected->isKindOfType())
11141 return false;
11142
11143 // Strip off __kindof and protocol qualifiers, then check whether
11144 // we can assign the other way.
11146 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
11147 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
11148 BlockReturnType);
11149 };
11150
11151 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
11152 return true;
11153
11154 if (LHSOPT->isObjCBuiltinType()) {
11155 return finish(RHSOPT->isObjCBuiltinType() ||
11156 RHSOPT->isObjCQualifiedIdType());
11157 }
11158
11159 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
11160 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
11161 // Use for block parameters previous type checking for compatibility.
11162 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
11163 // Or corrected type checking as in non-compat mode.
11164 (!BlockReturnType &&
11165 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
11166 else
11168 (BlockReturnType ? LHSOPT : RHSOPT),
11169 (BlockReturnType ? RHSOPT : LHSOPT), false));
11170 }
11171
11172 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
11173 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
11174 if (LHS && RHS) { // We have 2 user-defined types.
11175 if (LHS != RHS) {
11176 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
11177 return finish(BlockReturnType);
11178 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
11179 return finish(!BlockReturnType);
11180 }
11181 else
11182 return true;
11183 }
11184 return false;
11185}
11186
11187/// Comparison routine for Objective-C protocols to be used with
11188/// llvm::array_pod_sort.
11190 ObjCProtocolDecl * const *rhs) {
11191 return (*lhs)->getName().compare((*rhs)->getName());
11192}
11193
11194/// getIntersectionOfProtocols - This routine finds the intersection of set
11195/// of protocols inherited from two distinct objective-c pointer objects with
11196/// the given common base.
11197/// It is used to build composite qualifier list of the composite type of
11198/// the conditional expression involving two objective-c pointer objects.
11199static
11201 const ObjCInterfaceDecl *CommonBase,
11202 const ObjCObjectPointerType *LHSOPT,
11203 const ObjCObjectPointerType *RHSOPT,
11204 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
11205
11206 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11207 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11208 assert(LHS->getInterface() && "LHS must have an interface base");
11209 assert(RHS->getInterface() && "RHS must have an interface base");
11210
11211 // Add all of the protocols for the LHS.
11213
11214 // Start with the protocol qualifiers.
11215 for (auto *proto : LHS->quals()) {
11216 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
11217 }
11218
11219 // Also add the protocols associated with the LHS interface.
11220 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
11221
11222 // Add all of the protocols for the RHS.
11224
11225 // Start with the protocol qualifiers.
11226 for (auto *proto : RHS->quals()) {
11227 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
11228 }
11229
11230 // Also add the protocols associated with the RHS interface.
11231 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
11232
11233 // Compute the intersection of the collected protocol sets.
11234 for (auto *proto : LHSProtocolSet) {
11235 if (RHSProtocolSet.count(proto))
11236 IntersectionSet.push_back(proto);
11237 }
11238
11239 // Compute the set of protocols that is implied by either the common type or
11240 // the protocols within the intersection.
11242 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
11243
11244 // Remove any implied protocols from the list of inherited protocols.
11245 if (!ImpliedProtocols.empty()) {
11246 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
11247 return ImpliedProtocols.contains(proto);
11248 });
11249 }
11250
11251 // Sort the remaining protocols by name.
11252 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
11254}
11255
11256/// Determine whether the first type is a subtype of the second.
11258 QualType rhs) {
11259 // Common case: two object pointers.
11260 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
11261 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
11262 if (lhsOPT && rhsOPT)
11263 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
11264
11265 // Two block pointers.
11266 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
11267 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
11268 if (lhsBlock && rhsBlock)
11269 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
11270
11271 // If either is an unqualified 'id' and the other is a block, it's
11272 // acceptable.
11273 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
11274 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
11275 return true;
11276
11277 return false;
11278}
11279
11280// Check that the given Objective-C type argument lists are equivalent.
11282 const ObjCInterfaceDecl *iface,
11283 ArrayRef<QualType> lhsArgs,
11284 ArrayRef<QualType> rhsArgs,
11285 bool stripKindOf) {
11286 if (lhsArgs.size() != rhsArgs.size())
11287 return false;
11288
11289 ObjCTypeParamList *typeParams = iface->getTypeParamList();
11290 if (!typeParams)
11291 return false;
11292
11293 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
11294 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
11295 continue;
11296
11297 switch (typeParams->begin()[i]->getVariance()) {
11299 if (!stripKindOf ||
11300 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
11301 rhsArgs[i].stripObjCKindOfType(ctx))) {
11302 return false;
11303 }
11304 break;
11305
11307 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
11308 return false;
11309 break;
11310
11312 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
11313 return false;
11314 break;
11315 }
11316 }
11317
11318 return true;
11319}
11320
11322 const ObjCObjectPointerType *Lptr,
11323 const ObjCObjectPointerType *Rptr) {
11324 const ObjCObjectType *LHS = Lptr->getObjectType();
11325 const ObjCObjectType *RHS = Rptr->getObjectType();
11326 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
11327 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
11328
11329 if (!LDecl || !RDecl)
11330 return {};
11331
11332 // When either LHS or RHS is a kindof type, we should return a kindof type.
11333 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
11334 // kindof(A).
11335 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
11336
11337 // Follow the left-hand side up the class hierarchy until we either hit a
11338 // root or find the RHS. Record the ancestors in case we don't find it.
11339 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
11340 LHSAncestors;
11341 while (true) {
11342 // Record this ancestor. We'll need this if the common type isn't in the
11343 // path from the LHS to the root.
11344 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
11345
11346 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
11347 // Get the type arguments.
11348 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
11349 bool anyChanges = false;
11350 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11351 // Both have type arguments, compare them.
11352 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11353 LHS->getTypeArgs(), RHS->getTypeArgs(),
11354 /*stripKindOf=*/true))
11355 return {};
11356 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11357 // If only one has type arguments, the result will not have type
11358 // arguments.
11359 LHSTypeArgs = {};
11360 anyChanges = true;
11361 }
11362
11363 // Compute the intersection of protocols.
11365 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
11366 Protocols);
11367 if (!Protocols.empty())
11368 anyChanges = true;
11369
11370 // If anything in the LHS will have changed, build a new result type.
11371 // If we need to return a kindof type but LHS is not a kindof type, we
11372 // build a new result type.
11373 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
11374 QualType Result = getObjCInterfaceType(LHS->getInterface());
11375 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
11376 anyKindOf || LHS->isKindOfType());
11378 }
11379
11380 return getObjCObjectPointerType(QualType(LHS, 0));
11381 }
11382
11383 // Find the superclass.
11384 QualType LHSSuperType = LHS->getSuperClassType();
11385 if (LHSSuperType.isNull())
11386 break;
11387
11388 LHS = LHSSuperType->castAs<ObjCObjectType>();
11389 }
11390
11391 // We didn't find anything by following the LHS to its root; now check
11392 // the RHS against the cached set of ancestors.
11393 while (true) {
11394 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
11395 if (KnownLHS != LHSAncestors.end()) {
11396 LHS = KnownLHS->second;
11397
11398 // Get the type arguments.
11399 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
11400 bool anyChanges = false;
11401 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11402 // Both have type arguments, compare them.
11403 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11404 LHS->getTypeArgs(), RHS->getTypeArgs(),
11405 /*stripKindOf=*/true))
11406 return {};
11407 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11408 // If only one has type arguments, the result will not have type
11409 // arguments.
11410 RHSTypeArgs = {};
11411 anyChanges = true;
11412 }
11413
11414 // Compute the intersection of protocols.
11416 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
11417 Protocols);
11418 if (!Protocols.empty())
11419 anyChanges = true;
11420
11421 // If we need to return a kindof type but RHS is not a kindof type, we
11422 // build a new result type.
11423 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
11424 QualType Result = getObjCInterfaceType(RHS->getInterface());
11425 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
11426 anyKindOf || RHS->isKindOfType());
11428 }
11429
11430 return getObjCObjectPointerType(QualType(RHS, 0));
11431 }
11432
11433 // Find the superclass of the RHS.
11434 QualType RHSSuperType = RHS->getSuperClassType();
11435 if (RHSSuperType.isNull())
11436 break;
11437
11438 RHS = RHSSuperType->castAs<ObjCObjectType>();
11439 }
11440
11441 return {};
11442}
11443
11445 const ObjCObjectType *RHS) {
11446 assert(LHS->getInterface() && "LHS is not an interface type");
11447 assert(RHS->getInterface() && "RHS is not an interface type");
11448
11449 // Verify that the base decls are compatible: the RHS must be a subclass of
11450 // the LHS.
11451 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
11452 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
11453 if (!IsSuperClass)
11454 return false;
11455
11456 // If the LHS has protocol qualifiers, determine whether all of them are
11457 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
11458 // LHS).
11459 if (LHS->getNumProtocols() > 0) {
11460 // OK if conversion of LHS to SuperClass results in narrowing of types
11461 // ; i.e., SuperClass may implement at least one of the protocols
11462 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
11463 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
11464 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
11465 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
11466 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
11467 // qualifiers.
11468 for (auto *RHSPI : RHS->quals())
11469 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
11470 // If there is no protocols associated with RHS, it is not a match.
11471 if (SuperClassInheritedProtocols.empty())
11472 return false;
11473
11474 for (const auto *LHSProto : LHS->quals()) {
11475 bool SuperImplementsProtocol = false;
11476 for (auto *SuperClassProto : SuperClassInheritedProtocols)
11477 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
11478 SuperImplementsProtocol = true;
11479 break;
11480 }
11481 if (!SuperImplementsProtocol)
11482 return false;
11483 }
11484 }
11485
11486 // If the LHS is specialized, we may need to check type arguments.
11487 if (LHS->isSpecialized()) {
11488 // Follow the superclass chain until we've matched the LHS class in the
11489 // hierarchy. This substitutes type arguments through.
11490 const ObjCObjectType *RHSSuper = RHS;
11491 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
11492 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
11493
11494 // If the RHS is specializd, compare type arguments.
11495 if (RHSSuper->isSpecialized() &&
11496 !sameObjCTypeArgs(*this, LHS->getInterface(),
11497 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
11498 /*stripKindOf=*/true)) {
11499 return false;
11500 }
11501 }
11502
11503 return true;
11504}
11505
11507 // get the "pointed to" types
11508 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
11509 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
11510
11511 if (!LHSOPT || !RHSOPT)
11512 return false;
11513
11514 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
11515 canAssignObjCInterfaces(RHSOPT, LHSOPT);
11516}
11517
11520 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
11521 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
11522}
11523
11524/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
11525/// both shall have the identically qualified version of a compatible type.
11526/// C99 6.2.7p1: Two types have compatible types if their types are the
11527/// same. See 6.7.[2,3,5] for additional rules.
11529 bool CompareUnqualified) {
11530 if (getLangOpts().CPlusPlus)
11531 return hasSameType(LHS, RHS);
11532
11533 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
11534}
11535
11537 return typesAreCompatible(LHS, RHS);
11538}
11539
11541 return !mergeTypes(LHS, RHS, true).isNull();
11542}
11543
11544/// mergeTransparentUnionType - if T is a transparent union type and a member
11545/// of T is compatible with SubType, return the merged type, else return
11546/// QualType()
11548 bool OfBlockPointer,
11549 bool Unqualified) {
11550 if (const RecordType *UT = T->getAsUnionType()) {
11551 RecordDecl *UD = UT->getDecl()->getMostRecentDecl();
11552 if (UD->hasAttr<TransparentUnionAttr>()) {
11553 for (const auto *I : UD->fields()) {
11554 QualType ET = I->getType().getUnqualifiedType();
11555 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
11556 if (!MT.isNull())
11557 return MT;
11558 }
11559 }
11560 }
11561
11562 return {};
11563}
11564
11565/// mergeFunctionParameterTypes - merge two types which appear as function
11566/// parameter types
11568 bool OfBlockPointer,
11569 bool Unqualified) {
11570 // GNU extension: two types are compatible if they appear as a function
11571 // argument, one of the types is a transparent union type and the other
11572 // type is compatible with a union member
11573 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
11574 Unqualified);
11575 if (!lmerge.isNull())
11576 return lmerge;
11577
11578 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
11579 Unqualified);
11580 if (!rmerge.isNull())
11581 return rmerge;
11582
11583 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
11584}
11585
11587 bool OfBlockPointer, bool Unqualified,
11588 bool AllowCXX,
11589 bool IsConditionalOperator) {
11590 const auto *lbase = lhs->castAs<FunctionType>();
11591 const auto *rbase = rhs->castAs<FunctionType>();
11592 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
11593 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
11594 bool allLTypes = true;
11595 bool allRTypes = true;
11596
11597 // Check return type
11598 QualType retType;
11599 if (OfBlockPointer) {
11600 QualType RHS = rbase->getReturnType();
11601 QualType LHS = lbase->getReturnType();
11602 bool UnqualifiedResult = Unqualified;
11603 if (!UnqualifiedResult)
11604 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
11605 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
11606 }
11607 else
11608 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
11609 Unqualified);
11610 if (retType.isNull())
11611 return {};
11612
11613 if (Unqualified)
11614 retType = retType.getUnqualifiedType();
11615
11616 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
11617 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
11618 if (Unqualified) {
11619 LRetType = LRetType.getUnqualifiedType();
11620 RRetType = RRetType.getUnqualifiedType();
11621 }
11622
11623 if (getCanonicalType(retType) != LRetType)
11624 allLTypes = false;
11625 if (getCanonicalType(retType) != RRetType)
11626 allRTypes = false;
11627
11628 // FIXME: double check this
11629 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
11630 // rbase->getRegParmAttr() != 0 &&
11631 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
11632 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
11633 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
11634
11635 // Compatible functions must have compatible calling conventions
11636 if (lbaseInfo.getCC() != rbaseInfo.getCC())
11637 return {};
11638
11639 // Regparm is part of the calling convention.
11640 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
11641 return {};
11642 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
11643 return {};
11644
11645 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
11646 return {};
11647 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
11648 return {};
11649 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
11650 return {};
11651
11652 // When merging declarations, it's common for supplemental information like
11653 // attributes to only be present in one of the declarations, and we generally
11654 // want type merging to preserve the union of information. So a merged
11655 // function type should be noreturn if it was noreturn in *either* operand
11656 // type.
11657 //
11658 // But for the conditional operator, this is backwards. The result of the
11659 // operator could be either operand, and its type should conservatively
11660 // reflect that. So a function type in a composite type is noreturn only
11661 // if it's noreturn in *both* operand types.
11662 //
11663 // Arguably, noreturn is a kind of subtype, and the conditional operator
11664 // ought to produce the most specific common supertype of its operand types.
11665 // That would differ from this rule in contravariant positions. However,
11666 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
11667 // as a practical matter, it would only affect C code that does abstraction of
11668 // higher-order functions (taking noreturn callbacks!), which is uncommon to
11669 // say the least. So we use the simpler rule.
11670 bool NoReturn = IsConditionalOperator
11671 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
11672 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
11673 if (lbaseInfo.getNoReturn() != NoReturn)
11674 allLTypes = false;
11675 if (rbaseInfo.getNoReturn() != NoReturn)
11676 allRTypes = false;
11677
11678 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
11679
11680 std::optional<FunctionEffectSet> MergedFX;
11681
11682 if (lproto && rproto) { // two C99 style function prototypes
11683 assert((AllowCXX ||
11684 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
11685 "C++ shouldn't be here");
11686 // Compatible functions must have the same number of parameters
11687 if (lproto->getNumParams() != rproto->getNumParams())
11688 return {};
11689
11690 // Variadic and non-variadic functions aren't compatible
11691 if (lproto->isVariadic() != rproto->isVariadic())
11692 return {};
11693
11694 if (lproto->getMethodQuals() != rproto->getMethodQuals())
11695 return {};
11696
11697 // Function protos with different 'cfi_salt' values aren't compatible.
11698 if (lproto->getExtraAttributeInfo().CFISalt !=
11699 rproto->getExtraAttributeInfo().CFISalt)
11700 return {};
11701
11702 // Function effects are handled similarly to noreturn, see above.
11703 FunctionEffectsRef LHSFX = lproto->getFunctionEffects();
11704 FunctionEffectsRef RHSFX = rproto->getFunctionEffects();
11705 if (LHSFX != RHSFX) {
11706 if (IsConditionalOperator)
11707 MergedFX = FunctionEffectSet::getIntersection(LHSFX, RHSFX);
11708 else {
11710 MergedFX = FunctionEffectSet::getUnion(LHSFX, RHSFX, Errs);
11711 // Here we're discarding a possible error due to conflicts in the effect
11712 // sets. But we're not in a context where we can report it. The
11713 // operation does however guarantee maintenance of invariants.
11714 }
11715 if (*MergedFX != LHSFX)
11716 allLTypes = false;
11717 if (*MergedFX != RHSFX)
11718 allRTypes = false;
11719 }
11720
11722 bool canUseLeft, canUseRight;
11723 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
11724 newParamInfos))
11725 return {};
11726
11727 if (!canUseLeft)
11728 allLTypes = false;
11729 if (!canUseRight)
11730 allRTypes = false;
11731
11732 // Check parameter type compatibility
11734 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
11735 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
11736 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
11738 lParamType, rParamType, OfBlockPointer, Unqualified);
11739 if (paramType.isNull())
11740 return {};
11741
11742 if (Unqualified)
11743 paramType = paramType.getUnqualifiedType();
11744
11745 types.push_back(paramType);
11746 if (Unqualified) {
11747 lParamType = lParamType.getUnqualifiedType();
11748 rParamType = rParamType.getUnqualifiedType();
11749 }
11750
11751 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
11752 allLTypes = false;
11753 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
11754 allRTypes = false;
11755 }
11756
11757 if (allLTypes) return lhs;
11758 if (allRTypes) return rhs;
11759
11760 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
11761 EPI.ExtInfo = einfo;
11762 EPI.ExtParameterInfos =
11763 newParamInfos.empty() ? nullptr : newParamInfos.data();
11764 if (MergedFX)
11765 EPI.FunctionEffects = *MergedFX;
11766 return getFunctionType(retType, types, EPI);
11767 }
11768
11769 if (lproto) allRTypes = false;
11770 if (rproto) allLTypes = false;
11771
11772 const FunctionProtoType *proto = lproto ? lproto : rproto;
11773 if (proto) {
11774 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
11775 if (proto->isVariadic())
11776 return {};
11777 // Check that the types are compatible with the types that
11778 // would result from default argument promotions (C99 6.7.5.3p15).
11779 // The only types actually affected are promotable integer
11780 // types and floats, which would be passed as a different
11781 // type depending on whether the prototype is visible.
11782 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
11783 QualType paramTy = proto->getParamType(i);
11784
11785 // Look at the converted type of enum types, since that is the type used
11786 // to pass enum values.
11787 if (const auto *ED = paramTy->getAsEnumDecl()) {
11788 paramTy = ED->getIntegerType();
11789 if (paramTy.isNull())
11790 return {};
11791 }
11792
11793 if (isPromotableIntegerType(paramTy) ||
11794 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
11795 return {};
11796 }
11797
11798 if (allLTypes) return lhs;
11799 if (allRTypes) return rhs;
11800
11802 EPI.ExtInfo = einfo;
11803 if (MergedFX)
11804 EPI.FunctionEffects = *MergedFX;
11805 return getFunctionType(retType, proto->getParamTypes(), EPI);
11806 }
11807
11808 if (allLTypes) return lhs;
11809 if (allRTypes) return rhs;
11810 return getFunctionNoProtoType(retType, einfo);
11811}
11812
11813/// Given that we have an enum type and a non-enum type, try to merge them.
11814static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
11815 QualType other, bool isBlockReturnType) {
11816 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
11817 // a signed integer type, or an unsigned integer type.
11818 // Compatibility is based on the underlying type, not the promotion
11819 // type.
11820 QualType underlyingType =
11821 ET->getDecl()->getDefinitionOrSelf()->getIntegerType();
11822 if (underlyingType.isNull())
11823 return {};
11824 if (Context.hasSameType(underlyingType, other))
11825 return other;
11826
11827 // In block return types, we're more permissive and accept any
11828 // integral type of the same size.
11829 if (isBlockReturnType && other->isIntegerType() &&
11830 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
11831 return other;
11832
11833 return {};
11834}
11835
11837 // C17 and earlier and C++ disallow two tag definitions within the same TU
11838 // from being compatible.
11839 if (LangOpts.CPlusPlus || !LangOpts.C23)
11840 return {};
11841
11842 // Nameless tags are comparable only within outer definitions. At the top
11843 // level they are not comparable.
11844 const TagDecl *LTagD = LHS->castAsTagDecl(), *RTagD = RHS->castAsTagDecl();
11845 if (!LTagD->getIdentifier() || !RTagD->getIdentifier())
11846 return {};
11847
11848 // C23, on the other hand, requires the members to be "the same enough", so
11849 // we use a structural equivalence check.
11852 getLangOpts(), *this, *this, NonEquivalentDecls,
11853 StructuralEquivalenceKind::Default, /*StrictTypeSpelling=*/false,
11854 /*Complain=*/false, /*ErrorOnTagTypeMismatch=*/true);
11855 return Ctx.IsEquivalent(LHS, RHS) ? LHS : QualType{};
11856}
11857
11859 QualType LHS, QualType RHS, bool OfBlockPointer, bool Unqualified,
11860 bool BlockReturnType, bool IsConditionalOperator) {
11861 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
11862 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
11863
11864 if (!LHSOBT && !RHSOBT)
11865 return std::nullopt;
11866
11867 if (LHSOBT) {
11868 if (RHSOBT) {
11869 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
11870 return QualType();
11871
11872 QualType MergedUnderlying = mergeTypes(
11873 LHSOBT->getUnderlyingType(), RHSOBT->getUnderlyingType(),
11874 OfBlockPointer, Unqualified, BlockReturnType, IsConditionalOperator);
11875
11876 if (MergedUnderlying.isNull())
11877 return QualType();
11878
11879 if (getCanonicalType(LHSOBT) == getCanonicalType(RHSOBT)) {
11880 if (LHSOBT->getUnderlyingType() == RHSOBT->getUnderlyingType())
11881 return getCommonSugaredType(LHS, RHS);
11883 LHSOBT->getBehaviorKind(),
11884 getCanonicalType(LHSOBT->getUnderlyingType()));
11885 }
11886
11887 // For different underlying types that successfully merge, wrap the
11888 // merged underlying type with the common overflow behavior
11889 return getOverflowBehaviorType(LHSOBT->getBehaviorKind(),
11890 MergedUnderlying);
11891 }
11892 return mergeTypes(LHSOBT->getUnderlyingType(), RHS, OfBlockPointer,
11893 Unqualified, BlockReturnType, IsConditionalOperator);
11894 }
11895
11896 return mergeTypes(LHS, RHSOBT->getUnderlyingType(), OfBlockPointer,
11897 Unqualified, BlockReturnType, IsConditionalOperator);
11898}
11899
11900QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
11901 bool Unqualified, bool BlockReturnType,
11902 bool IsConditionalOperator) {
11903 // For C++ we will not reach this code with reference types (see below),
11904 // for OpenMP variant call overloading we might.
11905 //
11906 // C++ [expr]: If an expression initially has the type "reference to T", the
11907 // type is adjusted to "T" prior to any further analysis, the expression
11908 // designates the object or function denoted by the reference, and the
11909 // expression is an lvalue unless the reference is an rvalue reference and
11910 // the expression is a function call (possibly inside parentheses).
11911 auto *LHSRefTy = LHS->getAs<ReferenceType>();
11912 auto *RHSRefTy = RHS->getAs<ReferenceType>();
11913 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
11914 LHS->getTypeClass() == RHS->getTypeClass())
11915 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
11916 OfBlockPointer, Unqualified, BlockReturnType);
11917 if (LHSRefTy || RHSRefTy)
11918 return {};
11919
11920 if (std::optional<QualType> MergedOBT =
11921 tryMergeOverflowBehaviorTypes(LHS, RHS, OfBlockPointer, Unqualified,
11922 BlockReturnType, IsConditionalOperator))
11923 return *MergedOBT;
11924
11925 if (Unqualified) {
11926 LHS = LHS.getUnqualifiedType();
11927 RHS = RHS.getUnqualifiedType();
11928 }
11929
11930 QualType LHSCan = getCanonicalType(LHS),
11931 RHSCan = getCanonicalType(RHS);
11932
11933 // If two types are identical, they are compatible.
11934 if (LHSCan == RHSCan)
11935 return LHS;
11936
11937 // If the qualifiers are different, the types aren't compatible... mostly.
11938 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11939 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11940 if (LQuals != RQuals) {
11941 // If any of these qualifiers are different, we have a type
11942 // mismatch.
11943 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11944 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
11945 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
11946 !LQuals.getPointerAuth().isEquivalent(RQuals.getPointerAuth()) ||
11947 LQuals.hasUnaligned() != RQuals.hasUnaligned())
11948 return {};
11949
11950 // Exactly one GC qualifier difference is allowed: __strong is
11951 // okay if the other type has no GC qualifier but is an Objective
11952 // C object pointer (i.e. implicitly strong by default). We fix
11953 // this by pretending that the unqualified type was actually
11954 // qualified __strong.
11955 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11956 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11957 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11958
11959 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11960 return {};
11961
11962 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
11964 }
11965 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
11967 }
11968 return {};
11969 }
11970
11971 // Okay, qualifiers are equal.
11972
11973 Type::TypeClass LHSClass = LHSCan->getTypeClass();
11974 Type::TypeClass RHSClass = RHSCan->getTypeClass();
11975
11976 // We want to consider the two function types to be the same for these
11977 // comparisons, just force one to the other.
11978 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
11979 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
11980
11981 // Same as above for arrays
11982 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
11983 LHSClass = Type::ConstantArray;
11984 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
11985 RHSClass = Type::ConstantArray;
11986
11987 // ObjCInterfaces are just specialized ObjCObjects.
11988 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
11989 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
11990
11991 // Canonicalize ExtVector -> Vector.
11992 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
11993 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
11994
11995 // If the canonical type classes don't match.
11996 if (LHSClass != RHSClass) {
11997 // Note that we only have special rules for turning block enum
11998 // returns into block int returns, not vice-versa.
11999 if (const auto *ETy = LHS->getAsCanonical<EnumType>()) {
12000 return mergeEnumWithInteger(*this, ETy, RHS, false);
12001 }
12002 if (const EnumType *ETy = RHS->getAsCanonical<EnumType>()) {
12003 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
12004 }
12005 // allow block pointer type to match an 'id' type.
12006 if (OfBlockPointer && !BlockReturnType) {
12007 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
12008 return LHS;
12009 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
12010 return RHS;
12011 }
12012 // Allow __auto_type to match anything; it merges to the type with more
12013 // information.
12014 if (const auto *AT = LHS->getAs<AutoType>()) {
12015 if (!AT->isDeduced() && AT->isGNUAutoType())
12016 return RHS;
12017 }
12018 if (const auto *AT = RHS->getAs<AutoType>()) {
12019 if (!AT->isDeduced() && AT->isGNUAutoType())
12020 return LHS;
12021 }
12022 return {};
12023 }
12024
12025 // The canonical type classes match.
12026 switch (LHSClass) {
12027#define TYPE(Class, Base)
12028#define ABSTRACT_TYPE(Class, Base)
12029#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
12030#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
12031#define DEPENDENT_TYPE(Class, Base) case Type::Class:
12032#include "clang/AST/TypeNodes.inc"
12033 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
12034
12035 case Type::Auto:
12036 case Type::DeducedTemplateSpecialization:
12037 case Type::LValueReference:
12038 case Type::RValueReference:
12039 case Type::MemberPointer:
12040 llvm_unreachable("C++ should never be in mergeTypes");
12041
12042 case Type::ObjCInterface:
12043 case Type::IncompleteArray:
12044 case Type::VariableArray:
12045 case Type::FunctionProto:
12046 case Type::ExtVector:
12047 case Type::OverflowBehavior:
12048 llvm_unreachable("Types are eliminated above");
12049
12050 case Type::Pointer:
12051 {
12052 // Merge two pointer types, while trying to preserve typedef info
12053 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
12054 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
12055 if (Unqualified) {
12056 LHSPointee = LHSPointee.getUnqualifiedType();
12057 RHSPointee = RHSPointee.getUnqualifiedType();
12058 }
12059 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
12060 Unqualified);
12061 if (ResultType.isNull())
12062 return {};
12063 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
12064 return LHS;
12065 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
12066 return RHS;
12067 return getPointerType(ResultType);
12068 }
12069 case Type::BlockPointer:
12070 {
12071 // Merge two block pointer types, while trying to preserve typedef info
12072 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
12073 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
12074 if (Unqualified) {
12075 LHSPointee = LHSPointee.getUnqualifiedType();
12076 RHSPointee = RHSPointee.getUnqualifiedType();
12077 }
12078 if (getLangOpts().OpenCL) {
12079 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
12080 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
12081 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
12082 // 6.12.5) thus the following check is asymmetric.
12083 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual, *this))
12084 return {};
12085 LHSPteeQual.removeAddressSpace();
12086 RHSPteeQual.removeAddressSpace();
12087 LHSPointee =
12088 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
12089 RHSPointee =
12090 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
12091 }
12092 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
12093 Unqualified);
12094 if (ResultType.isNull())
12095 return {};
12096 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
12097 return LHS;
12098 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
12099 return RHS;
12100 return getBlockPointerType(ResultType);
12101 }
12102 case Type::Atomic:
12103 {
12104 // Merge two pointer types, while trying to preserve typedef info
12105 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
12106 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
12107 if (Unqualified) {
12108 LHSValue = LHSValue.getUnqualifiedType();
12109 RHSValue = RHSValue.getUnqualifiedType();
12110 }
12111 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
12112 Unqualified);
12113 if (ResultType.isNull())
12114 return {};
12115 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
12116 return LHS;
12117 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
12118 return RHS;
12119 return getAtomicType(ResultType);
12120 }
12121 case Type::ConstantArray:
12122 {
12123 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
12124 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
12125 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
12126 return {};
12127
12128 QualType LHSElem = getAsArrayType(LHS)->getElementType();
12129 QualType RHSElem = getAsArrayType(RHS)->getElementType();
12130 if (Unqualified) {
12131 LHSElem = LHSElem.getUnqualifiedType();
12132 RHSElem = RHSElem.getUnqualifiedType();
12133 }
12134
12135 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
12136 if (ResultType.isNull())
12137 return {};
12138
12139 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
12140 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
12141
12142 // If either side is a variable array, and both are complete, check whether
12143 // the current dimension is definite.
12144 if (LVAT || RVAT) {
12145 auto SizeFetch = [this](const VariableArrayType* VAT,
12146 const ConstantArrayType* CAT)
12147 -> std::pair<bool,llvm::APInt> {
12148 if (VAT) {
12149 std::optional<llvm::APSInt> TheInt;
12150 Expr *E = VAT->getSizeExpr();
12151 if (E && (TheInt = E->getIntegerConstantExpr(*this)))
12152 return std::make_pair(true, *TheInt);
12153 return std::make_pair(false, llvm::APSInt());
12154 }
12155 if (CAT)
12156 return std::make_pair(true, CAT->getSize());
12157 return std::make_pair(false, llvm::APInt());
12158 };
12159
12160 bool HaveLSize, HaveRSize;
12161 llvm::APInt LSize, RSize;
12162 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
12163 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
12164 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
12165 return {}; // Definite, but unequal, array dimension
12166 }
12167
12168 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
12169 return LHS;
12170 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
12171 return RHS;
12172 if (LCAT)
12173 return getConstantArrayType(ResultType, LCAT->getSize(),
12174 LCAT->getSizeExpr(), ArraySizeModifier(), 0);
12175 if (RCAT)
12176 return getConstantArrayType(ResultType, RCAT->getSize(),
12177 RCAT->getSizeExpr(), ArraySizeModifier(), 0);
12178 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
12179 return LHS;
12180 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
12181 return RHS;
12182 if (LVAT) {
12183 // FIXME: This isn't correct! But tricky to implement because
12184 // the array's size has to be the size of LHS, but the type
12185 // has to be different.
12186 return LHS;
12187 }
12188 if (RVAT) {
12189 // FIXME: This isn't correct! But tricky to implement because
12190 // the array's size has to be the size of RHS, but the type
12191 // has to be different.
12192 return RHS;
12193 }
12194 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
12195 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
12196 return getIncompleteArrayType(ResultType, ArraySizeModifier(), 0);
12197 }
12198 case Type::FunctionNoProto:
12199 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified,
12200 /*AllowCXX=*/false, IsConditionalOperator);
12201 case Type::Record:
12202 case Type::Enum:
12203 return mergeTagDefinitions(LHS, RHS);
12204 case Type::Builtin:
12205 // Only exactly equal builtin types are compatible, which is tested above.
12206 return {};
12207 case Type::Complex:
12208 // Distinct complex types are incompatible.
12209 return {};
12210 case Type::Vector:
12211 // FIXME: The merged type should be an ExtVector!
12212 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
12213 RHSCan->castAs<VectorType>()))
12214 return LHS;
12215 return {};
12216 case Type::ConstantMatrix:
12218 RHSCan->castAs<ConstantMatrixType>()))
12219 return LHS;
12220 return {};
12221 case Type::ObjCObject: {
12222 // Check if the types are assignment compatible.
12223 // FIXME: This should be type compatibility, e.g. whether
12224 // "LHS x; RHS x;" at global scope is legal.
12226 RHS->castAs<ObjCObjectType>()))
12227 return LHS;
12228 return {};
12229 }
12230 case Type::ObjCObjectPointer:
12231 if (OfBlockPointer) {
12234 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
12235 return LHS;
12236 return {};
12237 }
12240 return LHS;
12241 return {};
12242 case Type::Pipe:
12243 assert(LHS != RHS &&
12244 "Equivalent pipe types should have already been handled!");
12245 return {};
12246 case Type::ArrayParameter:
12247 assert(LHS != RHS &&
12248 "Equivalent ArrayParameter types should have already been handled!");
12249 return {};
12250 case Type::BitInt: {
12251 // Merge two bit-precise int types, while trying to preserve typedef info.
12252 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
12253 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
12254 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
12255 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
12256
12257 // Like unsigned/int, shouldn't have a type if they don't match.
12258 if (LHSUnsigned != RHSUnsigned)
12259 return {};
12260
12261 if (LHSBits != RHSBits)
12262 return {};
12263 return LHS;
12264 }
12265 case Type::HLSLAttributedResource: {
12266 const HLSLAttributedResourceType *LHSTy =
12267 LHS->castAs<HLSLAttributedResourceType>();
12268 const HLSLAttributedResourceType *RHSTy =
12269 RHS->castAs<HLSLAttributedResourceType>();
12270 assert(LHSTy->getWrappedType() == RHSTy->getWrappedType() &&
12271 LHSTy->getWrappedType()->isHLSLResourceType() &&
12272 "HLSLAttributedResourceType should always wrap __hlsl_resource_t");
12273
12274 if (LHSTy->getAttrs() == RHSTy->getAttrs() &&
12275 LHSTy->getContainedType() == RHSTy->getContainedType())
12276 return LHS;
12277 return {};
12278 }
12279 case Type::HLSLInlineSpirv:
12280 const HLSLInlineSpirvType *LHSTy = LHS->castAs<HLSLInlineSpirvType>();
12281 const HLSLInlineSpirvType *RHSTy = RHS->castAs<HLSLInlineSpirvType>();
12282
12283 if (LHSTy->getOpcode() == RHSTy->getOpcode() &&
12284 LHSTy->getSize() == RHSTy->getSize() &&
12285 LHSTy->getAlignment() == RHSTy->getAlignment()) {
12286 for (size_t I = 0; I < LHSTy->getOperands().size(); I++)
12287 if (LHSTy->getOperands()[I] != RHSTy->getOperands()[I])
12288 return {};
12289
12290 return LHS;
12291 }
12292 return {};
12293 }
12294
12295 llvm_unreachable("Invalid Type::Class!");
12296}
12297
12299 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
12300 bool &CanUseFirst, bool &CanUseSecond,
12302 assert(NewParamInfos.empty() && "param info list not empty");
12303 CanUseFirst = CanUseSecond = true;
12304 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
12305 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
12306
12307 // Fast path: if the first type doesn't have ext parameter infos,
12308 // we match if and only if the second type also doesn't have them.
12309 if (!FirstHasInfo && !SecondHasInfo)
12310 return true;
12311
12312 bool NeedParamInfo = false;
12313 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
12314 : SecondFnType->getExtParameterInfos().size();
12315
12316 for (size_t I = 0; I < E; ++I) {
12317 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
12318 if (FirstHasInfo)
12319 FirstParam = FirstFnType->getExtParameterInfo(I);
12320 if (SecondHasInfo)
12321 SecondParam = SecondFnType->getExtParameterInfo(I);
12322
12323 // Cannot merge unless everything except the noescape flag matches.
12324 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
12325 return false;
12326
12327 bool FirstNoEscape = FirstParam.isNoEscape();
12328 bool SecondNoEscape = SecondParam.isNoEscape();
12329 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
12330 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
12331 if (NewParamInfos.back().getOpaqueValue())
12332 NeedParamInfo = true;
12333 if (FirstNoEscape != IsNoEscape)
12334 CanUseFirst = false;
12335 if (SecondNoEscape != IsNoEscape)
12336 CanUseSecond = false;
12337 }
12338
12339 if (!NeedParamInfo)
12340 NewParamInfos.clear();
12341
12342 return true;
12343}
12344
12346 if (auto It = ObjCLayouts.find(D); It != ObjCLayouts.end()) {
12347 It->second = nullptr;
12348 for (auto *SubClass : ObjCSubClasses.lookup(D))
12349 ResetObjCLayout(SubClass);
12350 }
12351}
12352
12353/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
12354/// 'RHS' attributes and returns the merged version; including for function
12355/// return types.
12357 QualType LHSCan = getCanonicalType(LHS),
12358 RHSCan = getCanonicalType(RHS);
12359 // If two types are identical, they are compatible.
12360 if (LHSCan == RHSCan)
12361 return LHS;
12362 if (RHSCan->isFunctionType()) {
12363 if (!LHSCan->isFunctionType())
12364 return {};
12365 QualType OldReturnType =
12366 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
12367 QualType NewReturnType =
12368 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
12369 QualType ResReturnType =
12370 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
12371 if (ResReturnType.isNull())
12372 return {};
12373 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
12374 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
12375 // In either case, use OldReturnType to build the new function type.
12376 const auto *F = LHS->castAs<FunctionType>();
12377 if (const auto *FPT = cast<FunctionProtoType>(F)) {
12378 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12379 EPI.ExtInfo = getFunctionExtInfo(LHS);
12380 QualType ResultType =
12381 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
12382 return ResultType;
12383 }
12384 }
12385 return {};
12386 }
12387
12388 // If the qualifiers are different, the types can still be merged.
12389 Qualifiers LQuals = LHSCan.getLocalQualifiers();
12390 Qualifiers RQuals = RHSCan.getLocalQualifiers();
12391 if (LQuals != RQuals) {
12392 // If any of these qualifiers are different, we have a type mismatch.
12393 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
12394 LQuals.getAddressSpace() != RQuals.getAddressSpace())
12395 return {};
12396
12397 // Exactly one GC qualifier difference is allowed: __strong is
12398 // okay if the other type has no GC qualifier but is an Objective
12399 // C object pointer (i.e. implicitly strong by default). We fix
12400 // this by pretending that the unqualified type was actually
12401 // qualified __strong.
12402 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
12403 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
12404 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
12405
12406 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
12407 return {};
12408
12409 if (GC_L == Qualifiers::Strong)
12410 return LHS;
12411 if (GC_R == Qualifiers::Strong)
12412 return RHS;
12413 return {};
12414 }
12415
12416 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
12417 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12418 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12419 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
12420 if (ResQT == LHSBaseQT)
12421 return LHS;
12422 if (ResQT == RHSBaseQT)
12423 return RHS;
12424 }
12425 return {};
12426}
12427
12428//===----------------------------------------------------------------------===//
12429// Integer Predicates
12430//===----------------------------------------------------------------------===//
12431
12433 if (const auto *ED = T->getAsEnumDecl())
12434 T = ED->getIntegerType();
12435 if (T->isBooleanType())
12436 return 1;
12437 if (const auto *EIT = T->getAs<BitIntType>())
12438 return EIT->getNumBits();
12439 // For builtin types, just use the standard type sizing method
12440 return (unsigned)getTypeSize(T);
12441}
12442
12444 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12445 T->isFixedPointType()) &&
12446 "Unexpected type");
12447
12448 // Turn <4 x signed int> -> <4 x unsigned int>
12449 if (const auto *VTy = T->getAs<VectorType>())
12450 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
12451 VTy->getNumElements(), VTy->getVectorKind());
12452
12453 // For _BitInt, return an unsigned _BitInt with same width.
12454 if (const auto *EITy = T->getAs<BitIntType>())
12455 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
12456
12457 // For the overflow behavior types, construct a new unsigned variant
12458 if (const auto *OBT = T->getAs<OverflowBehaviorType>())
12460 OBT->getBehaviorKind(),
12461 getCorrespondingUnsignedType(OBT->getUnderlyingType()));
12462
12463 // For enums, get the underlying integer type of the enum, and let the general
12464 // integer type signchanging code handle it.
12465 if (const auto *ED = T->getAsEnumDecl())
12466 T = ED->getIntegerType();
12467
12468 switch (T->castAs<BuiltinType>()->getKind()) {
12469 case BuiltinType::Char_U:
12470 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
12471 case BuiltinType::Char_S:
12472 case BuiltinType::SChar:
12473 case BuiltinType::Char8:
12474 return UnsignedCharTy;
12475 case BuiltinType::Short:
12476 return UnsignedShortTy;
12477 case BuiltinType::Int:
12478 return UnsignedIntTy;
12479 case BuiltinType::Long:
12480 return UnsignedLongTy;
12481 case BuiltinType::LongLong:
12482 return UnsignedLongLongTy;
12483 case BuiltinType::Int128:
12484 return UnsignedInt128Ty;
12485 // wchar_t is special. It is either signed or not, but when it's signed,
12486 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
12487 // version of its underlying type instead.
12488 case BuiltinType::WChar_S:
12489 return getUnsignedWCharType();
12490
12491 case BuiltinType::ShortAccum:
12492 return UnsignedShortAccumTy;
12493 case BuiltinType::Accum:
12494 return UnsignedAccumTy;
12495 case BuiltinType::LongAccum:
12496 return UnsignedLongAccumTy;
12497 case BuiltinType::SatShortAccum:
12499 case BuiltinType::SatAccum:
12500 return SatUnsignedAccumTy;
12501 case BuiltinType::SatLongAccum:
12503 case BuiltinType::ShortFract:
12504 return UnsignedShortFractTy;
12505 case BuiltinType::Fract:
12506 return UnsignedFractTy;
12507 case BuiltinType::LongFract:
12508 return UnsignedLongFractTy;
12509 case BuiltinType::SatShortFract:
12511 case BuiltinType::SatFract:
12512 return SatUnsignedFractTy;
12513 case BuiltinType::SatLongFract:
12515 default:
12516 assert((T->hasUnsignedIntegerRepresentation() ||
12517 T->isUnsignedFixedPointType()) &&
12518 "Unexpected signed integer or fixed point type");
12519 return T;
12520 }
12521}
12522
12524 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12525 T->isFixedPointType()) &&
12526 "Unexpected type");
12527
12528 // Turn <4 x unsigned int> -> <4 x signed int>
12529 if (const auto *VTy = T->getAs<VectorType>())
12530 return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
12531 VTy->getNumElements(), VTy->getVectorKind());
12532
12533 // For _BitInt, return a signed _BitInt with same width.
12534 if (const auto *EITy = T->getAs<BitIntType>())
12535 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
12536
12537 // For enums, get the underlying integer type of the enum, and let the general
12538 // integer type signchanging code handle it.
12539 if (const auto *ED = T->getAsEnumDecl())
12540 T = ED->getIntegerType();
12541
12542 switch (T->castAs<BuiltinType>()->getKind()) {
12543 case BuiltinType::Char_S:
12544 // Plain `char` is mapped to `signed char` even if it's already signed
12545 case BuiltinType::Char_U:
12546 case BuiltinType::UChar:
12547 case BuiltinType::Char8:
12548 return SignedCharTy;
12549 case BuiltinType::UShort:
12550 return ShortTy;
12551 case BuiltinType::UInt:
12552 return IntTy;
12553 case BuiltinType::ULong:
12554 return LongTy;
12555 case BuiltinType::ULongLong:
12556 return LongLongTy;
12557 case BuiltinType::UInt128:
12558 return Int128Ty;
12559 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
12560 // there's no matching "signed wchar_t". Therefore we return the signed
12561 // version of its underlying type instead.
12562 case BuiltinType::WChar_U:
12563 return getSignedWCharType();
12564
12565 case BuiltinType::UShortAccum:
12566 return ShortAccumTy;
12567 case BuiltinType::UAccum:
12568 return AccumTy;
12569 case BuiltinType::ULongAccum:
12570 return LongAccumTy;
12571 case BuiltinType::SatUShortAccum:
12572 return SatShortAccumTy;
12573 case BuiltinType::SatUAccum:
12574 return SatAccumTy;
12575 case BuiltinType::SatULongAccum:
12576 return SatLongAccumTy;
12577 case BuiltinType::UShortFract:
12578 return ShortFractTy;
12579 case BuiltinType::UFract:
12580 return FractTy;
12581 case BuiltinType::ULongFract:
12582 return LongFractTy;
12583 case BuiltinType::SatUShortFract:
12584 return SatShortFractTy;
12585 case BuiltinType::SatUFract:
12586 return SatFractTy;
12587 case BuiltinType::SatULongFract:
12588 return SatLongFractTy;
12589 default:
12590 assert(
12591 (T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
12592 "Unexpected signed integer or fixed point type");
12593 return T;
12594 }
12595}
12596
12598
12601
12602//===----------------------------------------------------------------------===//
12603// Builtin Type Computation
12604//===----------------------------------------------------------------------===//
12605
12606/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
12607/// pointer over the consumed characters. This returns the resultant type. If
12608/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
12609/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
12610/// a vector of "i*".
12611///
12612/// RequiresICE is filled in on return to indicate whether the value is required
12613/// to be an Integer Constant Expression.
12614static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
12616 bool &RequiresICE,
12617 bool AllowTypeModifiers) {
12618 // Modifiers.
12619 int HowLong = 0;
12620 bool Signed = false, Unsigned = false;
12621 bool IsChar = false, IsShort = false;
12622 RequiresICE = false;
12623
12624 // Read the prefixed modifiers first.
12625 bool Done = false;
12626 #ifndef NDEBUG
12627 bool IsSpecial = false;
12628 #endif
12629 while (!Done) {
12630 switch (*Str++) {
12631 default: Done = true; --Str; break;
12632 case 'I':
12633 RequiresICE = true;
12634 break;
12635 case 'S':
12636 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
12637 assert(!Signed && "Can't use 'S' modifier multiple times!");
12638 Signed = true;
12639 break;
12640 case 'U':
12641 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
12642 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
12643 Unsigned = true;
12644 break;
12645 case 'B':
12646 // This modifier represents int8 type (byte-width).
12647 assert(!IsSpecial &&
12648 "Can't use two 'N', 'W', 'Z', 'O', 'B', or 'T' modifiers!");
12649 assert(HowLong == 0 && "Can't use both 'L' and 'B' modifiers!");
12650#ifndef NDEBUG
12651 IsSpecial = true;
12652#endif
12653 IsChar = true;
12654 break;
12655 case 'T':
12656 // This modifier represents int16 type (short-width).
12657 assert(!IsSpecial &&
12658 "Can't use two 'N', 'W', 'Z', 'O', 'B', or 'T' modifiers!");
12659 assert(HowLong == 0 && "Can't use both 'L' and 'T' modifiers!");
12660#ifndef NDEBUG
12661 IsSpecial = true;
12662#endif
12663 IsShort = true;
12664 break;
12665 case 'L':
12666 assert(!IsSpecial &&
12667 "Can't use 'L' with 'W', 'N', 'Z', 'O', 'B', or 'T' modifiers");
12668 assert(HowLong <= 2 && "Can't have LLLL modifier");
12669 ++HowLong;
12670 break;
12671 case 'N':
12672 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
12673 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12674 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
12675 #ifndef NDEBUG
12676 IsSpecial = true;
12677 #endif
12678 if (Context.getTargetInfo().getLongWidth() == 32)
12679 ++HowLong;
12680 break;
12681 case 'W':
12682 // This modifier represents int64 type.
12683 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12684 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
12685 #ifndef NDEBUG
12686 IsSpecial = true;
12687 #endif
12688 switch (Context.getTargetInfo().getInt64Type()) {
12689 default:
12690 llvm_unreachable("Unexpected integer type");
12692 HowLong = 1;
12693 break;
12695 HowLong = 2;
12696 break;
12697 }
12698 break;
12699 case 'Z':
12700 // This modifier represents int32 type.
12701 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12702 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
12703 #ifndef NDEBUG
12704 IsSpecial = true;
12705 #endif
12706 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
12707 default:
12708 llvm_unreachable("Unexpected integer type");
12710 HowLong = 0;
12711 break;
12713 HowLong = 1;
12714 break;
12716 HowLong = 2;
12717 break;
12718 }
12719 break;
12720 case 'O':
12721 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12722 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
12723 #ifndef NDEBUG
12724 IsSpecial = true;
12725 #endif
12726 if (Context.getLangOpts().OpenCL)
12727 HowLong = 1;
12728 else
12729 HowLong = 2;
12730 break;
12731 }
12732 }
12733
12734 QualType Type;
12735
12736 // Read the base type.
12737 switch (*Str++) {
12738 default:
12739 llvm_unreachable("Unknown builtin type letter!");
12740 case 'x':
12741 assert(HowLong == 0 && !Signed && !Unsigned &&
12742 "Bad modifiers used with 'x'!");
12743 Type = Context.Float16Ty;
12744 break;
12745 case 'y':
12746 assert(HowLong == 0 && !Signed && !Unsigned &&
12747 "Bad modifiers used with 'y'!");
12748 Type = Context.BFloat16Ty;
12749 break;
12750 case 'v':
12751 assert(HowLong == 0 && !Signed && !Unsigned &&
12752 "Bad modifiers used with 'v'!");
12753 Type = Context.VoidTy;
12754 break;
12755 case 'h':
12756 assert(HowLong == 0 && !Signed && !Unsigned &&
12757 "Bad modifiers used with 'h'!");
12758 Type = Context.HalfTy;
12759 break;
12760 case 'f':
12761 assert(HowLong == 0 && !Signed && !Unsigned &&
12762 "Bad modifiers used with 'f'!");
12763 Type = Context.FloatTy;
12764 break;
12765 case 'd':
12766 assert(HowLong < 3 && !Signed && !Unsigned &&
12767 "Bad modifiers used with 'd'!");
12768 if (HowLong == 1)
12769 Type = Context.LongDoubleTy;
12770 else if (HowLong == 2)
12771 Type = Context.Float128Ty;
12772 else
12773 Type = Context.DoubleTy;
12774 break;
12775 case 's':
12776 assert(HowLong == 0 && "Bad modifiers used with 's'!");
12777 if (Unsigned)
12778 Type = Context.UnsignedShortTy;
12779 else
12780 Type = Context.ShortTy;
12781 break;
12782 case 'i':
12783 if (IsChar)
12784 Type = Unsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
12785 else if (IsShort)
12786 Type = Unsigned ? Context.UnsignedShortTy : Context.ShortTy;
12787 else if (HowLong == 3)
12788 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
12789 else if (HowLong == 2)
12790 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
12791 else if (HowLong == 1)
12792 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
12793 else
12794 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
12795 break;
12796 case 'c':
12797 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
12798 if (Signed)
12799 Type = Context.SignedCharTy;
12800 else if (Unsigned)
12801 Type = Context.UnsignedCharTy;
12802 else
12803 Type = Context.CharTy;
12804 break;
12805 case 'b': // boolean
12806 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
12807 Type = Context.BoolTy;
12808 break;
12809 case 'z': // size_t.
12810 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
12811 Type = Context.getSizeType();
12812 break;
12813 case 'w': // wchar_t.
12814 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
12815 Type = Context.getWideCharType();
12816 break;
12817 case 'F':
12818 Type = Context.getCFConstantStringType();
12819 break;
12820 case 'G':
12821 Type = Context.getObjCIdType();
12822 break;
12823 case 'H':
12824 Type = Context.getObjCSelType();
12825 break;
12826 case 'M':
12827 Type = Context.getObjCSuperType();
12828 break;
12829 case 'a':
12830 Type = Context.getBuiltinVaListType();
12831 assert(!Type.isNull() && "builtin va list type not initialized!");
12832 break;
12833 case 'A':
12834 // This is a "reference" to a va_list; however, what exactly
12835 // this means depends on how va_list is defined. There are two
12836 // different kinds of va_list: ones passed by value, and ones
12837 // passed by reference. An example of a by-value va_list is
12838 // x86, where va_list is a char*. An example of by-ref va_list
12839 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
12840 // we want this argument to be a char*&; for x86-64, we want
12841 // it to be a __va_list_tag*.
12842 Type = Context.getBuiltinVaListType();
12843 assert(!Type.isNull() && "builtin va list type not initialized!");
12844 if (Type->isArrayType())
12845 Type = Context.getArrayDecayedType(Type);
12846 else
12847 Type = Context.getLValueReferenceType(Type);
12848 break;
12849 case 'q': {
12850 char *End;
12851 unsigned NumElements = strtoul(Str, &End, 10);
12852 assert(End != Str && "Missing vector size");
12853 Str = End;
12854
12855 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12856 RequiresICE, false);
12857 assert(!RequiresICE && "Can't require vector ICE");
12858
12859 Type = Context.getScalableVectorType(ElementType, NumElements);
12860 break;
12861 }
12862 case 'Q': {
12863 switch (*Str++) {
12864 case 'a': {
12865 Type = Context.SveCountTy;
12866 break;
12867 }
12868 case 'b': {
12869 Type = Context.AMDGPUBufferRsrcTy;
12870 break;
12871 }
12872 case 'c': {
12873 Type = Context.AMDGPUFeaturePredicateTy;
12874 break;
12875 }
12876 case 't': {
12877 Type = Context.AMDGPUTextureTy;
12878 break;
12879 }
12880 case 'r': {
12881 Type = Context.HLSLResourceTy;
12882 break;
12883 }
12884 default:
12885 llvm_unreachable("Unexpected target builtin type");
12886 }
12887 break;
12888 }
12889 case 'V': {
12890 char *End;
12891 unsigned NumElements = strtoul(Str, &End, 10);
12892 assert(End != Str && "Missing vector size");
12893 Str = End;
12894
12895 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12896 RequiresICE, false);
12897 assert(!RequiresICE && "Can't require vector ICE");
12898
12899 // TODO: No way to make AltiVec vectors in builtins yet.
12900 Type = Context.getVectorType(ElementType, NumElements, VectorKind::Generic);
12901 break;
12902 }
12903 case 'E': {
12904 char *End;
12905
12906 unsigned NumElements = strtoul(Str, &End, 10);
12907 assert(End != Str && "Missing vector size");
12908
12909 Str = End;
12910
12911 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12912 false);
12913 Type = Context.getExtVectorType(ElementType, NumElements);
12914 break;
12915 }
12916 case 'X': {
12917 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12918 false);
12919 assert(!RequiresICE && "Can't require complex ICE");
12920 Type = Context.getComplexType(ElementType);
12921 break;
12922 }
12923 case 'Y':
12924 Type = Context.getPointerDiffType();
12925 break;
12926 case 'P':
12927 Type = Context.getFILEType();
12928 if (Type.isNull()) {
12930 return {};
12931 }
12932 break;
12933 case 'J':
12934 if (Signed)
12935 Type = Context.getsigjmp_bufType();
12936 else
12937 Type = Context.getjmp_bufType();
12938
12939 if (Type.isNull()) {
12941 return {};
12942 }
12943 break;
12944 case 'K':
12945 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
12946 Type = Context.getucontext_tType();
12947
12948 if (Type.isNull()) {
12950 return {};
12951 }
12952 break;
12953 case 'p':
12954 Type = Context.getProcessIDType();
12955 break;
12956 case 'm':
12957 Type = Context.MFloat8Ty;
12958 break;
12959 }
12960
12961 // If there are modifiers and if we're allowed to parse them, go for it.
12962 Done = !AllowTypeModifiers;
12963 while (!Done) {
12964 switch (char c = *Str++) {
12965 default: Done = true; --Str; break;
12966 case '*':
12967 case '&': {
12968 // Both pointers and references can have their pointee types
12969 // qualified with an address space.
12970 char *End;
12971 unsigned AddrSpace = strtoul(Str, &End, 10);
12972 if (End != Str) {
12973 // Note AddrSpace == 0 is not the same as an unspecified address space.
12974 Type = Context.getAddrSpaceQualType(
12975 Type,
12976 Context.getLangASForBuiltinAddressSpace(AddrSpace));
12977 Str = End;
12978 }
12979 if (c == '*')
12980 Type = Context.getPointerType(Type);
12981 else
12982 Type = Context.getLValueReferenceType(Type);
12983 break;
12984 }
12985 // FIXME: There's no way to have a built-in with an rvalue ref arg.
12986 case 'C':
12987 Type = Type.withConst();
12988 break;
12989 case 'D':
12990 Type = Context.getVolatileType(Type);
12991 break;
12992 case 'R':
12993 Type = Type.withRestrict();
12994 break;
12995 }
12996 }
12997
12998 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
12999 "Integer constant 'I' type must be an integer");
13000
13001 return Type;
13002}
13003
13004// On some targets such as PowerPC, some of the builtins are defined with custom
13005// type descriptors for target-dependent types. These descriptors are decoded in
13006// other functions, but it may be useful to be able to fall back to default
13007// descriptor decoding to define builtins mixing target-dependent and target-
13008// independent types. This function allows decoding one type descriptor with
13009// default decoding.
13010QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
13011 GetBuiltinTypeError &Error, bool &RequireICE,
13012 bool AllowTypeModifiers) const {
13013 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
13014}
13015
13016/// GetBuiltinType - Return the type for the specified builtin.
13019 unsigned *IntegerConstantArgs) const {
13020 const char *TypeStr = BuiltinInfo.getTypeString(Id);
13021 if (TypeStr[0] == '\0') {
13023 return {};
13024 }
13025
13026 SmallVector<QualType, 8> ArgTypes;
13027
13028 bool RequiresICE = false;
13029 Error = GE_None;
13030 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
13031 RequiresICE, true);
13032 if (Error != GE_None)
13033 return {};
13034
13035 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
13036
13037 while (TypeStr[0] && TypeStr[0] != '.') {
13038 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
13039 if (Error != GE_None)
13040 return {};
13041
13042 // If this argument is required to be an IntegerConstantExpression and the
13043 // caller cares, fill in the bitmask we return.
13044 if (RequiresICE && IntegerConstantArgs)
13045 *IntegerConstantArgs |= 1 << ArgTypes.size();
13046
13047 // Do array -> pointer decay. The builtin should use the decayed type.
13048 if (Ty->isArrayType())
13049 Ty = getArrayDecayedType(Ty);
13050
13051 ArgTypes.push_back(Ty);
13052 }
13053
13054 if (Id == Builtin::BI__GetExceptionInfo)
13055 return {};
13056
13057 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
13058 "'.' should only occur at end of builtin type list!");
13059
13060 bool Variadic = (TypeStr[0] == '.');
13061
13062 FunctionType::ExtInfo EI(Target->getDefaultCallingConv());
13063 if (BuiltinInfo.isNoReturn(Id))
13064 EI = EI.withNoReturn(true);
13065
13066 // We really shouldn't be making a no-proto type here.
13067 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
13068 return getFunctionNoProtoType(ResType, EI);
13069
13071 EPI.ExtInfo = EI;
13072 EPI.Variadic = Variadic;
13073 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
13074 EPI.ExceptionSpec.Type =
13076
13077 return getFunctionType(ResType, ArgTypes, EPI);
13078}
13079
13081 const FunctionDecl *FD) {
13082 if (!FD->isExternallyVisible())
13083 return GVA_Internal;
13084
13085 // Non-user-provided functions get emitted as weak definitions with every
13086 // use, no matter whether they've been explicitly instantiated etc.
13087 if (!FD->isUserProvided())
13088 return GVA_DiscardableODR;
13089
13091 switch (FD->getTemplateSpecializationKind()) {
13092 case TSK_Undeclared:
13095 break;
13096
13098 return GVA_StrongODR;
13099
13100 // C++11 [temp.explicit]p10:
13101 // [ Note: The intent is that an inline function that is the subject of
13102 // an explicit instantiation declaration will still be implicitly
13103 // instantiated when used so that the body can be considered for
13104 // inlining, but that no out-of-line copy of the inline function would be
13105 // generated in the translation unit. -- end note ]
13108
13111 break;
13112 }
13113
13114 if (!FD->isInlined())
13115 return External;
13116
13117 if ((!Context.getLangOpts().CPlusPlus &&
13118 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13119 !FD->hasAttr<DLLExportAttr>()) ||
13120 FD->hasAttr<GNUInlineAttr>()) {
13121 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
13122
13123 // GNU or C99 inline semantics. Determine whether this symbol should be
13124 // externally visible.
13125 if (auto *Def = FD->getDefinition();
13127 return External;
13128
13129 // C99 inline semantics, where the symbol is not externally visible.
13131 }
13132
13133 // Functions specified with extern and inline in -fms-compatibility mode
13134 // forcibly get emitted. While the body of the function cannot be later
13135 // replaced, the function definition cannot be discarded.
13136 if (FD->isMSExternInline())
13137 return GVA_StrongODR;
13138
13139 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13141 cast<CXXConstructorDecl>(FD)->isInheritingConstructor() &&
13142 !FD->hasAttr<DLLExportAttr>()) {
13143 // Both Clang and MSVC implement inherited constructors as forwarding
13144 // thunks that delegate to the base constructor. Keep non-dllexport
13145 // inheriting constructor thunks internal since they are not needed
13146 // outside the translation unit.
13147 //
13148 // dllexport inherited constructors are exempted so they are externally
13149 // visible, matching MSVC's export behavior. Inherited constructors
13150 // whose parameters prevent ABI-compatible forwarding (e.g. callee-
13151 // cleanup types) are excluded from export in Sema to avoid silent
13152 // runtime mismatches.
13153 return GVA_Internal;
13154 }
13155
13156 return GVA_DiscardableODR;
13157}
13158
13160 const Decl *D, GVALinkage L) {
13161 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
13162 // dllexport/dllimport on inline functions.
13163 if (D->hasAttr<DLLImportAttr>()) {
13164 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
13166 } else if (D->hasAttr<DLLExportAttr>()) {
13167 if (L == GVA_DiscardableODR)
13168 return GVA_StrongODR;
13169 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
13170 // Device-side functions with __global__ attribute must always be
13171 // visible externally so they can be launched from host.
13172 if (D->hasAttr<CUDAGlobalAttr>() &&
13173 (L == GVA_DiscardableODR || L == GVA_Internal))
13174 return GVA_StrongODR;
13175 // Single source offloading languages like CUDA/HIP need to be able to
13176 // access static device variables from host code of the same compilation
13177 // unit. This is done by externalizing the static variable with a shared
13178 // name between the host and device compilation which is the same for the
13179 // same compilation unit whereas different among different compilation
13180 // units.
13181 if (Context.shouldExternalize(D))
13182 return GVA_StrongExternal;
13183 }
13184 return L;
13185}
13186
13187/// Adjust the GVALinkage for a declaration based on what an external AST source
13188/// knows about whether there can be other definitions of this declaration.
13189static GVALinkage
13191 GVALinkage L) {
13192 ExternalASTSource *Source = Ctx.getExternalSource();
13193 if (!Source)
13194 return L;
13195
13196 switch (Source->hasExternalDefinitions(D)) {
13198 // Other translation units rely on us to provide the definition.
13199 if (L == GVA_DiscardableODR)
13200 return GVA_StrongODR;
13201 break;
13202
13205
13207 break;
13208 }
13209 return L;
13210}
13211
13217
13219 const VarDecl *VD) {
13220 // As an extension for interactive REPLs, make sure constant variables are
13221 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
13222 // marking them as internal.
13223 if (Context.getLangOpts().CPlusPlus &&
13224 Context.getLangOpts().IncrementalExtensions &&
13225 VD->getType().isConstQualified() &&
13226 !VD->getType().isVolatileQualified() && !VD->isInline() &&
13228 return GVA_DiscardableODR;
13229
13230 if (!VD->isExternallyVisible())
13231 return GVA_Internal;
13232
13233 if (VD->isStaticLocal()) {
13234 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
13235 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
13236 LexicalContext = LexicalContext->getLexicalParent();
13237
13238 // ObjC Blocks can create local variables that don't have a FunctionDecl
13239 // LexicalContext.
13240 if (!LexicalContext)
13241 return GVA_DiscardableODR;
13242
13243 // Otherwise, let the static local variable inherit its linkage from the
13244 // nearest enclosing function.
13245 auto StaticLocalLinkage =
13246 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
13247
13248 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
13249 // be emitted in any object with references to the symbol for the object it
13250 // contains, whether inline or out-of-line."
13251 // Similar behavior is observed with MSVC. An alternative ABI could use
13252 // StrongODR/AvailableExternally to match the function, but none are
13253 // known/supported currently.
13254 if (StaticLocalLinkage == GVA_StrongODR ||
13255 StaticLocalLinkage == GVA_AvailableExternally)
13256 return GVA_DiscardableODR;
13257 return StaticLocalLinkage;
13258 }
13259
13260 // MSVC treats in-class initialized static data members as definitions.
13261 // By giving them non-strong linkage, out-of-line definitions won't
13262 // cause link errors.
13263 if (Context.isMSStaticDataMemberInlineDefinition(VD))
13264 return GVA_DiscardableODR;
13265
13266 // Most non-template variables have strong linkage; inline variables are
13267 // linkonce_odr or (occasionally, for compatibility) weak_odr.
13268 GVALinkage StrongLinkage;
13269 switch (Context.getInlineVariableDefinitionKind(VD)) {
13271 StrongLinkage = GVA_StrongExternal;
13272 break;
13275 StrongLinkage = GVA_DiscardableODR;
13276 break;
13278 StrongLinkage = GVA_StrongODR;
13279 break;
13280 }
13281
13282 switch (VD->getTemplateSpecializationKind()) {
13283 case TSK_Undeclared:
13284 return StrongLinkage;
13285
13287 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13288 VD->isStaticDataMember()
13290 : StrongLinkage;
13291
13293 return GVA_StrongODR;
13294
13297
13299 return GVA_DiscardableODR;
13300 }
13301
13302 llvm_unreachable("Invalid Linkage!");
13303}
13304
13310
13312 if (const auto *VD = dyn_cast<VarDecl>(D)) {
13313 if (!VD->isFileVarDecl())
13314 return false;
13315 // Global named register variables (GNU extension) are never emitted.
13316 if (VD->getStorageClass() == SC_Register)
13317 return false;
13318 if (VD->getDescribedVarTemplate() ||
13320 return false;
13321 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13322 // We never need to emit an uninstantiated function template.
13323 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13324 return false;
13325 } else if (isa<PragmaCommentDecl>(D))
13326 return true;
13328 return true;
13329 else if (isa<OMPRequiresDecl>(D))
13330 return true;
13331 else if (isa<OMPThreadPrivateDecl>(D))
13332 return !D->getDeclContext()->isDependentContext();
13333 else if (isa<OMPAllocateDecl>(D))
13334 return !D->getDeclContext()->isDependentContext();
13336 return !D->getDeclContext()->isDependentContext();
13337 else if (isa<ImportDecl>(D))
13338 return true;
13339 else
13340 return false;
13341
13342 // If this is a member of a class template, we do not need to emit it.
13344 return false;
13345
13346 // Weak references don't produce any output by themselves.
13347 if (D->hasAttr<WeakRefAttr>())
13348 return false;
13349
13350 // SYCL device compilation requires that functions defined with the
13351 // sycl_kernel_entry_point or sycl_external attributes be emitted. All
13352 // other entities are emitted only if they are used by a function
13353 // defined with one of those attributes.
13354 if (LangOpts.SYCLIsDevice)
13355 return isa<FunctionDecl>(D) && (D->hasAttr<SYCLKernelEntryPointAttr>() ||
13356 D->hasAttr<SYCLExternalAttr>());
13357
13358 // Aliases and used decls are required.
13359 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
13360 return true;
13361
13362 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13363 // Forward declarations aren't required.
13364 if (!FD->doesThisDeclarationHaveABody())
13365 return FD->doesDeclarationForceExternallyVisibleDefinition();
13366
13367 // Constructors and destructors are required.
13368 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
13369 return true;
13370
13371 // The key function for a class is required. This rule only comes
13372 // into play when inline functions can be key functions, though.
13373 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13374 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13375 const CXXRecordDecl *RD = MD->getParent();
13376 if (MD->isOutOfLine() && RD->isDynamicClass()) {
13377 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
13378 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
13379 return true;
13380 }
13381 }
13382 }
13383
13385
13386 // static, static inline, always_inline, and extern inline functions can
13387 // always be deferred. Normal inline functions can be deferred in C99/C++.
13388 // Implicit template instantiations can also be deferred in C++.
13390 }
13391
13392 const auto *VD = cast<VarDecl>(D);
13393 assert(VD->isFileVarDecl() && "Expected file scoped var");
13394
13395 // If the decl is marked as `declare target to`, it should be emitted for the
13396 // host and for the device.
13397 if (LangOpts.OpenMP &&
13398 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
13399 return true;
13400
13401 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
13403 return false;
13404
13405 if (VD->shouldEmitInExternalSource())
13406 return false;
13407
13408 // Variables that can be needed in other TUs are required.
13411 return true;
13412
13413 // We never need to emit a variable that is available in another TU.
13415 return false;
13416
13417 // Variables that have destruction with side-effects are required.
13418 if (VD->needsDestruction(*this))
13419 return true;
13420
13421 // Variables that have initialization with side-effects are required.
13422 if (VD->hasInitWithSideEffects())
13423 return true;
13424
13425 // Likewise, variables with tuple-like bindings are required if their
13426 // bindings have side-effects.
13427 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) {
13428 for (const auto *BD : DD->flat_bindings())
13429 if (const auto *BindingVD = BD->getHoldingVar())
13430 if (DeclMustBeEmitted(BindingVD))
13431 return true;
13432 }
13433
13434 return false;
13435}
13436
13438 const FunctionDecl *FD,
13439 llvm::function_ref<void(FunctionDecl *)> Pred) const {
13440 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
13441 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
13442 FD = FD->getMostRecentDecl();
13443 // FIXME: The order of traversal here matters and depends on the order of
13444 // lookup results, which happens to be (mostly) oldest-to-newest, but we
13445 // shouldn't rely on that.
13446 for (auto *CurDecl :
13448 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
13449 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
13450 SeenDecls.insert(CurFD).second) {
13451 Pred(CurFD);
13452 }
13453 }
13454}
13455
13457 bool IsCXXMethod) const {
13458 // Pass through to the C++ ABI object
13459 if (IsCXXMethod)
13460 return ABI->getDefaultMethodCallConv(IsVariadic);
13461
13462 switch (LangOpts.getDefaultCallingConv()) {
13464 break;
13466 return CC_C;
13468 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
13469 return CC_X86FastCall;
13470 break;
13472 if (!IsVariadic)
13473 return CC_X86StdCall;
13474 break;
13476 // __vectorcall cannot be applied to variadic functions.
13477 if (!IsVariadic)
13478 return CC_X86VectorCall;
13479 break;
13481 // __regcall cannot be applied to variadic functions.
13482 if (!IsVariadic)
13483 return CC_X86RegCall;
13484 break;
13486 if (!IsVariadic)
13487 return CC_M68kRTD;
13488 break;
13489 }
13490 return Target->getDefaultCallingConv();
13491}
13492
13494 // Pass through to the C++ ABI object
13495 return ABI->isNearlyEmpty(RD);
13496}
13497
13499 if (!VTContext) {
13500 auto ABI = Target->getCXXABI();
13501 if (ABI.isMicrosoft())
13502 VTContext.reset(new MicrosoftVTableContext(*this));
13503 else {
13504 VTContext.reset(new ItaniumVTableContext(*this));
13505 }
13506 }
13507 return VTContext.get();
13508}
13509
13511 if (!T)
13512 T = Target;
13513 switch (T->getCXXABI().getKind()) {
13514 case TargetCXXABI::AppleARM64:
13515 case TargetCXXABI::Fuchsia:
13516 case TargetCXXABI::GenericAArch64:
13517 case TargetCXXABI::GenericItanium:
13518 case TargetCXXABI::GenericARM:
13519 case TargetCXXABI::GenericMIPS:
13520 case TargetCXXABI::iOS:
13521 case TargetCXXABI::WebAssembly:
13522 case TargetCXXABI::WatchOS:
13523 case TargetCXXABI::XL:
13525 case TargetCXXABI::Microsoft:
13527 }
13528 llvm_unreachable("Unsupported ABI");
13529}
13530
13532 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
13533 "Device mangle context does not support Microsoft mangling.");
13534 switch (T.getCXXABI().getKind()) {
13535 case TargetCXXABI::AppleARM64:
13536 case TargetCXXABI::Fuchsia:
13537 case TargetCXXABI::GenericAArch64:
13538 case TargetCXXABI::GenericItanium:
13539 case TargetCXXABI::GenericARM:
13540 case TargetCXXABI::GenericMIPS:
13541 case TargetCXXABI::iOS:
13542 case TargetCXXABI::WebAssembly:
13543 case TargetCXXABI::WatchOS:
13544 case TargetCXXABI::XL:
13546 *this, getDiagnostics(),
13547 [](ASTContext &, const NamedDecl *ND) -> UnsignedOrNone {
13548 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
13549 return RD->getDeviceLambdaManglingNumber();
13550 return std::nullopt;
13551 },
13552 /*IsAux=*/true);
13553 case TargetCXXABI::Microsoft:
13555 /*IsAux=*/true);
13556 }
13557 llvm_unreachable("Unsupported ABI");
13558}
13559
13561 // If the host and device have different C++ ABIs, mark it as the device
13562 // mangle context so that the mangling needs to retrieve the additional
13563 // device lambda mangling number instead of the regular host one.
13564 if (getAuxTargetInfo() && getTargetInfo().getCXXABI().isMicrosoft() &&
13565 getAuxTargetInfo()->getCXXABI().isItaniumFamily()) {
13567 }
13568
13570}
13571
13572CXXABI::~CXXABI() = default;
13573
13575 return ASTRecordLayouts.getMemorySize() +
13576 llvm::capacity_in_bytes(ObjCLayouts) +
13577 llvm::capacity_in_bytes(KeyFunctions) +
13578 llvm::capacity_in_bytes(ObjCImpls) +
13579 llvm::capacity_in_bytes(BlockVarCopyInits) +
13580 llvm::capacity_in_bytes(DeclAttrs) +
13581 llvm::capacity_in_bytes(TemplateOrInstantiation) +
13582 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
13583 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
13584 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
13585 llvm::capacity_in_bytes(OverriddenMethods) +
13586 llvm::capacity_in_bytes(Types) +
13587 llvm::capacity_in_bytes(VariableArrayTypes);
13588}
13589
13590/// getIntTypeForBitwidth -
13591/// sets integer QualTy according to specified details:
13592/// bitwidth, signed/unsigned.
13593/// Returns empty type if there is no appropriate target types.
13595 unsigned Signed) const {
13597 CanQualType QualTy = getFromTargetType(Ty);
13598 if (!QualTy && DestWidth == 128)
13599 return Signed ? Int128Ty : UnsignedInt128Ty;
13600 return QualTy;
13601}
13602
13604 unsigned Signed) const {
13605 return getFromTargetType(
13606 getTargetInfo().getLeastIntTypeByWidth(DestWidth, Signed));
13607}
13608
13609/// getRealTypeForBitwidth -
13610/// sets floating point QualTy according to specified bitwidth.
13611/// Returns empty type if there is no appropriate target types.
13613 FloatModeKind ExplicitType) const {
13614 FloatModeKind Ty =
13615 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
13616 switch (Ty) {
13618 return HalfTy;
13620 return FloatTy;
13622 return DoubleTy;
13624 return LongDoubleTy;
13626 return Float128Ty;
13628 return Ibm128Ty;
13630 return {};
13631 }
13632
13633 llvm_unreachable("Unhandled TargetInfo::RealType value");
13634}
13635
13636void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
13637 if (Number <= 1)
13638 return;
13639
13640 MangleNumbers[ND] = Number;
13641
13642 if (Listener)
13643 Listener->AddedManglingNumber(ND, Number);
13644}
13645
13647 bool ForAuxTarget) const {
13648 auto I = MangleNumbers.find(ND);
13649 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
13650 // CUDA/HIP host compilation encodes host and device mangling numbers
13651 // as lower and upper half of 32 bit integer.
13652 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
13653 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
13654 } else {
13655 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
13656 "number for aux target");
13657 }
13658 return Res > 1 ? Res : 1;
13659}
13660
13661void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
13662 if (Number <= 1)
13663 return;
13664
13665 StaticLocalNumbers[VD] = Number;
13666
13667 if (Listener)
13668 Listener->AddedStaticLocalNumbers(VD, Number);
13669}
13670
13672 auto I = StaticLocalNumbers.find(VD);
13673 return I != StaticLocalNumbers.end() ? I->second : 1;
13674}
13675
13677 bool IsDestroying) {
13678 if (!IsDestroying) {
13679 assert(!DestroyingOperatorDeletes.contains(FD->getCanonicalDecl()));
13680 return;
13681 }
13682 DestroyingOperatorDeletes.insert(FD->getCanonicalDecl());
13683}
13684
13686 return DestroyingOperatorDeletes.contains(FD->getCanonicalDecl());
13687}
13688
13690 bool IsTypeAware) {
13691 if (!IsTypeAware) {
13692 assert(!TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl()));
13693 return;
13694 }
13695 TypeAwareOperatorNewAndDeletes.insert(FD->getCanonicalDecl());
13696}
13697
13699 return TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl());
13700}
13701
13703 FunctionDecl *OperatorDelete,
13704 OperatorDeleteKind K) const {
13705 switch (K) {
13707 OperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] = OperatorDelete;
13708 break;
13710 GlobalOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13711 OperatorDelete;
13712 break;
13714 ArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13715 OperatorDelete;
13716 break;
13718 GlobalArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13719 OperatorDelete;
13720 break;
13721 }
13722}
13723
13725 OperatorDeleteKind K) const {
13726 switch (K) {
13728 return OperatorDeletesForVirtualDtor.contains(Dtor->getCanonicalDecl());
13730 return GlobalOperatorDeletesForVirtualDtor.contains(
13731 Dtor->getCanonicalDecl());
13733 return ArrayOperatorDeletesForVirtualDtor.contains(
13734 Dtor->getCanonicalDecl());
13736 return GlobalArrayOperatorDeletesForVirtualDtor.contains(
13737 Dtor->getCanonicalDecl());
13738 }
13739 return false;
13740}
13741
13744 OperatorDeleteKind K) const {
13745 const CXXDestructorDecl *Canon = Dtor->getCanonicalDecl();
13746 switch (K) {
13748 if (OperatorDeletesForVirtualDtor.contains(Canon))
13749 return OperatorDeletesForVirtualDtor[Canon];
13750 return nullptr;
13752 if (GlobalOperatorDeletesForVirtualDtor.contains(Canon))
13753 return GlobalOperatorDeletesForVirtualDtor[Canon];
13754 return nullptr;
13756 if (ArrayOperatorDeletesForVirtualDtor.contains(Canon))
13757 return ArrayOperatorDeletesForVirtualDtor[Canon];
13758 return nullptr;
13760 if (GlobalArrayOperatorDeletesForVirtualDtor.contains(Canon))
13761 return GlobalArrayOperatorDeletesForVirtualDtor[Canon];
13762 return nullptr;
13763 }
13764 return nullptr;
13765}
13766
13768 const CXXRecordDecl *RD) {
13769 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13770 return false;
13771
13772 return MaybeRequireVectorDeletingDtor.count(RD);
13773}
13774
13776 const CXXRecordDecl *RD) {
13777 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13778 return;
13779
13780 MaybeRequireVectorDeletingDtor.insert(RD);
13781}
13782
13785 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13786 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
13787 if (!MCtx)
13789 return *MCtx;
13790}
13791
13794 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13795 std::unique_ptr<MangleNumberingContext> &MCtx =
13796 ExtraMangleNumberingContexts[D];
13797 if (!MCtx)
13799 return *MCtx;
13800}
13801
13802std::unique_ptr<MangleNumberingContext>
13804 return ABI->createMangleNumberingContext();
13805}
13806
13807const CXXConstructorDecl *
13809 return ABI->getCopyConstructorForExceptionObject(
13811}
13812
13814 CXXConstructorDecl *CD) {
13815 return ABI->addCopyConstructorForExceptionObject(
13818}
13819
13821 TypedefNameDecl *DD) {
13822 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
13823}
13824
13827 return ABI->getTypedefNameForUnnamedTagDecl(TD);
13828}
13829
13831 DeclaratorDecl *DD) {
13832 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
13833}
13834
13836 return ABI->getDeclaratorForUnnamedTagDecl(TD);
13837}
13838
13840 ParamIndices[D] = index;
13841}
13842
13844 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
13845 assert(I != ParamIndices.end() &&
13846 "ParmIndices lacks entry set by ParmVarDecl");
13847 return I->second;
13848}
13849
13851 unsigned Length) const {
13852 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
13853 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
13854 EltTy = EltTy.withConst();
13855
13856 EltTy = adjustStringLiteralBaseType(EltTy);
13857
13858 // Get an array type for the string, according to C99 6.4.5. This includes
13859 // the null terminator character.
13860 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
13861 ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
13862}
13863
13866 StringLiteral *&Result = StringLiteralCache[Key];
13867 if (!Result)
13869 *this, Key, StringLiteralKind::Ordinary,
13870 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
13871 SourceLocation());
13872 return Result;
13873}
13874
13875MSGuidDecl *
13877 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
13878
13879 llvm::FoldingSetNodeID ID;
13880 MSGuidDecl::Profile(ID, Parts);
13881
13882 void *InsertPos;
13883 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
13884 return Existing;
13885
13886 QualType GUIDType = getMSGuidType().withConst();
13887 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
13888 MSGuidDecls.InsertNode(New, InsertPos);
13889 return New;
13890}
13891
13894 const APValue &APVal) const {
13895 llvm::FoldingSetNodeID ID;
13897
13898 void *InsertPos;
13899 if (UnnamedGlobalConstantDecl *Existing =
13900 UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos))
13901 return Existing;
13902
13904 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
13905 UnnamedGlobalConstantDecls.InsertNode(New, InsertPos);
13906 return New;
13907}
13908
13911 assert(T->isRecordType() && "template param object of unexpected type");
13912
13913 // C++ [temp.param]p8:
13914 // [...] a static storage duration object of type 'const T' [...]
13915 T.addConst();
13916
13917 llvm::FoldingSetNodeID ID;
13919
13920 void *InsertPos;
13921 if (TemplateParamObjectDecl *Existing =
13922 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
13923 return Existing;
13924
13925 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
13926 TemplateParamObjectDecls.InsertNode(New, InsertPos);
13927 return New;
13928}
13929
13931 const llvm::Triple &T = getTargetInfo().getTriple();
13932 if (!T.isOSDarwin())
13933 return false;
13934
13935 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
13936 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
13937 return false;
13938
13939 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
13940 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
13941 uint64_t Size = sizeChars.getQuantity();
13942 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
13943 unsigned Align = alignChars.getQuantity();
13944 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
13945 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
13946}
13947
13948bool
13950 const ObjCMethodDecl *MethodImpl) {
13951 // No point trying to match an unavailable/deprecated mothod.
13952 if (MethodDecl->hasAttr<UnavailableAttr>()
13953 || MethodDecl->hasAttr<DeprecatedAttr>())
13954 return false;
13955 if (MethodDecl->getObjCDeclQualifier() !=
13956 MethodImpl->getObjCDeclQualifier())
13957 return false;
13958 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
13959 return false;
13960
13961 if (MethodDecl->param_size() != MethodImpl->param_size())
13962 return false;
13963
13964 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
13965 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
13966 EF = MethodDecl->param_end();
13967 IM != EM && IF != EF; ++IM, ++IF) {
13968 const ParmVarDecl *DeclVar = (*IF);
13969 const ParmVarDecl *ImplVar = (*IM);
13970 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
13971 return false;
13972 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
13973 return false;
13974 }
13975
13976 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
13977}
13978
13980 LangAS AS;
13982 AS = LangAS::Default;
13983 else
13984 AS = QT->getPointeeType().getAddressSpace();
13985
13987}
13988
13991}
13992
13993bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
13994 if (X == Y)
13995 return true;
13996 if (!X || !Y)
13997 return false;
13998 llvm::FoldingSetNodeID IDX, IDY;
13999 X->Profile(IDX, *this, /*Canonical=*/true);
14000 Y->Profile(IDY, *this, /*Canonical=*/true);
14001 return IDX == IDY;
14002}
14003
14004// The getCommon* helpers return, for given 'same' X and Y entities given as
14005// inputs, another entity which is also the 'same' as the inputs, but which
14006// is closer to the canonical form of the inputs, each according to a given
14007// criteria.
14008// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
14009// the regular ones.
14010
14012 if (!declaresSameEntity(X, Y))
14013 return nullptr;
14014 for (const Decl *DX : X->redecls()) {
14015 // If we reach Y before reaching the first decl, that means X is older.
14016 if (DX == Y)
14017 return X;
14018 // If we reach the first decl, then Y is older.
14019 if (DX->isFirstDecl())
14020 return Y;
14021 }
14022 llvm_unreachable("Corrupt redecls chain");
14023}
14024
14025template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
14026static T *getCommonDecl(T *X, T *Y) {
14027 return cast_or_null<T>(
14028 getCommonDecl(const_cast<Decl *>(cast_or_null<Decl>(X)),
14029 const_cast<Decl *>(cast_or_null<Decl>(Y))));
14030}
14031
14032template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
14033static T *getCommonDeclChecked(T *X, T *Y) {
14034 return cast<T>(getCommonDecl(const_cast<Decl *>(cast<Decl>(X)),
14035 const_cast<Decl *>(cast<Decl>(Y))));
14036}
14037
14039 TemplateName Y,
14040 bool IgnoreDeduced = false) {
14041 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
14042 return X;
14043 // FIXME: There are cases here where we could find a common template name
14044 // with more sugar. For example one could be a SubstTemplateTemplate*
14045 // replacing the other.
14046 TemplateName CX = Ctx.getCanonicalTemplateName(X, IgnoreDeduced);
14047 if (CX.getAsVoidPointer() !=
14049 return TemplateName();
14050 return CX;
14051}
14052
14055 bool IgnoreDeduced) {
14056 TemplateName R = getCommonTemplateName(Ctx, X, Y, IgnoreDeduced);
14057 assert(R.getAsVoidPointer() != nullptr);
14058 return R;
14059}
14060
14062 ArrayRef<QualType> Ys, bool Unqualified = false) {
14063 assert(Xs.size() == Ys.size());
14064 SmallVector<QualType, 8> Rs(Xs.size());
14065 for (size_t I = 0; I < Rs.size(); ++I)
14066 Rs[I] = Ctx.getCommonSugaredType(Xs[I], Ys[I], Unqualified);
14067 return Rs;
14068}
14069
14070template <class T>
14071static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
14072 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
14073 : SourceLocation();
14074}
14075
14077 const TemplateArgument &X,
14078 const TemplateArgument &Y) {
14079 if (X.getKind() != Y.getKind())
14080 return TemplateArgument();
14081
14082 switch (X.getKind()) {
14084 if (!Ctx.hasSameType(X.getAsType(), Y.getAsType()))
14085 return TemplateArgument();
14086 return TemplateArgument(
14087 Ctx.getCommonSugaredType(X.getAsType(), Y.getAsType()));
14089 if (!Ctx.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
14090 return TemplateArgument();
14091 return TemplateArgument(
14092 Ctx.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
14093 /*Unqualified=*/true);
14095 if (!Ctx.hasSameType(X.getAsExpr()->getType(), Y.getAsExpr()->getType()))
14096 return TemplateArgument();
14097 // FIXME: Try to keep the common sugar.
14098 return X;
14100 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
14101 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
14102 if (!CTN.getAsVoidPointer())
14103 return TemplateArgument();
14104 return TemplateArgument(CTN);
14105 }
14107 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
14109 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
14110 if (!CTN.getAsVoidPointer())
14111 return TemplateName();
14112 auto NExpX = X.getNumTemplateExpansions();
14113 assert(NExpX == Y.getNumTemplateExpansions());
14114 return TemplateArgument(CTN, NExpX);
14115 }
14116 default:
14117 // FIXME: Handle the other argument kinds.
14118 return X;
14119 }
14120}
14121
14126 if (Xs.size() != Ys.size())
14127 return true;
14128 R.resize(Xs.size());
14129 for (size_t I = 0; I < R.size(); ++I) {
14130 R[I] = getCommonTemplateArgument(Ctx, Xs[I], Ys[I]);
14131 if (R[I].isNull())
14132 return true;
14133 }
14134 return false;
14135}
14136
14141 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
14142 assert(!Different);
14143 (void)Different;
14144 return R;
14145}
14146
14147template <class T>
14149 bool IsSame) {
14150 ElaboratedTypeKeyword KX = X->getKeyword(), KY = Y->getKeyword();
14151 if (KX == KY)
14152 return KX;
14154 assert(!IsSame || KX == getCanonicalElaboratedTypeKeyword(KY));
14155 return KX;
14156}
14157
14158/// Returns a NestedNameSpecifier which has only the common sugar
14159/// present in both NNS1 and NNS2.
14162 NestedNameSpecifier NNS2, bool IsSame) {
14163 // If they are identical, all sugar is common.
14164 if (NNS1 == NNS2)
14165 return NNS1;
14166
14167 // IsSame implies both Qualifiers are equivalent.
14168 NestedNameSpecifier Canon = NNS1.getCanonical();
14169 if (Canon != NNS2.getCanonical()) {
14170 assert(!IsSame && "Should be the same NestedNameSpecifier");
14171 // If they are not the same, there is nothing to unify.
14172 return std::nullopt;
14173 }
14174
14175 NestedNameSpecifier R = std::nullopt;
14176 NestedNameSpecifier::Kind Kind = NNS1.getKind();
14177 assert(Kind == NNS2.getKind());
14178 switch (Kind) {
14180 auto [Namespace1, Prefix1] = NNS1.getAsNamespaceAndPrefix();
14181 auto [Namespace2, Prefix2] = NNS2.getAsNamespaceAndPrefix();
14182 auto Kind = Namespace1->getKind();
14183 if (Kind != Namespace2->getKind() ||
14184 (Kind == Decl::NamespaceAlias &&
14185 !declaresSameEntity(Namespace1, Namespace2))) {
14187 Ctx,
14188 ::getCommonDeclChecked(Namespace1->getNamespace(),
14189 Namespace2->getNamespace()),
14190 /*Prefix=*/std::nullopt);
14191 break;
14192 }
14193 // The prefixes for namespaces are not significant, its declaration
14194 // identifies it uniquely.
14195 NestedNameSpecifier Prefix = ::getCommonNNS(Ctx, Prefix1, Prefix2,
14196 /*IsSame=*/false);
14197 R = NestedNameSpecifier(Ctx, ::getCommonDeclChecked(Namespace1, Namespace2),
14198 Prefix);
14199 break;
14200 }
14202 const Type *T1 = NNS1.getAsType(), *T2 = NNS2.getAsType();
14203 const Type *T = Ctx.getCommonSugaredType(QualType(T1, 0), QualType(T2, 0),
14204 /*Unqualified=*/true)
14205 .getTypePtr();
14206 R = NestedNameSpecifier(T);
14207 break;
14208 }
14210 // FIXME: Can __super even be used with data members?
14211 // If it's only usable in functions, we will never see it here,
14212 // unless we save the qualifiers used in function types.
14213 // In that case, it might be possible NNS2 is a type,
14214 // in which case we should degrade the result to
14215 // a CXXRecordType.
14217 NNS2.getAsMicrosoftSuper()));
14218 break;
14219 }
14222 // These are singletons.
14223 llvm_unreachable("singletons did not compare equal");
14224 }
14225 assert(R.getCanonical() == Canon);
14226 return R;
14227}
14228
14229template <class T>
14231 const T *Y, bool IsSame) {
14232 return ::getCommonNNS(Ctx, X->getQualifier(), Y->getQualifier(), IsSame);
14233}
14234
14235template <class T>
14236static QualType getCommonElementType(const ASTContext &Ctx, const T *X,
14237 const T *Y) {
14238 return Ctx.getCommonSugaredType(X->getElementType(), Y->getElementType());
14239}
14240
14242 QualType X, QualType Y,
14243 Qualifiers &QX,
14244 Qualifiers &QY) {
14245 QualType R = Ctx.getCommonSugaredType(X, Y,
14246 /*Unqualified=*/true);
14247 // Qualifiers common to both element types.
14248 Qualifiers RQ = R.getQualifiers();
14249 // For each side, move to the top level any qualifiers which are not common to
14250 // both element types. The caller must assume top level qualifiers might
14251 // be different, even if they are the same type, and can be treated as sugar.
14252 QX += X.getQualifiers() - RQ;
14253 QY += Y.getQualifiers() - RQ;
14254 return R;
14255}
14256
14257template <class T>
14259 Qualifiers &QX, const T *Y,
14260 Qualifiers &QY) {
14261 return getCommonTypeWithQualifierLifting(Ctx, X->getElementType(),
14262 Y->getElementType(), QX, QY);
14263}
14264
14265template <class T>
14266static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X,
14267 const T *Y) {
14268 return Ctx.getCommonSugaredType(X->getPointeeType(), Y->getPointeeType());
14269}
14270
14271template <class T>
14272static auto *getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y) {
14273 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
14274 return X->getSizeExpr();
14275}
14276
14277static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
14278 assert(X->getSizeModifier() == Y->getSizeModifier());
14279 return X->getSizeModifier();
14280}
14281
14283 const ArrayType *Y) {
14284 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
14285 return X->getIndexTypeCVRQualifiers();
14286}
14287
14288// Merges two type lists such that the resulting vector will contain
14289// each type (in a canonical sense) only once, in the order they appear
14290// from X to Y. If they occur in both X and Y, the result will contain
14291// the common sugared type between them.
14292static void mergeTypeLists(const ASTContext &Ctx,
14295 llvm::DenseMap<QualType, unsigned> Found;
14296 for (auto Ts : {X, Y}) {
14297 for (QualType T : Ts) {
14298 auto Res = Found.try_emplace(Ctx.getCanonicalType(T), Out.size());
14299 if (!Res.second) {
14300 QualType &U = Out[Res.first->second];
14301 U = Ctx.getCommonSugaredType(U, T);
14302 } else {
14303 Out.emplace_back(T);
14304 }
14305 }
14306 }
14307}
14308
14309FunctionProtoType::ExceptionSpecInfo
14312 SmallVectorImpl<QualType> &ExceptionTypeStorage,
14313 bool AcceptDependent) const {
14314 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
14315
14316 // If either of them can throw anything, that is the result.
14317 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
14318 if (EST1 == I)
14319 return ESI1;
14320 if (EST2 == I)
14321 return ESI2;
14322 }
14323
14324 // If either of them is non-throwing, the result is the other.
14325 for (auto I :
14327 if (EST1 == I)
14328 return ESI2;
14329 if (EST2 == I)
14330 return ESI1;
14331 }
14332
14333 // If we're left with value-dependent computed noexcept expressions, we're
14334 // stuck. Before C++17, we can just drop the exception specification entirely,
14335 // since it's not actually part of the canonical type. And this should never
14336 // happen in C++17, because it would mean we were computing the composite
14337 // pointer type of dependent types, which should never happen.
14338 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
14339 assert(AcceptDependent &&
14340 "computing composite pointer type of dependent types");
14342 }
14343
14344 // Switch over the possibilities so that people adding new values know to
14345 // update this function.
14346 switch (EST1) {
14347 case EST_None:
14348 case EST_DynamicNone:
14349 case EST_MSAny:
14350 case EST_BasicNoexcept:
14352 case EST_NoexceptFalse:
14353 case EST_NoexceptTrue:
14354 case EST_NoThrow:
14355 llvm_unreachable("These ESTs should be handled above");
14356
14357 case EST_Dynamic: {
14358 // This is the fun case: both exception specifications are dynamic. Form
14359 // the union of the two lists.
14360 assert(EST2 == EST_Dynamic && "other cases should already be handled");
14361 mergeTypeLists(*this, ExceptionTypeStorage, ESI1.Exceptions,
14362 ESI2.Exceptions);
14364 Result.Exceptions = ExceptionTypeStorage;
14365 return Result;
14366 }
14367
14368 case EST_Unevaluated:
14369 case EST_Uninstantiated:
14370 case EST_Unparsed:
14371 llvm_unreachable("shouldn't see unresolved exception specifications here");
14372 }
14373
14374 llvm_unreachable("invalid ExceptionSpecificationType");
14375}
14376
14378 Qualifiers &QX, const Type *Y,
14379 Qualifiers &QY) {
14380 Type::TypeClass TC = X->getTypeClass();
14381 assert(TC == Y->getTypeClass());
14382 switch (TC) {
14383#define UNEXPECTED_TYPE(Class, Kind) \
14384 case Type::Class: \
14385 llvm_unreachable("Unexpected " Kind ": " #Class);
14386
14387#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
14388#define TYPE(Class, Base)
14389#include "clang/AST/TypeNodes.inc"
14390
14391#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
14393 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
14394 SUGAR_FREE_TYPE(DependentBitInt)
14396 SUGAR_FREE_TYPE(ObjCInterface)
14397 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
14398 SUGAR_FREE_TYPE(SubstBuiltinTemplatePack)
14399 SUGAR_FREE_TYPE(UnresolvedUsing)
14400 SUGAR_FREE_TYPE(HLSLAttributedResource)
14401 SUGAR_FREE_TYPE(HLSLInlineSpirv)
14402#undef SUGAR_FREE_TYPE
14403#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
14404 NON_UNIQUE_TYPE(TypeOfExpr)
14405 NON_UNIQUE_TYPE(VariableArray)
14406#undef NON_UNIQUE_TYPE
14407
14408 UNEXPECTED_TYPE(TypeOf, "sugar")
14409
14410#undef UNEXPECTED_TYPE
14411
14412 case Type::Auto: {
14413 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14414 assert(AX->getDeducedKind() == AY->getDeducedKind());
14415 assert(AX->getDeducedKind() != DeducedKind::Deduced);
14416 assert(AX->getKeyword() == AY->getKeyword());
14417 TemplateDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(),
14418 AY->getTypeConstraintConcept());
14420 if (CD &&
14421 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
14422 AY->getTypeConstraintArguments())) {
14423 CD = nullptr; // The arguments differ, so make it unconstrained.
14424 As.clear();
14425 }
14426 return Ctx.getAutoType(AX->getDeducedKind(), QualType(), AX->getKeyword(),
14427 CD, As);
14428 }
14429 case Type::IncompleteArray: {
14430 const auto *AX = cast<IncompleteArrayType>(X),
14432 return Ctx.getIncompleteArrayType(
14433 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14435 }
14436 case Type::DependentSizedArray: {
14437 const auto *AX = cast<DependentSizedArrayType>(X),
14439 return Ctx.getDependentSizedArrayType(
14440 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14441 getCommonSizeExpr(Ctx, AX, AY), getCommonSizeModifier(AX, AY),
14443 }
14444 case Type::ConstantArray: {
14445 const auto *AX = cast<ConstantArrayType>(X),
14446 *AY = cast<ConstantArrayType>(Y);
14447 assert(AX->getSize() == AY->getSize());
14448 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14449 ? AX->getSizeExpr()
14450 : nullptr;
14451 return Ctx.getConstantArrayType(
14452 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14454 }
14455 case Type::ArrayParameter: {
14456 const auto *AX = cast<ArrayParameterType>(X),
14457 *AY = cast<ArrayParameterType>(Y);
14458 assert(AX->getSize() == AY->getSize());
14459 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14460 ? AX->getSizeExpr()
14461 : nullptr;
14462 auto ArrayTy = Ctx.getConstantArrayType(
14463 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14465 return Ctx.getArrayParameterType(ArrayTy);
14466 }
14467 case Type::Atomic: {
14468 const auto *AX = cast<AtomicType>(X), *AY = cast<AtomicType>(Y);
14469 return Ctx.getAtomicType(
14470 Ctx.getCommonSugaredType(AX->getValueType(), AY->getValueType()));
14471 }
14472 case Type::Complex: {
14473 const auto *CX = cast<ComplexType>(X), *CY = cast<ComplexType>(Y);
14474 return Ctx.getComplexType(getCommonArrayElementType(Ctx, CX, QX, CY, QY));
14475 }
14476 case Type::Pointer: {
14477 const auto *PX = cast<PointerType>(X), *PY = cast<PointerType>(Y);
14478 return Ctx.getPointerType(getCommonPointeeType(Ctx, PX, PY));
14479 }
14480 case Type::BlockPointer: {
14481 const auto *PX = cast<BlockPointerType>(X), *PY = cast<BlockPointerType>(Y);
14482 return Ctx.getBlockPointerType(getCommonPointeeType(Ctx, PX, PY));
14483 }
14484 case Type::ObjCObjectPointer: {
14485 const auto *PX = cast<ObjCObjectPointerType>(X),
14487 return Ctx.getObjCObjectPointerType(getCommonPointeeType(Ctx, PX, PY));
14488 }
14489 case Type::MemberPointer: {
14490 const auto *PX = cast<MemberPointerType>(X),
14491 *PY = cast<MemberPointerType>(Y);
14492 assert(declaresSameEntity(PX->getMostRecentCXXRecordDecl(),
14493 PY->getMostRecentCXXRecordDecl()));
14494 return Ctx.getMemberPointerType(
14495 getCommonPointeeType(Ctx, PX, PY),
14496 getCommonQualifier(Ctx, PX, PY, /*IsSame=*/true),
14497 PX->getMostRecentCXXRecordDecl());
14498 }
14499 case Type::LValueReference: {
14500 const auto *PX = cast<LValueReferenceType>(X),
14502 // FIXME: Preserve PointeeTypeAsWritten.
14503 return Ctx.getLValueReferenceType(getCommonPointeeType(Ctx, PX, PY),
14504 PX->isSpelledAsLValue() ||
14505 PY->isSpelledAsLValue());
14506 }
14507 case Type::RValueReference: {
14508 const auto *PX = cast<RValueReferenceType>(X),
14510 // FIXME: Preserve PointeeTypeAsWritten.
14511 return Ctx.getRValueReferenceType(getCommonPointeeType(Ctx, PX, PY));
14512 }
14513 case Type::DependentAddressSpace: {
14514 const auto *PX = cast<DependentAddressSpaceType>(X),
14516 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
14517 return Ctx.getDependentAddressSpaceType(getCommonPointeeType(Ctx, PX, PY),
14518 PX->getAddrSpaceExpr(),
14519 getCommonAttrLoc(PX, PY));
14520 }
14521 case Type::FunctionNoProto: {
14522 const auto *FX = cast<FunctionNoProtoType>(X),
14524 assert(FX->getExtInfo() == FY->getExtInfo());
14525 return Ctx.getFunctionNoProtoType(
14526 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType()),
14527 FX->getExtInfo());
14528 }
14529 case Type::FunctionProto: {
14530 const auto *FX = cast<FunctionProtoType>(X),
14531 *FY = cast<FunctionProtoType>(Y);
14532 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
14533 EPIY = FY->getExtProtoInfo();
14534 assert(EPIX.ExtInfo == EPIY.ExtInfo);
14535 assert(!EPIX.ExtParameterInfos == !EPIY.ExtParameterInfos);
14536 assert(!EPIX.ExtParameterInfos ||
14537 llvm::equal(
14538 llvm::ArrayRef(EPIX.ExtParameterInfos, FX->getNumParams()),
14539 llvm::ArrayRef(EPIY.ExtParameterInfos, FY->getNumParams())));
14540 assert(EPIX.RefQualifier == EPIY.RefQualifier);
14541 assert(EPIX.TypeQuals == EPIY.TypeQuals);
14542 assert(EPIX.Variadic == EPIY.Variadic);
14543
14544 // FIXME: Can we handle an empty EllipsisLoc?
14545 // Use emtpy EllipsisLoc if X and Y differ.
14546
14547 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
14548
14549 QualType R =
14550 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType());
14551 auto P = getCommonTypes(Ctx, FX->param_types(), FY->param_types(),
14552 /*Unqualified=*/true);
14553
14554 SmallVector<QualType, 8> Exceptions;
14556 EPIX.ExceptionSpec, EPIY.ExceptionSpec, Exceptions, true);
14557 return Ctx.getFunctionType(R, P, EPIX);
14558 }
14559 case Type::ObjCObject: {
14560 const auto *OX = cast<ObjCObjectType>(X), *OY = cast<ObjCObjectType>(Y);
14561 assert(
14562 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
14563 OY->getProtocols().begin(), OY->getProtocols().end(),
14564 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
14565 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
14566 }) &&
14567 "protocol lists must be the same");
14568 auto TAs = getCommonTypes(Ctx, OX->getTypeArgsAsWritten(),
14569 OY->getTypeArgsAsWritten());
14570 return Ctx.getObjCObjectType(
14571 Ctx.getCommonSugaredType(OX->getBaseType(), OY->getBaseType()), TAs,
14572 OX->getProtocols(),
14573 OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
14574 }
14575 case Type::ConstantMatrix: {
14576 const auto *MX = cast<ConstantMatrixType>(X),
14577 *MY = cast<ConstantMatrixType>(Y);
14578 assert(MX->getNumRows() == MY->getNumRows());
14579 assert(MX->getNumColumns() == MY->getNumColumns());
14580 return Ctx.getConstantMatrixType(getCommonElementType(Ctx, MX, MY),
14581 MX->getNumRows(), MX->getNumColumns());
14582 }
14583 case Type::DependentSizedMatrix: {
14584 const auto *MX = cast<DependentSizedMatrixType>(X),
14586 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
14587 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
14588 return Ctx.getDependentSizedMatrixType(
14589 getCommonElementType(Ctx, MX, MY), MX->getRowExpr(),
14590 MX->getColumnExpr(), getCommonAttrLoc(MX, MY));
14591 }
14592 case Type::Vector: {
14593 const auto *VX = cast<VectorType>(X), *VY = cast<VectorType>(Y);
14594 assert(VX->getNumElements() == VY->getNumElements());
14595 assert(VX->getVectorKind() == VY->getVectorKind());
14596 return Ctx.getVectorType(getCommonElementType(Ctx, VX, VY),
14597 VX->getNumElements(), VX->getVectorKind());
14598 }
14599 case Type::ExtVector: {
14600 const auto *VX = cast<ExtVectorType>(X), *VY = cast<ExtVectorType>(Y);
14601 assert(VX->getNumElements() == VY->getNumElements());
14602 return Ctx.getExtVectorType(getCommonElementType(Ctx, VX, VY),
14603 VX->getNumElements());
14604 }
14605 case Type::DependentSizedExtVector: {
14606 const auto *VX = cast<DependentSizedExtVectorType>(X),
14609 getCommonSizeExpr(Ctx, VX, VY),
14610 getCommonAttrLoc(VX, VY));
14611 }
14612 case Type::DependentVector: {
14613 const auto *VX = cast<DependentVectorType>(X),
14615 assert(VX->getVectorKind() == VY->getVectorKind());
14616 return Ctx.getDependentVectorType(
14617 getCommonElementType(Ctx, VX, VY), getCommonSizeExpr(Ctx, VX, VY),
14618 getCommonAttrLoc(VX, VY), VX->getVectorKind());
14619 }
14620 case Type::Enum:
14621 case Type::Record:
14622 case Type::InjectedClassName: {
14623 const auto *TX = cast<TagType>(X), *TY = cast<TagType>(Y);
14624 return Ctx.getTagType(::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14625 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false),
14626 ::getCommonDeclChecked(TX->getDecl(), TY->getDecl()),
14627 /*OwnedTag=*/false);
14628 }
14629 case Type::TemplateSpecialization: {
14630 const auto *TX = cast<TemplateSpecializationType>(X),
14632 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
14633 TY->template_arguments());
14635 getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14636 ::getCommonTemplateNameChecked(Ctx, TX->getTemplateName(),
14637 TY->getTemplateName(),
14638 /*IgnoreDeduced=*/true),
14639 As, /*CanonicalArgs=*/{}, X->getCanonicalTypeInternal());
14640 }
14641 case Type::Decltype: {
14642 const auto *DX = cast<DecltypeType>(X);
14643 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Y);
14644 assert(DX->isDependentType());
14645 assert(DY->isDependentType());
14646 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
14647 // As Decltype is not uniqued, building a common type would be wasteful.
14648 return QualType(DX, 0);
14649 }
14650 case Type::PackIndexing: {
14651 const auto *DX = cast<PackIndexingType>(X);
14652 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Y);
14653 assert(DX->isDependentType());
14654 assert(DY->isDependentType());
14655 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
14656 return QualType(DX, 0);
14657 }
14658 case Type::DependentName: {
14659 const auto *NX = cast<DependentNameType>(X),
14660 *NY = cast<DependentNameType>(Y);
14661 assert(NX->getIdentifier() == NY->getIdentifier());
14662 return Ctx.getDependentNameType(
14663 getCommonTypeKeyword(NX, NY, /*IsSame=*/true),
14664 getCommonQualifier(Ctx, NX, NY, /*IsSame=*/true), NX->getIdentifier());
14665 }
14666 case Type::OverflowBehavior: {
14667 const auto *NX = cast<OverflowBehaviorType>(X),
14669 assert(NX->getBehaviorKind() == NY->getBehaviorKind());
14670 return Ctx.getOverflowBehaviorType(
14671 NX->getBehaviorKind(),
14672 getCommonTypeWithQualifierLifting(Ctx, NX->getUnderlyingType(),
14673 NY->getUnderlyingType(), QX, QY));
14674 }
14675 case Type::UnaryTransform: {
14676 const auto *TX = cast<UnaryTransformType>(X),
14677 *TY = cast<UnaryTransformType>(Y);
14678 assert(TX->getUTTKind() == TY->getUTTKind());
14679 return Ctx.getUnaryTransformType(
14680 Ctx.getCommonSugaredType(TX->getBaseType(), TY->getBaseType()),
14681 Ctx.getCommonSugaredType(TX->getUnderlyingType(),
14682 TY->getUnderlyingType()),
14683 TX->getUTTKind());
14684 }
14685 case Type::PackExpansion: {
14686 const auto *PX = cast<PackExpansionType>(X),
14687 *PY = cast<PackExpansionType>(Y);
14688 assert(PX->getNumExpansions() == PY->getNumExpansions());
14689 return Ctx.getPackExpansionType(
14690 Ctx.getCommonSugaredType(PX->getPattern(), PY->getPattern()),
14691 PX->getNumExpansions(), false);
14692 }
14693 case Type::Pipe: {
14694 const auto *PX = cast<PipeType>(X), *PY = cast<PipeType>(Y);
14695 assert(PX->isReadOnly() == PY->isReadOnly());
14696 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
14698 return (Ctx.*MP)(getCommonElementType(Ctx, PX, PY));
14699 }
14700 case Type::TemplateTypeParm: {
14701 const auto *TX = cast<TemplateTypeParmType>(X),
14703 assert(TX->getDepth() == TY->getDepth());
14704 assert(TX->getIndex() == TY->getIndex());
14705 assert(TX->isParameterPack() == TY->isParameterPack());
14706 return Ctx.getTemplateTypeParmType(
14707 TX->getDepth(), TX->getIndex(), TX->isParameterPack(),
14708 getCommonDecl(TX->getDecl(), TY->getDecl()));
14709 }
14710 }
14711 llvm_unreachable("Unknown Type Class");
14712}
14713
14715 const Type *Y,
14716 SplitQualType Underlying) {
14717 Type::TypeClass TC = X->getTypeClass();
14718 if (TC != Y->getTypeClass())
14719 return QualType();
14720 switch (TC) {
14721#define UNEXPECTED_TYPE(Class, Kind) \
14722 case Type::Class: \
14723 llvm_unreachable("Unexpected " Kind ": " #Class);
14724#define TYPE(Class, Base)
14725#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
14726#include "clang/AST/TypeNodes.inc"
14727
14728#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
14731 CANONICAL_TYPE(BlockPointer)
14734 CANONICAL_TYPE(ConstantArray)
14735 CANONICAL_TYPE(ArrayParameter)
14736 CANONICAL_TYPE(ConstantMatrix)
14738 CANONICAL_TYPE(ExtVector)
14739 CANONICAL_TYPE(FunctionNoProto)
14740 CANONICAL_TYPE(FunctionProto)
14741 CANONICAL_TYPE(IncompleteArray)
14742 CANONICAL_TYPE(HLSLAttributedResource)
14743 CANONICAL_TYPE(HLSLInlineSpirv)
14744 CANONICAL_TYPE(LValueReference)
14745 CANONICAL_TYPE(ObjCInterface)
14746 CANONICAL_TYPE(ObjCObject)
14747 CANONICAL_TYPE(ObjCObjectPointer)
14748 CANONICAL_TYPE(OverflowBehavior)
14752 CANONICAL_TYPE(RValueReference)
14753 CANONICAL_TYPE(VariableArray)
14755#undef CANONICAL_TYPE
14756
14757#undef UNEXPECTED_TYPE
14758
14759 case Type::Adjusted: {
14760 const auto *AX = cast<AdjustedType>(X), *AY = cast<AdjustedType>(Y);
14761 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
14762 if (!Ctx.hasSameType(OX, OY))
14763 return QualType();
14764 // FIXME: It's inefficient to have to unify the original types.
14765 return Ctx.getAdjustedType(Ctx.getCommonSugaredType(OX, OY),
14766 Ctx.getQualifiedType(Underlying));
14767 }
14768 case Type::Decayed: {
14769 const auto *DX = cast<DecayedType>(X), *DY = cast<DecayedType>(Y);
14770 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
14771 if (!Ctx.hasSameType(OX, OY))
14772 return QualType();
14773 // FIXME: It's inefficient to have to unify the original types.
14774 return Ctx.getDecayedType(Ctx.getCommonSugaredType(OX, OY),
14775 Ctx.getQualifiedType(Underlying));
14776 }
14777 case Type::Attributed: {
14778 const auto *AX = cast<AttributedType>(X), *AY = cast<AttributedType>(Y);
14779 AttributedType::Kind Kind = AX->getAttrKind();
14780 if (Kind != AY->getAttrKind())
14781 return QualType();
14782 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
14783 if (!Ctx.hasSameType(MX, MY))
14784 return QualType();
14785 // FIXME: It's inefficient to have to unify the modified types.
14786 return Ctx.getAttributedType(Kind, Ctx.getCommonSugaredType(MX, MY),
14787 Ctx.getQualifiedType(Underlying),
14788 AX->getAttr());
14789 }
14790 case Type::BTFTagAttributed: {
14791 const auto *BX = cast<BTFTagAttributedType>(X);
14792 const BTFTypeTagAttr *AX = BX->getAttr();
14793 // The attribute is not uniqued, so just compare the tag.
14794 if (AX->getBTFTypeTag() !=
14795 cast<BTFTagAttributedType>(Y)->getAttr()->getBTFTypeTag())
14796 return QualType();
14797 return Ctx.getBTFTagAttributedType(AX, Ctx.getQualifiedType(Underlying));
14798 }
14799 case Type::Auto: {
14800 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14801 assert(AX->getDeducedKind() == DeducedKind::Deduced);
14802 assert(AY->getDeducedKind() == DeducedKind::Deduced);
14803
14804 AutoTypeKeyword KW = AX->getKeyword();
14805 if (KW != AY->getKeyword())
14806 return QualType();
14807
14808 TemplateDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(),
14809 AY->getTypeConstraintConcept());
14811 if (CD &&
14812 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
14813 AY->getTypeConstraintArguments())) {
14814 CD = nullptr; // The arguments differ, so make it unconstrained.
14815 As.clear();
14816 }
14817
14818 // Both auto types can't be dependent, otherwise they wouldn't have been
14819 // sugar. This implies they can't contain unexpanded packs either.
14821 Ctx.getQualifiedType(Underlying), AX->getKeyword(),
14822 CD, As);
14823 }
14824 case Type::PackIndexing:
14825 case Type::Decltype:
14826 return QualType();
14827 case Type::DeducedTemplateSpecialization:
14828 // FIXME: Try to merge these.
14829 return QualType();
14830 case Type::MacroQualified: {
14831 const auto *MX = cast<MacroQualifiedType>(X),
14832 *MY = cast<MacroQualifiedType>(Y);
14833 const IdentifierInfo *IX = MX->getMacroIdentifier();
14834 if (IX != MY->getMacroIdentifier())
14835 return QualType();
14836 return Ctx.getMacroQualifiedType(Ctx.getQualifiedType(Underlying), IX);
14837 }
14838 case Type::SubstTemplateTypeParm: {
14839 const auto *SX = cast<SubstTemplateTypeParmType>(X),
14841 Decl *CD =
14842 ::getCommonDecl(SX->getAssociatedDecl(), SY->getAssociatedDecl());
14843 if (!CD)
14844 return QualType();
14845 unsigned Index = SX->getIndex();
14846 if (Index != SY->getIndex())
14847 return QualType();
14848 auto PackIndex = SX->getPackIndex();
14849 if (PackIndex != SY->getPackIndex())
14850 return QualType();
14851 return Ctx.getSubstTemplateTypeParmType(Ctx.getQualifiedType(Underlying),
14852 CD, Index, PackIndex,
14853 SX->getFinal() && SY->getFinal());
14854 }
14855 case Type::ObjCTypeParam:
14856 // FIXME: Try to merge these.
14857 return QualType();
14858 case Type::Paren:
14859 return Ctx.getParenType(Ctx.getQualifiedType(Underlying));
14860
14861 case Type::TemplateSpecialization: {
14862 const auto *TX = cast<TemplateSpecializationType>(X),
14864 TemplateName CTN =
14865 ::getCommonTemplateName(Ctx, TX->getTemplateName(),
14866 TY->getTemplateName(), /*IgnoreDeduced=*/true);
14867 if (!CTN.getAsVoidPointer())
14868 return QualType();
14870 if (getCommonTemplateArguments(Ctx, As, TX->template_arguments(),
14871 TY->template_arguments()))
14872 return QualType();
14874 getCommonTypeKeyword(TX, TY, /*IsSame=*/false), CTN, As,
14875 /*CanonicalArgs=*/{}, Ctx.getQualifiedType(Underlying));
14876 }
14877 case Type::Typedef: {
14878 const auto *TX = cast<TypedefType>(X), *TY = cast<TypedefType>(Y);
14879 const TypedefNameDecl *CD = ::getCommonDecl(TX->getDecl(), TY->getDecl());
14880 if (!CD)
14881 return QualType();
14882 return Ctx.getTypedefType(
14883 ::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14884 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false), CD,
14885 Ctx.getQualifiedType(Underlying));
14886 }
14887 case Type::TypeOf: {
14888 // The common sugar between two typeof expressions, where one is
14889 // potentially a typeof_unqual and the other is not, we unify to the
14890 // qualified type as that retains the most information along with the type.
14891 // We only return a typeof_unqual type when both types are unqual types.
14896 return Ctx.getTypeOfType(Ctx.getQualifiedType(Underlying), Kind);
14897 }
14898 case Type::TypeOfExpr:
14899 return QualType();
14900
14901 case Type::UnaryTransform: {
14902 const auto *UX = cast<UnaryTransformType>(X),
14903 *UY = cast<UnaryTransformType>(Y);
14904 UnaryTransformType::UTTKind KX = UX->getUTTKind();
14905 if (KX != UY->getUTTKind())
14906 return QualType();
14907 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
14908 if (!Ctx.hasSameType(BX, BY))
14909 return QualType();
14910 // FIXME: It's inefficient to have to unify the base types.
14911 return Ctx.getUnaryTransformType(Ctx.getCommonSugaredType(BX, BY),
14912 Ctx.getQualifiedType(Underlying), KX);
14913 }
14914 case Type::Using: {
14915 const auto *UX = cast<UsingType>(X), *UY = cast<UsingType>(Y);
14916 const UsingShadowDecl *CD = ::getCommonDecl(UX->getDecl(), UY->getDecl());
14917 if (!CD)
14918 return QualType();
14919 return Ctx.getUsingType(::getCommonTypeKeyword(UX, UY, /*IsSame=*/false),
14920 ::getCommonQualifier(Ctx, UX, UY, /*IsSame=*/false),
14921 CD, Ctx.getQualifiedType(Underlying));
14922 }
14923 case Type::MemberPointer: {
14924 const auto *PX = cast<MemberPointerType>(X),
14925 *PY = cast<MemberPointerType>(Y);
14926 CXXRecordDecl *Cls = PX->getMostRecentCXXRecordDecl();
14927 assert(Cls == PY->getMostRecentCXXRecordDecl());
14928 return Ctx.getMemberPointerType(
14929 ::getCommonPointeeType(Ctx, PX, PY),
14930 ::getCommonQualifier(Ctx, PX, PY, /*IsSame=*/false), Cls);
14931 }
14932 case Type::CountAttributed: {
14933 const auto *DX = cast<CountAttributedType>(X),
14935 if (DX->isCountInBytes() != DY->isCountInBytes())
14936 return QualType();
14937 if (DX->isOrNull() != DY->isOrNull())
14938 return QualType();
14939 Expr *CEX = DX->getCountExpr();
14940 Expr *CEY = DY->getCountExpr();
14941 ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
14942 if (Ctx.hasSameExpr(CEX, CEY))
14943 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14944 DX->isCountInBytes(), DX->isOrNull(),
14945 CDX);
14946 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
14947 return QualType();
14948 // Two declarations with the same integer constant may still differ in their
14949 // expression pointers, so we need to evaluate them.
14950 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
14951 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
14952 if (VX != VY)
14953 return QualType();
14954 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14955 DX->isCountInBytes(), DX->isOrNull(),
14956 CDX);
14957 }
14958 case Type::PredefinedSugar:
14959 assert(cast<PredefinedSugarType>(X)->getKind() !=
14961 return QualType();
14962 }
14963 llvm_unreachable("Unhandled Type Class");
14964}
14965
14966static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
14968 while (true) {
14969 QTotal.addConsistentQualifiers(T.Quals);
14971 if (NT == QualType(T.Ty, 0))
14972 break;
14973 R.push_back(T);
14974 T = NT.split();
14975 }
14976 return R;
14977}
14978
14980 bool Unqualified) const {
14981 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
14982 if (X == Y)
14983 return X;
14984 if (!Unqualified) {
14985 if (X.isCanonical())
14986 return X;
14987 if (Y.isCanonical())
14988 return Y;
14989 }
14990
14991 SplitQualType SX = X.split(), SY = Y.split();
14992 Qualifiers QX, QY;
14993 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
14994 // until we reach their underlying "canonical nodes". Note these are not
14995 // necessarily canonical types, as they may still have sugared properties.
14996 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
14997 auto Xs = ::unwrapSugar(SX, QX), Ys = ::unwrapSugar(SY, QY);
14998
14999 // If this is an ArrayType, the element qualifiers are interchangeable with
15000 // the top level qualifiers.
15001 // * In case the canonical nodes are the same, the elements types are already
15002 // the same.
15003 // * Otherwise, the element types will be made the same, and any different
15004 // element qualifiers will be moved up to the top level qualifiers, per
15005 // 'getCommonArrayElementType'.
15006 // In both cases, this means there may be top level qualifiers which differ
15007 // between X and Y. If so, these differing qualifiers are redundant with the
15008 // element qualifiers, and can be removed without changing the canonical type.
15009 // The desired behaviour is the same as for the 'Unqualified' case here:
15010 // treat the redundant qualifiers as sugar, remove the ones which are not
15011 // common to both sides.
15012 bool KeepCommonQualifiers =
15014
15015 if (SX.Ty != SY.Ty) {
15016 // The canonical nodes differ. Build a common canonical node out of the two,
15017 // unifying their sugar. This may recurse back here.
15018 SX.Ty =
15019 ::getCommonNonSugarTypeNode(*this, SX.Ty, QX, SY.Ty, QY).getTypePtr();
15020 } else {
15021 // The canonical nodes were identical: We may have desugared too much.
15022 // Add any common sugar back in.
15023 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
15024 QX -= SX.Quals;
15025 QY -= SY.Quals;
15026 SX = Xs.pop_back_val();
15027 SY = Ys.pop_back_val();
15028 }
15029 }
15030 if (KeepCommonQualifiers)
15032 else
15033 assert(QX == QY);
15034
15035 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
15036 // related. Walk up these nodes, unifying them and adding the result.
15037 while (!Xs.empty() && !Ys.empty()) {
15038 auto Underlying = SplitQualType(
15039 SX.Ty, Qualifiers::removeCommonQualifiers(SX.Quals, SY.Quals));
15040 SX = Xs.pop_back_val();
15041 SY = Ys.pop_back_val();
15042 SX.Ty = ::getCommonSugarTypeNode(*this, SX.Ty, SY.Ty, Underlying)
15044 // Stop at the first pair which is unrelated.
15045 if (!SX.Ty) {
15046 SX.Ty = Underlying.Ty;
15047 break;
15048 }
15049 QX -= Underlying.Quals;
15050 };
15051
15052 // Add back the missing accumulated qualifiers, which were stripped off
15053 // with the sugar nodes we could not unify.
15054 QualType R = getQualifiedType(SX.Ty, QX);
15055 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
15056 return R;
15057}
15058
15060 assert(Ty->isFixedPointType());
15061
15063 return Ty;
15064
15065 switch (Ty->castAs<BuiltinType>()->getKind()) {
15066 default:
15067 llvm_unreachable("Not a saturated fixed point type!");
15068 case BuiltinType::SatShortAccum:
15069 return ShortAccumTy;
15070 case BuiltinType::SatAccum:
15071 return AccumTy;
15072 case BuiltinType::SatLongAccum:
15073 return LongAccumTy;
15074 case BuiltinType::SatUShortAccum:
15075 return UnsignedShortAccumTy;
15076 case BuiltinType::SatUAccum:
15077 return UnsignedAccumTy;
15078 case BuiltinType::SatULongAccum:
15079 return UnsignedLongAccumTy;
15080 case BuiltinType::SatShortFract:
15081 return ShortFractTy;
15082 case BuiltinType::SatFract:
15083 return FractTy;
15084 case BuiltinType::SatLongFract:
15085 return LongFractTy;
15086 case BuiltinType::SatUShortFract:
15087 return UnsignedShortFractTy;
15088 case BuiltinType::SatUFract:
15089 return UnsignedFractTy;
15090 case BuiltinType::SatULongFract:
15091 return UnsignedLongFractTy;
15092 }
15093}
15094
15096 assert(Ty->isFixedPointType());
15097
15098 if (Ty->isSaturatedFixedPointType()) return Ty;
15099
15100 switch (Ty->castAs<BuiltinType>()->getKind()) {
15101 default:
15102 llvm_unreachable("Not a fixed point type!");
15103 case BuiltinType::ShortAccum:
15104 return SatShortAccumTy;
15105 case BuiltinType::Accum:
15106 return SatAccumTy;
15107 case BuiltinType::LongAccum:
15108 return SatLongAccumTy;
15109 case BuiltinType::UShortAccum:
15111 case BuiltinType::UAccum:
15112 return SatUnsignedAccumTy;
15113 case BuiltinType::ULongAccum:
15115 case BuiltinType::ShortFract:
15116 return SatShortFractTy;
15117 case BuiltinType::Fract:
15118 return SatFractTy;
15119 case BuiltinType::LongFract:
15120 return SatLongFractTy;
15121 case BuiltinType::UShortFract:
15123 case BuiltinType::UFract:
15124 return SatUnsignedFractTy;
15125 case BuiltinType::ULongFract:
15127 }
15128}
15129
15131 if (LangOpts.OpenCL)
15133
15134 if (LangOpts.CUDA)
15136
15137 return getLangASFromTargetAS(AS);
15138}
15139
15140// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
15141// doesn't include ASTContext.h
15142template
15144 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
15146 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
15147 const clang::ASTContext &Ctx, Decl *Value);
15148
15150 assert(Ty->isFixedPointType());
15151
15152 const TargetInfo &Target = getTargetInfo();
15153 switch (Ty->castAs<BuiltinType>()->getKind()) {
15154 default:
15155 llvm_unreachable("Not a fixed point type!");
15156 case BuiltinType::ShortAccum:
15157 case BuiltinType::SatShortAccum:
15158 return Target.getShortAccumScale();
15159 case BuiltinType::Accum:
15160 case BuiltinType::SatAccum:
15161 return Target.getAccumScale();
15162 case BuiltinType::LongAccum:
15163 case BuiltinType::SatLongAccum:
15164 return Target.getLongAccumScale();
15165 case BuiltinType::UShortAccum:
15166 case BuiltinType::SatUShortAccum:
15167 return Target.getUnsignedShortAccumScale();
15168 case BuiltinType::UAccum:
15169 case BuiltinType::SatUAccum:
15170 return Target.getUnsignedAccumScale();
15171 case BuiltinType::ULongAccum:
15172 case BuiltinType::SatULongAccum:
15173 return Target.getUnsignedLongAccumScale();
15174 case BuiltinType::ShortFract:
15175 case BuiltinType::SatShortFract:
15176 return Target.getShortFractScale();
15177 case BuiltinType::Fract:
15178 case BuiltinType::SatFract:
15179 return Target.getFractScale();
15180 case BuiltinType::LongFract:
15181 case BuiltinType::SatLongFract:
15182 return Target.getLongFractScale();
15183 case BuiltinType::UShortFract:
15184 case BuiltinType::SatUShortFract:
15185 return Target.getUnsignedShortFractScale();
15186 case BuiltinType::UFract:
15187 case BuiltinType::SatUFract:
15188 return Target.getUnsignedFractScale();
15189 case BuiltinType::ULongFract:
15190 case BuiltinType::SatULongFract:
15191 return Target.getUnsignedLongFractScale();
15192 }
15193}
15194
15196 assert(Ty->isFixedPointType());
15197
15198 const TargetInfo &Target = getTargetInfo();
15199 switch (Ty->castAs<BuiltinType>()->getKind()) {
15200 default:
15201 llvm_unreachable("Not a fixed point type!");
15202 case BuiltinType::ShortAccum:
15203 case BuiltinType::SatShortAccum:
15204 return Target.getShortAccumIBits();
15205 case BuiltinType::Accum:
15206 case BuiltinType::SatAccum:
15207 return Target.getAccumIBits();
15208 case BuiltinType::LongAccum:
15209 case BuiltinType::SatLongAccum:
15210 return Target.getLongAccumIBits();
15211 case BuiltinType::UShortAccum:
15212 case BuiltinType::SatUShortAccum:
15213 return Target.getUnsignedShortAccumIBits();
15214 case BuiltinType::UAccum:
15215 case BuiltinType::SatUAccum:
15216 return Target.getUnsignedAccumIBits();
15217 case BuiltinType::ULongAccum:
15218 case BuiltinType::SatULongAccum:
15219 return Target.getUnsignedLongAccumIBits();
15220 case BuiltinType::ShortFract:
15221 case BuiltinType::SatShortFract:
15222 case BuiltinType::Fract:
15223 case BuiltinType::SatFract:
15224 case BuiltinType::LongFract:
15225 case BuiltinType::SatLongFract:
15226 case BuiltinType::UShortFract:
15227 case BuiltinType::SatUShortFract:
15228 case BuiltinType::UFract:
15229 case BuiltinType::SatUFract:
15230 case BuiltinType::ULongFract:
15231 case BuiltinType::SatULongFract:
15232 return 0;
15233 }
15234}
15235
15236llvm::FixedPointSemantics
15238 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
15239 "Can only get the fixed point semantics for a "
15240 "fixed point or integer type.");
15241 if (Ty->isIntegerType())
15242 return llvm::FixedPointSemantics::GetIntegerSemantics(
15243 getIntWidth(Ty), Ty->isSignedIntegerType());
15244
15245 bool isSigned = Ty->isSignedFixedPointType();
15246 return llvm::FixedPointSemantics(
15247 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
15249 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
15250}
15251
15252llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
15253 assert(Ty->isFixedPointType());
15254 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
15255}
15256
15257llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
15258 assert(Ty->isFixedPointType());
15259 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
15260}
15261
15263 assert(Ty->isUnsignedFixedPointType() &&
15264 "Expected unsigned fixed point type");
15265
15266 switch (Ty->castAs<BuiltinType>()->getKind()) {
15267 case BuiltinType::UShortAccum:
15268 return ShortAccumTy;
15269 case BuiltinType::UAccum:
15270 return AccumTy;
15271 case BuiltinType::ULongAccum:
15272 return LongAccumTy;
15273 case BuiltinType::SatUShortAccum:
15274 return SatShortAccumTy;
15275 case BuiltinType::SatUAccum:
15276 return SatAccumTy;
15277 case BuiltinType::SatULongAccum:
15278 return SatLongAccumTy;
15279 case BuiltinType::UShortFract:
15280 return ShortFractTy;
15281 case BuiltinType::UFract:
15282 return FractTy;
15283 case BuiltinType::ULongFract:
15284 return LongFractTy;
15285 case BuiltinType::SatUShortFract:
15286 return SatShortFractTy;
15287 case BuiltinType::SatUFract:
15288 return SatFractTy;
15289 case BuiltinType::SatULongFract:
15290 return SatLongFractTy;
15291 default:
15292 llvm_unreachable("Unexpected unsigned fixed point type");
15293 }
15294}
15295
15296// Given a list of FMV features, return a concatenated list of the
15297// corresponding backend features (which may contain duplicates).
15298static std::vector<std::string> getFMVBackendFeaturesFor(
15299 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) {
15300 std::vector<std::string> BackendFeats;
15301 llvm::AArch64::ExtensionSet FeatureBits;
15302 for (StringRef F : FMVFeatStrings)
15303 if (auto FMVExt = llvm::AArch64::parseFMVExtension(F))
15304 if (FMVExt->ID)
15305 FeatureBits.enable(*FMVExt->ID);
15306 FeatureBits.toLLVMFeatureList(BackendFeats);
15307 return BackendFeats;
15308}
15309
15310ParsedTargetAttr
15311ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
15312 assert(TD != nullptr);
15313 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TD->getFeaturesStr());
15314
15315 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
15316 return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
15317 });
15318 return ParsedAttr;
15319}
15320
15321void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15322 const FunctionDecl *FD) const {
15323 if (FD)
15324 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
15325 else
15326 Target->initFeatureMap(FeatureMap, getDiagnostics(),
15327 Target->getTargetOpts().CPU,
15328 Target->getTargetOpts().Features);
15329}
15330
15331// Fills in the supplied string map with the set of target features for the
15332// passed in function.
15333void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15334 GlobalDecl GD) const {
15335 StringRef TargetCPU = Target->getTargetOpts().CPU;
15336 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
15337 if (const auto *TD = FD->getAttr<TargetAttr>()) {
15339
15340 // Make a copy of the features as passed on the command line into the
15341 // beginning of the additional features from the function to override.
15342 // AArch64 handles command line option features in parseTargetAttr().
15343 if (!Target->getTriple().isAArch64())
15344 ParsedAttr.Features.insert(
15345 ParsedAttr.Features.begin(),
15346 Target->getTargetOpts().FeaturesAsWritten.begin(),
15347 Target->getTargetOpts().FeaturesAsWritten.end());
15348
15349 if (ParsedAttr.CPU != "" && Target->isValidCPUName(ParsedAttr.CPU))
15350 TargetCPU = ParsedAttr.CPU;
15351
15352 // Now populate the feature map, first with the TargetCPU which is either
15353 // the default or a new one from the target attribute string. Then we'll use
15354 // the passed in features (FeaturesAsWritten) along with the new ones from
15355 // the attribute.
15356 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
15357 ParsedAttr.Features);
15358 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
15360 Target->getCPUSpecificCPUDispatchFeatures(
15361 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
15362 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
15363 Features.insert(Features.begin(),
15364 Target->getTargetOpts().FeaturesAsWritten.begin(),
15365 Target->getTargetOpts().FeaturesAsWritten.end());
15366 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15367 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
15368 if (Target->getTriple().isAArch64()) {
15370 TC->getFeatures(Feats, GD.getMultiVersionIndex());
15371 std::vector<std::string> Features = getFMVBackendFeaturesFor(Feats);
15372 Features.insert(Features.begin(),
15373 Target->getTargetOpts().FeaturesAsWritten.begin(),
15374 Target->getTargetOpts().FeaturesAsWritten.end());
15375 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15376 } else if (Target->getTriple().isRISCV()) {
15377 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15378 std::vector<std::string> Features;
15379 if (VersionStr != "default") {
15380 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(VersionStr);
15381 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
15382 ParsedAttr.Features.end());
15383 }
15384 Features.insert(Features.begin(),
15385 Target->getTargetOpts().FeaturesAsWritten.begin(),
15386 Target->getTargetOpts().FeaturesAsWritten.end());
15387 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15388 } else if (Target->getTriple().isOSAIX()) {
15389 std::vector<std::string> Features;
15390 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15391 if (VersionStr.starts_with("cpu="))
15392 TargetCPU = VersionStr.drop_front(sizeof("cpu=") - 1);
15393 else
15394 assert(VersionStr == "default");
15395 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15396 } else {
15397 std::vector<std::string> Features;
15398 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15399 if (VersionStr.starts_with("arch="))
15400 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
15401 else if (VersionStr != "default")
15402 Features.push_back((StringRef{"+"} + VersionStr).str());
15403 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15404 }
15405 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
15406 std::vector<std::string> Features;
15407 if (Target->getTriple().isRISCV()) {
15408 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TV->getName());
15409 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
15410 ParsedAttr.Features.end());
15411 } else {
15412 assert(Target->getTriple().isAArch64());
15414 TV->getFeatures(Feats);
15415 Features = getFMVBackendFeaturesFor(Feats);
15416 }
15417 Features.insert(Features.begin(),
15418 Target->getTargetOpts().FeaturesAsWritten.begin(),
15419 Target->getTargetOpts().FeaturesAsWritten.end());
15420 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15421 } else {
15422 FeatureMap = Target->getTargetOpts().FeatureMap;
15423 }
15424}
15425
15427 CanQualType KernelNameType,
15428 const FunctionDecl *FD) {
15429 // Host and device compilation may use different ABIs and different ABIs
15430 // may allocate name mangling discriminators differently. A discriminator
15431 // override is used to ensure consistent discriminator allocation across
15432 // host and device compilation.
15433 auto DeviceDiscriminatorOverrider =
15434 [](ASTContext &Ctx, const NamedDecl *ND) -> UnsignedOrNone {
15435 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
15436 if (RD->isLambda())
15437 return RD->getDeviceLambdaManglingNumber();
15438 return std::nullopt;
15439 };
15440 std::unique_ptr<MangleContext> MC{ItaniumMangleContext::create(
15441 Context, Context.getDiagnostics(), DeviceDiscriminatorOverrider)};
15442
15443 // Construct a mangled name for the SYCL kernel caller offload entry point.
15444 // FIXME: The Itanium typeinfo mangling (_ZTS<type>) is currently used to
15445 // name the SYCL kernel caller offload entry point function. This mangling
15446 // does not suffice to clearly identify symbols that correspond to SYCL
15447 // kernel caller functions, nor is this mangling natural for targets that
15448 // use a non-Itanium ABI.
15449 std::string Buffer;
15450 Buffer.reserve(128);
15451 llvm::raw_string_ostream Out(Buffer);
15452 MC->mangleCanonicalTypeName(KernelNameType, Out);
15453 std::string KernelName = Out.str();
15454
15455 return {KernelNameType, FD, KernelName};
15456}
15457
15459 // If the function declaration to register is invalid or dependent, the
15460 // registration attempt is ignored.
15461 if (FD->isInvalidDecl() || FD->isTemplated())
15462 return;
15463
15464 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
15465 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
15466
15467 // Be tolerant of multiple registration attempts so long as each attempt
15468 // is for the same entity. Callers are obligated to detect and diagnose
15469 // conflicting kernel names prior to calling this function.
15470 CanQualType KernelNameType = getCanonicalType(SKEPAttr->getKernelName());
15471 auto IT = SYCLKernels.find(KernelNameType);
15472 assert((IT == SYCLKernels.end() ||
15473 declaresSameEntity(FD, IT->second.getKernelEntryPointDecl())) &&
15474 "SYCL kernel name conflict");
15475 (void)IT;
15476 SYCLKernels.insert(std::make_pair(
15477 KernelNameType, BuildSYCLKernelInfo(*this, KernelNameType, FD)));
15478}
15479
15481 CanQualType KernelNameType = getCanonicalType(T);
15482 return SYCLKernels.at(KernelNameType);
15483}
15484
15486 CanQualType KernelNameType = getCanonicalType(T);
15487 auto IT = SYCLKernels.find(KernelNameType);
15488 if (IT != SYCLKernels.end())
15489 return &IT->second;
15490 return nullptr;
15491}
15492
15494 OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
15495 return *OMPTraitInfoVector.back();
15496}
15497
15500 const ASTContext::SectionInfo &Section) {
15501 if (Section.Decl)
15502 return DB << Section.Decl;
15503 return DB << "a prior #pragma section";
15504}
15505
15506bool ASTContext::mayExternalize(const Decl *D) const {
15507 bool IsInternalVar =
15508 isa<VarDecl>(D) &&
15510 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
15511 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
15512 (D->hasAttr<CUDAConstantAttr>() &&
15513 !D->getAttr<CUDAConstantAttr>()->isImplicit());
15514 // CUDA/HIP: managed variables need to be externalized since it is
15515 // a declaration in IR, therefore cannot have internal linkage. Kernels in
15516 // anonymous name space needs to be externalized to avoid duplicate symbols.
15517 return (IsInternalVar &&
15518 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
15519 (D->hasAttr<CUDAGlobalAttr>() &&
15521 GVA_Internal);
15522}
15523
15525 return mayExternalize(D) &&
15526 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
15528}
15529
15530StringRef ASTContext::getCUIDHash() const {
15531 if (!CUIDHash.empty())
15532 return CUIDHash;
15533 if (LangOpts.CUID.empty())
15534 return StringRef();
15535 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
15536 return CUIDHash;
15537}
15538
15539const CXXRecordDecl *
15541 assert(ThisClass);
15542 assert(ThisClass->isPolymorphic());
15543 const CXXRecordDecl *PrimaryBase = ThisClass;
15544 while (1) {
15545 assert(PrimaryBase);
15546 assert(PrimaryBase->isPolymorphic());
15547 auto &Layout = getASTRecordLayout(PrimaryBase);
15548 auto Base = Layout.getPrimaryBase();
15549 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
15550 break;
15551 PrimaryBase = Base;
15552 }
15553 return PrimaryBase;
15554}
15555
15557 StringRef MangledName) {
15558 auto *Method = cast<CXXMethodDecl>(VirtualMethodDecl.getDecl());
15559 assert(Method->isVirtual());
15560 bool DefaultIncludesPointerAuth =
15561 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics;
15562
15563 if (!DefaultIncludesPointerAuth)
15564 return true;
15565
15566 auto Existing = ThunksToBeAbbreviated.find(VirtualMethodDecl);
15567 if (Existing != ThunksToBeAbbreviated.end())
15568 return Existing->second.contains(MangledName.str());
15569
15570 std::unique_ptr<MangleContext> Mangler(createMangleContext());
15571 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks;
15572 auto VtableContext = getVTableContext();
15573 if (const auto *ThunkInfos = VtableContext->getThunkInfo(VirtualMethodDecl)) {
15574 auto *Destructor = dyn_cast<CXXDestructorDecl>(Method);
15575 for (const auto &Thunk : *ThunkInfos) {
15576 SmallString<256> ElidedName;
15577 llvm::raw_svector_ostream ElidedNameStream(ElidedName);
15578 if (Destructor)
15579 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15580 Thunk, /* elideOverrideInfo */ true,
15581 ElidedNameStream);
15582 else
15583 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ true,
15584 ElidedNameStream);
15585 SmallString<256> MangledName;
15586 llvm::raw_svector_ostream mangledNameStream(MangledName);
15587 if (Destructor)
15588 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15589 Thunk, /* elideOverrideInfo */ false,
15590 mangledNameStream);
15591 else
15592 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ false,
15593 mangledNameStream);
15594
15595 Thunks[ElidedName].push_back(std::string(MangledName));
15596 }
15597 }
15598 llvm::StringSet<> SimplifiedThunkNames;
15599 for (auto &ThunkList : Thunks) {
15600 llvm::sort(ThunkList.second);
15601 SimplifiedThunkNames.insert(ThunkList.second[0]);
15602 }
15603 bool Result = SimplifiedThunkNames.contains(MangledName);
15604 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames);
15605 return Result;
15606}
15607
15609 // Check for trivially-destructible here because non-trivially-destructible
15610 // types will always cause the type and any types derived from it to be
15611 // considered non-trivially-copyable. The same cannot be said for
15612 // trivially-copyable because deleting special members of a type derived from
15613 // a non-trivially-copyable type can cause the derived type to be considered
15614 // trivially copyable.
15615 if (getLangOpts().PointerFieldProtectionTagged)
15616 return !isa<CXXRecordDecl>(RD) ||
15617 cast<CXXRecordDecl>(RD)->hasTrivialDestructor();
15618 return true;
15619}
15620
15621static void findPFPFields(const ASTContext &Ctx, QualType Ty, CharUnits Offset,
15622 std::vector<PFPField> &Fields, bool IncludeVBases) {
15623 if (auto *AT = Ctx.getAsConstantArrayType(Ty)) {
15624 if (auto *ElemDecl = AT->getElementType()->getAsCXXRecordDecl()) {
15625 const ASTRecordLayout &ElemRL = Ctx.getASTRecordLayout(ElemDecl);
15626 for (unsigned i = 0; i != AT->getSize(); ++i)
15627 findPFPFields(Ctx, AT->getElementType(), Offset + i * ElemRL.getSize(),
15628 Fields, true);
15629 }
15630 }
15631 auto *Decl = Ty->getAsCXXRecordDecl();
15632 // isPFPType() is inherited from bases and members (including via arrays), so
15633 // we can early exit if it is false. Unions are excluded per the API
15634 // documentation.
15635 if (!Decl || !Decl->isPFPType() || Decl->isUnion())
15636 return;
15637 const ASTRecordLayout &RL = Ctx.getASTRecordLayout(Decl);
15638 for (FieldDecl *Field : Decl->fields()) {
15639 CharUnits FieldOffset =
15640 Offset +
15641 Ctx.toCharUnitsFromBits(RL.getFieldOffset(Field->getFieldIndex()));
15642 if (Ctx.isPFPField(Field))
15643 Fields.push_back({FieldOffset, Field});
15644 findPFPFields(Ctx, Field->getType(), FieldOffset, Fields,
15645 /*IncludeVBases=*/true);
15646 }
15647 // Pass false for IncludeVBases below because vbases are only included in
15648 // layout for top-level types, i.e. not bases or vbases.
15649 for (CXXBaseSpecifier &Base : Decl->bases()) {
15650 if (Base.isVirtual())
15651 continue;
15652 CharUnits BaseOffset =
15653 Offset + RL.getBaseClassOffset(Base.getType()->getAsCXXRecordDecl());
15654 findPFPFields(Ctx, Base.getType(), BaseOffset, Fields,
15655 /*IncludeVBases=*/false);
15656 }
15657 if (IncludeVBases) {
15658 for (CXXBaseSpecifier &Base : Decl->vbases()) {
15659 CharUnits BaseOffset =
15660 Offset + RL.getVBaseClassOffset(Base.getType()->getAsCXXRecordDecl());
15661 findPFPFields(Ctx, Base.getType(), BaseOffset, Fields,
15662 /*IncludeVBases=*/false);
15663 }
15664 }
15665}
15666
15667std::vector<PFPField> ASTContext::findPFPFields(QualType Ty) const {
15668 std::vector<PFPField> PFPFields;
15669 ::findPFPFields(*this, Ty, CharUnits::Zero(), PFPFields, true);
15670 return PFPFields;
15671}
15672
15674 return !findPFPFields(Ty).empty();
15675}
15676
15677bool ASTContext::isPFPField(const FieldDecl *FD) const {
15678 if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getParent()))
15679 return RD->isPFPType() && FD->getType()->isPointerType() &&
15680 !FD->hasAttr<NoFieldProtectionAttr>();
15681 return false;
15682}
15683
15685 auto *FD = dyn_cast<FieldDecl>(VD);
15686 if (!FD)
15687 FD = cast<FieldDecl>(cast<IndirectFieldDecl>(VD)->chain().back());
15688 if (isPFPField(FD))
15690}
15691
15693 if (E->getNumComponents() == 0)
15694 return;
15695 OffsetOfNode Comp = E->getComponent(E->getNumComponents() - 1);
15696 if (Comp.getKind() != OffsetOfNode::Field)
15697 return;
15698 if (FieldDecl *FD = Comp.getField(); isPFPField(FD))
15700}
This file provides AST data structures related to concepts.
static void SortAndUniqueProtocols(SmallVectorImpl< ObjCProtocolDecl * > &Protocols)
static bool isCanonicalExceptionSpecification(const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType)
static SourceLocation getCommonAttrLoc(const T *X, const T *Y)
static auto getCanonicalTemplateArguments(const ASTContext &C, ArrayRef< TemplateArgument > Args, bool &AnyNonCanonArgs)
static char getObjCEncodingForPrimitiveType(const ASTContext *C, const BuiltinType *BT)
static bool isSameQualifier(const NestedNameSpecifier X, const NestedNameSpecifier Y)
static bool unionHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD, bool CheckIfTriviallyCopyable)
static TypedefDecl * CreateHexagonBuiltinVaListDecl(const ASTContext *Context)
#define CANONICAL_TYPE(Class)
static ElaboratedTypeKeyword getCommonTypeKeyword(const T *X, const T *Y, bool IsSame)
static Decl * getCommonDecl(Decl *X, Decl *Y)
static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, const Decl *D, GVALinkage L)
static bool isTypeTypedefedAsBOOL(QualType T)
static void EncodeBitField(const ASTContext *Ctx, std::string &S, QualType T, const FieldDecl *FD)
static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, const VarDecl *VD)
static QualType getCommonArrayElementType(const ASTContext &Ctx, const T *X, Qualifiers &QX, const T *Y, Qualifiers &QY)
#define SUGAR_FREE_TYPE(Class)
static SYCLKernelInfo BuildSYCLKernelInfo(ASTContext &Context, CanQualType KernelNameType, const FunctionDecl *FD)
static bool hasTemplateSpecializationInEncodedString(const Type *T, bool VisitBasesAndFields)
static void getIntersectionOfProtocols(ASTContext &Context, const ObjCInterfaceDecl *CommonBase, const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT, SmallVectorImpl< ObjCProtocolDecl * > &IntersectionSet)
getIntersectionOfProtocols - This routine finds the intersection of set of protocols inherited from t...
static bool areCompatMatrixTypes(const ConstantMatrixType *LHS, const ConstantMatrixType *RHS)
areCompatMatrixTypes - Return true if the two specified matrix types are compatible.
static TypedefDecl * CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context)
static bool sameObjCTypeArgs(ASTContext &ctx, const ObjCInterfaceDecl *iface, ArrayRef< QualType > lhsArgs, ArrayRef< QualType > rhsArgs, bool stripKindOf)
static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs, QualType rhs)
Determine whether the first type is a subtype of the second.
static const Type * getIntegerTypeForEnum(const EnumType *ET)
static SmallVector< SourceLocation, 2 > getLocsForCommentSearch(ASTContext::RawCommentLookupKey Key, SourceManager &SourceMgr)
static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B)
static TemplateName getCommonTemplateName(const ASTContext &Ctx, TemplateName X, TemplateName Y, bool IgnoreDeduced=false)
static int CmpProtocolNames(ObjCProtocolDecl *const *LHS, ObjCProtocolDecl *const *RHS)
CmpProtocolNames - Comparison predicate for sorting protocols alphabetically.
static auto * getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y)
static TypedefDecl * CreatePowerABIBuiltinVaListDecl(const ASTContext *Context)
static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y)
static TemplateArgument getCommonTemplateArgument(const ASTContext &Ctx, const TemplateArgument &X, const TemplateArgument &Y)
static std::optional< int64_t > structHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD, bool CheckIfTriviallyCopyable)
static bool hasSameOverloadableAttrs(const FunctionDecl *A, const FunctionDecl *B)
Determine whether the attributes we can overload on are identical for A and B.
static T * getCommonDeclChecked(T *X, T *Y)
static NestedNameSpecifier getCommonNNS(const ASTContext &Ctx, NestedNameSpecifier NNS1, NestedNameSpecifier NNS2, bool IsSame)
Returns a NestedNameSpecifier which has only the common sugar present in both NNS1 and NNS2.
static TypedefDecl * CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context)
static int64_t getSubobjectOffset(const FieldDecl *Field, const ASTContext &Context, const clang::ASTRecordLayout &)
static QualType getCommonSugarTypeNode(const ASTContext &Ctx, const Type *X, const Type *Y, SplitQualType Underlying)
static TypedefDecl * CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context)
static QualType getCommonNonSugarTypeNode(const ASTContext &Ctx, const Type *X, Qualifiers &QX, const Type *Y, Qualifiers &QY)
static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, QualType other, bool isBlockReturnType)
Given that we have an enum type and a non-enum type, try to merge them.
static GVALinkage adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D, GVALinkage L)
Adjust the GVALinkage for a declaration based on what an external AST source knows about whether ther...
static TypedefDecl * CreateSystemZBuiltinVaListDecl(const ASTContext *Context)
static std::optional< int64_t > getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context, bool CheckIfTriviallyCopyable)
static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, const FunctionDecl *FD)
#define NON_UNIQUE_TYPE(Class)
static TypedefDecl * CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context)
static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI, const LangOptions &LangOpts)
static ElaboratedTypeKeyword getCanonicalElaboratedTypeKeyword(ElaboratedTypeKeyword Keyword)
static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X, const T *Y)
static auto getCommonIndexTypeCVRQualifiers(const ArrayType *X, const ArrayType *Y)
static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, ASTContext::GetBuiltinTypeError &Error, bool &RequiresICE, bool AllowTypeModifiers)
DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the pointer over the consume...
FloatingRank
@ FloatRank
@ LongDoubleRank
@ Float16Rank
@ Ibm128Rank
@ Float128Rank
@ BFloat16Rank
@ HalfRank
@ DoubleRank
static TypedefDecl * CreateCharPtrBuiltinVaListDecl(const ASTContext *Context)
static bool areSortedAndUniqued(ArrayRef< ObjCProtocolDecl * > Protocols)
static TypeInfoChars getConstantArrayInfoInChars(const ASTContext &Context, const ConstantArrayType *CAT)
getConstantArrayInfoInChars - Performing the computation in CharUnits instead of in bits prevents ove...
static FloatingRank getFloatingRank(QualType T)
getFloatingRank - Return a relative rank for floating point types.
static bool getCommonTemplateArguments(const ASTContext &Ctx, SmallVectorImpl< TemplateArgument > &R, ArrayRef< TemplateArgument > Xs, ArrayRef< TemplateArgument > Ys)
static TypedefDecl * CreateXtensaABIBuiltinVaListDecl(const ASTContext *Context)
static QualType getCommonElementType(const ASTContext &Ctx, const T *X, const T *Y)
static void mergeTypeLists(const ASTContext &Ctx, SmallVectorImpl< QualType > &Out, ArrayRef< QualType > X, ArrayRef< QualType > Y)
static bool matchesPostDecrInWhile(const UnaryOperator *UO, ASTContext &Ctx)
For the purposes of overflow pattern exclusion, does this match the while(i–) pattern?
static void encodeTypeForFunctionPointerAuth(const ASTContext &Ctx, raw_ostream &OS, QualType QT)
Encode a function type for use in the discriminator of a function pointer type.
static std::optional< int64_t > structSubobjectsHaveUniqueObjectRepresentations(const RangeT &Subobjects, int64_t CurOffsetInBits, const ASTContext &Context, const clang::ASTRecordLayout &Layout, bool CheckIfTriviallyCopyable)
static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty)
getRVVTypeSize - Return RVV vector register size.
static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal)
static TemplateName getCommonTemplateNameChecked(const ASTContext &Ctx, TemplateName X, TemplateName Y, bool IgnoreDeduced)
static int compareObjCProtocolsByName(ObjCProtocolDecl *const *lhs, ObjCProtocolDecl *const *rhs)
Comparison routine for Objective-C protocols to be used with llvm::array_pod_sort.
static std::string charUnitsToString(const CharUnits &CU)
static const TagDecl * getNonInjectedClassName(const TagDecl *TD)
static TypedefDecl * CreateZOSVaListDecl(const ASTContext *Context)
static bool hasAnyPackExpansions(ArrayRef< TemplateArgument > Args)
static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED)
static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod, SmallVectorImpl< const NamedDecl * > &Redeclared)
static QualType getCommonTypeWithQualifierLifting(const ASTContext &Ctx, QualType X, QualType Y, Qualifiers &QX, Qualifiers &QY)
static auto getCommonTypes(const ASTContext &Ctx, ArrayRef< QualType > Xs, ArrayRef< QualType > Ys, bool Unqualified=false)
static bool isCanonicalResultType(QualType T)
Determine whether T is canonical as the result type of a function.
static TypedefDecl * CreateMSVaListDecl(const ASTContext *Context)
static bool areCompatVectorTypes(const VectorType *LHS, const VectorType *RHS)
areCompatVectorTypes - Return true if the two specified vector types are compatible.
static TypedefDecl * CreateCharPtrNamedVaListDecl(const ASTContext *Context, StringRef Name)
static NestedNameSpecifier getCommonQualifier(const ASTContext &Ctx, const T *X, const T *Y, bool IsSame)
#define UNEXPECTED_TYPE(Class, Kind)
static TypedefDecl * CreateVaListDecl(const ASTContext *Context, TargetInfo::BuiltinVaListKind Kind)
static bool primaryBaseHaseAddressDiscriminatedVTableAuthentication(const ASTContext &Context, const CXXRecordDecl *Class)
static std::vector< std::string > getFMVBackendFeaturesFor(const llvm::SmallVectorImpl< StringRef > &FMVFeatStrings)
Defines the clang::ASTContext interface.
#define V(N, I)
#define BuiltinTemplate(BTName)
Definition ASTContext.h:475
Provides definitions for the various language-specific address spaces.
static bool isUnsigned(SValBuilder &SVB, NonLoc Value)
Defines enum values for all the target-independent builtin functions.
static bool CanThrow(Expr *E, ASTContext &Ctx)
Definition CFG.cpp:2851
Defines the clang::CommentOptions interface.
static Decl::Kind getKind(const Decl *D)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines OpenMP nodes for declarative directives.
Defines the C++ template declaration subclasses.
Defines the ExceptionSpecificationType enumeration and various utility functions.
Defines the clang::Expr interface and subclasses for C++ expressions.
FormatToken * Next
The next token in the unwrapped line.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
static const Decl * getCanonicalDecl(const Decl *D)
#define X(type, name)
Definition Value.h:97
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
llvm::MachO::Target Target
Definition MachO.h:51
llvm::MachO::Record Record
Definition MachO.h:31
Defines the clang::MacroInfo and clang::MacroDirective classes.
static bool hasFeature(StringRef Feature, const LangOptions &LangOpts, const TargetInfo &Target)
Determine whether a translation unit built using the current language options has the given feature.
Definition Module.cpp:95
Defines the clang::Module class, which describes a module in the source code.
static StringRef getTriple(const Command &Job)
Defines types useful for describing an Objective-C runtime.
#define SM(sm)
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
static QualType getUnderlyingType(const SubRegion *R)
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
static QualType getPointeeType(const MemRegion *R)
Defines the TargetCXXABI class, which abstracts details of the C++ ABI that we're targeting.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
QualType getReadPipeType(QualType T) const
Return a read_only pipe type for the specified type.
llvm::PointerUnion< const Decl *, const MacroInfo * > RawCommentLookupKey
Key used to look up the raw comment attached to a declaration or macro.
RawComment * getRawCommentNoCacheImpl(RawCommentLookupKey Key, const SourceLocation RepresentativeLoc, const std::map< unsigned, RawComment * > &CommentsInFile) const
QualType getWritePipeType(QualType T) const
Return a write_only pipe type for the specified type.
@ GE_Missing_stdio
Missing a type from <stdio.h>
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
bool isMemberPointerToDerivedMember() const
Definition APValue.cpp:1091
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1084
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition APValue.cpp:1098
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
bool getByrefLifetime(QualType Ty, Qualifiers::ObjCLifetime &Lifetime, bool &HasByrefExtendedLayout) const
Returns true, if given type has a known lifetime.
MSGuidDecl * getMSGuidDecl(MSGuidDeclParts Parts) const
Return a declaration for the global GUID object representing the given GUID value.
CanQualType AccumTy
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, const ObjCMethodDecl *MethodImp)
CanQualType ObjCBuiltinSelTy
TranslationUnitDecl * getTranslationUnitDecl() const
const ConstantArrayType * getAsConstantArrayType(QualType T) const
CanQualType getCanonicalFunctionResultType(QualType ResultType) const
Adjust the given function result type.
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
LangAS getOpenCLTypeAddrSpace(const Type *T) const
Get address space for OpenCL type.
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
void InitBuiltinTypes(const TargetInfo &Target, const TargetInfo *AuxTarget=nullptr)
Initialize built-in types.
ParentMapContext & getParentMapContext()
Returns the dynamic AST node parent map context.
QualType getParenType(QualType NamedType) const
size_t getSideTableAllocatedMemory() const
Return the total memory used for various side tables.
MemberSpecializationInfo * getInstantiatedFromStaticDataMember(const VarDecl *Var)
If this variable is an instantiated static data member of a class template specialization,...
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
CanQualType ARCUnbridgedCastTy
QualType getDependentSizedMatrixType(QualType ElementType, Expr *RowExpr, Expr *ColumnExpr, SourceLocation AttrLoc) const
Return the unique reference to the matrix type of the specified element type and size.
QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr, QualType Wrapped) const
llvm::DenseMap< const Decl *, comments::FullComment * > ParsedComments
Mapping from declarations to parsed comments attached to any redeclaration.
unsigned getManglingNumber(const NamedDecl *ND, bool ForAuxTarget=false) const
CanQualType LongTy
unsigned getIntWidth(QualType T) const
CanQualType getCanonicalParamType(QualType T) const
Return the canonical parameter type corresponding to the specific potentially non-canonical one.
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
TemplateOrSpecializationInfo getTemplateOrSpecializationInfo(const VarDecl *Var)
CanQualType WIntTy
@ Weak
Weak definition of inline variable.
@ WeakUnknown
Weak for now, might become strong later in this TU.
bool dtorHasOperatorDelete(const CXXDestructorDecl *Dtor, OperatorDeleteKind K) const
void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl)
TypedefDecl * getObjCClassDecl() const
Retrieve the typedef declaration corresponding to the predefined Objective-C 'Class' type.
TypedefNameDecl * getTypedefNameForUnnamedTagDecl(const TagDecl *TD)
TypedefDecl * getCFConstantStringDecl() const
CanQualType Int128Ty
CanQualType SatUnsignedFractTy
void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern)
Remember that the using decl Inst is an instantiation of the using decl Pattern of a class template.
bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an RISC-V vector builtin type and a VectorType that is a fixed-len...
ExternCContextDecl * getExternCContextDecl() const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD) const
Parses the target attributes passed in, and returns only the ones that are valid feature names.
QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
TypedefDecl * getObjCSelDecl() const
Retrieve the typedef corresponding to the predefined 'SEL' type in Objective-C.
CanQualType UnsignedShortAccumTy
TypedefDecl * getObjCInstanceTypeDecl()
Retrieve the typedef declaration corresponding to the Objective-C "instancetype" type.
bool isPFPField(const FieldDecl *Field) const
QualType adjustFunctionResultType(QualType FunctionType, QualType NewResultType)
Change the result type of a function type, preserving sugar such as attributed types.
void setTemplateOrSpecializationInfo(VarDecl *Inst, TemplateOrSpecializationInfo TSI)
bool isTypeAwareOperatorNewOrDelete(const FunctionDecl *FD) const
bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, ObjCProtocolDecl *rProto) const
ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the inheritance hierarchy of 'rProto...
TypedefDecl * buildImplicitTypedef(QualType T, StringRef Name) const
Create a new implicit TU-level typedef declaration.
QualType getCanonicalTemplateSpecializationType(ElaboratedTypeKeyword Keyword, TemplateName T, ArrayRef< TemplateArgument > CanonicalArgs) const
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl.
void adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig, ObjCTypeParamDecl *New) const
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
QualType getAutoRRefDeductType() const
C++11 deduction pattern for 'auto &&' type.
TypedefDecl * getBuiltinMSVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_ms_va_list type.
bool ObjCQualifiedIdTypesAreCompatible(const ObjCObjectPointerType *LHS, const ObjCObjectPointerType *RHS, bool ForCompare)
ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an ObjCQualifiedIDType.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool AllowCXX=false, bool IsConditionalOperator=false)
NamedDecl * getInstantiatedFromUsingDecl(NamedDecl *Inst)
If the given using decl Inst is an instantiation of another (possibly unresolved) using decl,...
DeclarationNameTable DeclarationNames
Definition ASTContext.h:812
comments::FullComment * cloneFullComment(comments::FullComment *FC, const Decl *D) const
CharUnits getObjCEncodingTypeSize(QualType T) const
Return the size of type T for Objective-C encoding purpose, in characters.
int getIntegerTypeOrder(QualType LHS, QualType RHS) const
Return the highest ranked integer type, see C99 6.3.1.8p1.
const TemplateArgument * getDefaultTemplateArgumentOrNone(const NamedDecl *P) const
Return the default argument of a template parameter, if one exists.
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType, const Attr *attr=nullptr) const
TypedefDecl * getObjCIdDecl() const
Retrieve the typedef corresponding to the predefined id type in Objective-C.
void setCurrentNamedModule(Module *M)
Set the (C++20) module we are building.
QualType getProcessIDType() const
Return the unique type for "pid_t" defined in <sys/types.h>.
CharUnits getMemberPointerPathAdjustment(const APValue &MP) const
Find the 'this' offset for the member path in a pointer-to-member APValue.
bool mayExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel may be externalized.
std::unique_ptr< MangleNumberingContext > createMangleNumberingContext() const
CanQualType SatAccumTy
ArrayRef< CXXDefaultArgExpr * > getCtorClosureDefaultArgs(const CXXConstructorDecl *CD)
QualType getUnsignedPointerDiffType() const
Return the unique unsigned counterpart of "ptrdiff_t" integer type.
QualType getScalableVectorType(QualType EltTy, unsigned NumElts, unsigned NumFields=1) const
Return the unique reference to a scalable vector type of the specified element type and scalable numb...
bool hasSameExpr(const Expr *X, const Expr *Y) const
Determine whether the given expressions X and Y are equivalent.
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
MangleContext * createMangleContext(const TargetInfo *T=nullptr)
If T is null pointer, assume the target in ASTContext.
RawComment * getRawCommentNoCache(RawCommentLookupKey Key) const
Return the documentation comment attached to a given declaration or macro, without looking into cache...
QualType getRealTypeForBitwidth(unsigned DestWidth, FloatModeKind ExplicitType) const
getRealTypeForBitwidth - sets floating point QualTy according to specified bitwidth.
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
CanQualType ShortAccumTy
ASTMutationListener * getASTMutationListener() const
Retrieve a pointer to the AST mutation listener associated with this AST context, if any.
unsigned NumImplicitCopyAssignmentOperatorsDeclared
The number of implicitly-declared copy assignment operators for which declarations were built.
uint64_t getTargetNullPointerValue(QualType QT) const
Get target-dependent integer value for null pointer which is used for constant folding.
unsigned getTypeUnadjustedAlign(QualType T) const
Return the ABI-specified natural alignment of a (complete) type T, before alignment adjustments,...
unsigned char getFixedPointIBits(QualType Ty) const
QualType getSubstBuiltinTemplatePack(const TemplateArgument &ArgPack)
QualType getCorrespondingSignedFixedPointType(QualType Ty) const
IntrusiveRefCntPtr< ExternalASTSource > ExternalSource
Definition ASTContext.h:813
CanQualType FloatTy
QualType getArrayParameterType(QualType Ty) const
Return the uniqued reference to a specified array parameter type from the original array type.
QualType getCountAttributedType(QualType T, Expr *CountExpr, bool CountInBytes, bool OrNull, ArrayRef< TypeCoupledDeclRefInfo > DependentDecls) const
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
unsigned NumImplicitDestructorsDeclared
The number of implicitly-declared destructors for which declarations were built.
bool mergeExtParameterInfo(const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, bool &CanUseFirst, bool &CanUseSecond, SmallVectorImpl< FunctionProtoType::ExtParameterInfo > &NewParamInfos)
This function merges the ExtParameterInfo lists of two functions.
bool ObjCQualifiedClassTypesAreCompatible(const ObjCObjectPointerType *LHS, const ObjCObjectPointerType *RHS)
ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and Class<pr1, ...>.
bool shouldExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel should be externalized.
bool propertyTypesAreCompatible(QualType, QualType)
void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, UsingShadowDecl *Pattern)
CanQualType DoubleTy
QualType getDependentVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc, VectorKind VecKind) const
Return the unique reference to the type for a dependently sized vector of the specified element type.
CanQualType SatLongAccumTy
CanQualType getIntMaxType() const
Return the unique type for "intmax_t" (C99 7.18.1.5), defined in <stdint.h>.
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
OpenCLTypeKind getOpenCLTypeKind(const Type *T) const
Map an AST Type to an OpenCLTypeKind enum value.
TemplateName getDependentTemplateName(const DependentTemplateStorage &Name) const
Retrieve the template name that represents a dependent template name such as MetaFun::template operat...
ArrayRef< Decl * > getModuleInitializers(Module *M)
Get the initializations to perform when importing a module, if any.
void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, std::string &S) const
Put the string version of the type qualifiers QT into S.
unsigned getPreferredTypeAlign(QualType T) const
Return the "preferred" alignment of the specified type T for the current target, in bits.
std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, bool Extended=false) const
Emit the encoded type for the method declaration Decl into S.
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
CanQualType LongDoubleTy
CanQualType OMPArrayShapingTy
ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents, SelectorTable &sels, Builtin::Context &builtins, TranslationUnitKind TUKind)
QualType getReadPipeType(QualType T) const
Return a read_only pipe type for the specified type.
std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
getObjCEncodingForPropertyDecl - Return the encoded type for this method declaration.
CanQualType Char16Ty
TemplateName getCanonicalTemplateName(TemplateName Name, bool IgnoreDeduced=false) const
Retrieves the "canonical" template name that refers to a given template.
unsigned getStaticLocalNumber(const VarDecl *VD) const
void addComment(const RawComment &RC)
void getLegacyIntegralTypeEncoding(QualType &t) const
getLegacyIntegralTypeEncoding - Another legacy compatibility encoding: 32-bit longs are encoded as 'l...
bool isSameTypeConstraint(const TypeConstraint *XTC, const TypeConstraint *YTC) const
Determine whether two type contraint are similar enough that they could used in declarations of the s...
void setRelocationInfoForCXXRecord(const CXXRecordDecl *, CXXRecordDeclRelocationInfo)
QualType getSubstTemplateTypeParmType(QualType Replacement, Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex, bool Final) const
Retrieve a substitution-result type.
RecordDecl * buildImplicitRecord(StringRef Name, RecordDecl::TagKind TK=RecordDecl::TagKind::Struct) const
Create a new implicit TU-level CXXRecordDecl or RecordDecl declaration.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or nullptr if there isn't on...
CanQualType UnsignedLongFractTy
QualType mergeTagDefinitions(QualType, QualType)
void setClassMaybeNeedsVectorDeletingDestructor(const CXXRecordDecl *RD)
overridden_method_range overridden_methods(const CXXMethodDecl *Method) const
void setIsTypeAwareOperatorNewOrDelete(const FunctionDecl *FD, bool IsTypeAware)
QualType getDependentBitIntType(bool Unsigned, Expr *BitsExpr) const
Return a dependent bit-precise integer type with the specified signedness and bit count.
void setObjCImplementation(ObjCInterfaceDecl *IFaceD, ObjCImplementationDecl *ImplD)
Set the implementation of ObjCInterfaceDecl.
StringRef getCUIDHash() const
bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const
Returns true if this is an inline-initialized static data member which is treated as a definition for...
bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
canAssignObjCInterfaces - Return true if the two interface types are compatible for assignment from R...
CanQualType VoidPtrTy
QualType getReferenceQualifiedType(const Expr *e) const
getReferenceQualifiedType - Given an expr, will return the type for that expression,...
bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const
Determine whether two function types are the same, ignoring exception specifications in cases where t...
QualType getBlockDescriptorExtendedType() const
Gets the struct used to keep track of the extended descriptor for pointer to blocks.
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT, ObjCInterfaceDecl *IDecl)
QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in QT's qualified-id protocol list adopt...
FunctionProtoType::ExceptionSpecInfo mergeExceptionSpecs(FunctionProtoType::ExceptionSpecInfo ESI1, FunctionProtoType::ExceptionSpecInfo ESI2, SmallVectorImpl< QualType > &ExceptionTypeStorage, bool AcceptDependent) const
llvm::PointerUnion< const Decl *, const MacroInfo * > RawCommentLookupKey
Key used to look up the raw comment attached to a declaration or macro.
void addLazyModuleInitializers(Module *M, ArrayRef< GlobalDeclID > IDs)
bool isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const
Determine whether two 'requires' expressions are similar enough that they may be used in re-declarati...
bool BlockRequiresCopying(QualType Ty, const VarDecl *D)
Returns true iff we need copy/dispose helpers for the given type.
CanQualType NullPtrTy
QualType getUsingType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UsingShadowDecl *D, QualType UnderlyingType=QualType()) const
std::optional< QualType > tryMergeOverflowBehaviorTypes(QualType LHS, QualType RHS, bool OfBlockPointer, bool Unqualified, bool BlockReturnType, bool IsConditionalOperator)
Attempts to merge two types that may be OverflowBehaviorTypes.
CanQualType WideCharTy
CanQualType OMPIteratorTy
IdentifierTable & Idents
Definition ASTContext.h:808
Builtin::Context & BuiltinInfo
Definition ASTContext.h:810
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
void addModuleInitializer(Module *M, Decl *Init)
Add a declaration to the list of declarations that are initialized for a module.
const LangOptions & getLangOpts() const
Definition ASTContext.h:965
QualType getFunctionTypeWithoutPtrSizes(QualType T)
Get a function type and produce the equivalent function type where pointer size address spaces in the...
uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID, const ObjCIvarDecl *Ivar) const
Get the offset of an ObjCIvarDecl in bits.
SelectorTable & Selectors
Definition ASTContext.h:809
bool isTypeIgnoredBySanitizer(const SanitizerMask &Mask, const QualType &Ty) const
Check if a type can have its sanitizer instrumentation elided based on its presence within an ignorel...
unsigned getMinGlobalAlignOfVar(uint64_t Size, const VarDecl *VD) const
Return the minimum alignment as specified by the target.
RawCommentList Comments
All comments in this translation unit.
bool isSameDefaultTemplateArgument(const NamedDecl *X, const NamedDecl *Y) const
Determine whether two default template arguments are similar enough that they may be used in declarat...
QualType applyObjCProtocolQualifiers(QualType type, ArrayRef< ObjCProtocolDecl * > protocols, bool &hasError, bool allowOnPointerType=false) const
Apply Objective-C protocol qualifiers to the given type.
QualType getMacroQualifiedType(QualType UnderlyingTy, const IdentifierInfo *MacroII) const
QualType removePtrSizeAddrSpace(QualType T) const
Remove the existing address space on the type if it is a pointer size address space and return the ty...
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
CanQualType SatShortFractTy
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod) const
Retrieves the default calling convention for the current context.
bool canBindObjCObjectType(QualType To, QualType From)
TemplateTemplateParmDecl * insertCanonicalTemplateTemplateParmDeclInternal(TemplateTemplateParmDecl *CanonTTP) const
int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const
Compare the rank of two floating point types as above, but compare equal if both types have the same ...
QualType getUIntPtrType() const
Return a type compatible with "uintptr_t" (C99 7.18.1.4), as defined by the target.
void setParameterIndex(const ParmVarDecl *D, unsigned index)
Used by ParmVarDecl to store on the side the index of the parameter when it exceeds the size of the n...
QualType getFunctionTypeWithExceptionSpec(QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const
Get a function type and produce the equivalent function type with the specified exception specificati...
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier NNS, const IdentifierInfo *Name) const
Qualifiers::GC getObjCGCAttrKind(QualType Ty) const
Return one of the GCNone, Weak or Strong Objective-C garbage collection attributes.
CanQualType Ibm128Ty
bool hasUniqueObjectRepresentations(QualType Ty, bool CheckIfTriviallyCopyable=true) const
Return true if the specified type has unique object representations according to (C++17 [meta....
CanQualType getCanonicalSizeType() const
bool typesAreBlockPointerCompatible(QualType, QualType)
CanQualType SatUnsignedAccumTy
bool useAbbreviatedThunkName(GlobalDecl VirtualMethodDecl, StringRef MangledName)
const ASTRecordLayout & getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const
Get or compute information about the layout of the specified Objective-C interface.
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
void setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst, UsingEnumDecl *Pattern)
Remember that the using enum decl Inst is an instantiation of the using enum decl Pattern of a class ...
QualType getAutoType(DeducedKind DK, QualType DeducedAsType, AutoTypeKeyword Keyword, TemplateDecl *TypeConstraintConcept=nullptr, ArrayRef< TemplateArgument > TypeConstraintArgs={}) const
C++11 deduced auto type.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
llvm::SetVector< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
QualType getSignatureParameterType(QualType T) const
Retrieve the parameter type as adjusted for use in the signature of a function, decaying array and fu...
CanQualType ArraySectionTy
CanQualType ObjCBuiltinIdTy
overridden_cxx_method_iterator overridden_methods_end(const CXXMethodDecl *Method) const
VTableContextBase * getVTableContext()
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>,...
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const
ObjCPropertyImplDecl * getObjCPropertyImplDeclForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
bool isNearlyEmpty(const CXXRecordDecl *RD) const
PointerAuthQualifier getObjCMemberSelTypePtrAuth()
QualType AutoDeductTy
CanQualType BoolTy
void attachCommentsToJustParsedDecls(ArrayRef< Decl * > Decls, const Preprocessor *PP)
Searches existing comments for doc comments that should be attached to Decls.
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth,...
void setStaticLocalNumber(const VarDecl *VD, unsigned Number)
QualType getCFConstantStringType() const
Return the C structure type used to represent constant CFStrings.
void eraseDeclAttrs(const Decl *D)
Erase the attributes corresponding to the given declaration.
UsingEnumDecl * getInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst)
If the given using-enum decl Inst is an instantiation of another using-enum decl, return it.
RecordDecl * getCFConstantStringTagDecl() const
std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const
Emit the encoded type for the function Decl into S.
TypeSourceInfo * getTemplateSpecializationTypeInfo(ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc, TemplateName T, SourceLocation TLoc, const TemplateArgumentListInfo &SpecifiedArgs, ArrayRef< TemplateArgument > CanonicalArgs, QualType Canon=QualType()) const
CanQualType UnsignedFractTy
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
QualType mergeFunctionParameterTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false)
mergeFunctionParameterTypes - merge two types which appear as function parameter types
void addOverriddenMethod(const CXXMethodDecl *Method, const CXXMethodDecl *Overridden)
Note that the given C++ Method overrides the given Overridden method.
TemplateTemplateParmDecl * findCanonicalTemplateTemplateParmDeclInternal(TemplateTemplateParmDecl *TTP) const
const TargetInfo * getAuxTargetInfo() const
Definition ASTContext.h:928
CanQualType Float128Ty
CanQualType ObjCBuiltinClassTy
unsigned NumImplicitDefaultConstructorsDeclared
The number of implicitly-declared default constructors for which declarations were built.
CanQualType UnresolvedTemplateTy
OMPTraitInfo & getNewOMPTraitInfo()
Return a new OMPTraitInfo object owned by this context.
friend class CXXRecordDecl
Definition ASTContext.h:586
CanQualType UnsignedLongTy
void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass, SmallVectorImpl< const ObjCIvarDecl * > &Ivars) const
DeepCollectObjCIvars - This routine first collects all declared, but not synthesized,...
bool computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits, unsigned NumPositiveBits, QualType &BestType, QualType &BestPromotionType)
Compute BestType and BestPromotionType for an enum based on the highest number of negative and positi...
llvm::APFixedPoint getFixedPointMin(QualType Ty) const
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
QualType adjustType(QualType OldType, llvm::function_ref< QualType(QualType)> Adjust) const
Rebuild a type, preserving any existing type sugar.
void addedLocalImportDecl(ImportDecl *Import)
Notify the AST context that a new import declaration has been parsed or implicitly created within thi...
const TranslationUnitKind TUKind
Definition ASTContext.h:811
CanQualType UnsignedLongAccumTy
QualType AutoRRefDeductTy
RawComment * getRawCommentNoCacheImpl(RawCommentLookupKey Key, const SourceLocation RepresentativeLoc, const std::map< unsigned, RawComment * > &CommentsInFile) const
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
CanQualType ShortFractTy
QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const
Return a type for a constant array for a string literal of the specified element type and length.
QualType getCorrespondingSaturatedType(QualType Ty) const
bool arePFPFieldsTriviallyCopyable(const RecordDecl *RD) const
Returns whether this record's PFP fields (if any) are trivially copyable (i.e.
bool isSameEntity(const NamedDecl *X, const NamedDecl *Y) const
Determine whether the two declarations refer to the same entity.
QualType getSubstTemplateTypeParmPackType(Decl *AssociatedDecl, unsigned Index, bool Final, const TemplateArgument &ArgPack)
CanQualType BoundMemberTy
CanQualType SatUnsignedShortFractTy
CanQualType CharTy
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
bool hasSameFunctionTypeIgnoringParamABI(QualType T, QualType U) const
Determine if two function types are the same, ignoring parameter ABI annotations.
TypedefDecl * getInt128Decl() const
Retrieve the declaration for the 128-bit signed integer type.
unsigned getOpenMPDefaultSimdAlign(QualType T) const
Get default simd alignment of the specified complete type in bits.
QualType getObjCSuperType() const
Returns the C struct type for objc_super.
QualType getBlockDescriptorType() const
Gets the struct used to keep track of the descriptor for pointer to blocks.
bool CommentsLoaded
True if comments are already loaded from ExternalASTSource.
BlockVarCopyInit getBlockVarCopyInit(const VarDecl *VD) const
Get the copy initialization expression of the VarDecl VD, or nullptr if none exists.
QualType getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size, uint32_t Alignment, ArrayRef< SpirvOperand > Operands)
unsigned NumImplicitMoveConstructorsDeclared
The number of implicitly-declared move constructors for which declarations were built.
bool isInSameModule(const Module *M1, const Module *M2) const
If the two module M1 and M2 are in the same module.
unsigned NumImplicitCopyConstructorsDeclared
The number of implicitly-declared copy constructors for which declarations were built.
QualType getLeastIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
CanQualType IntTy
CanQualType PseudoObjectTy
QualType getWebAssemblyExternrefType() const
Return a WebAssembly externref type.
void setTraversalScope(const std::vector< Decl * > &)
CharUnits getTypeUnadjustedAlignInChars(QualType T) const
getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a type, in characters,...
QualType getAdjustedType(QualType Orig, QualType New) const
Return the uniqued reference to a type adjusted from the original type to a new type.
friend class NestedNameSpecifier
Definition ASTContext.h:224
void PrintStats() const
MangleContext * cudaNVInitDeviceMC()
unsigned getAlignOfGlobalVar(QualType T, const VarDecl *VD) const
Return the alignment in bits that should be given to a global variable with type T.
bool areCompatibleOverflowBehaviorTypes(QualType LHS, QualType RHS)
Return true if two OverflowBehaviorTypes are compatible for assignment.
TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
comments::FullComment * getLocalCommentForDeclUncached(const Decl *D) const
Return parsed documentation comment attached to a given declaration.
unsigned NumImplicitDestructors
The number of implicitly-declared destructors.
CanQualType Float16Ty
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
bool isAlignmentRequired(const Type *T) const
Determine if the alignment the type has was required using an alignment attribute.
TagDecl * MSGuidTagDecl
bool areComparableObjCPointerTypes(QualType LHS, QualType RHS)
MangleContext * createDeviceMangleContext(const TargetInfo &T)
Creates a device mangle context to correctly mangle lambdas in a mixed architecture compile by settin...
CharUnits getExnObjectAlignment() const
Return the alignment (in bytes) of the thrown exception object.
CanQualType SignedCharTy
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
ASTMutationListener * Listener
Definition ASTContext.h:814
CanQualType ObjCBuiltinBoolTy
TypeInfoChars getTypeInfoInChars(const Type *T) const
QualType getPredefinedSugarType(PredefinedSugarType::Kind KD) const
QualType getObjCObjectType(QualType Base, ObjCProtocolDecl *const *Protocols, unsigned NumProtocols) const
Legacy interface: cannot provide type arguments or __kindof.
TemplateParamObjectDecl * getTemplateParamObjectDecl(QualType T, const APValue &V) const
Return the template parameter object of the given type with the given value.
interp::Context & getInterpContext() const
Returns the clang bytecode interpreter context.
CanQualType OverloadTy
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
TemplateTemplateParmDecl * getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const
Canonicalize the given TemplateTemplateParmDecl.
CanQualType OCLClkEventTy
void adjustExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, bool AsWritten=false)
Change the exception specification on a function once it is delay-parsed, instantiated,...
TypedefDecl * getUInt128Decl() const
Retrieve the declaration for the 128-bit unsigned integer type.
bool hasPFPFields(QualType Ty) const
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:861
void ResetObjCLayout(const ObjCInterfaceDecl *D)
ArrayRef< Module * > getModulesWithMergedDefinition(const NamedDecl *Def)
Get the additional modules in which the definition Def has been merged.
void setCtorClosureDefaultArgs(const CXXConstructorDecl *CD, ArrayRef< CXXDefaultArgExpr * > Args)
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
CanQualType SatUnsignedShortAccumTy
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false, bool IsConditionalOperator=false)
CharUnits getAlignOfGlobalVarInChars(QualType T, const VarDecl *VD) const
Return the alignment in characters that should be given to a global variable with type T.
const ObjCMethodDecl * getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const
Get the duplicate declaration of a ObjCMethod in the same interface, or null if none exists.
QualType getPackIndexingType(QualType Pattern, Expr *IndexExpr, bool FullySubstituted=false, ArrayRef< QualType > Expansions={}, UnsignedOrNone Index=std::nullopt) const
static bool isObjCNSObjectType(QualType Ty)
Return true if this is an NSObject object with its NSObject attribute set.
GVALinkage GetGVALinkageForVariable(const VarDecl *VD) const
llvm::PointerUnion< VarTemplateDecl *, MemberSpecializationInfo * > TemplateOrSpecializationInfo
A type synonym for the TemplateOrInstantiation mapping.
Definition ASTContext.h:578
UsingShadowDecl * getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst)
QualType getVariableArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a non-unique reference to the type for a variable array of the specified element type.
QualType getObjCIdType() const
Represents the Objective-CC id type.
Decl * getVaListTagDecl() const
Retrieve the C type declaration corresponding to the predefined __va_list_tag type used to help defin...
QualType getUnsignedWCharType() const
Return the type of "unsigned wchar_t".
QualType getFunctionTypeWithoutParamABIs(QualType T) const
Get or construct a function type that is equivalent to the input type except that the parameter ABI a...
QualType getCorrespondingUnsaturatedType(QualType Ty) const
comments::FullComment * getCommentForDecl(const Decl *D, const Preprocessor *PP) const
Return parsed documentation comment attached to a given declaration.
TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl) const
unsigned getTargetDefaultAlignForAttributeAligned() const
Return the default alignment for attribute((aligned)) on this target, to be used if no alignment valu...
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
llvm::DenseMap< CanQualType, SYCLKernelInfo > SYCLKernels
Map of SYCL kernels indexed by the unique type used to name the kernel.
bool isSameTemplateParameterList(const TemplateParameterList *X, const TemplateParameterList *Y) const
Determine whether two template parameter lists are similar enough that they may be used in declaratio...
QualType getWritePipeType(QualType T) const
Return a write_only pipe type for the specified type.
QualType getTypeDeclType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypeDecl *Decl) const
bool isDestroyingOperatorDelete(const FunctionDecl *FD) const
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CanQualType UnsignedInt128Ty
CanQualType BuiltinFnTy
ObjCInterfaceDecl * getObjCProtocolDecl() const
Retrieve the Objective-C class declaration corresponding to the predefined Protocol class.
unsigned NumImplicitDefaultConstructors
The number of implicitly-declared default constructors.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
llvm::iterator_range< overridden_cxx_method_iterator > overridden_method_range
unsigned NumImplicitMoveAssignmentOperatorsDeclared
The number of implicitly-declared move assignment operators for which declarations were built.
void setManglingNumber(const NamedDecl *ND, unsigned Number)
CanQualType OCLSamplerTy
TypedefDecl * getBuiltinVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_va_list type.
CanQualType getCanonicalTypeDeclType(const TypeDecl *TD) const
CanQualType VoidTy
QualType getPackExpansionType(QualType Pattern, UnsignedOrNone NumExpansions, bool ExpectPackInType=true) const
Form a pack expansion type with the given pattern.
CanQualType UnsignedCharTy
CanQualType UnsignedShortFractTy
BuiltinTemplateDecl * buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, const IdentifierInfo *II) const
void * Allocate(size_t Size, unsigned Align=8) const
Definition ASTContext.h:882
ArrayRef< ExplicitInstantiationDecl * > getExplicitInstantiationDecls(const NamedDecl *Spec) const
Get all ExplicitInstantiationDecls for a given specialization.
bool canBuiltinBeRedeclared(const FunctionDecl *) const
Return whether a declaration to a builtin is allowed to be overloaded/redeclared.
CanQualType UnsignedIntTy
unsigned NumImplicitMoveConstructors
The number of implicitly-declared move constructors.
QualType getTypedefType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType UnderlyingType=QualType(), std::optional< bool > TypeMatchesDeclOrNone=std::nullopt) const
Return the unique reference to the type for the specified typedef-name decl.
QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl, ArrayRef< ObjCProtocolDecl * > protocols) const
void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, QualType T, std::string &S, bool Extended) const
getObjCEncodingForMethodParameter - Return the encoded type for a single method parameter or return t...
void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD)
unsigned overridden_methods_size(const CXXMethodDecl *Method) const
std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const
Return the encoded type for this block declaration.
QualType getTemplateSpecializationType(ElaboratedTypeKeyword Keyword, TemplateName T, ArrayRef< TemplateArgument > SpecifiedArgs, ArrayRef< TemplateArgument > CanonicalArgs, QualType Underlying=QualType()) const
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
TemplateName getQualifiedTemplateName(NestedNameSpecifier Qualifier, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
bool isSameAssociatedConstraint(const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const
Determine whether two 'requires' expressions are similar enough that they may be used in re-declarati...
QualType getExceptionObjectType(QualType T) const
CanQualType UnknownAnyTy
void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
Note that the static data member Inst is an instantiation of the static data member template Tmpl of ...
FieldDecl * getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const
DeclaratorDecl * getDeclaratorForUnnamedTagDecl(const TagDecl *TD)
bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl)
ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's protocol list adopt all protocols in Q...
CanQualType UnsignedLongLongTy
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
CanQualType OCLReserveIDTy
bool isSameTemplateParameter(const NamedDecl *X, const NamedDecl *Y) const
Determine whether two template parameters are similar enough that they may be used in declarations of...
void registerSYCLEntryPointFunction(FunctionDecl *FD)
Generates and stores SYCL kernel metadata for the provided SYCL kernel entry point function.
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
overridden_cxx_method_iterator overridden_methods_begin(const CXXMethodDecl *Method) const
CanQualType UnsignedShortTy
FunctionDecl * getOperatorDeleteForVDtor(const CXXDestructorDecl *Dtor, OperatorDeleteKind K) const
unsigned getTypeAlignIfKnown(QualType T, bool NeedsPreferredAlignment=false) const
Return the alignment of a type, in bits, or 0 if the type is incomplete and we cannot determine the a...
void UnwrapSimilarArrayTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true) const
Attempt to unwrap two types that may both be array types with the same bound (or both be array types ...
bool isRepresentableIntegerValue(llvm::APSInt &Value, QualType T)
Determine whether the given integral value is representable within the given type T.
bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
llvm::DenseMap< RawCommentLookupKey, const RawComment * > RawComments
Mapping from declaration or macro to directly attached comment.
const SYCLKernelInfo & getSYCLKernelInfo(QualType T) const
Given a type used as a SYCL kernel name, returns a reference to the metadata generated from the corre...
bool canAssignObjCInterfacesInBlockPointer(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT, bool BlockReturnType)
canAssignObjCInterfacesInBlockPointer - This routine is specifically written for providing type-safet...
CanQualType SatUnsignedLongFractTy
QualType getMemberPointerType(QualType T, NestedNameSpecifier Qualifier, const CXXRecordDecl *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
const CXXConstructorDecl * getCopyConstructorForExceptionObject(CXXRecordDecl *RD)
QualType getDependentAddressSpaceType(QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttrLoc) const
QualType getTagType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TagDecl *TD, bool OwnsTag) const
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
CanQualType getMSGuidType() const
Retrieve the implicitly-predeclared 'struct _GUID' type.
const VariableArrayType * getAsVariableArrayType(QualType T) const
QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType, UnaryTransformType::UTTKind UKind) const
Unary type transforms.
void setExternalSource(IntrusiveRefCntPtr< ExternalASTSource > Source)
Attach an external AST source to the AST context.
const ObjCInterfaceDecl * getObjContainingInterface(const NamedDecl *ND) const
Returns the Objective-C interface that ND belongs to if it is an Objective-C method/property/ivar etc...
CanQualType ShortTy
StringLiteral * getPredefinedStringLiteralFromCache(StringRef Key) const
Return a string representing the human readable name for the specified function declaration or file n...
CanQualType getCanonicalUnresolvedUsingType(const UnresolvedUsingTypenameDecl *D) const
bool hasSimilarType(QualType T1, QualType T2) const
Determine if two types are similar, according to the C++ rules.
llvm::APFixedPoint getFixedPointMax(QualType Ty) const
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type.
bool classMaybeNeedsVectorDeletingDestructor(const CXXRecordDecl *RD)
QualType getTemplateTypeParmType(int Depth, int Index, bool ParameterPack, TemplateTypeParmDecl *ParmDecl=nullptr) const
Retrieve the template type parameter type for a template parameter or parameter pack with the given d...
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
CanQualType FractTy
Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const
Recurses in pointer/array types until it finds an Objective-C retainable type and returns its ownersh...
void addCopyConstructorForExceptionObject(CXXRecordDecl *RD, CXXConstructorDecl *CD)
void deduplicateMergedDefinitionsFor(NamedDecl *ND)
Clean up the merged definition list.
DiagnosticsEngine & getDiagnostics() const
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
CanQualType LongAccumTy
CanQualType Char32Ty
void recordOffsetOfEvaluation(const OffsetOfExpr *E)
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
UnnamedGlobalConstantDecl * getUnnamedGlobalConstantDecl(QualType Ty, const APValue &Value) const
Return a declaration for a uniquified anonymous global constant corresponding to a given APValue.
CanQualType SatFractTy
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
QualType getUnresolvedUsingType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UnresolvedUsingTypenameDecl *D) const
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec)
Return true if the given vector types are of the same unqualified type or if they are equivalent to t...
void getOverriddenMethods(const NamedDecl *Method, SmallVectorImpl< const NamedDecl * > &Overridden) const
Return C++ or ObjC overridden methods for the given Method.
DeclarationNameInfo getNameForTemplate(TemplateName Name, SourceLocation NameLoc) const
bool hasSameTemplateName(const TemplateName &X, const TemplateName &Y, bool IgnoreDeduced=false) const
Determine whether the given template names refer to the same template.
CanQualType SatLongFractTy
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:927
void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl)
CanQualType OCLQueueTy
CanQualType LongFractTy
OBTAssignResult checkOBTAssignmentCompatibility(QualType LHS, QualType RHS)
Check overflow behavior type compatibility for assignments.
CanQualType SatShortAccumTy
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CanQualType BFloat16Ty
unsigned NumImplicitCopyConstructors
The number of implicitly-declared copy constructors.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
void addExplicitInstantiationDecl(const NamedDecl *Spec, ExplicitInstantiationDecl *EID)
Add an ExplicitInstantiationDecl for a given specialization.
QualType getOverflowBehaviorType(const OverflowBehaviorAttr *Attr, QualType Wrapped) const
CanQualType IncompleteMatrixIdxTy
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
CanQualType getNSIntegerType() const
QualType getCorrespondingUnsignedType(QualType T) const
void setBlockVarCopyInit(const VarDecl *VD, Expr *CopyExpr, bool CanThrow)
Set the copy initialization expression of a block var decl.
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const
Retrieve the template name that corresponds to a non-empty lookup.
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
TemplateName getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack, Decl *AssociatedDecl, unsigned Index, bool Final) const
TargetCXXABI::Kind getCXXABIKind() const
Return the C++ ABI kind that should be used.
QualType getHLSLAttributedResourceType(QualType Wrapped, QualType Contained, const HLSLAttributedResourceType::Attributes &Attrs)
bool UnwrapSimilarTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true) const
Attempt to unwrap two types that may be similar (C++ [conv.qual]).
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
QualType getSignedSizeType() const
Return the unique signed counterpart of the integer type corresponding to size_t.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const
Return number of constant array elements.
CanQualType SatUnsignedLongAccumTy
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
CanQualType LongLongTy
CanQualType getCanonicalTagType(const TagDecl *TD) const
bool isSameTemplateArgument(const TemplateArgument &Arg1, const TemplateArgument &Arg2) const
Determine whether the given template arguments Arg1 and Arg2 are equivalent.
QualType getTypeOfType(QualType QT, TypeOfKind Kind) const
getTypeOfType - Unlike many "get<Type>" functions, we don't unique TypeOfType nodes.
QualType getCorrespondingSignedType(QualType T) const
QualType mergeObjCGCQualifiers(QualType, QualType)
mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 'RHS' attributes and ret...
llvm::DenseMap< const Decl *, const Decl * > CommentlessRedeclChains
Keeps track of redeclaration chains that don't have any comment attached.
uint64_t getArrayInitLoopExprElementCount(const ArrayInitLoopExpr *AILE) const
Return number of elements initialized in an ArrayInitLoopExpr.
unsigned getTargetAddressSpace(LangAS AS) const
std::vector< PFPField > findPFPFields(QualType Ty) const
Returns a list of PFP fields for the given type, including subfields in bases or other fields,...
QualType getIntPtrType() const
Return a type compatible with "intptr_t" (C99 7.18.1.4), as defined by the target.
void mergeDefinitionIntoModule(NamedDecl *ND, Module *M, bool NotifyListeners=true)
Note that the definition ND has been merged into module M, and should be visible whenever M is visibl...
QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a non-unique reference to the type for a dependently-sized array of the specified element type...
void addTranslationUnitDecl()
CanQualType WCharTy
void getObjCEncodingForPropertyType(QualType T, std::string &S) const
Emit the Objective-C property type encoding for the given type T into S.
unsigned NumImplicitCopyAssignmentOperators
The number of implicitly-declared copy assignment operators.
void CollectInheritedProtocols(const Decl *CDecl, llvm::SmallPtrSet< ObjCProtocolDecl *, 8 > &Protocols)
CollectInheritedProtocols - Collect all protocols in current class and those inherited by it.
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
llvm::DenseMap< const Decl *, const Decl * > RedeclChainComments
Mapping from canonical declaration to the first redeclaration in chain that has a comment attached.
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const
Return the uniqued reference to the type for an Objective-C gc-qualified type.
QualType getDecltypeType(Expr *e, QualType UnderlyingType) const
C++11 decltype.
std::optional< CXXRecordDeclRelocationInfo > getRelocationInfoForCXXRecord(const CXXRecordDecl *) const
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
InlineVariableDefinitionKind getInlineVariableDefinitionKind(const VarDecl *VD) const
Determine whether a definition of this inline variable should be treated as a weak or strong definiti...
const RawComment * getRawCommentForAnyRedecl(RawCommentLookupKey Key, const Decl **OriginalDecl=nullptr) const
Return the documentation comment attached to a given declaration or macro.
TemplateName getSubstTemplateTemplateParm(TemplateName replacement, Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex, bool Final) const
CanQualType getUIntMaxType() const
Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in <stdint.h>.
friend class DeclContext
uint16_t getPointerAuthVTablePointerDiscriminator(const CXXRecordDecl *RD)
Return the "other" discriminator used for the pointer auth schema used for vtable pointers in instanc...
CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const
Loading virtual member pointers using the virtual inheritance model always results in an adjustment u...
LangAS getLangASForBuiltinAddressSpace(unsigned AS) const
bool hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U)
Determine whether two function types are the same, ignoring pointer sizes in the return type and para...
void addOperatorDeleteForVDtor(const CXXDestructorDecl *Dtor, FunctionDecl *OperatorDelete, OperatorDeleteKind K) const
unsigned char getFixedPointScale(QualType Ty) const
QualType getIncompleteArrayType(QualType EltTy, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a unique reference to the type for an incomplete array of the specified element type.
QualType getDependentSizedExtVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc) const
QualType DecodeTypeStr(const char *&Str, const ASTContext &Context, ASTContext::GetBuiltinTypeError &Error, bool &RequireICE, bool AllowTypeModifiers) const
TemplateName getAssumedTemplateName(DeclarationName Name) const
Retrieve a template name representing an unqualified-id that has been assumed to name a template for ...
@ GE_None
No error.
@ GE_Missing_type
Missing a type.
QualType adjustStringLiteralBaseType(QualType StrLTy) const
uint16_t getPointerAuthTypeDiscriminator(QualType T)
Return the "other" type-specific discriminator for the given type.
llvm::SetVector< const FieldDecl * > PFPFieldsWithEvaluatedOffset
bool canonicalizeTemplateArguments(MutableArrayRef< TemplateArgument > Args) const
Canonicalize the given template argument list.
QualType getTypeOfExprType(Expr *E, TypeOfKind Kind) const
C23 feature and GCC extension.
CanQualType Char8Ty
bool isUnaryOverflowPatternExcluded(const UnaryOperator *UO)
QualType getSignedWCharType() const
Return the type of "signed wchar_t".
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
bool hasCvrSimilarType(QualType T1, QualType T2)
Determine if two types are similar, ignoring only CVR qualifiers.
TemplateName getDeducedTemplateName(TemplateName Underlying, DefaultArguments DefaultArgs) const
Represents a TemplateName which had some of its default arguments deduced.
ObjCImplementationDecl * getObjCImplementation(ObjCInterfaceDecl *D)
Get the implementation of the ObjCInterfaceDecl D, or nullptr if none exists.
CanQualType HalfTy
CanQualType UnsignedAccumTy
void setObjCMethodRedeclaration(const ObjCMethodDecl *MD, const ObjCMethodDecl *Redecl)
void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND)
QualType getConstantMatrixType(QualType ElementType, unsigned NumRows, unsigned NumColumns) const
Return the unique reference to the matrix type of the specified element type and size.
const CXXRecordDecl * baseForVTableAuthentication(const CXXRecordDecl *ThisClass) const
Resolve the root record to be used to derive the vtable pointer authentication policy for the specifi...
void cacheRawComment(RawCommentLookupKey Original, const RawComment &Comment) const
Attaches Comment to Original (a declaration or macro), and to its redeclaration chain when Original i...
QualType getVariableArrayDecayedType(QualType Ty) const
Returns a vla type where known sizes are replaced with [*].
void setCFConstantStringType(QualType T)
const SYCLKernelInfo * findSYCLKernelInfo(QualType T) const
Returns a pointer to the metadata generated from the corresponding SYCLkernel entry point if the prov...
unsigned getParameterIndex(const ParmVarDecl *D) const
Used by ParmVarDecl to retrieve on the side the index of the parameter when it exceeds the size of th...
QualType getCommonSugaredType(QualType X, QualType Y, bool Unqualified=false) const
CanQualType OCLEventTy
void AddDeallocation(void(*Callback)(void *), void *Data) const
Add a deallocation callback that will be invoked when the ASTContext is destroyed.
AttrVec & getDeclAttrs(const Decl *D)
Retrieve the attributes for the given declaration.
QualType getDeducedTemplateSpecializationType(DeducedKind DK, QualType DeducedAsType, ElaboratedTypeKeyword Keyword, TemplateName Template) const
C++17 deduced class template specialization type.
CXXMethodVector::const_iterator overridden_cxx_method_iterator
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
QualType mergeTransparentUnionType(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false)
mergeTransparentUnionType - if T is a transparent union type and a member of T is compatible with Sub...
QualType isPromotableBitField(Expr *E) const
Whether this is a promotable bitfield reference according to C99 6.3.1.1p2, bullet 2 (and GCC extensi...
bool isSentinelNullExpr(const Expr *E)
CanQualType getNSUIntegerType() const
void setIsDestroyingOperatorDelete(const FunctionDecl *FD, bool IsDestroying)
TypedefDecl * getBuiltinZOSVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_zos_va_list type.
void recordMemberDataPointerEvaluation(const ValueDecl *VD)
uint64_t getCharWidth() const
Return the size of the character type, in bits.
QualType getBitIntType(bool Unsigned, unsigned NumBits) const
Return a bit-precise integer type with the specified signedness and bit count.
unsigned NumImplicitMoveAssignmentOperators
The number of implicitly-declared move assignment operators.
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
virtual void DeducedReturnType(const FunctionDecl *FD, QualType ReturnType)
A function's return type has been deduced.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
CharUnits getAlignment() const
getAlignment - Get the record alignment in characters.
const CXXRecordDecl * getBaseSharingVBPtr() const
CharUnits getSize() const
getSize - Get the record size in characters.
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
CharUnits getDataSize() const
getDataSize() - Get the record data size, which is the record size without tail padding,...
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getNonVirtualSize() const
getNonVirtualSize - Get the non-virtual size (in chars) of an object, which is the size of the object...
CharUnits getUnadjustedAlignment() const
getUnadjustedAlignment - Get the record alignment in characters, before alignment adjustment.
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition TypeBase.h:3553
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3574
Represents a loop initializing the elements of an array.
Definition Expr.h:5980
llvm::APInt getArraySize() const
Definition Expr.h:6002
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:6000
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition TypeBase.h:3956
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3786
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3800
Qualifiers getIndexTypeQualifiers() const
Definition TypeBase.h:3804
QualType getElementType() const
Definition TypeBase.h:3798
unsigned getIndexTypeCVRQualifiers() const
Definition TypeBase.h:3808
A structure for storing the information associated with a name that has been assumed to be a template...
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition Expr.h:6940
Expr * getPtr() const
Definition Expr.h:6971
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8251
Attr - This represents one attribute.
Definition Attr.h:46
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8299
void Profile(llvm::FoldingSetNodeID &ID) const
Definition TypeBase.h:8316
unsigned getNumBits() const
Definition TypeBase.h:8311
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4714
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6684
Pointer to a block type.
Definition TypeBase.h:3606
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3623
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:3228
Kind getKind() const
Definition TypeBase.h:3276
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition Builtins.h:236
Implements C++ ABI-specific semantic analysis functions.
Definition CXXABI.h:29
virtual ~CXXABI()
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents a C++ constructor within a class.
Definition DeclCXX.h:2633
Represents a C++ destructor within a class.
Definition DeclCXX.h:2898
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2145
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2254
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr)
Definition DeclCXX.cpp:133
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:548
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1219
bool isDynamicClass() const
Definition DeclCXX.h:574
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1191
SplitQualType split() const
static CanQual< Type > CreateUnsafe(QualType Other)
QualType withConst() const
Retrieves a version of this type with const applied.
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
Qualifiers getQualifiers() const
Retrieve all qualifiers.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isPositive() const
isPositive - Test whether the quantity is greater than zero.
Definition CharUnits.h:128
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition CharUnits.h:53
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3339
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3354
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:3824
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition TypeBase.h:3920
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3880
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition TypeBase.h:3939
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3900
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4451
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4470
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4516
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4467
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition TypeBase.h:3500
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3536
Represents a pointer type decayed from an array or function type.
Definition TypeBase.h:3589
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1466
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
bool isFileContext() const
Definition DeclBase.h:2197
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2142
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void addDecl(Decl *D)
Add the declaration D into this context.
Decl::Kind getDeclKind() const
Definition DeclBase.h:2119
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1276
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
const DeclContext * getParentFunctionOrMethod(bool LexicalParent=false) const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext,...
Definition DeclBase.cpp: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:871
static Decl * castFromDeclContext(const DeclContext *)
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp:308
bool isCanonicalDecl() const
Whether this particular Decl is a canonical one.
Definition DeclBase.h:1001
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:854
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
ObjCDeclQualifier
ObjCDeclQualifier - 'Qualifiers' written next to the return and parameter types in method declaration...
Definition DeclBase.h:198
bool isInvalidDecl() const
Definition DeclBase.h:596
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:567
void setImplicit(bool I=true)
Definition DeclBase.h:602
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition DeclBase.h:1066
DeclContext * getDeclContext()
Definition DeclBase.h:456
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition DeclBase.cpp:382
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:935
bool hasAttr() const
Definition DeclBase.h:585
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:995
Kind getKind() const
Definition DeclBase.h:450
DeclarationNameLoc - Additional source/type location info for a declaration name.
static DeclarationNameLoc makeCXXOperatorNameLoc(SourceLocation BeginLoc, SourceLocation EndLoc)
Construct location information for a non-literal C++ operator.
The name of a declaration.
static int compare(DeclarationName LHS, DeclarationName RHS)
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:780
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
TemplateName getUnderlying() const
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) const
DefaultArguments getDefaultArguments() const
Represents an extended address space qualifier where the input address space value is dependent.
Definition TypeBase.h:4125
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4147
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:8344
Represents an array type in C++ whose size is a value-dependent expression.
Definition TypeBase.h:4075
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4104
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4165
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4190
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4537
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4557
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:6316
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:6321
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4291
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4316
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:234
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
A dynamically typed AST node container.
Represents an enum.
Definition Decl.h:4053
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4271
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4285
EnumDecl * getDefinitionOrSelf() const
Definition Decl.h:4169
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4226
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:3104
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:4238
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:837
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition Expr.h:223
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3079
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:4077
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:4331
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:5546
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:3202
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3305
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4750
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3287
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3438
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:4698
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:2027
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2727
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3740
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2959
bool isMSExternInline() const
The combination of the extern and inline keywords under MSVC forces the function to be required.
Definition Decl.cpp:3869
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3725
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition Decl.h:2316
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4395
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition Decl.h:2444
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:4056
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5339
static FunctionEffectSet getIntersection(FunctionEffectsRef LHS, FunctionEffectsRef RHS)
Definition Type.cpp:5858
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition Type.cpp:5896
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5171
ArrayRef< EffectConditionExpr > conditions() const
Definition TypeBase.h:5205
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:4949
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4965
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5371
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5875
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5678
unsigned getNumParams() const
Definition TypeBase.h:5649
QualType getParamType(unsigned i) const
Definition TypeBase.h:5651
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition Type.cpp:4086
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5684
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5775
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5660
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5656
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition TypeBase.h:5844
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition TypeBase.h:5840
Declaration of a template function.
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4678
CallingConv getCC() const
Definition TypeBase.h:4737
unsigned getRegParm() const
Definition TypeBase.h:4730
bool getNoCallerSavedRegs() const
Definition TypeBase.h:4726
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4749
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition TypeBase.h:4593
ExtParameterInfo withIsNoEscape(bool NoEscape) const
Definition TypeBase.h:4633
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4567
ExtInfo getExtInfo() const
Definition TypeBase.h:4923
QualType getReturnType() const
Definition TypeBase.h:4907
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:5095
Represents a C array with an unspecified size.
Definition TypeBase.h:3973
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3990
static ItaniumMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3681
@ 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:4419
static void Profile(llvm::FoldingSetNodeID &ID, Parts P)
Definition DeclCXX.h:4456
MSGuidDeclParts Parts
Definition DeclCXX.h:4421
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition TypeBase.h:6250
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:4422
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4415
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3717
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3760
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:3372
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:8009
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:8065
bool isObjCQualifiedClassType() const
True if this is equivalent to 'Class.
Definition TypeBase.h:8146
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:8140
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8222
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8102
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:8123
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8077
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:8117
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:8184
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition TypeBase.h:8129
Represents one property declaration in an Objective-C interface.
Definition DeclObjC.h:731
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
Definition DeclObjC.h:838
static ObjCPropertyDecl * findPropertyDecl(const DeclContext *DC, const IdentifierInfo *propertyID, ObjCPropertyQueryKind queryKind)
Lookup a property by name in the specified DeclContext.
Definition DeclObjC.cpp:176
bool isOptional() const
Definition DeclObjC.h:916
SetterKind getSetterKind() const
getSetterKind - Return the method used for doing assignment in the property setter.
Definition DeclObjC.h:873
Selector getSetterName() const
Definition DeclObjC.h:893
QualType getType() const
Definition DeclObjC.h:804
Selector getGetterName() const
Definition DeclObjC.h:885
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition DeclObjC.h:815
ObjCPropertyImplDecl - Represents implementation declaration of a property in a class or category imp...
Definition DeclObjC.h:2805
ObjCIvarDecl * getPropertyIvarDecl() const
Definition DeclObjC.h:2879
Represents an Objective-C protocol declaration.
Definition DeclObjC.h:2084
protocol_range protocols() const
Definition DeclObjC.h:2161
bool isGNUFamily() const
Is this runtime basically of the GNU family of runtimes?
Represents the declaration of an Objective-C type parameter.
Definition DeclObjC.h:578
ObjCTypeParamVariance getVariance() const
Determine the variance of this type parameter.
Definition DeclObjC.h:623
Stores a list of Objective-C type parameters for a parameterized class or a category/extension thereo...
Definition DeclObjC.h:662
OffsetOfExpr - [C99 7.17] - This represents an expression of the form offsetof(record-type,...
Definition Expr.h:2533
const OffsetOfNode & getComponent(unsigned Idx) const
Definition Expr.h:2580
unsigned getNumComponents() const
Definition Expr.h:2588
Helper class for OffsetOfExpr.
Definition Expr.h:2427
@ Field
A field.
Definition Expr.h:2434
A structure for storing the information associated with an overloaded template name.
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition ExprCXX.h:4363
Sugar for parentheses used when specifying types.
Definition TypeBase.h:3366
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3380
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:1817
ObjCDeclQualifier getObjCDeclQualifier() const
Definition Decl.h:1881
QualType getOriginalType() const
Definition Decl.cpp:2943
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8282
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:3392
QualType getPointeeType() const
Definition TypeBase.h:3402
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3407
PredefinedSugarKind Kind
Definition TypeBase.h:8358
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:8531
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2970
Qualifiers::GC getObjCGCAttr() const
Returns gc attribute of this type.
Definition TypeBase.h:8578
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8536
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:8447
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8573
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8487
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1453
QualType getCanonicalType() const
Definition TypeBase.h:8499
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8541
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition TypeBase.h:8468
QualType getNonPackExpansionType() const
Remove an outer pack expansion type (if any) from this type.
Definition Type.cpp:3679
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8520
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:8504
const Type * getTypePtrOrNull() const
Definition TypeBase.h:8451
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:3113
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8479
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:8387
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8394
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:3699
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:4367
bool isLambda() const
Determine whether this record is a class describing a lambda function object.
Definition Decl.cpp:5244
bool hasFlexibleArrayMember() const
Definition Decl.h:4400
field_range fields() const
Definition Decl.h:4570
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition Decl.cpp:5230
RecordDecl * getMostRecentDecl()
Definition Decl.h:4393
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition Decl.cpp:5289
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4551
bool field_empty() const
Definition Decl.h:4578
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:3637
QualType getPointeeType() const
Definition TypeBase.h:3655
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3663
This table allows us to fully hide how we implement multi-keyword caching.
std::string getAsString() const
Derive the full selector name (e.g.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
The streaming interface shared between DiagnosticBuilder and PartialDiagnostic.
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1805
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, ArrayRef< SourceLocation > Locs)
This is the "fully general" constructor that allows representation of strings formed from one or more...
Definition Expr.cpp:1194
A structure for storing an already-substituted template template parameter pack.
Decl * getAssociatedDecl() const
A template-like entity which owns the whole pattern being substituted.
void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context)
TemplateTemplateParmDecl * getParameterPack() const
Retrieve the template template parameter pack being substituted.
TemplateArgument getArgumentPack() const
Retrieve the template template argument pack with which this parameter was substituted.
unsigned getIndex() const
Returns the index of the replaced parameter in the associated declaration.
A structure for storing the information associated with a substituted template template parameter.
void Profile(llvm::FoldingSetNodeID &ID)
TemplateTemplateParmDecl * getParameter() const
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3759
TagTypeKind TagKind
Definition Decl.h:3764
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition Decl.h:3996
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4904
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4897
bool isUnion() const
Definition Decl.h:3970
TagKind getTagKind() const
Definition Decl.h:3959
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Kind
The basic C++ ABI kind.
static Kind getKind(StringRef Name)
Exposes information about the current target.
Definition TargetInfo.h:227
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
unsigned getMaxAtomicInlineWidth() const
Return the maximum width lock-free atomic operation which can be inlined given the supported features...
Definition TargetInfo.h:862
virtual LangAS getCUDABuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
virtual LangAS getOpenCLBuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
unsigned getDefaultAlignForAttributeAligned() const
Return the default alignment for attribute((aligned)) on this target, to be used if no alignment valu...
Definition TargetInfo.h:755
BuiltinVaListKind
The different kinds of __builtin_va_list types defined by the target implementation.
Definition TargetInfo.h:337
@ AArch64ABIBuiltinVaList
__builtin_va_list as defined by the AArch64 ABI http://infocenter.arm.com/help/topic/com....
Definition TargetInfo.h:346
@ PowerABIBuiltinVaList
__builtin_va_list as defined by the Power ABI: https://www.power.org /resources/downloads/Power-Arch-...
Definition TargetInfo.h:351
@ AAPCSABIBuiltinVaList
__builtin_va_list as defined by ARM AAPCS ABI http://infocenter.arm.com
Definition TargetInfo.h:360
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition TargetInfo.h:339
@ VoidPtrBuiltinVaList
typedef void* __builtin_va_list;
Definition TargetInfo.h:342
@ X86_64ABIBuiltinVaList
__builtin_va_list as defined by the x86-64 ABI: http://refspecs.linuxbase.org/elf/x86_64-abi-0....
Definition TargetInfo.h:355
virtual uint64_t getNullPointerValue(LangAS AddrSpace) const
Get integer value for null pointer.
Definition TargetInfo.h:509
static bool isTypeSigned(IntType T)
Returns true if the type is signed; false otherwise.
IntType getPtrDiffType(LangAS AddrSpace) const
Definition TargetInfo.h:411
IntType getSizeType() const
Definition TargetInfo.h:392
FloatModeKind getRealTypeByWidth(unsigned BitWidth, FloatModeKind ExplicitType) const
Return floating point type with specified width.
virtual IntType getIntTypeByWidth(unsigned BitWidth, bool IsSigned) const
Return integer type with specified width.
unsigned getMaxAlignedAttribute() const
Get the maximum alignment in bits for a static variable with aligned attribute.
Definition TargetInfo.h:982
virtual unsigned getMinGlobalAlign(uint64_t Size, bool HasNonWeakDef) const
getMinGlobalAlign - Return the minimum alignment of a global variable, unless its alignment is explic...
Definition TargetInfo.h:763
unsigned getTargetAddressSpace(LangAS AS) const
IntType getSignedSizeType() const
Definition TargetInfo.h:393
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
bool useAddressSpaceMapMangling() const
Specify if mangling based on address space map should be used or not for language specific address sp...
A convenient class for passing around template argument information.
ArrayRef< TemplateArgumentLoc > arguments() const
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Location wrapper for a TemplateArgument.
Represents a template argument.
ArrayRef< TemplateArgument > getPackAsArray() const
Return the array of arguments in this template argument pack.
QualType getStructuralValueType() const
Get the type of a StructuralValue.
QualType getParamTypeForDecl() const
Expr * getAsExpr() const
Retrieve the template argument as an expression.
UnsignedOrNone getNumTemplateExpansions() const
Retrieve the number of expansions that a template template argument expansion will produce,...
QualType getAsType() const
Retrieve the type for a type template argument.
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
static TemplateArgument CreatePackCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument pack by copying the given set of template arguments.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
bool structurallyEquals(const TemplateArgument &Other) const
Determines whether two template arguments are superficially the same.
QualType getIntegralType() const
Retrieve the type of the integral value.
bool getIsDefaulted() const
If returns 'true', this TemplateArgument corresponds to a default template parameter.
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
ArrayRef< TemplateArgument > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
@ Template
The template argument is a template name that was provided for a template template parameter.
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
@ Pack
The template argument is actually a parameter pack.
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
@ Type
The template argument is a type.
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
ArgKind getKind() const
Return the kind of stored template argument.
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
The base class of all kinds of template declarations (e.g., class, function, etc.).
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
DeducedTemplateStorage * getAsDeducedTemplateName() const
Retrieve the deduced template info, if any.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
std::optional< TemplateName > desugar(bool IgnoreDeduced) const
OverloadedTemplateStorage * getAsOverloadedTemplate() const
Retrieve the underlying, overloaded function template declarations that this template name refers to,...
AssumedTemplateStorage * getAsAssumedTemplateName() const
Retrieve information on a name that has been assumed to be a template-name in order to permit a call ...
NameKind getKind() const
void * getAsVoidPointer() const
Retrieve the template name as a void pointer.
@ UsingTemplate
A template name that refers to a template declaration found through a specific using shadow declarati...
@ OverloadedTemplate
A set of overloaded template declarations.
@ Template
A single template declaration.
@ DependentTemplate
A dependent template name that has not been resolved to a template (or set of templates).
@ SubstTemplateTemplateParm
A template template parameter that has been substituted for some other template name.
@ SubstTemplateTemplateParmPack
A template template parameter pack that has been substituted for a template template argument pack,...
@ DeducedTemplate
A template name that refers to another TemplateName with deduced default arguments.
@ QualifiedTemplate
A qualified template name, where the qualification is kept to describe the source code as written.
@ AssumedTemplate
An unqualified-id that has been assumed to name a function template that will be found by ADL.
UsingShadowDecl * getAsUsingShadowDecl() const
Retrieve the using shadow declaration through which the underlying template declaration is introduced...
SubstTemplateTemplateParmPackStorage * getAsSubstTemplateTemplateParmPack() const
Retrieve the substituted template template parameter pack, if known.
SubstTemplateTemplateParmStorage * getAsSubstTemplateTemplateParm() const
Retrieve the substituted template template parameter, if known.
A template parameter object.
static void Profile(llvm::FoldingSetNodeID &ID, QualType T, const APValue &V)
Stores a list of template parameters for a TemplateDecl and its derived classes.
NamedDecl * getParam(unsigned Idx)
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
NamedDecl *const * const_iterator
Iterates through the template parameters in this list.
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
ArrayRef< NamedDecl * > asArray()
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
TemplateNameKind templateParameterKind() const
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
bool isParameterPack() const
Whether this template template parameter is a template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, int D, int P, bool ParameterPack, IdentifierInfo *Id, TemplateNameKind ParameterKind, bool Typename, TemplateParameterList *Params)
unsigned getDepth() const
Get the nesting depth of the template parameter.
Declaration of a template type parameter.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, int D, int P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, UnsignedOrNone NumExpanded=std::nullopt)
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition ASTConcept.h:227
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition ASTConcept.h:244
TemplateDecl * getNamedConcept() const
Definition ASTConcept.h:254
ConceptReference * getConceptReference() const
Definition ASTConcept.h:248
Represents a declaration of a type.
Definition Decl.h:3555
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:6282
A container of type source information.
Definition TypeBase.h:8418
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:8704
bool isVoidType() const
Definition TypeBase.h:9050
bool isObjCBuiltinType() const
Definition TypeBase.h:8914
QualType getRVVEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an RVV builtin type.
Definition Type.cpp:2775
bool isIncompleteArrayType() const
Definition TypeBase.h:8791
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2270
bool isFloat16Type() const
Definition TypeBase.h:9059
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:8787
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2521
bool isArrayType() const
Definition TypeBase.h:8783
bool isCharType() const
Definition Type.cpp:2197
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:8684
TagDecl * castAsTagDecl() const
Definition Type.h:69
bool isArrayParameterType() const
Definition TypeBase.h:8799
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9094
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9344
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:9138
bool isEnumeralType() const
Definition TypeBase.h:8815
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8884
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:9172
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2963
bool isBitIntType() const
Definition TypeBase.h:8959
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8807
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2846
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9110
bool isHalfType() const
Definition TypeBase.h:9054
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9126
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:3183
@ 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:8896
bool isOverflowBehaviorType() const
Definition TypeBase.h:8855
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:9134
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9330
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2531
bool isFunctionType() const
Definition TypeBase.h:8680
bool isObjCObjectPointerType() const
Definition TypeBase.h:8863
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:9152
bool isVectorType() const
Definition TypeBase.h:8823
bool isObjCClassType() const
Definition TypeBase.h:8902
bool isRVVVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'riscv_rvv_vector_bits' type attribute,...
Definition Type.cpp:2757
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2692
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2985
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition Type.cpp:2336
bool isAnyPointerType() const
Definition TypeBase.h:8692
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:9277
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:9087
bool isRecordType() const
Definition TypeBase.h:8811
bool isObjCRetainableType() const
Definition Type.cpp:5435
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5156
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3709
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5764
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3604
QualType getUnderlyingType() const
Definition Decl.h:3659
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType Underlying)
Definition TypeBase.h:6226
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2250
Opcode getOpcode() const
Definition Expr.h:2286
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition DeclCXX.h:4476
static void Profile(llvm::FoldingSetNodeID &ID, QualType Ty, const APValue &APVal)
Definition DeclCXX.h:4504
The iterator over UnresolvedSets.
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition TypeBase.h:6087
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UnresolvedUsingTypenameDecl *D)
Definition TypeBase.h:6124
Represents a dependent using declaration which was marked with typename.
Definition DeclCXX.h:4058
UnresolvedUsingTypenameDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this declaration.
Definition DeclCXX.h:4123
Represents a C++ using-enum-declaration.
Definition DeclCXX.h:3813
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3420
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3484
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition DeclCXX.cpp:3485
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UsingShadowDecl *D, QualType UnderlyingType)
Definition TypeBase.h:6164
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:5579
void clear()
Definition Value.cpp:217
Represents a variable declaration or definition.
Definition Decl.h:932
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2771
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:1304
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1214
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1573
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1316
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:2740
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4030
Expr * getSizeExpr() const
Definition TypeBase.h:4044
Represents a GCC generic vector type.
Definition TypeBase.h:4239
unsigned getNumElements() const
Definition TypeBase.h:4254
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4263
VectorKind getVectorKind() const
Definition TypeBase.h:4259
QualType getElementType() const
Definition TypeBase.h:4253
A full comment attached to a declaration, contains block content.
Definition Comment.h:1097
ArrayRef< BlockContentComment * > getBlocks() const
Definition Comment.h:1135
const DeclInfo * getDeclInfo() const LLVM_READONLY
Definition Comment.h:1129
const Decl * getDecl() const LLVM_READONLY
Definition Comment.h:1125
Holds all information required to evaluate constexpr code in a module.
Definition Context.h:47
Defines the Linkage enumeration and various utility functions.
Defines the clang::TargetInfo interface.
Definition SPIR.cpp:47
mlir::Type getBaseType(mlir::Value varPtr)
const AstTypeMatcher< TagType > tagType
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ArrayType > arrayType
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus17
GVALinkage
A more specific kind of linkage than enum Linkage.
Definition Linkage.h:72
@ GVA_StrongODR
Definition Linkage.h:77
@ GVA_StrongExternal
Definition Linkage.h:76
@ GVA_AvailableExternally
Definition Linkage.h:74
@ GVA_DiscardableODR
Definition Linkage.h:75
@ GVA_Internal
Definition Linkage.h:73
AutoTypeKeyword
Which keyword(s) were used to create an AutoType.
Definition TypeBase.h: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:8582
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:3783
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:6000
@ Struct
The "struct" keyword.
Definition TypeBase.h:5997
@ Class
The "class" keyword.
Definition TypeBase.h:6006
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
const Decl & adjustDeclToTemplate(const Decl &D)
If we have a 'templated' declaration for a template, adjust 'D' to refer to the actual template.
FloatModeKind
Definition TargetInfo.h:75
bool isPtrSizeAddressSpace(LangAS AS)
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:133
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:145
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:140
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1305
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ConceptReference *C)
Insertion operator for diagnostics.
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:189
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:207
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:203
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:199
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:195
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:192
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:279
@ CC_M68kRTD
Definition Specifiers.h:300
@ CC_X86RegCall
Definition Specifiers.h:288
@ CC_X86VectorCall
Definition Specifiers.h:284
@ CC_X86StdCall
Definition Specifiers.h:281
@ CC_X86FastCall
Definition Specifiers.h:282
@ Invariant
The parameter is invariant: must match exactly.
Definition DeclObjC.h:555
@ Contravariant
The parameter is contravariant, e.g., X<T> is a subtype of X when the type parameter is covariant and...
Definition DeclObjC.h:563
@ Covariant
The parameter is covariant, e.g., X<T> is a subtype of X when the type parameter is covariant and T i...
Definition DeclObjC.h:559
@ AltiVecBool
is AltiVec 'vector bool ...'
Definition TypeBase.h:4209
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4218
@ AltiVecPixel
is AltiVec 'vector Pixel'
Definition TypeBase.h:4206
@ Generic
not a target-specific vector type
Definition TypeBase.h:4200
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
Definition TypeBase.h:4224
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
Definition TypeBase.h:4227
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4221
U cast(CodeGen::Address addr)
Definition Address.h:327
LangAS getLangASFromTargetAS(unsigned TargetAS)
AlignRequirementKind
Definition ASTContext.h:174
@ None
The alignment was not explicit in code.
Definition ASTContext.h:176
@ RequiredByEnum
The alignment comes from an alignment attribute on a enum type.
Definition ASTContext.h:185
@ RequiredByTypedef
The alignment comes from an alignment attribute on a typedef.
Definition ASTContext.h:179
@ RequiredByRecord
The alignment comes from an alignment attribute on a record type.
Definition ASTContext.h:182
@ PackIndex
Index of a pack indexing expression or specifier.
Definition Sema.h:851
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:5970
@ Interface
The "__interface" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5975
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5991
@ Struct
The "struct" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5972
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5981
@ Union
The "union" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5978
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5984
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:5988
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_DependentNoexcept
noexcept(expression), value-dependent
@ EST_Uninstantiated
not instantiated yet
@ EST_Unparsed
not parsed yet
@ EST_NoThrow
Microsoft __declspec(nothrow) extension.
@ EST_None
no exception specification
@ EST_MSAny
Microsoft throw(...) extension.
@ EST_BasicNoexcept
noexcept
@ EST_NoexceptFalse
noexcept(expression), evals to 'false'
@ EST_Unevaluated
not evaluated yet, for special member function
@ EST_NoexceptTrue
noexcept(expression), evals to 'true'
@ EST_Dynamic
throw(T1, T2)
unsigned long uint64_t
unsigned NumTemplateArgs
The number of template arguments in TemplateArgs.
const Expr * ConstraintExpr
Definition Decl.h:88
UnsignedOrNone ArgPackSubstIndex
Definition Decl.h:89
Copy initialization expr of a __block variable and a boolean flag that indicates whether the expressi...
Definition Expr.h:6730
Expr * getCopyExpr() const
Definition Expr.h:6737
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
ArrayRef< TemplateArgument > Args
Holds information about the various types of exception specification.
Definition TypeBase.h:5428
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5430
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition TypeBase.h:5433
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition TypeBase.h:5436
Extra information about a function prototype.
Definition TypeBase.h:5456
bool requiresFunctionProtoTypeArmAttributes() const
Definition TypeBase.h:5502
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5461
bool requiresFunctionProtoTypeExtraAttributeInfo() const
Definition TypeBase.h:5506
bool requiresFunctionProtoTypeExtraBitfields() const
Definition TypeBase.h:5495
const IdentifierInfo * getIdentifier() const
Returns the identifier to which this template name refers.
OverloadedOperatorKind getOperator() const
Return the overloaded operator to which this template name refers.
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition Type.cpp:3389
A 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:205
bool isAlignRequired()
Definition ASTContext.h:197
AlignRequirementKind AlignRequirement
Definition ASTContext.h:191
Information about the declaration, useful to clients of FullComment.
Definition Comment.h:974
const TemplateParameterList * TemplateParameters
Template parameters that can be referenced by \tparam if CommentDecl is a template (IsTemplateDecl or...
Definition Comment.h:1000
const Decl * CommentDecl
Declaration the comment is actually attached to (in the source).
Definition Comment.h:977