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 for (const auto &Value : ModuleInitializers)
993 Value.second->~PerModuleInitializers();
994 ModuleInitializers.clear();
995
996 TUDecl = nullptr;
997 XRayFilter.reset();
998 NoSanitizeL.reset();
999}
1000
1002
1003void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
1004 TraversalScope = TopLevelDecls;
1006}
1007
1008void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
1009 Deallocations.push_back({Callback, Data});
1010}
1011
1012void
1016
1018 llvm::errs() << "\n*** AST Context Stats:\n";
1019 llvm::errs() << " " << Types.size() << " types total.\n";
1020
1021 unsigned counts[] = {
1022#define TYPE(Name, Parent) 0,
1023#define ABSTRACT_TYPE(Name, Parent)
1024#include "clang/AST/TypeNodes.inc"
1025 0 // Extra
1026 };
1027
1028 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1029 Type *T = Types[i];
1030 counts[(unsigned)T->getTypeClass()]++;
1031 }
1032
1033 unsigned Idx = 0;
1034 unsigned TotalBytes = 0;
1035#define TYPE(Name, Parent) \
1036 if (counts[Idx]) \
1037 llvm::errs() << " " << counts[Idx] << " " << #Name \
1038 << " types, " << sizeof(Name##Type) << " each " \
1039 << "(" << counts[Idx] * sizeof(Name##Type) \
1040 << " bytes)\n"; \
1041 TotalBytes += counts[Idx] * sizeof(Name##Type); \
1042 ++Idx;
1043#define ABSTRACT_TYPE(Name, Parent)
1044#include "clang/AST/TypeNodes.inc"
1045
1046 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1047
1048 // Implicit special member functions.
1049 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1051 << " implicit default constructors created\n";
1052 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1054 << " implicit copy constructors created\n";
1055 if (getLangOpts().CPlusPlus)
1056 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1058 << " implicit move constructors created\n";
1059 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1061 << " implicit copy assignment operators created\n";
1062 if (getLangOpts().CPlusPlus)
1063 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1065 << " implicit move assignment operators created\n";
1066 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1068 << " implicit destructors created\n";
1069
1070 if (ExternalSource) {
1071 llvm::errs() << "\n";
1072 ExternalSource->PrintStats();
1073 }
1074
1075 BumpAlloc.PrintStats();
1076}
1077
1079 bool NotifyListeners) {
1080 if (NotifyListeners)
1081 if (auto *Listener = getASTMutationListener();
1083 Listener->RedefinedHiddenDefinition(ND, M);
1084
1085 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1086}
1087
1089 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1090 if (It == MergedDefModules.end())
1091 return;
1092
1093 auto &Merged = It->second;
1094 llvm::DenseSet<Module*> Found;
1095 for (Module *&M : Merged)
1096 if (!Found.insert(M).second)
1097 M = nullptr;
1098 llvm::erase(Merged, nullptr);
1099}
1100
1103 auto MergedIt =
1104 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1105 if (MergedIt == MergedDefModules.end())
1106 return {};
1107 return MergedIt->second;
1108}
1109
1110void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1111 if (LazyInitializers.empty())
1112 return;
1113
1114 auto *Source = Ctx.getExternalSource();
1115 assert(Source && "lazy initializers but no external source");
1116
1117 auto LazyInits = std::move(LazyInitializers);
1118 LazyInitializers.clear();
1119
1120 for (auto ID : LazyInits)
1121 Initializers.push_back(Source->GetExternalDecl(ID));
1122
1123 assert(LazyInitializers.empty() &&
1124 "GetExternalDecl for lazy module initializer added more inits");
1125}
1126
1128 // One special case: if we add a module initializer that imports another
1129 // module, and that module's only initializer is an ImportDecl, simplify.
1130 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1131 auto It = ModuleInitializers.find(ID->getImportedModule());
1132
1133 // Maybe the ImportDecl does nothing at all. (Common case.)
1134 if (It == ModuleInitializers.end())
1135 return;
1136
1137 // Maybe the ImportDecl only imports another ImportDecl.
1138 auto &Imported = *It->second;
1139 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1140 Imported.resolve(*this);
1141 auto *OnlyDecl = Imported.Initializers.front();
1142 if (isa<ImportDecl>(OnlyDecl))
1143 D = OnlyDecl;
1144 }
1145 }
1146
1147 auto *&Inits = ModuleInitializers[M];
1148 if (!Inits)
1149 Inits = new (*this) PerModuleInitializers;
1150 Inits->Initializers.push_back(D);
1151}
1152
1155 auto *&Inits = ModuleInitializers[M];
1156 if (!Inits)
1157 Inits = new (*this) PerModuleInitializers;
1158 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1159 IDs.begin(), IDs.end());
1160}
1161
1163 auto It = ModuleInitializers.find(M);
1164 if (It == ModuleInitializers.end())
1165 return {};
1166
1167 auto *Inits = It->second;
1168 Inits->resolve(*this);
1169 return Inits->Initializers;
1170}
1171
1173 assert(M->isNamedModule());
1174 assert(!CurrentCXXNamedModule &&
1175 "We should set named module for ASTContext for only once");
1176 CurrentCXXNamedModule = M;
1177}
1178
1179bool ASTContext::isInSameModule(const Module *M1, const Module *M2) const {
1180 if (!M1 != !M2)
1181 return false;
1182
1183 /// Get the representative module for M. The representative module is the
1184 /// first module unit for a specific primary module name. So that the module
1185 /// units have the same representative module belongs to the same module.
1186 ///
1187 /// The process is helpful to reduce the expensive string operations.
1188 auto GetRepresentativeModule = [this](const Module *M) {
1189 auto Iter = SameModuleLookupSet.find(M);
1190 if (Iter != SameModuleLookupSet.end())
1191 return Iter->second;
1192
1193 const Module *RepresentativeModule =
1194 PrimaryModuleNameMap.try_emplace(M->getPrimaryModuleInterfaceName(), M)
1195 .first->second;
1196 SameModuleLookupSet[M] = RepresentativeModule;
1197 return RepresentativeModule;
1198 };
1199
1200 assert(M1 && "Shouldn't call `isInSameModule` if both M1 and M2 are none.");
1201 return GetRepresentativeModule(M1) == GetRepresentativeModule(M2);
1202}
1203
1205 if (!ExternCContext)
1206 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1207
1208 return ExternCContext;
1209}
1210
1221
1222#define BuiltinTemplate(BTName) \
1223 BuiltinTemplateDecl *ASTContext::get##BTName##Decl() const { \
1224 if (!Decl##BTName) \
1225 Decl##BTName = \
1226 buildBuiltinTemplateDecl(BTK##BTName, get##BTName##Name()); \
1227 return Decl##BTName; \
1228 }
1229#include "clang/Basic/BuiltinTemplates.inc"
1230
1232 RecordDecl::TagKind TK) const {
1233 SourceLocation Loc;
1234 RecordDecl *NewDecl;
1235 if (getLangOpts().CPlusPlus)
1236 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1237 Loc, &Idents.get(Name));
1238 else
1239 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1240 &Idents.get(Name));
1241 NewDecl->setImplicit();
1242 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1243 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1244 return NewDecl;
1245}
1246
1248 StringRef Name) const {
1251 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1252 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1253 NewDecl->setImplicit();
1254 return NewDecl;
1255}
1256
1258 if (!Int128Decl)
1259 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1260 return Int128Decl;
1261}
1262
1264 if (!UInt128Decl)
1265 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1266 return UInt128Decl;
1267}
1268
1269void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1270 auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K);
1272 Types.push_back(Ty);
1273}
1274
1276 const TargetInfo *AuxTarget) {
1277 assert((!this->Target || this->Target == &Target) &&
1278 "Incorrect target reinitialization");
1279 assert(VoidTy.isNull() && "Context reinitialized?");
1280
1281 this->Target = &Target;
1282 this->AuxTarget = AuxTarget;
1283
1284 ABI.reset(createCXXABI(Target));
1285 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1286
1287 // C99 6.2.5p19.
1288 InitBuiltinType(VoidTy, BuiltinType::Void);
1289
1290 // C99 6.2.5p2.
1291 InitBuiltinType(BoolTy, BuiltinType::Bool);
1292 // C99 6.2.5p3.
1293 if (LangOpts.CharIsSigned)
1294 InitBuiltinType(CharTy, BuiltinType::Char_S);
1295 else
1296 InitBuiltinType(CharTy, BuiltinType::Char_U);
1297 // C99 6.2.5p4.
1298 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1299 InitBuiltinType(ShortTy, BuiltinType::Short);
1300 InitBuiltinType(IntTy, BuiltinType::Int);
1301 InitBuiltinType(LongTy, BuiltinType::Long);
1302 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1303
1304 // C99 6.2.5p6.
1305 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1306 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1307 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1308 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1309 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1310
1311 // C99 6.2.5p10.
1312 InitBuiltinType(FloatTy, BuiltinType::Float);
1313 InitBuiltinType(DoubleTy, BuiltinType::Double);
1314 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1315
1316 // GNU extension, __float128 for IEEE quadruple precision
1317 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1318
1319 // __ibm128 for IBM extended precision
1320 InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128);
1321
1322 // C11 extension ISO/IEC TS 18661-3
1323 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1324
1325 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1326 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1327 InitBuiltinType(AccumTy, BuiltinType::Accum);
1328 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1329 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1330 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1331 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1332 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1333 InitBuiltinType(FractTy, BuiltinType::Fract);
1334 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1335 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1336 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1337 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1338 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1339 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1340 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1341 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1342 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1343 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1344 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1345 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1346 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1347 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1348 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1349 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
1350
1351 // GNU extension, 128-bit integers.
1352 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1353 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1354
1355 // C++ 3.9.1p5
1356 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1357 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1358 else // -fshort-wchar makes wchar_t be unsigned.
1359 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1360 if (LangOpts.CPlusPlus && LangOpts.WChar)
1362 else {
1363 // C99 (or C++ using -fno-wchar).
1364 WideCharTy = getFromTargetType(Target.getWCharType());
1365 }
1366
1367 WIntTy = getFromTargetType(Target.getWIntType());
1368
1369 // C++20 (proposed)
1370 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1371
1372 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1373 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1374 else // C99
1375 Char16Ty = getFromTargetType(Target.getChar16Type());
1376
1377 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1378 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1379 else // C99
1380 Char32Ty = getFromTargetType(Target.getChar32Type());
1381
1382 // Placeholder type for type-dependent expressions whose type is
1383 // completely unknown. No code should ever check a type against
1384 // DependentTy and users should never see it; however, it is here to
1385 // help diagnose failures to properly check for type-dependent
1386 // expressions.
1387 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1388
1389 // Placeholder type for functions.
1390 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1391
1392 // Placeholder type for bound members.
1393 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1394
1395 // Placeholder type for unresolved templates.
1396 InitBuiltinType(UnresolvedTemplateTy, BuiltinType::UnresolvedTemplate);
1397
1398 // Placeholder type for pseudo-objects.
1399 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1400
1401 // "any" type; useful for debugger-like clients.
1402 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1403
1404 // Placeholder type for unbridged ARC casts.
1405 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1406
1407 // Placeholder type for builtin functions.
1408 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1409
1410 // Placeholder type for OMP array sections.
1411 if (LangOpts.OpenMP) {
1412 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1413 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1414 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1415 }
1416 // Placeholder type for OpenACC array sections, if we are ALSO in OMP mode,
1417 // don't bother, as we're just using the same type as OMP.
1418 if (LangOpts.OpenACC && !LangOpts.OpenMP) {
1419 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1420 }
1421 if (LangOpts.MatrixTypes)
1422 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1423
1424 // Builtin types for 'id', 'Class', and 'SEL'.
1425 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1426 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1427 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1428
1429 if (LangOpts.OpenCL) {
1430#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1431 InitBuiltinType(SingletonId, BuiltinType::Id);
1432#include "clang/Basic/OpenCLImageTypes.def"
1433
1434 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1435 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1436 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1437 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1438 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1439
1440#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1441 InitBuiltinType(Id##Ty, BuiltinType::Id);
1442#include "clang/Basic/OpenCLExtensionTypes.def"
1443 }
1444
1445 if (LangOpts.HLSL) {
1446#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1447 InitBuiltinType(SingletonId, BuiltinType::Id);
1448#include "clang/Basic/HLSLIntangibleTypes.def"
1449 }
1450
1451 if (Target.hasAArch64ACLETypes() ||
1452 (AuxTarget && AuxTarget->hasAArch64ACLETypes())) {
1453#define SVE_TYPE(Name, Id, SingletonId) \
1454 InitBuiltinType(SingletonId, BuiltinType::Id);
1455#include "clang/Basic/AArch64ACLETypes.def"
1456 }
1457
1458 if (Target.getTriple().isPPC64()) {
1459#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1460 InitBuiltinType(Id##Ty, BuiltinType::Id);
1461#include "clang/Basic/PPCTypes.def"
1462#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1463 InitBuiltinType(Id##Ty, BuiltinType::Id);
1464#include "clang/Basic/PPCTypes.def"
1465 }
1466
1467 if (Target.hasRISCVVTypes()) {
1468#define RVV_TYPE(Name, Id, SingletonId) \
1469 InitBuiltinType(SingletonId, BuiltinType::Id);
1470#include "clang/Basic/RISCVVTypes.def"
1471 }
1472
1473 if (Target.getTriple().isWasm() && Target.hasFeature("reference-types")) {
1474#define WASM_TYPE(Name, Id, SingletonId) \
1475 InitBuiltinType(SingletonId, BuiltinType::Id);
1476#include "clang/Basic/WebAssemblyReferenceTypes.def"
1477 }
1478
1479 if (Target.getTriple().isAMDGPU() ||
1480 (Target.getTriple().isSPIRV() &&
1481 Target.getTriple().getVendor() == llvm::Triple::AMD) ||
1482 (AuxTarget &&
1483 (AuxTarget->getTriple().isAMDGPU() ||
1484 ((AuxTarget->getTriple().isSPIRV() &&
1485 AuxTarget->getTriple().getVendor() == llvm::Triple::AMD))))) {
1486#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
1487 InitBuiltinType(SingletonId, BuiltinType::Id);
1488#include "clang/Basic/AMDGPUTypes.def"
1489 }
1490
1491 // Builtin type for __objc_yes and __objc_no
1492 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1494
1495 ObjCConstantStringType = QualType();
1496
1497 ObjCSuperType = QualType();
1498
1499 // void * type
1500 if (LangOpts.OpenCLGenericAddressSpace) {
1501 auto Q = VoidTy.getQualifiers();
1502 Q.setAddressSpace(LangAS::opencl_generic);
1504 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1505 } else {
1507 }
1508
1509 // nullptr type (C++0x 2.14.7)
1510 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1511
1512 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1513 InitBuiltinType(HalfTy, BuiltinType::Half);
1514
1515 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1516
1517 // Builtin type used to help define __builtin_va_list.
1518 VaListTagDecl = nullptr;
1519
1520 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1521 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1524 }
1525}
1526
1528 return SourceMgr.getDiagnostics();
1529}
1530
1532 AttrVec *&Result = DeclAttrs[D];
1533 if (!Result) {
1534 void *Mem = Allocate(sizeof(AttrVec));
1535 Result = new (Mem) AttrVec;
1536 }
1537
1538 return *Result;
1539}
1540
1541/// Erase the attributes corresponding to the given declaration.
1543 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1544 if (Pos != DeclAttrs.end()) {
1545 Pos->second->~AttrVec();
1546 DeclAttrs.erase(Pos);
1547 }
1548}
1549
1552 auto It =
1553 ExplicitInstantiations.find(cast<NamedDecl>(Spec->getCanonicalDecl()));
1554 if (It != ExplicitInstantiations.end())
1555 return It->second;
1556 return {};
1557}
1558
1561 ExplicitInstantiations[cast<NamedDecl>(Spec->getCanonicalDecl())].push_back(
1562 EID);
1563}
1564
1565// FIXME: Remove ?
1568 assert(Var->isStaticDataMember() && "Not a static data member");
1570 .dyn_cast<MemberSpecializationInfo *>();
1571}
1572
1575 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1576 TemplateOrInstantiation.find(Var);
1577 if (Pos == TemplateOrInstantiation.end())
1578 return {};
1579
1580 return Pos->second;
1581}
1582
1583void
1586 SourceLocation PointOfInstantiation) {
1587 assert(Inst->isStaticDataMember() && "Not a static data member");
1588 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1590 Tmpl, TSK, PointOfInstantiation));
1591}
1592
1593void
1596 assert(!TemplateOrInstantiation[Inst] &&
1597 "Already noted what the variable was instantiated from");
1598 TemplateOrInstantiation[Inst] = TSI;
1599}
1600
1601NamedDecl *
1603 return InstantiatedFromUsingDecl.lookup(UUD);
1604}
1605
1606void
1608 assert((isa<UsingDecl>(Pattern) ||
1611 "pattern decl is not a using decl");
1612 assert((isa<UsingDecl>(Inst) ||
1615 "instantiation did not produce a using decl");
1616 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1617 InstantiatedFromUsingDecl[Inst] = Pattern;
1618}
1619
1622 return InstantiatedFromUsingEnumDecl.lookup(UUD);
1623}
1624
1626 UsingEnumDecl *Pattern) {
1627 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1628 InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1629}
1630
1633 return InstantiatedFromUsingShadowDecl.lookup(Inst);
1634}
1635
1636void
1638 UsingShadowDecl *Pattern) {
1639 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1640 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1641}
1642
1643FieldDecl *
1645 return InstantiatedFromUnnamedFieldDecl.lookup(Field);
1646}
1647
1649 FieldDecl *Tmpl) {
1650 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1651 "Instantiated field decl is not unnamed");
1652 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1653 "Template field decl is not unnamed");
1654 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1655 "Already noted what unnamed field was instantiated from");
1656
1657 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1658}
1659
1664
1669
1670unsigned
1672 auto Range = overridden_methods(Method);
1673 return Range.end() - Range.begin();
1674}
1675
1678 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1679 OverriddenMethods.find(Method->getCanonicalDecl());
1680 if (Pos == OverriddenMethods.end())
1681 return overridden_method_range(nullptr, nullptr);
1682 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1683}
1684
1686 const CXXMethodDecl *Overridden) {
1687 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1688 OverriddenMethods[Method].push_back(Overridden);
1689}
1690
1692 const NamedDecl *D,
1693 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1694 assert(D);
1695
1696 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1697 Overridden.append(overridden_methods_begin(CXXMethod),
1698 overridden_methods_end(CXXMethod));
1699 return;
1700 }
1701
1702 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1703 if (!Method)
1704 return;
1705
1707 Method->getOverriddenMethods(OverDecls);
1708 Overridden.append(OverDecls.begin(), OverDecls.end());
1709}
1710
1711std::optional<ASTContext::CXXRecordDeclRelocationInfo>
1713 assert(RD);
1714 CXXRecordDecl *D = RD->getDefinition();
1715 auto it = RelocatableClasses.find(D);
1716 if (it != RelocatableClasses.end())
1717 return it->getSecond();
1718 return std::nullopt;
1719}
1720
1723 assert(RD);
1724 CXXRecordDecl *D = RD->getDefinition();
1725 assert(RelocatableClasses.find(D) == RelocatableClasses.end());
1726 RelocatableClasses.insert({D, Info});
1727}
1728
1730 const ASTContext &Context, const CXXRecordDecl *Class) {
1731 if (!Class->isPolymorphic())
1732 return false;
1733 const CXXRecordDecl *BaseType = Context.baseForVTableAuthentication(Class);
1734 using AuthAttr = VTablePointerAuthenticationAttr;
1735 const AuthAttr *ExplicitAuth = BaseType->getAttr<AuthAttr>();
1736 if (!ExplicitAuth)
1737 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1738 AuthAttr::AddressDiscriminationMode AddressDiscrimination =
1739 ExplicitAuth->getAddressDiscrimination();
1740 if (AddressDiscrimination == AuthAttr::DefaultAddressDiscrimination)
1741 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1742 return AddressDiscrimination == AuthAttr::AddressDiscrimination;
1743}
1744
1745ASTContext::PointerAuthContent
1746ASTContext::findPointerAuthContent(QualType T) const {
1747 assert(isPointerAuthenticationAvailable());
1748
1749 T = T.getCanonicalType();
1750 if (T->isDependentType())
1751 return PointerAuthContent::None;
1752
1754 return PointerAuthContent::AddressDiscriminatedData;
1755 const RecordDecl *RD = T->getAsRecordDecl();
1756 if (!RD)
1757 return PointerAuthContent::None;
1758
1759 if (RD->isInvalidDecl())
1760 return PointerAuthContent::None;
1761
1762 if (auto Existing = RecordContainsAddressDiscriminatedPointerAuth.find(RD);
1763 Existing != RecordContainsAddressDiscriminatedPointerAuth.end())
1764 return Existing->second;
1765
1766 PointerAuthContent Result = PointerAuthContent::None;
1767
1768 auto SaveResultAndReturn = [&]() -> PointerAuthContent {
1769 auto [ResultIter, DidAdd] =
1770 RecordContainsAddressDiscriminatedPointerAuth.try_emplace(RD, Result);
1771 (void)ResultIter;
1772 (void)DidAdd;
1773 assert(DidAdd);
1774 return Result;
1775 };
1776 auto ShouldContinueAfterUpdate = [&](PointerAuthContent NewResult) {
1777 static_assert(PointerAuthContent::None <
1778 PointerAuthContent::AddressDiscriminatedVTable);
1779 static_assert(PointerAuthContent::AddressDiscriminatedVTable <
1780 PointerAuthContent::AddressDiscriminatedData);
1781 if (NewResult > Result)
1782 Result = NewResult;
1783 return Result != PointerAuthContent::AddressDiscriminatedData;
1784 };
1785 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1787 !ShouldContinueAfterUpdate(
1788 PointerAuthContent::AddressDiscriminatedVTable))
1789 return SaveResultAndReturn();
1790 for (auto Base : CXXRD->bases()) {
1791 if (!ShouldContinueAfterUpdate(findPointerAuthContent(Base.getType())))
1792 return SaveResultAndReturn();
1793 }
1794 }
1795 for (auto *FieldDecl : RD->fields()) {
1796 if (!ShouldContinueAfterUpdate(
1797 findPointerAuthContent(FieldDecl->getType())))
1798 return SaveResultAndReturn();
1799 }
1800 return SaveResultAndReturn();
1801}
1802
1804 assert(!Import->getNextLocalImport() &&
1805 "Import declaration already in the chain");
1806 assert(!Import->isFromASTFile() && "Non-local import declaration");
1807 if (!FirstLocalImport) {
1808 FirstLocalImport = Import;
1809 LastLocalImport = Import;
1810 return;
1811 }
1812
1813 LastLocalImport->setNextLocalImport(Import);
1814 LastLocalImport = Import;
1815}
1816
1817//===----------------------------------------------------------------------===//
1818// Type Sizing and Analysis
1819//===----------------------------------------------------------------------===//
1820
1821/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1822/// scalar floating point type.
1823const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1824 switch (T->castAs<BuiltinType>()->getKind()) {
1825 default:
1826 llvm_unreachable("Not a floating point type!");
1827 case BuiltinType::BFloat16:
1828 return Target->getBFloat16Format();
1829 case BuiltinType::Float16:
1830 return Target->getHalfFormat();
1831 case BuiltinType::Half:
1832 return Target->getHalfFormat();
1833 case BuiltinType::Float: return Target->getFloatFormat();
1834 case BuiltinType::Double: return Target->getDoubleFormat();
1835 case BuiltinType::Ibm128:
1836 return Target->getIbm128Format();
1837 case BuiltinType::LongDouble:
1838 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1839 return AuxTarget->getLongDoubleFormat();
1840 return Target->getLongDoubleFormat();
1841 case BuiltinType::Float128:
1842 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1843 return AuxTarget->getFloat128Format();
1844 return Target->getFloat128Format();
1845 }
1846}
1847
1848CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1849 unsigned Align = Target->getCharWidth();
1850
1851 const unsigned AlignFromAttr = D->getMaxAlignment();
1852 if (AlignFromAttr)
1853 Align = AlignFromAttr;
1854
1855 // __attribute__((aligned)) can increase or decrease alignment
1856 // *except* on a struct or struct member, where it only increases
1857 // alignment unless 'packed' is also specified.
1858 //
1859 // It is an error for alignas to decrease alignment, so we can
1860 // ignore that possibility; Sema should diagnose it.
1861 bool UseAlignAttrOnly;
1862 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D))
1863 UseAlignAttrOnly =
1864 FD->hasAttr<PackedAttr>() || FD->getParent()->hasAttr<PackedAttr>();
1865 else
1866 UseAlignAttrOnly = AlignFromAttr != 0;
1867 // If we're using the align attribute only, just ignore everything
1868 // else about the declaration and its type.
1869 if (UseAlignAttrOnly) {
1870 // do nothing
1871 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1872 QualType T = VD->getType();
1873 if (const auto *RT = T->getAs<ReferenceType>()) {
1874 if (ForAlignof)
1875 T = RT->getPointeeType();
1876 else
1877 T = getPointerType(RT->getPointeeType());
1878 }
1879 QualType BaseT = getBaseElementType(T);
1880 if (T->isFunctionType())
1881 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1882 else if (!BaseT->isIncompleteType()) {
1883 // Adjust alignments of declarations with array type by the
1884 // large-array alignment on the target.
1885 if (const ArrayType *arrayType = getAsArrayType(T)) {
1886 unsigned MinWidth = Target->getLargeArrayMinWidth();
1887 if (!ForAlignof && MinWidth) {
1889 Align = std::max(Align, Target->getLargeArrayAlign());
1892 Align = std::max(Align, Target->getLargeArrayAlign());
1893 }
1894 }
1895 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1896 if (BaseT.getQualifiers().hasUnaligned())
1897 Align = Target->getCharWidth();
1898 }
1899
1900 // Ensure minimum alignment for global variables.
1901 if (const auto *VD = dyn_cast<VarDecl>(D))
1902 if (VD->hasGlobalStorage() && !ForAlignof) {
1903 uint64_t TypeSize =
1904 !BaseT->isIncompleteType() ? getTypeSize(T.getTypePtr()) : 0;
1905 Align = std::max(Align, getMinGlobalAlignOfVar(TypeSize, VD));
1906 }
1907
1908 // Fields can be subject to extra alignment constraints, like if
1909 // the field is packed, the struct is packed, or the struct has a
1910 // a max-field-alignment constraint (#pragma pack). So calculate
1911 // the actual alignment of the field within the struct, and then
1912 // (as we're expected to) constrain that by the alignment of the type.
1913 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1914 const RecordDecl *Parent = Field->getParent();
1915 // We can only produce a sensible answer if the record is valid.
1916 if (!Parent->isInvalidDecl()) {
1917 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1918
1919 // Start with the record's overall alignment.
1920 unsigned FieldAlign = toBits(Layout.getAlignment());
1921
1922 // Use the GCD of that and the offset within the record.
1923 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1924 if (Offset > 0) {
1925 // Alignment is always a power of 2, so the GCD will be a power of 2,
1926 // which means we get to do this crazy thing instead of Euclid's.
1927 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1928 if (LowBitOfOffset < FieldAlign)
1929 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1930 }
1931
1932 Align = std::min(Align, FieldAlign);
1933 }
1934 }
1935 }
1936
1937 // Some targets have hard limitation on the maximum requestable alignment in
1938 // aligned attribute for static variables.
1939 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1940 const auto *VD = dyn_cast<VarDecl>(D);
1941 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1942 Align = std::min(Align, MaxAlignedAttr);
1943
1944 return toCharUnitsFromBits(Align);
1945}
1946
1948 return toCharUnitsFromBits(Target->getExnObjectAlignment());
1949}
1950
1951// getTypeInfoDataSizeInChars - Return the size of a type, in
1952// chars. If the type is a record, its data size is returned. This is
1953// the size of the memcpy that's performed when assigning this type
1954// using a trivial copy/move assignment operator.
1957
1958 // In C++, objects can sometimes be allocated into the tail padding
1959 // of a base-class subobject. We decide whether that's possible
1960 // during class layout, so here we can just trust the layout results.
1961 if (getLangOpts().CPlusPlus) {
1962 if (const auto *RD = T->getAsCXXRecordDecl(); RD && !RD->isInvalidDecl()) {
1963 const ASTRecordLayout &layout = getASTRecordLayout(RD);
1964 Info.Width = layout.getDataSize();
1965 }
1966 }
1967
1968 return Info;
1969}
1970
1971/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1972/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1975 const ConstantArrayType *CAT) {
1976 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1977 uint64_t Size = CAT->getZExtSize();
1978 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1979 (uint64_t)(-1)/Size) &&
1980 "Overflow in array type char size evaluation");
1981 uint64_t Width = EltInfo.Width.getQuantity() * Size;
1982 unsigned Align = EltInfo.Align.getQuantity();
1983 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1984 Context.getTargetInfo().getPointerWidth(LangAS::Default) == 64)
1985 Width = llvm::alignTo(Width, Align);
1988 EltInfo.AlignRequirement);
1989}
1990
1992 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1993 return getConstantArrayInfoInChars(*this, CAT);
1994 TypeInfo Info = getTypeInfo(T);
1997}
1998
2000 return getTypeInfoInChars(T.getTypePtr());
2001}
2002
2004 // HLSL doesn't promote all small integer types to int, it
2005 // just uses the rank-based promotion rules for all types.
2006 if (getLangOpts().HLSL)
2007 return false;
2008
2009 if (const auto *BT = T->getAs<BuiltinType>())
2010 switch (BT->getKind()) {
2011 case BuiltinType::Bool:
2012 case BuiltinType::Char_S:
2013 case BuiltinType::Char_U:
2014 case BuiltinType::SChar:
2015 case BuiltinType::UChar:
2016 case BuiltinType::Short:
2017 case BuiltinType::UShort:
2018 case BuiltinType::WChar_S:
2019 case BuiltinType::WChar_U:
2020 case BuiltinType::Char8:
2021 case BuiltinType::Char16:
2022 case BuiltinType::Char32:
2023 return true;
2024 default:
2025 return false;
2026 }
2027
2028 // Enumerated types are promotable to their compatible integer types
2029 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
2030 if (const auto *ED = T->getAsEnumDecl()) {
2031 if (T->isDependentType() || ED->getPromotionType().isNull() ||
2032 ED->isScoped())
2033 return false;
2034
2035 return true;
2036 }
2037
2038 // OverflowBehaviorTypes are promotable if their underlying type is promotable
2039 if (const auto *OBT = T->getAs<OverflowBehaviorType>()) {
2040 return isPromotableIntegerType(OBT->getUnderlyingType());
2041 }
2042
2043 return false;
2044}
2045
2049
2051 return isAlignmentRequired(T.getTypePtr());
2052}
2053
2055 bool NeedsPreferredAlignment) const {
2056 // An alignment on a typedef overrides anything else.
2057 if (const auto *TT = T->getAs<TypedefType>())
2058 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2059 return Align;
2060
2061 // If we have an (array of) complete type, we're done.
2062 T = getBaseElementType(T);
2063 if (!T->isIncompleteType())
2064 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
2065
2066 // If we had an array type, its element type might be a typedef
2067 // type with an alignment attribute.
2068 if (const auto *TT = T->getAs<TypedefType>())
2069 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2070 return Align;
2071
2072 // Otherwise, see if the declaration of the type had an attribute.
2073 if (const auto *TD = T->getAsTagDecl())
2074 return TD->getMaxAlignment();
2075
2076 return 0;
2077}
2078
2080 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
2081 if (I != MemoizedTypeInfo.end())
2082 return I->second;
2083
2084 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
2085 TypeInfo TI = getTypeInfoImpl(T);
2086 MemoizedTypeInfo[T] = TI;
2087 return TI;
2088}
2089
2090/// getTypeInfoImpl - Return the size of the specified type, in bits. This
2091/// method does not work on incomplete types.
2092///
2093/// FIXME: Pointers into different addr spaces could have different sizes and
2094/// alignment requirements: getPointerInfo should take an AddrSpace, this
2095/// should take a QualType, &c.
2096TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
2097 uint64_t Width = 0;
2098 unsigned Align = 8;
2101 switch (T->getTypeClass()) {
2102#define TYPE(Class, Base)
2103#define ABSTRACT_TYPE(Class, Base)
2104#define NON_CANONICAL_TYPE(Class, Base)
2105#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2106#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
2107 case Type::Class: \
2108 assert(!T->isDependentType() && "should not see dependent types here"); \
2109 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
2110#include "clang/AST/TypeNodes.inc"
2111 llvm_unreachable("Should not see dependent types");
2112
2113 case Type::FunctionNoProto:
2114 case Type::FunctionProto:
2115 // GCC extension: alignof(function) = 32 bits
2116 Width = 0;
2117 Align = 32;
2118 break;
2119
2120 case Type::IncompleteArray:
2121 case Type::VariableArray:
2122 case Type::ConstantArray:
2123 case Type::ArrayParameter: {
2124 // Model non-constant sized arrays as size zero, but track the alignment.
2125 uint64_t Size = 0;
2126 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
2127 Size = CAT->getZExtSize();
2128
2129 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
2130 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
2131 "Overflow in array type bit size evaluation");
2132 Width = EltInfo.Width * Size;
2133 Align = EltInfo.Align;
2134 AlignRequirement = EltInfo.AlignRequirement;
2135 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
2136 getTargetInfo().getPointerWidth(LangAS::Default) == 64)
2137 Width = llvm::alignTo(Width, Align);
2138 break;
2139 }
2140
2141 case Type::ExtVector:
2142 case Type::Vector: {
2143 const auto *VT = cast<VectorType>(T);
2144 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
2145 Width = VT->isPackedVectorBoolType(*this)
2146 ? VT->getNumElements()
2147 : EltInfo.Width * VT->getNumElements();
2148 // Enforce at least byte size and alignment.
2149 Width = std::max<unsigned>(8, Width);
2150 Align = std::max<unsigned>(
2151 8, Target->vectorsAreElementAligned() ? EltInfo.Width : Width);
2152
2153 // If the alignment is not a power of 2, round up to the next power of 2.
2154 // This happens for non-power-of-2 length vectors.
2155 if (Align & (Align-1)) {
2156 Align = llvm::bit_ceil(Align);
2157 Width = llvm::alignTo(Width, Align);
2158 }
2159 // Adjust the alignment based on the target max.
2160 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
2161 if (TargetVectorAlign && TargetVectorAlign < Align)
2162 Align = TargetVectorAlign;
2163 if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
2164 // Adjust the alignment for fixed-length SVE vectors. This is important
2165 // for non-power-of-2 vector lengths.
2166 Align = 128;
2167 else if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
2168 // Adjust the alignment for fixed-length SVE predicates.
2169 Align = 16;
2170 else if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
2171 VT->getVectorKind() == VectorKind::RVVFixedLengthMask ||
2172 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
2173 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
2174 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4)
2175 // Adjust the alignment for fixed-length RVV vectors.
2176 Align = std::min<unsigned>(64, Width);
2177 break;
2178 }
2179
2180 case Type::ConstantMatrix: {
2181 const auto *MT = cast<ConstantMatrixType>(T);
2182 TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
2183 // The internal layout of a matrix value is implementation defined.
2184 // Initially be ABI compatible with arrays with respect to alignment and
2185 // size.
2186 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
2187 Align = ElementInfo.Align;
2188 break;
2189 }
2190
2191 case Type::Builtin:
2192 switch (cast<BuiltinType>(T)->getKind()) {
2193 default: llvm_unreachable("Unknown builtin type!");
2194 case BuiltinType::Void:
2195 // GCC extension: alignof(void) = 8 bits.
2196 Width = 0;
2197 Align = 8;
2198 break;
2199 case BuiltinType::Bool:
2200 Width = Target->getBoolWidth();
2201 Align = Target->getBoolAlign();
2202 break;
2203 case BuiltinType::Char_S:
2204 case BuiltinType::Char_U:
2205 case BuiltinType::UChar:
2206 case BuiltinType::SChar:
2207 case BuiltinType::Char8:
2208 Width = Target->getCharWidth();
2209 Align = Target->getCharAlign();
2210 break;
2211 case BuiltinType::WChar_S:
2212 case BuiltinType::WChar_U:
2213 Width = Target->getWCharWidth();
2214 Align = Target->getWCharAlign();
2215 break;
2216 case BuiltinType::Char16:
2217 Width = Target->getChar16Width();
2218 Align = Target->getChar16Align();
2219 break;
2220 case BuiltinType::Char32:
2221 Width = Target->getChar32Width();
2222 Align = Target->getChar32Align();
2223 break;
2224 case BuiltinType::UShort:
2225 case BuiltinType::Short:
2226 Width = Target->getShortWidth();
2227 Align = Target->getShortAlign();
2228 break;
2229 case BuiltinType::UInt:
2230 case BuiltinType::Int:
2231 Width = Target->getIntWidth();
2232 Align = Target->getIntAlign();
2233 break;
2234 case BuiltinType::ULong:
2235 case BuiltinType::Long:
2236 Width = Target->getLongWidth();
2237 Align = Target->getLongAlign();
2238 break;
2239 case BuiltinType::ULongLong:
2240 case BuiltinType::LongLong:
2241 Width = Target->getLongLongWidth();
2242 Align = Target->getLongLongAlign();
2243 break;
2244 case BuiltinType::Int128:
2245 case BuiltinType::UInt128:
2246 Width = 128;
2247 Align = Target->getInt128Align();
2248 break;
2249 case BuiltinType::ShortAccum:
2250 case BuiltinType::UShortAccum:
2251 case BuiltinType::SatShortAccum:
2252 case BuiltinType::SatUShortAccum:
2253 Width = Target->getShortAccumWidth();
2254 Align = Target->getShortAccumAlign();
2255 break;
2256 case BuiltinType::Accum:
2257 case BuiltinType::UAccum:
2258 case BuiltinType::SatAccum:
2259 case BuiltinType::SatUAccum:
2260 Width = Target->getAccumWidth();
2261 Align = Target->getAccumAlign();
2262 break;
2263 case BuiltinType::LongAccum:
2264 case BuiltinType::ULongAccum:
2265 case BuiltinType::SatLongAccum:
2266 case BuiltinType::SatULongAccum:
2267 Width = Target->getLongAccumWidth();
2268 Align = Target->getLongAccumAlign();
2269 break;
2270 case BuiltinType::ShortFract:
2271 case BuiltinType::UShortFract:
2272 case BuiltinType::SatShortFract:
2273 case BuiltinType::SatUShortFract:
2274 Width = Target->getShortFractWidth();
2275 Align = Target->getShortFractAlign();
2276 break;
2277 case BuiltinType::Fract:
2278 case BuiltinType::UFract:
2279 case BuiltinType::SatFract:
2280 case BuiltinType::SatUFract:
2281 Width = Target->getFractWidth();
2282 Align = Target->getFractAlign();
2283 break;
2284 case BuiltinType::LongFract:
2285 case BuiltinType::ULongFract:
2286 case BuiltinType::SatLongFract:
2287 case BuiltinType::SatULongFract:
2288 Width = Target->getLongFractWidth();
2289 Align = Target->getLongFractAlign();
2290 break;
2291 case BuiltinType::BFloat16:
2292 if (Target->hasBFloat16Type()) {
2293 Width = Target->getBFloat16Width();
2294 Align = Target->getBFloat16Align();
2295 } else if ((getLangOpts().SYCLIsDevice ||
2296 (getLangOpts().OpenMP &&
2297 getLangOpts().OpenMPIsTargetDevice)) &&
2298 AuxTarget->hasBFloat16Type()) {
2299 Width = AuxTarget->getBFloat16Width();
2300 Align = AuxTarget->getBFloat16Align();
2301 }
2302 break;
2303 case BuiltinType::Float16:
2304 case BuiltinType::Half:
2305 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2306 !getLangOpts().OpenMPIsTargetDevice) {
2307 Width = Target->getHalfWidth();
2308 Align = Target->getHalfAlign();
2309 } else {
2310 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2311 "Expected OpenMP device compilation.");
2312 Width = AuxTarget->getHalfWidth();
2313 Align = AuxTarget->getHalfAlign();
2314 }
2315 break;
2316 case BuiltinType::Float:
2317 Width = Target->getFloatWidth();
2318 Align = Target->getFloatAlign();
2319 break;
2320 case BuiltinType::Double:
2321 Width = Target->getDoubleWidth();
2322 Align = Target->getDoubleAlign();
2323 break;
2324 case BuiltinType::Ibm128:
2325 Width = Target->getIbm128Width();
2326 Align = Target->getIbm128Align();
2327 break;
2328 case BuiltinType::LongDouble:
2329 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2330 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2331 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2332 Width = AuxTarget->getLongDoubleWidth();
2333 Align = AuxTarget->getLongDoubleAlign();
2334 } else {
2335 Width = Target->getLongDoubleWidth();
2336 Align = Target->getLongDoubleAlign();
2337 }
2338 break;
2339 case BuiltinType::Float128:
2340 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2341 !getLangOpts().OpenMPIsTargetDevice) {
2342 Width = Target->getFloat128Width();
2343 Align = Target->getFloat128Align();
2344 } else {
2345 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2346 "Expected OpenMP device compilation.");
2347 Width = AuxTarget->getFloat128Width();
2348 Align = AuxTarget->getFloat128Align();
2349 }
2350 break;
2351 case BuiltinType::NullPtr:
2352 // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
2353 Width = Target->getPointerWidth(LangAS::Default);
2354 Align = Target->getPointerAlign(LangAS::Default);
2355 break;
2356 case BuiltinType::ObjCId:
2357 case BuiltinType::ObjCClass:
2358 case BuiltinType::ObjCSel:
2359 Width = Target->getPointerWidth(LangAS::Default);
2360 Align = Target->getPointerAlign(LangAS::Default);
2361 break;
2362 case BuiltinType::OCLSampler:
2363 case BuiltinType::OCLEvent:
2364 case BuiltinType::OCLClkEvent:
2365 case BuiltinType::OCLQueue:
2366 case BuiltinType::OCLReserveID:
2367#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2368 case BuiltinType::Id:
2369#include "clang/Basic/OpenCLImageTypes.def"
2370#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2371 case BuiltinType::Id:
2372#include "clang/Basic/OpenCLExtensionTypes.def"
2373 AS = Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
2374 Width = Target->getPointerWidth(AS);
2375 Align = Target->getPointerAlign(AS);
2376 break;
2377 // The SVE types are effectively target-specific. The length of an
2378 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2379 // of 128 bits. There is one predicate bit for each vector byte, so the
2380 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2381 //
2382 // Because the length is only known at runtime, we use a dummy value
2383 // of 0 for the static length. The alignment values are those defined
2384 // by the Procedure Call Standard for the Arm Architecture.
2385#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
2386 case BuiltinType::Id: \
2387 Width = 0; \
2388 Align = 128; \
2389 break;
2390#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
2391 case BuiltinType::Id: \
2392 Width = 0; \
2393 Align = 16; \
2394 break;
2395#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
2396 case BuiltinType::Id: \
2397 Width = 0; \
2398 Align = 16; \
2399 break;
2400#define SVE_SCALAR_TYPE(Name, MangledName, Id, SingletonId, Bits) \
2401 case BuiltinType::Id: \
2402 Width = Bits; \
2403 Align = Bits; \
2404 break;
2405#include "clang/Basic/AArch64ACLETypes.def"
2406#define PPC_VECTOR_TYPE(Name, Id, Size) \
2407 case BuiltinType::Id: \
2408 Width = Size; \
2409 Align = Size; \
2410 break;
2411#include "clang/Basic/PPCTypes.def"
2412#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
2413 IsFP, IsBF) \
2414 case BuiltinType::Id: \
2415 Width = 0; \
2416 Align = ElBits; \
2417 break;
2418#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2419 case BuiltinType::Id: \
2420 Width = 0; \
2421 Align = 8; \
2422 break;
2423#include "clang/Basic/RISCVVTypes.def"
2424#define WASM_TYPE(Name, Id, SingletonId) \
2425 case BuiltinType::Id: \
2426 Width = 0; \
2427 Align = 8; \
2428 break;
2429#include "clang/Basic/WebAssemblyReferenceTypes.def"
2430#define AMDGPU_TYPE(NAME, ID, SINGLETONID, WIDTH, ALIGN) \
2431 case BuiltinType::ID: \
2432 Width = WIDTH; \
2433 Align = ALIGN; \
2434 break;
2435#include "clang/Basic/AMDGPUTypes.def"
2436#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2437#include "clang/Basic/HLSLIntangibleTypes.def"
2438 Width = Target->getPointerWidth(LangAS::Default);
2439 Align = Target->getPointerAlign(LangAS::Default);
2440 break;
2441 }
2442 break;
2443 case Type::ObjCObjectPointer:
2444 Width = Target->getPointerWidth(LangAS::Default);
2445 Align = Target->getPointerAlign(LangAS::Default);
2446 break;
2447 case Type::BlockPointer:
2448 AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
2449 Width = Target->getPointerWidth(AS);
2450 Align = Target->getPointerAlign(AS);
2451 break;
2452 case Type::LValueReference:
2453 case Type::RValueReference:
2454 // alignof and sizeof should never enter this code path here, so we go
2455 // the pointer route.
2456 AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
2457 Width = Target->getPointerWidth(AS);
2458 Align = Target->getPointerAlign(AS);
2459 break;
2460 case Type::Pointer:
2461 AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
2462 Width = Target->getPointerWidth(AS);
2463 Align = Target->getPointerAlign(AS);
2464 break;
2465 case Type::MemberPointer: {
2466 const auto *MPT = cast<MemberPointerType>(T);
2467 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2468 Width = MPI.Width;
2469 Align = MPI.Align;
2470 break;
2471 }
2472 case Type::Complex: {
2473 // Complex types have the same alignment as their elements, but twice the
2474 // size.
2475 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2476 Width = EltInfo.Width * 2;
2477 Align = EltInfo.Align;
2478 break;
2479 }
2480 case Type::ObjCObject:
2481 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2482 case Type::Adjusted:
2483 case Type::Decayed:
2484 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2485 case Type::ObjCInterface: {
2486 const auto *ObjCI = cast<ObjCInterfaceType>(T);
2487 if (ObjCI->getDecl()->isInvalidDecl()) {
2488 Width = 8;
2489 Align = 8;
2490 break;
2491 }
2492 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2493 Width = toBits(Layout.getSize());
2494 Align = toBits(Layout.getAlignment());
2495 break;
2496 }
2497 case Type::BitInt: {
2498 const auto *EIT = cast<BitIntType>(T);
2499 Align = Target->getBitIntAlign(EIT->getNumBits());
2500 Width = Target->getBitIntWidth(EIT->getNumBits());
2501 break;
2502 }
2503 case Type::Record:
2504 case Type::Enum: {
2505 const auto *TT = cast<TagType>(T);
2506 const TagDecl *TD = TT->getDecl()->getDefinitionOrSelf();
2507
2508 if (TD->isInvalidDecl()) {
2509 Width = 8;
2510 Align = 8;
2511 break;
2512 }
2513
2514 if (isa<EnumType>(TT)) {
2515 const EnumDecl *ED = cast<EnumDecl>(TD);
2516 TypeInfo Info =
2518 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2519 Info.Align = AttrAlign;
2521 }
2522 return Info;
2523 }
2524
2525 const auto *RD = cast<RecordDecl>(TD);
2526 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2527 Width = toBits(Layout.getSize());
2528 Align = toBits(Layout.getAlignment());
2529 AlignRequirement = RD->hasAttr<AlignedAttr>()
2531 : AlignRequirementKind::None;
2532 break;
2533 }
2534
2535 case Type::SubstTemplateTypeParm:
2537 getReplacementType().getTypePtr());
2538
2539 case Type::Auto:
2540 case Type::DeducedTemplateSpecialization: {
2541 const auto *A = cast<DeducedType>(T);
2542 assert(!A->getDeducedType().isNull() &&
2543 "cannot request the size of an undeduced or dependent auto type");
2544 return getTypeInfo(A->getDeducedType().getTypePtr());
2545 }
2546
2547 case Type::Paren:
2548 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2549
2550 case Type::MacroQualified:
2551 return getTypeInfo(
2552 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2553
2554 case Type::ObjCTypeParam:
2555 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2556
2557 case Type::Using:
2558 return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr());
2559
2560 case Type::Typedef: {
2561 const auto *TT = cast<TypedefType>(T);
2562 TypeInfo Info = getTypeInfo(TT->desugar().getTypePtr());
2563 // If the typedef has an aligned attribute on it, it overrides any computed
2564 // alignment we have. This violates the GCC documentation (which says that
2565 // attribute(aligned) can only round up) but matches its implementation.
2566 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2567 Align = AttrAlign;
2568 AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2569 } else {
2570 Align = Info.Align;
2571 AlignRequirement = Info.AlignRequirement;
2572 }
2573 Width = Info.Width;
2574 break;
2575 }
2576
2577 case Type::Attributed:
2578 return getTypeInfo(
2579 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2580
2581 case Type::CountAttributed:
2582 return getTypeInfo(cast<CountAttributedType>(T)->desugar().getTypePtr());
2583
2584 case Type::BTFTagAttributed:
2585 return getTypeInfo(
2586 cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr());
2587
2588 case Type::OverflowBehavior:
2589 return getTypeInfo(
2591
2592 case Type::HLSLAttributedResource:
2593 return getTypeInfo(
2594 cast<HLSLAttributedResourceType>(T)->getWrappedType().getTypePtr());
2595
2596 case Type::HLSLInlineSpirv: {
2597 const auto *ST = cast<HLSLInlineSpirvType>(T);
2598 // Size is specified in bytes, convert to bits
2599 Width = ST->getSize() * 8;
2600 Align = ST->getAlignment();
2601 if (Width == 0 && Align == 0) {
2602 // We are defaulting to laying out opaque SPIR-V types as 32-bit ints.
2603 Width = 32;
2604 Align = 32;
2605 }
2606 break;
2607 }
2608
2609 case Type::Atomic: {
2610 // Start with the base type information.
2611 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2612 Width = Info.Width;
2613 Align = Info.Align;
2614
2615 if (!Width) {
2616 // An otherwise zero-sized type should still generate an
2617 // atomic operation.
2618 Width = Target->getCharWidth();
2619 assert(Align);
2620 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2621 // If the size of the type doesn't exceed the platform's max
2622 // atomic promotion width, make the size and alignment more
2623 // favorable to atomic operations:
2624
2625 // Round the size up to a power of 2.
2626 Width = llvm::bit_ceil(Width);
2627
2628 // Set the alignment equal to the size.
2629 Align = static_cast<unsigned>(Width);
2630 }
2631 }
2632 break;
2633
2634 case Type::PredefinedSugar:
2635 return getTypeInfo(cast<PredefinedSugarType>(T)->desugar().getTypePtr());
2636
2637 case Type::Pipe:
2638 Width = Target->getPointerWidth(LangAS::opencl_global);
2639 Align = Target->getPointerAlign(LangAS::opencl_global);
2640 break;
2641 }
2642
2643 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2644 return TypeInfo(Width, Align, AlignRequirement);
2645}
2646
2648 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2649 if (I != MemoizedUnadjustedAlign.end())
2650 return I->second;
2651
2652 unsigned UnadjustedAlign;
2653 if (const auto *RT = T->getAsCanonical<RecordType>()) {
2654 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
2655 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2656 } else if (const auto *ObjCI = T->getAsCanonical<ObjCInterfaceType>()) {
2657 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2658 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2659 } else {
2660 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2661 }
2662
2663 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2664 return UnadjustedAlign;
2665}
2666
2668 unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign(
2669 getTargetInfo().getTriple(), Target->getTargetOpts().FeatureMap);
2670 return SimdAlign;
2671}
2672
2673/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2675 return CharUnits::fromQuantity(BitSize / getCharWidth());
2676}
2677
2678/// toBits - Convert a size in characters to a size in characters.
2679int64_t ASTContext::toBits(CharUnits CharSize) const {
2680 return CharSize.getQuantity() * getCharWidth();
2681}
2682
2683/// getTypeSizeInChars - Return the size of the specified type, in characters.
2684/// This method does not work on incomplete types.
2691
2692/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2693/// characters. This method does not work on incomplete types.
2700
2701/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2702/// type, in characters, before alignment adjustments. This method does
2703/// not work on incomplete types.
2710
2711/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2712/// type for the current target in bits. This can be different than the ABI
2713/// alignment in cases where it is beneficial for performance or backwards
2714/// compatibility preserving to overalign a data type. (Note: despite the name,
2715/// the preferred alignment is ABI-impacting, and not an optimization.)
2716unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
2717 TypeInfo TI = getTypeInfo(T);
2718 unsigned ABIAlign = TI.Align;
2719
2720 T = T->getBaseElementTypeUnsafe();
2721
2722 // The preferred alignment of member pointers is that of a pointer.
2723 if (T->isMemberPointerType())
2724 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2725
2726 if (!Target->allowsLargerPreferedTypeAlignment())
2727 return ABIAlign;
2728
2729 if (const auto *RD = T->getAsRecordDecl()) {
2730 // When used as part of a typedef, or together with a 'packed' attribute,
2731 // the 'aligned' attribute can be used to decrease alignment. Note that the
2732 // 'packed' case is already taken into consideration when computing the
2733 // alignment, we only need to handle the typedef case here.
2735 RD->isInvalidDecl())
2736 return ABIAlign;
2737
2738 unsigned PreferredAlign = static_cast<unsigned>(
2739 toBits(getASTRecordLayout(RD).PreferredAlignment));
2740 assert(PreferredAlign >= ABIAlign &&
2741 "PreferredAlign should be at least as large as ABIAlign.");
2742 return PreferredAlign;
2743 }
2744
2745 // Double (and, for targets supporting AIX `power` alignment, long double) and
2746 // long long should be naturally aligned (despite requiring less alignment) if
2747 // possible.
2748 if (const auto *CT = T->getAs<ComplexType>())
2749 T = CT->getElementType().getTypePtr();
2750 if (const auto *ED = T->getAsEnumDecl())
2751 T = ED->getIntegerType().getTypePtr();
2752 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2753 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2754 T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2755 (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2756 Target->defaultsToAIXPowerAlignment()))
2757 // Don't increase the alignment if an alignment attribute was specified on a
2758 // typedef declaration.
2759 if (!TI.isAlignRequired())
2760 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2761
2762 return ABIAlign;
2763}
2764
2765/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2766/// for __attribute__((aligned)) on this target, to be used if no alignment
2767/// value is specified.
2771
2772/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2773/// to a global variable of the specified type.
2775 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2776 return std::max(getPreferredTypeAlign(T),
2777 getMinGlobalAlignOfVar(TypeSize, VD));
2778}
2779
2780/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2781/// should be given to a global variable of the specified type.
2786
2788 const VarDecl *VD) const {
2789 // Make the default handling as that of a non-weak definition in the
2790 // current translation unit.
2791 bool HasNonWeakDef = !VD || (VD->hasDefinition() && !VD->isWeak());
2792 return getTargetInfo().getMinGlobalAlign(Size, HasNonWeakDef);
2793}
2794
2796 CharUnits Offset = CharUnits::Zero();
2797 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2798 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2799 Offset += Layout->getBaseClassOffset(Base);
2800 Layout = &getASTRecordLayout(Base);
2801 }
2802 return Offset;
2803}
2804
2806 const ValueDecl *MPD = MP.getMemberPointerDecl();
2809 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2811 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2812 const CXXRecordDecl *Base = RD;
2813 const CXXRecordDecl *Derived = Path[I];
2814 if (DerivedMember)
2815 std::swap(Base, Derived);
2817 RD = Path[I];
2818 }
2819 if (DerivedMember)
2821 return ThisAdjustment;
2822}
2823
2824/// DeepCollectObjCIvars -
2825/// This routine first collects all declared, but not synthesized, ivars in
2826/// super class and then collects all ivars, including those synthesized for
2827/// current class. This routine is used for implementation of current class
2828/// when all ivars, declared and synthesized are known.
2830 bool leafClass,
2832 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2833 DeepCollectObjCIvars(SuperClass, false, Ivars);
2834 if (!leafClass) {
2835 llvm::append_range(Ivars, OI->ivars());
2836 } else {
2837 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2838 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2839 Iv= Iv->getNextIvar())
2840 Ivars.push_back(Iv);
2841 }
2842}
2843
2844/// CollectInheritedProtocols - Collect all protocols in current class and
2845/// those inherited by it.
2848 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2849 // We can use protocol_iterator here instead of
2850 // all_referenced_protocol_iterator since we are walking all categories.
2851 for (auto *Proto : OI->all_referenced_protocols()) {
2852 CollectInheritedProtocols(Proto, Protocols);
2853 }
2854
2855 // Categories of this Interface.
2856 for (const auto *Cat : OI->visible_categories())
2857 CollectInheritedProtocols(Cat, Protocols);
2858
2859 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2860 while (SD) {
2861 CollectInheritedProtocols(SD, Protocols);
2862 SD = SD->getSuperClass();
2863 }
2864 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2865 for (auto *Proto : OC->protocols()) {
2866 CollectInheritedProtocols(Proto, Protocols);
2867 }
2868 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2869 // Insert the protocol.
2870 if (!Protocols.insert(
2871 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2872 return;
2873
2874 for (auto *Proto : OP->protocols())
2875 CollectInheritedProtocols(Proto, Protocols);
2876 }
2877}
2878
2880 const RecordDecl *RD,
2881 bool CheckIfTriviallyCopyable) {
2882 assert(RD->isUnion() && "Must be union type");
2883 CharUnits UnionSize =
2884 Context.getTypeSizeInChars(Context.getCanonicalTagType(RD));
2885
2886 for (const auto *Field : RD->fields()) {
2887 if (!Context.hasUniqueObjectRepresentations(Field->getType(),
2888 CheckIfTriviallyCopyable))
2889 return false;
2890 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2891 if (FieldSize != UnionSize)
2892 return false;
2893 }
2894 return !RD->field_empty();
2895}
2896
2897static int64_t getSubobjectOffset(const FieldDecl *Field,
2898 const ASTContext &Context,
2899 const clang::ASTRecordLayout & /*Layout*/) {
2900 return Context.getFieldOffset(Field);
2901}
2902
2903static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2904 const ASTContext &Context,
2905 const clang::ASTRecordLayout &Layout) {
2906 return Context.toBits(Layout.getBaseClassOffset(RD));
2907}
2908
2909static std::optional<int64_t>
2911 const RecordDecl *RD,
2912 bool CheckIfTriviallyCopyable);
2913
2914static std::optional<int64_t>
2915getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context,
2916 bool CheckIfTriviallyCopyable) {
2917 if (const auto *RD = Field->getType()->getAsRecordDecl();
2918 RD && !RD->isUnion())
2919 return structHasUniqueObjectRepresentations(Context, RD,
2920 CheckIfTriviallyCopyable);
2921
2922 // A _BitInt type may not be unique if it has padding bits
2923 // but if it is a bitfield the padding bits are not used.
2924 bool IsBitIntType = Field->getType()->isBitIntType();
2925 if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2926 !Context.hasUniqueObjectRepresentations(Field->getType(),
2927 CheckIfTriviallyCopyable))
2928 return std::nullopt;
2929
2930 int64_t FieldSizeInBits =
2931 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2932 if (Field->isBitField()) {
2933 // If we have explicit padding bits, they don't contribute bits
2934 // to the actual object representation, so return 0.
2935 if (Field->isUnnamedBitField())
2936 return 0;
2937
2938 int64_t BitfieldSize = Field->getBitWidthValue();
2939 if (IsBitIntType) {
2940 if ((unsigned)BitfieldSize >
2941 cast<BitIntType>(Field->getType())->getNumBits())
2942 return std::nullopt;
2943 } else if (BitfieldSize > FieldSizeInBits) {
2944 return std::nullopt;
2945 }
2946 FieldSizeInBits = BitfieldSize;
2947 } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations(
2948 Field->getType(), CheckIfTriviallyCopyable)) {
2949 return std::nullopt;
2950 }
2951 return FieldSizeInBits;
2952}
2953
2954static std::optional<int64_t>
2956 bool CheckIfTriviallyCopyable) {
2957 return structHasUniqueObjectRepresentations(Context, RD,
2958 CheckIfTriviallyCopyable);
2959}
2960
2961template <typename RangeT>
2963 const RangeT &Subobjects, int64_t CurOffsetInBits,
2964 const ASTContext &Context, const clang::ASTRecordLayout &Layout,
2965 bool CheckIfTriviallyCopyable) {
2966 for (const auto *Subobject : Subobjects) {
2967 std::optional<int64_t> SizeInBits =
2968 getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable);
2969 if (!SizeInBits)
2970 return std::nullopt;
2971 if (*SizeInBits != 0) {
2972 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2973 if (Offset != CurOffsetInBits)
2974 return std::nullopt;
2975 CurOffsetInBits += *SizeInBits;
2976 }
2977 }
2978 return CurOffsetInBits;
2979}
2980
2981static std::optional<int64_t>
2983 const RecordDecl *RD,
2984 bool CheckIfTriviallyCopyable) {
2985 assert(!RD->isUnion() && "Must be struct/class type");
2986 const auto &Layout = Context.getASTRecordLayout(RD);
2987
2988 int64_t CurOffsetInBits = 0;
2989 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2990 if (ClassDecl->isDynamicClass())
2991 return std::nullopt;
2992
2994 for (const auto &Base : ClassDecl->bases()) {
2995 // Empty types can be inherited from, and non-empty types can potentially
2996 // have tail padding, so just make sure there isn't an error.
2997 Bases.emplace_back(Base.getType()->getAsCXXRecordDecl());
2998 }
2999
3000 llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
3001 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
3002 });
3003
3004 std::optional<int64_t> OffsetAfterBases =
3006 Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable);
3007 if (!OffsetAfterBases)
3008 return std::nullopt;
3009 CurOffsetInBits = *OffsetAfterBases;
3010 }
3011
3012 std::optional<int64_t> OffsetAfterFields =
3014 RD->fields(), CurOffsetInBits, Context, Layout,
3015 CheckIfTriviallyCopyable);
3016 if (!OffsetAfterFields)
3017 return std::nullopt;
3018 CurOffsetInBits = *OffsetAfterFields;
3019
3020 return CurOffsetInBits;
3021}
3022
3024 QualType Ty, bool CheckIfTriviallyCopyable) const {
3025 // C++17 [meta.unary.prop]:
3026 // The predicate condition for a template specialization
3027 // has_unique_object_representations<T> shall be satisfied if and only if:
3028 // (9.1) - T is trivially copyable, and
3029 // (9.2) - any two objects of type T with the same value have the same
3030 // object representation, where:
3031 // - two objects of array or non-union class type are considered to have
3032 // the same value if their respective sequences of direct subobjects
3033 // have the same values, and
3034 // - two objects of union type are considered to have the same value if
3035 // they have the same active member and the corresponding members have
3036 // the same value.
3037 // The set of scalar types for which this condition holds is
3038 // implementation-defined. [ Note: If a type has padding bits, the condition
3039 // does not hold; otherwise, the condition holds true for unsigned integral
3040 // types. -- end note ]
3041 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
3042
3043 // Arrays are unique only if their element type is unique.
3044 if (Ty->isArrayType())
3046 CheckIfTriviallyCopyable);
3047
3048 assert((Ty->isVoidType() || !Ty->isIncompleteType()) &&
3049 "hasUniqueObjectRepresentations should not be called with an "
3050 "incomplete type");
3051
3052 // (9.1) - T is trivially copyable...
3053 if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(*this))
3054 return false;
3055
3056 // All integrals and enums are unique.
3057 if (Ty->isIntegralOrEnumerationType()) {
3058 // Address discriminated integer types are not unique.
3060 return false;
3061 // Except _BitInt types that have padding bits.
3062 if (const auto *BIT = Ty->getAs<BitIntType>())
3063 return getTypeSize(BIT) == BIT->getNumBits();
3064
3065 return true;
3066 }
3067
3068 // All other pointers are unique.
3069 if (Ty->isPointerType())
3071
3072 if (const auto *MPT = Ty->getAs<MemberPointerType>())
3073 return !ABI->getMemberPointerInfo(MPT).HasPadding;
3074
3075 if (const auto *Record = Ty->getAsRecordDecl()) {
3076 if (Record->isInvalidDecl())
3077 return false;
3078
3079 if (Record->isUnion())
3081 CheckIfTriviallyCopyable);
3082
3083 std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(
3084 *this, Record, CheckIfTriviallyCopyable);
3085
3086 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(Ty));
3087 }
3088
3089 // FIXME: More cases to handle here (list by rsmith):
3090 // vectors (careful about, eg, vector of 3 foo)
3091 // _Complex int and friends
3092 // _Atomic T
3093 // Obj-C block pointers
3094 // Obj-C object pointers
3095 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
3096 // clk_event_t, queue_t, reserve_id_t)
3097 // There're also Obj-C class types and the Obj-C selector type, but I think it
3098 // makes sense for those to return false here.
3099
3100 return false;
3101}
3102
3104 unsigned count = 0;
3105 // Count ivars declared in class extension.
3106 for (const auto *Ext : OI->known_extensions())
3107 count += Ext->ivar_size();
3108
3109 // Count ivar defined in this class's implementation. This
3110 // includes synthesized ivars.
3111 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
3112 count += ImplDecl->ivar_size();
3113
3114 return count;
3115}
3116
3118 if (!E)
3119 return false;
3120
3121 // nullptr_t is always treated as null.
3122 if (E->getType()->isNullPtrType()) return true;
3123
3124 if (E->getType()->isAnyPointerType() &&
3127 return true;
3128
3129 // Unfortunately, __null has type 'int'.
3130 if (isa<GNUNullExpr>(E)) return true;
3131
3132 return false;
3133}
3134
3135/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
3136/// exists.
3138 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3139 I = ObjCImpls.find(D);
3140 if (I != ObjCImpls.end())
3141 return cast<ObjCImplementationDecl>(I->second);
3142 return nullptr;
3143}
3144
3145/// Get the implementation of ObjCCategoryDecl, or nullptr if none
3146/// exists.
3148 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3149 I = ObjCImpls.find(D);
3150 if (I != ObjCImpls.end())
3151 return cast<ObjCCategoryImplDecl>(I->second);
3152 return nullptr;
3153}
3154
3155/// Set the implementation of ObjCInterfaceDecl.
3157 ObjCImplementationDecl *ImplD) {
3158 assert(IFaceD && ImplD && "Passed null params");
3159 ObjCImpls[IFaceD] = ImplD;
3160}
3161
3162/// Set the implementation of ObjCCategoryDecl.
3164 ObjCCategoryImplDecl *ImplD) {
3165 assert(CatD && ImplD && "Passed null params");
3166 ObjCImpls[CatD] = ImplD;
3167}
3168
3169const ObjCMethodDecl *
3171 return ObjCMethodRedecls.lookup(MD);
3172}
3173
3175 const ObjCMethodDecl *Redecl) {
3176 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
3177 ObjCMethodRedecls[MD] = Redecl;
3178}
3179
3181 const NamedDecl *ND) const {
3182 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
3183 return ID;
3184 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
3185 return CD->getClassInterface();
3186 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
3187 return IMD->getClassInterface();
3188
3189 return nullptr;
3190}
3191
3192/// Get the copy initialization expression of VarDecl, or nullptr if
3193/// none exists.
3195 assert(VD && "Passed null params");
3196 assert(VD->hasAttr<BlocksAttr>() &&
3197 "getBlockVarCopyInits - not __block var");
3198 auto I = BlockVarCopyInits.find(VD);
3199 if (I != BlockVarCopyInits.end())
3200 return I->second;
3201 return {nullptr, false};
3202}
3203
3204/// Set the copy initialization expression of a block var decl.
3206 bool CanThrow) {
3207 assert(VD && CopyExpr && "Passed null params");
3208 assert(VD->hasAttr<BlocksAttr>() &&
3209 "setBlockVarCopyInits - not __block var");
3210 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
3211}
3212
3214 unsigned DataSize) const {
3215 if (!DataSize)
3216 DataSize = TypeLoc::getFullDataSizeForType(T);
3217 else
3218 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
3219 "incorrect data size provided to CreateTypeSourceInfo!");
3220
3221 auto *TInfo =
3222 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
3223 new (TInfo) TypeSourceInfo(T, DataSize);
3224 return TInfo;
3225}
3226
3228 SourceLocation L) const {
3230 TSI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
3231 return TSI;
3232}
3233
3234const ASTRecordLayout &
3236 return getObjCLayout(D);
3237}
3238
3241 bool &AnyNonCanonArgs) {
3242 SmallVector<TemplateArgument, 16> CanonArgs(Args);
3243 AnyNonCanonArgs |= C.canonicalizeTemplateArguments(CanonArgs);
3244 return CanonArgs;
3245}
3246
3249 bool AnyNonCanonArgs = false;
3250 for (auto &Arg : Args) {
3251 TemplateArgument OrigArg = Arg;
3253 AnyNonCanonArgs |= !Arg.structurallyEquals(OrigArg);
3254 }
3255 return AnyNonCanonArgs;
3256}
3257
3258//===----------------------------------------------------------------------===//
3259// Type creation/memoization methods
3260//===----------------------------------------------------------------------===//
3261
3263ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3264 unsigned fastQuals = quals.getFastQualifiers();
3265 quals.removeFastQualifiers();
3266
3267 // Check if we've already instantiated this type.
3268 llvm::FoldingSetNodeID ID;
3269 ExtQuals::Profile(ID, baseType, quals);
3270 void *insertPos = nullptr;
3271 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
3272 assert(eq->getQualifiers() == quals);
3273 return QualType(eq, fastQuals);
3274 }
3275
3276 // If the base type is not canonical, make the appropriate canonical type.
3277 QualType canon;
3278 if (!baseType->isCanonicalUnqualified()) {
3279 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3280 canonSplit.Quals.addConsistentQualifiers(quals);
3281 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
3282
3283 // Re-find the insert position.
3284 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
3285 }
3286
3287 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3288 ExtQualNodes.InsertNode(eq, insertPos);
3289 return QualType(eq, fastQuals);
3290}
3291
3293 LangAS AddressSpace) const {
3294 QualType CanT = getCanonicalType(T);
3295 if (CanT.getAddressSpace() == AddressSpace)
3296 return T;
3297
3298 // If we are composing extended qualifiers together, merge together
3299 // into one ExtQuals node.
3300 QualifierCollector Quals;
3301 const Type *TypeNode = Quals.strip(T);
3302
3303 // If this type already has an address space specified, it cannot get
3304 // another one.
3305 assert(!Quals.hasAddressSpace() &&
3306 "Type cannot be in multiple addr spaces!");
3307 Quals.addAddressSpace(AddressSpace);
3308
3309 return getExtQualType(TypeNode, Quals);
3310}
3311
3313 // If the type is not qualified with an address space, just return it
3314 // immediately.
3315 if (!T.hasAddressSpace())
3316 return T;
3317
3318 QualifierCollector Quals;
3319 const Type *TypeNode;
3320 // For arrays, strip the qualifier off the element type, then reconstruct the
3321 // array type
3322 if (T.getTypePtr()->isArrayType()) {
3323 T = getUnqualifiedArrayType(T, Quals);
3324 TypeNode = T.getTypePtr();
3325 } else {
3326 // If we are composing extended qualifiers together, merge together
3327 // into one ExtQuals node.
3328 while (T.hasAddressSpace()) {
3329 TypeNode = Quals.strip(T);
3330
3331 // If the type no longer has an address space after stripping qualifiers,
3332 // jump out.
3333 if (!QualType(TypeNode, 0).hasAddressSpace())
3334 break;
3335
3336 // There might be sugar in the way. Strip it and try again.
3337 T = T.getSingleStepDesugaredType(*this);
3338 }
3339 }
3340
3341 Quals.removeAddressSpace();
3342
3343 // Removal of the address space can mean there are no longer any
3344 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3345 // or required.
3346 if (Quals.hasNonFastQualifiers())
3347 return getExtQualType(TypeNode, Quals);
3348 else
3349 return QualType(TypeNode, Quals.getFastQualifiers());
3350}
3351
3352uint16_t
3354 assert(RD->isPolymorphic() &&
3355 "Attempted to get vtable pointer discriminator on a monomorphic type");
3356 std::unique_ptr<MangleContext> MC(createMangleContext());
3357 SmallString<256> Str;
3358 llvm::raw_svector_ostream Out(Str);
3359 MC->mangleCXXVTable(RD, Out);
3360 return llvm::getPointerAuthStableSipHash(Str);
3361}
3362
3363/// Encode a function type for use in the discriminator of a function pointer
3364/// type. We can't use the itanium scheme for this since C has quite permissive
3365/// rules for type compatibility that we need to be compatible with.
3366///
3367/// Formally, this function associates every function pointer type T with an
3368/// encoded string E(T). Let the equivalence relation T1 ~ T2 be defined as
3369/// E(T1) == E(T2). E(T) is part of the ABI of values of type T. C type
3370/// compatibility requires equivalent treatment under the ABI, so
3371/// CCompatible(T1, T2) must imply E(T1) == E(T2), that is, CCompatible must be
3372/// a subset of ~. Crucially, however, it must be a proper subset because
3373/// CCompatible is not an equivalence relation: for example, int[] is compatible
3374/// with both int[1] and int[2], but the latter are not compatible with each
3375/// other. Therefore this encoding function must be careful to only distinguish
3376/// types if there is no third type with which they are both required to be
3377/// compatible.
3379 raw_ostream &OS, QualType QT) {
3380 // FIXME: Consider address space qualifiers.
3381 const Type *T = QT.getCanonicalType().getTypePtr();
3382
3383 // FIXME: Consider using the C++ type mangling when we encounter a construct
3384 // that is incompatible with C.
3385
3386 switch (T->getTypeClass()) {
3387 case Type::Atomic:
3389 Ctx, OS, cast<AtomicType>(T)->getValueType());
3390
3391 case Type::LValueReference:
3392 OS << "R";
3395 return;
3396 case Type::RValueReference:
3397 OS << "O";
3400 return;
3401
3402 case Type::Pointer:
3403 // C11 6.7.6.1p2:
3404 // For two pointer types to be compatible, both shall be identically
3405 // qualified and both shall be pointers to compatible types.
3406 // FIXME: we should also consider pointee types.
3407 OS << "P";
3408 return;
3409
3410 case Type::ObjCObjectPointer:
3411 case Type::BlockPointer:
3412 OS << "P";
3413 return;
3414
3415 case Type::Complex:
3416 OS << "C";
3418 Ctx, OS, cast<ComplexType>(T)->getElementType());
3419
3420 case Type::VariableArray:
3421 case Type::ConstantArray:
3422 case Type::IncompleteArray:
3423 case Type::ArrayParameter:
3424 // C11 6.7.6.2p6:
3425 // For two array types to be compatible, both shall have compatible
3426 // element types, and if both size specifiers are present, and are integer
3427 // constant expressions, then both size specifiers shall have the same
3428 // constant value [...]
3429 //
3430 // So since ElemType[N] has to be compatible ElemType[], we can't encode the
3431 // width of the array.
3432 OS << "A";
3434 Ctx, OS, cast<ArrayType>(T)->getElementType());
3435
3436 case Type::ObjCInterface:
3437 case Type::ObjCObject:
3438 OS << "<objc_object>";
3439 return;
3440
3441 case Type::Enum: {
3442 // C11 6.7.2.2p4:
3443 // Each enumerated type shall be compatible with char, a signed integer
3444 // type, or an unsigned integer type.
3445 //
3446 // So we have to treat enum types as integers.
3447 QualType UnderlyingType = T->castAsEnumDecl()->getIntegerType();
3449 Ctx, OS, UnderlyingType.isNull() ? Ctx.IntTy : UnderlyingType);
3450 }
3451
3452 case Type::FunctionNoProto:
3453 case Type::FunctionProto: {
3454 // C11 6.7.6.3p15:
3455 // For two function types to be compatible, both shall specify compatible
3456 // return types. Moreover, the parameter type lists, if both are present,
3457 // shall agree in the number of parameters and in the use of the ellipsis
3458 // terminator; corresponding parameters shall have compatible types.
3459 //
3460 // That paragraph goes on to describe how unprototyped functions are to be
3461 // handled, which we ignore here. Unprototyped function pointers are hashed
3462 // as though they were prototyped nullary functions since thats probably
3463 // what the user meant. This behavior is non-conforming.
3464 // FIXME: If we add a "custom discriminator" function type attribute we
3465 // should encode functions as their discriminators.
3466 OS << "F";
3467 const auto *FuncType = cast<FunctionType>(T);
3468 encodeTypeForFunctionPointerAuth(Ctx, OS, FuncType->getReturnType());
3469 if (const auto *FPT = dyn_cast<FunctionProtoType>(FuncType)) {
3470 for (QualType Param : FPT->param_types()) {
3471 Param = Ctx.getSignatureParameterType(Param);
3472 encodeTypeForFunctionPointerAuth(Ctx, OS, Param);
3473 }
3474 if (FPT->isVariadic())
3475 OS << "z";
3476 }
3477 OS << "E";
3478 return;
3479 }
3480
3481 case Type::MemberPointer: {
3482 OS << "M";
3483 const auto *MPT = T->castAs<MemberPointerType>();
3485 Ctx, OS, QualType(MPT->getQualifier().getAsType(), 0));
3486 encodeTypeForFunctionPointerAuth(Ctx, OS, MPT->getPointeeType());
3487 return;
3488 }
3489 case Type::ExtVector:
3490 case Type::Vector:
3491 OS << "Dv" << Ctx.getTypeSizeInChars(T).getQuantity();
3492 break;
3493
3494 // Don't bother discriminating based on these types.
3495 case Type::Pipe:
3496 case Type::BitInt:
3497 case Type::ConstantMatrix:
3498 OS << "?";
3499 return;
3500
3501 case Type::Builtin: {
3502 const auto *BTy = T->castAs<BuiltinType>();
3503 switch (BTy->getKind()) {
3504#define SIGNED_TYPE(Id, SingletonId) \
3505 case BuiltinType::Id: \
3506 OS << "i"; \
3507 return;
3508#define UNSIGNED_TYPE(Id, SingletonId) \
3509 case BuiltinType::Id: \
3510 OS << "i"; \
3511 return;
3512#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
3513#define BUILTIN_TYPE(Id, SingletonId)
3514#include "clang/AST/BuiltinTypes.def"
3515 llvm_unreachable("placeholder types should not appear here.");
3516
3517 case BuiltinType::Half:
3518 OS << "Dh";
3519 return;
3520 case BuiltinType::Float:
3521 OS << "f";
3522 return;
3523 case BuiltinType::Double:
3524 OS << "d";
3525 return;
3526 case BuiltinType::LongDouble:
3527 OS << "e";
3528 return;
3529 case BuiltinType::Float16:
3530 OS << "DF16_";
3531 return;
3532 case BuiltinType::Float128:
3533 OS << "g";
3534 return;
3535
3536 case BuiltinType::Void:
3537 OS << "v";
3538 return;
3539
3540 case BuiltinType::ObjCId:
3541 case BuiltinType::ObjCClass:
3542 case BuiltinType::ObjCSel:
3543 case BuiltinType::NullPtr:
3544 OS << "P";
3545 return;
3546
3547 // Don't bother discriminating based on OpenCL types.
3548 case BuiltinType::OCLSampler:
3549 case BuiltinType::OCLEvent:
3550 case BuiltinType::OCLClkEvent:
3551 case BuiltinType::OCLQueue:
3552 case BuiltinType::OCLReserveID:
3553 case BuiltinType::BFloat16:
3554 case BuiltinType::VectorQuad:
3555 case BuiltinType::VectorPair:
3556 case BuiltinType::DMR1024:
3557 case BuiltinType::DMR2048:
3558 OS << "?";
3559 return;
3560
3561 // Don't bother discriminating based on these seldom-used types.
3562 case BuiltinType::Ibm128:
3563 return;
3564#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3565 case BuiltinType::Id: \
3566 return;
3567#include "clang/Basic/OpenCLImageTypes.def"
3568#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3569 case BuiltinType::Id: \
3570 return;
3571#include "clang/Basic/OpenCLExtensionTypes.def"
3572#define SVE_TYPE(Name, Id, SingletonId) \
3573 case BuiltinType::Id: \
3574 return;
3575#include "clang/Basic/AArch64ACLETypes.def"
3576#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3577 case BuiltinType::Id: \
3578 return;
3579#include "clang/Basic/HLSLIntangibleTypes.def"
3580 case BuiltinType::Dependent:
3581 llvm_unreachable("should never get here");
3582#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
3583#include "clang/Basic/AMDGPUTypes.def"
3584 case BuiltinType::WasmExternRef:
3585#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3586#include "clang/Basic/RISCVVTypes.def"
3587 llvm_unreachable("not yet implemented");
3588 }
3589 llvm_unreachable("should never get here");
3590 }
3591 case Type::Record: {
3592 const RecordDecl *RD = T->castAsCanonical<RecordType>()->getDecl();
3593 const IdentifierInfo *II = RD->getIdentifier();
3594
3595 // In C++, an immediate typedef of an anonymous struct or union
3596 // is considered to name it for ODR purposes, but C's specification
3597 // of type compatibility does not have a similar rule. Using the typedef
3598 // name in function type discriminators anyway, as we do here,
3599 // therefore technically violates the C standard: two function pointer
3600 // types defined in terms of two typedef'd anonymous structs with
3601 // different names are formally still compatible, but we are assigning
3602 // them different discriminators and therefore incompatible ABIs.
3603 //
3604 // This is a relatively minor violation that significantly improves
3605 // discrimination in some cases and has not caused problems in
3606 // practice. Regardless, it is now part of the ABI in places where
3607 // function type discrimination is used, and it can no longer be
3608 // changed except on new platforms.
3609
3610 if (!II)
3611 if (const TypedefNameDecl *Typedef = RD->getTypedefNameForAnonDecl())
3612 II = Typedef->getDeclName().getAsIdentifierInfo();
3613
3614 if (!II) {
3615 OS << "<anonymous_record>";
3616 return;
3617 }
3618 OS << II->getLength() << II->getName();
3619 return;
3620 }
3621 case Type::HLSLAttributedResource:
3622 case Type::HLSLInlineSpirv:
3623 llvm_unreachable("should never get here");
3624 break;
3625 case Type::OverflowBehavior:
3626 llvm_unreachable("should never get here");
3627 break;
3628 case Type::DeducedTemplateSpecialization:
3629 case Type::Auto:
3630#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3631#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3632#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3633#define ABSTRACT_TYPE(Class, Base)
3634#define TYPE(Class, Base)
3635#include "clang/AST/TypeNodes.inc"
3636 llvm_unreachable("unexpected non-canonical or dependent type!");
3637 return;
3638 }
3639}
3640
3642 assert(!T->isDependentType() &&
3643 "cannot compute type discriminator of a dependent type");
3644 SmallString<256> Str;
3645 llvm::raw_svector_ostream Out(Str);
3646
3647 if (T->isFunctionPointerType() || T->isFunctionReferenceType())
3648 T = T->getPointeeType();
3649
3650 if (T->isFunctionType()) {
3651 encodeTypeForFunctionPointerAuth(*this, Out, T);
3652 } else {
3653 T = T.getUnqualifiedType();
3654 // Calls to member function pointers don't need to worry about
3655 // language interop or the laxness of the C type compatibility rules.
3656 // We just mangle the member pointer type directly, which is
3657 // implicitly much stricter about type matching. However, we do
3658 // strip any top-level exception specification before this mangling.
3659 // C++23 requires calls to work when the function type is convertible
3660 // to the pointer type by a function pointer conversion, which can
3661 // change the exception specification. This does not technically
3662 // require the exception specification to not affect representation,
3663 // because the function pointer conversion is still always a direct
3664 // value conversion and therefore an opportunity to resign the
3665 // pointer. (This is in contrast to e.g. qualification conversions,
3666 // which can be applied in nested pointer positions, effectively
3667 // requiring qualified and unqualified representations to match.)
3668 // However, it is pragmatic to ignore exception specifications
3669 // because it allows a certain amount of `noexcept` mismatching
3670 // to not become a visible ODR problem. This also leaves some
3671 // room for the committee to add laxness to function pointer
3672 // conversions in future standards.
3673 if (auto *MPT = T->getAs<MemberPointerType>())
3674 if (MPT->isMemberFunctionPointer()) {
3675 QualType PointeeType = MPT->getPointeeType();
3676 if (PointeeType->castAs<FunctionProtoType>()->getExceptionSpecType() !=
3677 EST_None) {
3679 T = getMemberPointerType(FT, MPT->getQualifier(),
3680 MPT->getMostRecentCXXRecordDecl());
3681 }
3682 }
3683 std::unique_ptr<MangleContext> MC(createMangleContext());
3684 MC->mangleCanonicalTypeName(T, Out);
3685 }
3686
3687 return llvm::getPointerAuthStableSipHash(Str);
3688}
3689
3691 Qualifiers::GC GCAttr) const {
3692 QualType CanT = getCanonicalType(T);
3693 if (CanT.getObjCGCAttr() == GCAttr)
3694 return T;
3695
3696 if (const auto *ptr = T->getAs<PointerType>()) {
3697 QualType Pointee = ptr->getPointeeType();
3698 if (Pointee->isAnyPointerType()) {
3699 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
3700 return getPointerType(ResultType);
3701 }
3702 }
3703
3704 // If we are composing extended qualifiers together, merge together
3705 // into one ExtQuals node.
3706 QualifierCollector Quals;
3707 const Type *TypeNode = Quals.strip(T);
3708
3709 // If this type already has an ObjCGC specified, it cannot get
3710 // another one.
3711 assert(!Quals.hasObjCGCAttr() &&
3712 "Type cannot have multiple ObjCGCs!");
3713 Quals.addObjCGCAttr(GCAttr);
3714
3715 return getExtQualType(TypeNode, Quals);
3716}
3717
3719 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3720 QualType Pointee = Ptr->getPointeeType();
3721 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3722 return getPointerType(removeAddrSpaceQualType(Pointee));
3723 }
3724 }
3725 return T;
3726}
3727
3729 QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull,
3730 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3731 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3732
3733 llvm::FoldingSetNodeID ID;
3734 CountAttributedType::Profile(ID, WrappedTy, CountExpr, CountInBytes, OrNull);
3735
3736 void *InsertPos = nullptr;
3737 CountAttributedType *CATy =
3738 CountAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
3739 if (CATy)
3740 return QualType(CATy, 0);
3741
3742 QualType CanonTy = getCanonicalType(WrappedTy);
3743 size_t Size = CountAttributedType::totalSizeToAlloc<TypeCoupledDeclRefInfo>(
3744 DependentDecls.size());
3746 new (CATy) CountAttributedType(WrappedTy, CanonTy, CountExpr, CountInBytes,
3747 OrNull, DependentDecls);
3748 Types.push_back(CATy);
3749 CountAttributedTypes.InsertNode(CATy, InsertPos);
3750
3751 return QualType(CATy, 0);
3752}
3753
3756 llvm::function_ref<QualType(QualType)> Adjust) const {
3757 switch (Orig->getTypeClass()) {
3758 case Type::Attributed: {
3759 const auto *AT = cast<AttributedType>(Orig);
3760 return getAttributedType(AT->getAttrKind(),
3761 adjustType(AT->getModifiedType(), Adjust),
3762 adjustType(AT->getEquivalentType(), Adjust),
3763 AT->getAttr());
3764 }
3765
3766 case Type::BTFTagAttributed: {
3767 const auto *BTFT = dyn_cast<BTFTagAttributedType>(Orig);
3768 return getBTFTagAttributedType(BTFT->getAttr(),
3769 adjustType(BTFT->getWrappedType(), Adjust));
3770 }
3771
3772 case Type::OverflowBehavior: {
3773 const auto *OB = dyn_cast<OverflowBehaviorType>(Orig);
3774 return getOverflowBehaviorType(OB->getBehaviorKind(),
3775 adjustType(OB->getUnderlyingType(), Adjust));
3776 }
3777
3778 case Type::Paren:
3779 return getParenType(
3780 adjustType(cast<ParenType>(Orig)->getInnerType(), Adjust));
3781
3782 case Type::Adjusted: {
3783 const auto *AT = cast<AdjustedType>(Orig);
3784 return getAdjustedType(AT->getOriginalType(),
3785 adjustType(AT->getAdjustedType(), Adjust));
3786 }
3787
3788 case Type::MacroQualified: {
3789 const auto *MQT = cast<MacroQualifiedType>(Orig);
3790 return getMacroQualifiedType(adjustType(MQT->getUnderlyingType(), Adjust),
3791 MQT->getMacroIdentifier());
3792 }
3793
3794 default:
3795 return Adjust(Orig);
3796 }
3797}
3798
3800 FunctionType::ExtInfo Info) {
3801 if (T->getExtInfo() == Info)
3802 return T;
3803
3805 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3806 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3807 } else {
3808 const auto *FPT = cast<FunctionProtoType>(T);
3809 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3810 EPI.ExtInfo = Info;
3811 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3812 }
3813
3814 return cast<FunctionType>(Result.getTypePtr());
3815}
3816
3818 QualType ResultType) {
3819 return adjustType(FunctionType, [&](QualType Orig) {
3820 if (const auto *FNPT = Orig->getAs<FunctionNoProtoType>())
3821 return getFunctionNoProtoType(ResultType, FNPT->getExtInfo());
3822
3823 const auto *FPT = Orig->castAs<FunctionProtoType>();
3824 return getFunctionType(ResultType, FPT->getParamTypes(),
3825 FPT->getExtProtoInfo());
3826 });
3827}
3828
3830 QualType ResultType) {
3831 FD = FD->getMostRecentDecl();
3832 while (true) {
3833 FD->setType(adjustFunctionResultType(FD->getType(), ResultType));
3834 if (FunctionDecl *Next = FD->getPreviousDecl())
3835 FD = Next;
3836 else
3837 break;
3838 }
3840 L->DeducedReturnType(FD, ResultType);
3841}
3842
3843/// Get a function type and produce the equivalent function type with the
3844/// specified exception specification. Type sugar that can be present on a
3845/// declaration of a function with an exception specification is permitted
3846/// and preserved. Other type sugar (for instance, typedefs) is not.
3848 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3849 return adjustType(Orig, [&](QualType Ty) {
3850 const auto *Proto = Ty->castAs<FunctionProtoType>();
3851 return getFunctionType(Proto->getReturnType(), Proto->getParamTypes(),
3852 Proto->getExtProtoInfo().withExceptionSpec(ESI));
3853 });
3854}
3855
3863
3865 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3866 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3867 SmallVector<QualType, 16> Args(Proto->param_types().size());
3868 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3869 Args[i] = removePtrSizeAddrSpace(Proto->param_types()[i]);
3870 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3871 }
3872
3873 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3874 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3875 return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3876 }
3877
3878 return T;
3879}
3880
3886
3888 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3889 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3890 EPI.ExtParameterInfos = nullptr;
3891 return getFunctionType(Proto->getReturnType(), Proto->param_types(), EPI);
3892 }
3893 return T;
3894}
3895
3901
3904 bool AsWritten) {
3905 // Update the type.
3906 QualType Updated =
3908 FD->setType(Updated);
3909
3910 if (!AsWritten)
3911 return;
3912
3913 // Update the type in the type source information too.
3914 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3915 // If the type and the type-as-written differ, we may need to update
3916 // the type-as-written too.
3917 if (TSInfo->getType() != FD->getType())
3918 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3919
3920 // FIXME: When we get proper type location information for exceptions,
3921 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3922 // up the TypeSourceInfo;
3923 assert(TypeLoc::getFullDataSizeForType(Updated) ==
3924 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3925 "TypeLoc size mismatch from updating exception specification");
3926 TSInfo->overrideType(Updated);
3927 }
3928}
3929
3930/// getComplexType - Return the uniqued reference to the type for a complex
3931/// number with the specified element type.
3933 // Unique pointers, to guarantee there is only one pointer of a particular
3934 // structure.
3935 llvm::FoldingSetNodeID ID;
3936 ComplexType::Profile(ID, T);
3937
3938 void *InsertPos = nullptr;
3939 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3940 return QualType(CT, 0);
3941
3942 // If the pointee type isn't canonical, this won't be a canonical type either,
3943 // so fill in the canonical type field.
3944 QualType Canonical;
3945 if (!T.isCanonical()) {
3946 Canonical = getComplexType(getCanonicalType(T));
3947
3948 // Get the new insert position for the node we care about.
3949 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3950 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3951 }
3952 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
3953 Types.push_back(New);
3954 ComplexTypes.InsertNode(New, InsertPos);
3955 return QualType(New, 0);
3956}
3957
3958/// getPointerType - Return the uniqued reference to the type for a pointer to
3959/// the specified type.
3961 // Unique pointers, to guarantee there is only one pointer of a particular
3962 // structure.
3963 llvm::FoldingSetNodeID ID;
3964 PointerType::Profile(ID, T);
3965
3966 void *InsertPos = nullptr;
3967 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3968 return QualType(PT, 0);
3969
3970 // If the pointee type isn't canonical, this won't be a canonical type either,
3971 // so fill in the canonical type field.
3972 QualType Canonical;
3973 if (!T.isCanonical()) {
3974 Canonical = getPointerType(getCanonicalType(T));
3975
3976 // Get the new insert position for the node we care about.
3977 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3978 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3979 }
3980 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
3981 Types.push_back(New);
3982 PointerTypes.InsertNode(New, InsertPos);
3983 return QualType(New, 0);
3984}
3985
3987 llvm::FoldingSetNodeID ID;
3988 AdjustedType::Profile(ID, Orig, New);
3989 void *InsertPos = nullptr;
3990 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3991 if (AT)
3992 return QualType(AT, 0);
3993
3994 QualType Canonical = getCanonicalType(New);
3995
3996 // Get the new insert position for the node we care about.
3997 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3998 assert(!AT && "Shouldn't be in the map!");
3999
4000 AT = new (*this, alignof(AdjustedType))
4001 AdjustedType(Type::Adjusted, Orig, New, Canonical);
4002 Types.push_back(AT);
4003 AdjustedTypes.InsertNode(AT, InsertPos);
4004 return QualType(AT, 0);
4005}
4006
4008 llvm::FoldingSetNodeID ID;
4009 AdjustedType::Profile(ID, Orig, Decayed);
4010 void *InsertPos = nullptr;
4011 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
4012 if (AT)
4013 return QualType(AT, 0);
4014
4015 QualType Canonical = getCanonicalType(Decayed);
4016
4017 // Get the new insert position for the node we care about.
4018 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
4019 assert(!AT && "Shouldn't be in the map!");
4020
4021 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
4022 Types.push_back(AT);
4023 AdjustedTypes.InsertNode(AT, InsertPos);
4024 return QualType(AT, 0);
4025}
4026
4028 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
4029
4030 QualType Decayed;
4031
4032 // C99 6.7.5.3p7:
4033 // A declaration of a parameter as "array of type" shall be
4034 // adjusted to "qualified pointer to type", where the type
4035 // qualifiers (if any) are those specified within the [ and ] of
4036 // the array type derivation.
4037 if (T->isArrayType())
4038 Decayed = getArrayDecayedType(T);
4039
4040 // C99 6.7.5.3p8:
4041 // A declaration of a parameter as "function returning type"
4042 // shall be adjusted to "pointer to function returning type", as
4043 // in 6.3.2.1.
4044 if (T->isFunctionType())
4045 Decayed = getPointerType(T);
4046
4047 return getDecayedType(T, Decayed);
4048}
4049
4051 if (Ty->isArrayParameterType())
4052 return Ty;
4053 assert(Ty->isConstantArrayType() && "Ty must be an array type.");
4054 QualType DTy = Ty.getDesugaredType(*this);
4055 const auto *ATy = cast<ConstantArrayType>(DTy);
4056 llvm::FoldingSetNodeID ID;
4057 ATy->Profile(ID, *this, ATy->getElementType(), ATy->getZExtSize(),
4058 ATy->getSizeExpr(), ATy->getSizeModifier(),
4059 ATy->getIndexTypeQualifiers().getAsOpaqueValue());
4060 void *InsertPos = nullptr;
4061 ArrayParameterType *AT =
4062 ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
4063 if (AT)
4064 return QualType(AT, 0);
4065
4066 QualType Canonical;
4067 if (!DTy.isCanonical()) {
4068 Canonical = getArrayParameterType(getCanonicalType(Ty));
4069
4070 // Get the new insert position for the node we care about.
4071 AT = ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
4072 assert(!AT && "Shouldn't be in the map!");
4073 }
4074
4075 AT = new (*this, alignof(ArrayParameterType))
4076 ArrayParameterType(ATy, Canonical);
4077 Types.push_back(AT);
4078 ArrayParameterTypes.InsertNode(AT, InsertPos);
4079 return QualType(AT, 0);
4080}
4081
4082/// getBlockPointerType - Return the uniqued reference to the type for
4083/// a pointer to the specified block.
4085 assert(T->isFunctionType() && "block of function types only");
4086 // Unique pointers, to guarantee there is only one block of a particular
4087 // structure.
4088 llvm::FoldingSetNodeID ID;
4090
4091 void *InsertPos = nullptr;
4092 if (BlockPointerType *PT =
4093 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4094 return QualType(PT, 0);
4095
4096 // If the block pointee type isn't canonical, this won't be a canonical
4097 // type either so fill in the canonical type field.
4098 QualType Canonical;
4099 if (!T.isCanonical()) {
4100 Canonical = getBlockPointerType(getCanonicalType(T));
4101
4102 // Get the new insert position for the node we care about.
4103 BlockPointerType *NewIP =
4104 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4105 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4106 }
4107 auto *New =
4108 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
4109 Types.push_back(New);
4110 BlockPointerTypes.InsertNode(New, InsertPos);
4111 return QualType(New, 0);
4112}
4113
4114/// getLValueReferenceType - Return the uniqued reference to the type for an
4115/// lvalue reference to the specified type.
4117ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
4118 assert((!T->isPlaceholderType() ||
4119 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4120 "Unresolved placeholder type");
4121
4122 // Unique pointers, to guarantee there is only one pointer of a particular
4123 // structure.
4124 llvm::FoldingSetNodeID ID;
4125 ReferenceType::Profile(ID, T, SpelledAsLValue);
4126
4127 void *InsertPos = nullptr;
4128 if (LValueReferenceType *RT =
4129 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4130 return QualType(RT, 0);
4131
4132 const auto *InnerRef = T->getAs<ReferenceType>();
4133
4134 // If the referencee type isn't canonical, this won't be a canonical type
4135 // either, so fill in the canonical type field.
4136 QualType Canonical;
4137 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
4138 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4139 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
4140
4141 // Get the new insert position for the node we care about.
4142 LValueReferenceType *NewIP =
4143 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4144 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4145 }
4146
4147 auto *New = new (*this, alignof(LValueReferenceType))
4148 LValueReferenceType(T, Canonical, SpelledAsLValue);
4149 Types.push_back(New);
4150 LValueReferenceTypes.InsertNode(New, InsertPos);
4151
4152 return QualType(New, 0);
4153}
4154
4155/// getRValueReferenceType - Return the uniqued reference to the type for an
4156/// rvalue reference to the specified type.
4158 assert((!T->isPlaceholderType() ||
4159 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4160 "Unresolved placeholder type");
4161
4162 // Unique pointers, to guarantee there is only one pointer of a particular
4163 // structure.
4164 llvm::FoldingSetNodeID ID;
4165 ReferenceType::Profile(ID, T, false);
4166
4167 void *InsertPos = nullptr;
4168 if (RValueReferenceType *RT =
4169 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4170 return QualType(RT, 0);
4171
4172 const auto *InnerRef = T->getAs<ReferenceType>();
4173
4174 // If the referencee type isn't canonical, this won't be a canonical type
4175 // either, so fill in the canonical type field.
4176 QualType Canonical;
4177 if (InnerRef || !T.isCanonical()) {
4178 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4179 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
4180
4181 // Get the new insert position for the node we care about.
4182 RValueReferenceType *NewIP =
4183 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4184 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4185 }
4186
4187 auto *New = new (*this, alignof(RValueReferenceType))
4188 RValueReferenceType(T, Canonical);
4189 Types.push_back(New);
4190 RValueReferenceTypes.InsertNode(New, InsertPos);
4191 return QualType(New, 0);
4192}
4193
4195 NestedNameSpecifier Qualifier,
4196 const CXXRecordDecl *Cls) const {
4197 if (!Qualifier) {
4198 assert(Cls && "At least one of Qualifier or Cls must be provided");
4199 Qualifier = NestedNameSpecifier(getCanonicalTagType(Cls).getTypePtr());
4200 } else if (!Cls) {
4201 Cls = Qualifier.getAsRecordDecl();
4202 }
4203 // Unique pointers, to guarantee there is only one pointer of a particular
4204 // structure.
4205 llvm::FoldingSetNodeID ID;
4206 MemberPointerType::Profile(ID, T, Qualifier, Cls);
4207
4208 void *InsertPos = nullptr;
4209 if (MemberPointerType *PT =
4210 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4211 return QualType(PT, 0);
4212
4213 NestedNameSpecifier CanonicalQualifier = [&] {
4214 if (!Cls)
4215 return Qualifier.getCanonical();
4216 NestedNameSpecifier R(getCanonicalTagType(Cls).getTypePtr());
4217 assert(R.isCanonical());
4218 return R;
4219 }();
4220 // If the pointee or class type isn't canonical, this won't be a canonical
4221 // type either, so fill in the canonical type field.
4222 QualType Canonical;
4223 if (!T.isCanonical() || Qualifier != CanonicalQualifier) {
4224 Canonical =
4225 getMemberPointerType(getCanonicalType(T), CanonicalQualifier, Cls);
4226 assert(!cast<MemberPointerType>(Canonical)->isSugared());
4227 // Get the new insert position for the node we care about.
4228 [[maybe_unused]] MemberPointerType *NewIP =
4229 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4230 assert(!NewIP && "Shouldn't be in the map!");
4231 }
4232 auto *New = new (*this, alignof(MemberPointerType))
4233 MemberPointerType(T, Qualifier, Canonical);
4234 Types.push_back(New);
4235 MemberPointerTypes.InsertNode(New, InsertPos);
4236 return QualType(New, 0);
4237}
4238
4239/// getConstantArrayType - Return the unique reference to the type for an
4240/// array of the specified element type.
4242 const llvm::APInt &ArySizeIn,
4243 const Expr *SizeExpr,
4245 unsigned IndexTypeQuals) const {
4246 assert((EltTy->isDependentType() ||
4247 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
4248 "Constant array of VLAs is illegal!");
4249
4250 // We only need the size as part of the type if it's instantiation-dependent.
4251 if (SizeExpr && !SizeExpr->isInstantiationDependent())
4252 SizeExpr = nullptr;
4253
4254 // Convert the array size into a canonical width matching the pointer size for
4255 // the target.
4256 llvm::APInt ArySize(ArySizeIn);
4257 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
4258
4259 llvm::FoldingSetNodeID ID;
4260 ConstantArrayType::Profile(ID, *this, EltTy, ArySize.getZExtValue(), SizeExpr,
4261 ASM, IndexTypeQuals);
4262
4263 void *InsertPos = nullptr;
4264 if (ConstantArrayType *ATP =
4265 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
4266 return QualType(ATP, 0);
4267
4268 // If the element type isn't canonical or has qualifiers, or the array bound
4269 // is instantiation-dependent, this won't be a canonical type either, so fill
4270 // in the canonical type field.
4271 QualType Canon;
4272 // FIXME: Check below should look for qualifiers behind sugar.
4273 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
4274 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4275 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
4276 ASM, IndexTypeQuals);
4277 Canon = getQualifiedType(Canon, canonSplit.Quals);
4278
4279 // Get the new insert position for the node we care about.
4280 ConstantArrayType *NewIP =
4281 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
4282 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4283 }
4284
4285 auto *New = ConstantArrayType::Create(*this, EltTy, Canon, ArySize, SizeExpr,
4286 ASM, IndexTypeQuals);
4287 ConstantArrayTypes.InsertNode(New, InsertPos);
4288 Types.push_back(New);
4289 return QualType(New, 0);
4290}
4291
4292/// getVariableArrayDecayedType - Turns the given type, which may be
4293/// variably-modified, into the corresponding type with all the known
4294/// sizes replaced with [*].
4296 // Vastly most common case.
4297 if (!type->isVariablyModifiedType()) return type;
4298
4299 QualType result;
4300
4301 SplitQualType split = type.getSplitDesugaredType();
4302 const Type *ty = split.Ty;
4303 switch (ty->getTypeClass()) {
4304#define TYPE(Class, Base)
4305#define ABSTRACT_TYPE(Class, Base)
4306#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4307#include "clang/AST/TypeNodes.inc"
4308 llvm_unreachable("didn't desugar past all non-canonical types?");
4309
4310 // These types should never be variably-modified.
4311 case Type::Builtin:
4312 case Type::Complex:
4313 case Type::Vector:
4314 case Type::DependentVector:
4315 case Type::ExtVector:
4316 case Type::DependentSizedExtVector:
4317 case Type::ConstantMatrix:
4318 case Type::DependentSizedMatrix:
4319 case Type::DependentAddressSpace:
4320 case Type::ObjCObject:
4321 case Type::ObjCInterface:
4322 case Type::ObjCObjectPointer:
4323 case Type::Record:
4324 case Type::Enum:
4325 case Type::UnresolvedUsing:
4326 case Type::TypeOfExpr:
4327 case Type::TypeOf:
4328 case Type::Decltype:
4329 case Type::UnaryTransform:
4330 case Type::DependentName:
4331 case Type::InjectedClassName:
4332 case Type::TemplateSpecialization:
4333 case Type::TemplateTypeParm:
4334 case Type::SubstTemplateTypeParmPack:
4335 case Type::SubstBuiltinTemplatePack:
4336 case Type::Auto:
4337 case Type::DeducedTemplateSpecialization:
4338 case Type::PackExpansion:
4339 case Type::PackIndexing:
4340 case Type::BitInt:
4341 case Type::DependentBitInt:
4342 case Type::ArrayParameter:
4343 case Type::HLSLAttributedResource:
4344 case Type::HLSLInlineSpirv:
4345 case Type::OverflowBehavior:
4346 llvm_unreachable("type should never be variably-modified");
4347
4348 // These types can be variably-modified but should never need to
4349 // further decay.
4350 case Type::FunctionNoProto:
4351 case Type::FunctionProto:
4352 case Type::BlockPointer:
4353 case Type::MemberPointer:
4354 case Type::Pipe:
4355 return type;
4356
4357 // These types can be variably-modified. All these modifications
4358 // preserve structure except as noted by comments.
4359 // TODO: if we ever care about optimizing VLAs, there are no-op
4360 // optimizations available here.
4361 case Type::Pointer:
4364 break;
4365
4366 case Type::LValueReference: {
4367 const auto *lv = cast<LValueReferenceType>(ty);
4368 result = getLValueReferenceType(
4369 getVariableArrayDecayedType(lv->getPointeeType()),
4370 lv->isSpelledAsLValue());
4371 break;
4372 }
4373
4374 case Type::RValueReference: {
4375 const auto *lv = cast<RValueReferenceType>(ty);
4376 result = getRValueReferenceType(
4377 getVariableArrayDecayedType(lv->getPointeeType()));
4378 break;
4379 }
4380
4381 case Type::Atomic: {
4382 const auto *at = cast<AtomicType>(ty);
4383 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
4384 break;
4385 }
4386
4387 case Type::ConstantArray: {
4388 const auto *cat = cast<ConstantArrayType>(ty);
4389 result = getConstantArrayType(
4390 getVariableArrayDecayedType(cat->getElementType()),
4391 cat->getSize(),
4392 cat->getSizeExpr(),
4393 cat->getSizeModifier(),
4394 cat->getIndexTypeCVRQualifiers());
4395 break;
4396 }
4397
4398 case Type::DependentSizedArray: {
4399 const auto *dat = cast<DependentSizedArrayType>(ty);
4401 getVariableArrayDecayedType(dat->getElementType()), dat->getSizeExpr(),
4402 dat->getSizeModifier(), dat->getIndexTypeCVRQualifiers());
4403 break;
4404 }
4405
4406 // Turn incomplete types into [*] types.
4407 case Type::IncompleteArray: {
4408 const auto *iat = cast<IncompleteArrayType>(ty);
4409 result =
4411 /*size*/ nullptr, ArraySizeModifier::Normal,
4412 iat->getIndexTypeCVRQualifiers());
4413 break;
4414 }
4415
4416 // Turn VLA types into [*] types.
4417 case Type::VariableArray: {
4418 const auto *vat = cast<VariableArrayType>(ty);
4419 result =
4421 /*size*/ nullptr, ArraySizeModifier::Star,
4422 vat->getIndexTypeCVRQualifiers());
4423 break;
4424 }
4425 }
4426
4427 // Apply the top-level qualifiers from the original.
4428 return getQualifiedType(result, split.Quals);
4429}
4430
4431/// getVariableArrayType - Returns a non-unique reference to the type for a
4432/// variable array of the specified element type.
4435 unsigned IndexTypeQuals) const {
4436 // Since we don't unique expressions, it isn't possible to unique VLA's
4437 // that have an expression provided for their size.
4438 QualType Canon;
4439
4440 // Be sure to pull qualifiers off the element type.
4441 // FIXME: Check below should look for qualifiers behind sugar.
4442 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
4443 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4444 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
4445 IndexTypeQuals);
4446 Canon = getQualifiedType(Canon, canonSplit.Quals);
4447 }
4448
4449 auto *New = new (*this, alignof(VariableArrayType))
4450 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals);
4451
4452 VariableArrayTypes.push_back(New);
4453 Types.push_back(New);
4454 return QualType(New, 0);
4455}
4456
4457/// getDependentSizedArrayType - Returns a non-unique reference to
4458/// the type for a dependently-sized array of the specified element
4459/// type.
4463 unsigned elementTypeQuals) const {
4464 assert((!numElements || numElements->isTypeDependent() ||
4465 numElements->isValueDependent()) &&
4466 "Size must be type- or value-dependent!");
4467
4468 SplitQualType canonElementType = getCanonicalType(elementType).split();
4469
4470 void *insertPos = nullptr;
4471 llvm::FoldingSetNodeID ID;
4473 ID, *this, numElements ? QualType(canonElementType.Ty, 0) : elementType,
4474 ASM, elementTypeQuals, numElements);
4475
4476 // Look for an existing type with these properties.
4477 DependentSizedArrayType *canonTy =
4478 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4479
4480 // Dependently-sized array types that do not have a specified number
4481 // of elements will have their sizes deduced from a dependent
4482 // initializer.
4483 if (!numElements) {
4484 if (canonTy)
4485 return QualType(canonTy, 0);
4486
4487 auto *newType = new (*this, alignof(DependentSizedArrayType))
4488 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
4489 elementTypeQuals);
4490 DependentSizedArrayTypes.InsertNode(newType, insertPos);
4491 Types.push_back(newType);
4492 return QualType(newType, 0);
4493 }
4494
4495 // If we don't have one, build one.
4496 if (!canonTy) {
4497 canonTy = new (*this, alignof(DependentSizedArrayType))
4498 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
4499 numElements, ASM, elementTypeQuals);
4500 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
4501 Types.push_back(canonTy);
4502 }
4503
4504 // Apply qualifiers from the element type to the array.
4505 QualType canon = getQualifiedType(QualType(canonTy,0),
4506 canonElementType.Quals);
4507
4508 // If we didn't need extra canonicalization for the element type or the size
4509 // expression, then just use that as our result.
4510 if (QualType(canonElementType.Ty, 0) == elementType &&
4511 canonTy->getSizeExpr() == numElements)
4512 return canon;
4513
4514 // Otherwise, we need to build a type which follows the spelling
4515 // of the element type.
4516 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
4517 DependentSizedArrayType(elementType, canon, numElements, ASM,
4518 elementTypeQuals);
4519 Types.push_back(sugaredType);
4520 return QualType(sugaredType, 0);
4521}
4522
4525 unsigned elementTypeQuals) const {
4526 llvm::FoldingSetNodeID ID;
4527 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
4528
4529 void *insertPos = nullptr;
4530 if (IncompleteArrayType *iat =
4531 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
4532 return QualType(iat, 0);
4533
4534 // If the element type isn't canonical, this won't be a canonical type
4535 // either, so fill in the canonical type field. We also have to pull
4536 // qualifiers off the element type.
4537 QualType canon;
4538
4539 // FIXME: Check below should look for qualifiers behind sugar.
4540 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
4541 SplitQualType canonSplit = getCanonicalType(elementType).split();
4542 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
4543 ASM, elementTypeQuals);
4544 canon = getQualifiedType(canon, canonSplit.Quals);
4545
4546 // Get the new insert position for the node we care about.
4547 IncompleteArrayType *existing =
4548 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4549 assert(!existing && "Shouldn't be in the map!"); (void) existing;
4550 }
4551
4552 auto *newType = new (*this, alignof(IncompleteArrayType))
4553 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
4554
4555 IncompleteArrayTypes.InsertNode(newType, insertPos);
4556 Types.push_back(newType);
4557 return QualType(newType, 0);
4558}
4559
4562#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
4563 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
4564 NUMVECTORS};
4565
4566#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
4567 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
4568
4569 switch (Ty->getKind()) {
4570 default:
4571 llvm_unreachable("Unsupported builtin vector type");
4572
4573#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4574 ElBits, NF, IsSigned) \
4575 case BuiltinType::Id: \
4576 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4577 llvm::ElementCount::getScalable(NumEls), NF};
4578#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4579 ElBits, NF) \
4580 case BuiltinType::Id: \
4581 return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy), \
4582 llvm::ElementCount::getScalable(NumEls), NF};
4583#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4584 ElBits, NF) \
4585 case BuiltinType::Id: \
4586 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4587#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4588 ElBits, NF) \
4589 case BuiltinType::Id: \
4590 return {MFloat8Ty, llvm::ElementCount::getScalable(NumEls), NF};
4591#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4592 case BuiltinType::Id: \
4593 return {BoolTy, llvm::ElementCount::getScalable(NumEls), NF};
4594#include "clang/Basic/AArch64ACLETypes.def"
4595
4596#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4597 IsSigned) \
4598 case BuiltinType::Id: \
4599 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4600 llvm::ElementCount::getScalable(NumEls), NF};
4601#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4602 case BuiltinType::Id: \
4603 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4604 llvm::ElementCount::getScalable(NumEls), NF};
4605#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4606 case BuiltinType::Id: \
4607 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4608#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4609 case BuiltinType::Id: \
4610 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4611#include "clang/Basic/RISCVVTypes.def"
4612 }
4613}
4614
4615/// getExternrefType - Return a WebAssembly externref type, which represents an
4616/// opaque reference to a host value.
4618 if (Target->getTriple().isWasm() && Target->hasFeature("reference-types")) {
4619#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4620 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4621 return SingletonId;
4622#include "clang/Basic/WebAssemblyReferenceTypes.def"
4623 }
4624 llvm_unreachable(
4625 "shouldn't try to generate type externref outside WebAssembly target");
4626}
4627
4628/// getScalableVectorType - Return the unique reference to a scalable vector
4629/// type of the specified element type and size. VectorType must be a built-in
4630/// type.
4632 unsigned NumFields) const {
4633 auto K = llvm::ScalableVecTyKey{EltTy, NumElts, NumFields};
4634 if (auto It = ScalableVecTyMap.find(K); It != ScalableVecTyMap.end())
4635 return It->second;
4636
4637 if (Target->hasAArch64ACLETypes()) {
4638 uint64_t EltTySize = getTypeSize(EltTy);
4639
4640#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4641 ElBits, NF, IsSigned) \
4642 if (EltTy->hasIntegerRepresentation() && !EltTy->isBooleanType() && \
4643 EltTy->hasSignedIntegerRepresentation() == IsSigned && \
4644 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4645 return ScalableVecTyMap[K] = SingletonId; \
4646 }
4647#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4648 ElBits, NF) \
4649 if (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4650 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4651 return ScalableVecTyMap[K] = SingletonId; \
4652 }
4653#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4654 ElBits, NF) \
4655 if (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4656 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4657 return ScalableVecTyMap[K] = SingletonId; \
4658 }
4659#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4660 ElBits, NF) \
4661 if (EltTy->isMFloat8Type() && EltTySize == ElBits && \
4662 NumElts == (NumEls * NF) && NumFields == 1) { \
4663 return ScalableVecTyMap[K] = SingletonId; \
4664 }
4665#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4666 if (EltTy->isBooleanType() && NumElts == (NumEls * NF) && NumFields == 1) \
4667 return ScalableVecTyMap[K] = SingletonId;
4668#include "clang/Basic/AArch64ACLETypes.def"
4669 } else if (Target->hasRISCVVTypes()) {
4670 uint64_t EltTySize = getTypeSize(EltTy);
4671#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4672 IsFP, IsBF) \
4673 if (!EltTy->isBooleanType() && \
4674 ((EltTy->hasIntegerRepresentation() && \
4675 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4676 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4677 IsFP && !IsBF) || \
4678 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4679 IsBF && !IsFP)) && \
4680 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4681 return ScalableVecTyMap[K] = SingletonId;
4682#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4683 if (EltTy->isBooleanType() && NumElts == NumEls) \
4684 return ScalableVecTyMap[K] = SingletonId;
4685#include "clang/Basic/RISCVVTypes.def"
4686 }
4687 return QualType();
4688}
4689
4690/// getVectorType - Return the unique reference to a vector type of
4691/// the specified element type and size. VectorType must be a built-in type.
4693 VectorKind VecKind) const {
4694 assert(vecType->isBuiltinType() ||
4695 (vecType->isBitIntType() &&
4696 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4697 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4698
4699 // Check if we've already instantiated a vector of this type.
4700 llvm::FoldingSetNodeID ID;
4701 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
4702
4703 void *InsertPos = nullptr;
4704 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4705 return QualType(VTP, 0);
4706
4707 // If the element type isn't canonical, this won't be a canonical type either,
4708 // so fill in the canonical type field.
4709 QualType Canonical;
4710 if (!vecType.isCanonical()) {
4711 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4712
4713 // Get the new insert position for the node we care about.
4714 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4715 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4716 }
4717 auto *New = new (*this, alignof(VectorType))
4718 VectorType(vecType, NumElts, Canonical, VecKind);
4719 VectorTypes.InsertNode(New, InsertPos);
4720 Types.push_back(New);
4721 return QualType(New, 0);
4722}
4723
4725 SourceLocation AttrLoc,
4726 VectorKind VecKind) const {
4727 llvm::FoldingSetNodeID ID;
4728 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4729 VecKind);
4730 void *InsertPos = nullptr;
4731 DependentVectorType *Canon =
4732 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4734
4735 if (Canon) {
4736 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4737 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4738 } else {
4739 QualType CanonVecTy = getCanonicalType(VecType);
4740 if (CanonVecTy == VecType) {
4741 New = new (*this, alignof(DependentVectorType))
4742 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4743
4744 DependentVectorType *CanonCheck =
4745 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4746 assert(!CanonCheck &&
4747 "Dependent-sized vector_size canonical type broken");
4748 (void)CanonCheck;
4749 DependentVectorTypes.InsertNode(New, InsertPos);
4750 } else {
4751 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4752 SourceLocation(), VecKind);
4753 New = new (*this, alignof(DependentVectorType))
4754 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4755 }
4756 }
4757
4758 Types.push_back(New);
4759 return QualType(New, 0);
4760}
4761
4762/// getExtVectorType - Return the unique reference to an extended vector type of
4763/// the specified element type and size. VectorType must be a built-in type.
4765 unsigned NumElts) const {
4766 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4767 (vecType->isBitIntType() &&
4768 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4769 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4770
4771 // Check if we've already instantiated a vector of this type.
4772 llvm::FoldingSetNodeID ID;
4773 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4775 void *InsertPos = nullptr;
4776 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4777 return QualType(VTP, 0);
4778
4779 // If the element type isn't canonical, this won't be a canonical type either,
4780 // so fill in the canonical type field.
4781 QualType Canonical;
4782 if (!vecType.isCanonical()) {
4783 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4784
4785 // Get the new insert position for the node we care about.
4786 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4787 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4788 }
4789 auto *New = new (*this, alignof(ExtVectorType))
4790 ExtVectorType(vecType, NumElts, Canonical);
4791 VectorTypes.InsertNode(New, InsertPos);
4792 Types.push_back(New);
4793 return QualType(New, 0);
4794}
4795
4798 Expr *SizeExpr,
4799 SourceLocation AttrLoc) const {
4800 llvm::FoldingSetNodeID ID;
4802 SizeExpr);
4803
4804 void *InsertPos = nullptr;
4806 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4808 if (Canon) {
4809 // We already have a canonical version of this array type; use it as
4810 // the canonical type for a newly-built type.
4811 New = new (*this, alignof(DependentSizedExtVectorType))
4812 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4813 AttrLoc);
4814 } else {
4815 QualType CanonVecTy = getCanonicalType(vecType);
4816 if (CanonVecTy == vecType) {
4817 New = new (*this, alignof(DependentSizedExtVectorType))
4818 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4819
4820 DependentSizedExtVectorType *CanonCheck
4821 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4822 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4823 (void)CanonCheck;
4824 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4825 } else {
4826 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4827 SourceLocation());
4828 New = new (*this, alignof(DependentSizedExtVectorType))
4829 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4830 }
4831 }
4832
4833 Types.push_back(New);
4834 return QualType(New, 0);
4835}
4836
4838 unsigned NumColumns) const {
4839 llvm::FoldingSetNodeID ID;
4840 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4841 Type::ConstantMatrix);
4842
4843 assert(MatrixType::isValidElementType(ElementTy, getLangOpts()) &&
4844 "need a valid element type");
4845 assert(NumRows > 0 && NumRows <= LangOpts.MaxMatrixDimension &&
4846 NumColumns > 0 && NumColumns <= LangOpts.MaxMatrixDimension &&
4847 "need valid matrix dimensions");
4848 void *InsertPos = nullptr;
4849 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4850 return QualType(MTP, 0);
4851
4852 QualType Canonical;
4853 if (!ElementTy.isCanonical()) {
4854 Canonical =
4855 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4856
4857 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4858 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4859 (void)NewIP;
4860 }
4861
4862 auto *New = new (*this, alignof(ConstantMatrixType))
4863 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4864 MatrixTypes.InsertNode(New, InsertPos);
4865 Types.push_back(New);
4866 return QualType(New, 0);
4867}
4868
4870 Expr *RowExpr,
4871 Expr *ColumnExpr,
4872 SourceLocation AttrLoc) const {
4873 QualType CanonElementTy = getCanonicalType(ElementTy);
4874 llvm::FoldingSetNodeID ID;
4875 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4876 ColumnExpr);
4877
4878 void *InsertPos = nullptr;
4880 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4881
4882 if (!Canon) {
4883 Canon = new (*this, alignof(DependentSizedMatrixType))
4884 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4885 ColumnExpr, AttrLoc);
4886#ifndef NDEBUG
4887 DependentSizedMatrixType *CanonCheck =
4888 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4889 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4890#endif
4891 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4892 Types.push_back(Canon);
4893 }
4894
4895 // Already have a canonical version of the matrix type
4896 //
4897 // If it exactly matches the requested type, use it directly.
4898 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4899 Canon->getRowExpr() == ColumnExpr)
4900 return QualType(Canon, 0);
4901
4902 // Use Canon as the canonical type for newly-built type.
4904 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4905 ColumnExpr, AttrLoc);
4906 Types.push_back(New);
4907 return QualType(New, 0);
4908}
4909
4911 Expr *AddrSpaceExpr,
4912 SourceLocation AttrLoc) const {
4913 assert(AddrSpaceExpr->isInstantiationDependent());
4914
4915 QualType canonPointeeType = getCanonicalType(PointeeType);
4916
4917 void *insertPos = nullptr;
4918 llvm::FoldingSetNodeID ID;
4919 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4920 AddrSpaceExpr);
4921
4922 DependentAddressSpaceType *canonTy =
4923 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4924
4925 if (!canonTy) {
4926 canonTy = new (*this, alignof(DependentAddressSpaceType))
4927 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
4928 AttrLoc);
4929 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4930 Types.push_back(canonTy);
4931 }
4932
4933 if (canonPointeeType == PointeeType &&
4934 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4935 return QualType(canonTy, 0);
4936
4937 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
4938 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
4939 AddrSpaceExpr, AttrLoc);
4940 Types.push_back(sugaredType);
4941 return QualType(sugaredType, 0);
4942}
4943
4944/// Determine whether \p T is canonical as the result type of a function.
4946 return T.isCanonical() &&
4947 (T.getObjCLifetime() == Qualifiers::OCL_None ||
4948 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4949}
4950
4951/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4952QualType
4954 const FunctionType::ExtInfo &Info) const {
4955 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
4956 // functionality creates a function without a prototype regardless of
4957 // language mode (so it makes them even in C++). Once the rewriter has been
4958 // fixed, this assertion can be enabled again.
4959 //assert(!LangOpts.requiresStrictPrototypes() &&
4960 // "strict prototypes are disabled");
4961
4962 // Unique functions, to guarantee there is only one function of a particular
4963 // structure.
4964 llvm::FoldingSetNodeID ID;
4965 FunctionNoProtoType::Profile(ID, ResultTy, Info);
4966
4967 void *InsertPos = nullptr;
4968 if (FunctionNoProtoType *FT =
4969 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4970 return QualType(FT, 0);
4971
4972 QualType Canonical;
4973 if (!isCanonicalResultType(ResultTy)) {
4974 Canonical =
4976
4977 // Get the new insert position for the node we care about.
4978 FunctionNoProtoType *NewIP =
4979 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4980 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4981 }
4982
4983 auto *New = new (*this, alignof(FunctionNoProtoType))
4984 FunctionNoProtoType(ResultTy, Canonical, Info);
4985 Types.push_back(New);
4986 FunctionNoProtoTypes.InsertNode(New, InsertPos);
4987 return QualType(New, 0);
4988}
4989
4992 CanQualType CanResultType = getCanonicalType(ResultType);
4993
4994 // Canonical result types do not have ARC lifetime qualifiers.
4995 if (CanResultType.getQualifiers().hasObjCLifetime()) {
4996 Qualifiers Qs = CanResultType.getQualifiers();
4997 Qs.removeObjCLifetime();
4999 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
5000 }
5001
5002 return CanResultType;
5003}
5004
5006 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
5007 if (ESI.Type == EST_None)
5008 return true;
5009 if (!NoexceptInType)
5010 return false;
5011
5012 // C++17 onwards: exception specification is part of the type, as a simple
5013 // boolean "can this function type throw".
5014 if (ESI.Type == EST_BasicNoexcept)
5015 return true;
5016
5017 // A noexcept(expr) specification is (possibly) canonical if expr is
5018 // value-dependent.
5019 if (ESI.Type == EST_DependentNoexcept)
5020 return true;
5021
5022 // A dynamic exception specification is canonical if it only contains pack
5023 // expansions (so we can't tell whether it's non-throwing) and all its
5024 // contained types are canonical.
5025 if (ESI.Type == EST_Dynamic) {
5026 bool AnyPackExpansions = false;
5027 for (QualType ET : ESI.Exceptions) {
5028 if (!ET.isCanonical())
5029 return false;
5030 if (ET->getAs<PackExpansionType>())
5031 AnyPackExpansions = true;
5032 }
5033 return AnyPackExpansions;
5034 }
5035
5036 return false;
5037}
5038
5039QualType ASTContext::getFunctionTypeInternal(
5040 QualType ResultTy, ArrayRef<QualType> ArgArray,
5041 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
5042 size_t NumArgs = ArgArray.size();
5043
5044 // Unique functions, to guarantee there is only one function of a particular
5045 // structure.
5046 llvm::FoldingSetNodeID ID;
5047 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
5048 *this, true);
5049
5050 QualType Canonical;
5051 bool Unique = false;
5052
5053 void *InsertPos = nullptr;
5054 if (FunctionProtoType *FPT =
5055 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
5056 QualType Existing = QualType(FPT, 0);
5057
5058 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
5059 // it so long as our exception specification doesn't contain a dependent
5060 // noexcept expression, or we're just looking for a canonical type.
5061 // Otherwise, we're going to need to create a type
5062 // sugar node to hold the concrete expression.
5063 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
5064 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
5065 return Existing;
5066
5067 // We need a new type sugar node for this one, to hold the new noexcept
5068 // expression. We do no canonicalization here, but that's OK since we don't
5069 // expect to see the same noexcept expression much more than once.
5070 Canonical = getCanonicalType(Existing);
5071 Unique = true;
5072 }
5073
5074 bool NoexceptInType = getLangOpts().CPlusPlus17;
5075 bool IsCanonicalExceptionSpec =
5077
5078 // Determine whether the type being created is already canonical or not.
5079 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
5080 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
5081 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
5082 if (!ArgArray[i].isCanonicalAsParam())
5083 isCanonical = false;
5084
5085 if (OnlyWantCanonical)
5086 assert(isCanonical &&
5087 "given non-canonical parameters constructing canonical type");
5088
5089 // If this type isn't canonical, get the canonical version of it if we don't
5090 // already have it. The exception spec is only partially part of the
5091 // canonical type, and only in C++17 onwards.
5092 if (!isCanonical && Canonical.isNull()) {
5093 SmallVector<QualType, 16> CanonicalArgs;
5094 CanonicalArgs.reserve(NumArgs);
5095 for (unsigned i = 0; i != NumArgs; ++i)
5096 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
5097
5098 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
5099 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
5100 CanonicalEPI.HasTrailingReturn = false;
5101
5102 if (IsCanonicalExceptionSpec) {
5103 // Exception spec is already OK.
5104 } else if (NoexceptInType) {
5105 switch (EPI.ExceptionSpec.Type) {
5107 // We don't know yet. It shouldn't matter what we pick here; no-one
5108 // should ever look at this.
5109 [[fallthrough]];
5110 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
5111 CanonicalEPI.ExceptionSpec.Type = EST_None;
5112 break;
5113
5114 // A dynamic exception specification is almost always "not noexcept",
5115 // with the exception that a pack expansion might expand to no types.
5116 case EST_Dynamic: {
5117 bool AnyPacks = false;
5118 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
5119 if (ET->getAs<PackExpansionType>())
5120 AnyPacks = true;
5121 ExceptionTypeStorage.push_back(getCanonicalType(ET));
5122 }
5123 if (!AnyPacks)
5124 CanonicalEPI.ExceptionSpec.Type = EST_None;
5125 else {
5126 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
5127 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
5128 }
5129 break;
5130 }
5131
5132 case EST_DynamicNone:
5133 case EST_BasicNoexcept:
5134 case EST_NoexceptTrue:
5135 case EST_NoThrow:
5136 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
5137 break;
5138
5140 llvm_unreachable("dependent noexcept is already canonical");
5141 }
5142 } else {
5143 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
5144 }
5145
5146 // Adjust the canonical function result type.
5147 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
5148 Canonical =
5149 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
5150
5151 // Get the new insert position for the node we care about.
5152 FunctionProtoType *NewIP =
5153 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
5154 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5155 }
5156
5157 // Compute the needed size to hold this FunctionProtoType and the
5158 // various trailing objects.
5159 auto ESH = FunctionProtoType::getExceptionSpecSize(
5160 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
5161 size_t Size = FunctionProtoType::totalSizeToAlloc<
5162 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
5163 FunctionType::FunctionTypeExtraAttributeInfo,
5164 FunctionType::FunctionTypeArmAttributes, FunctionType::ExceptionType,
5165 Expr *, FunctionDecl *, FunctionProtoType::ExtParameterInfo, Qualifiers,
5166 FunctionEffect, EffectConditionExpr>(
5169 EPI.requiresFunctionProtoTypeArmAttributes(), ESH.NumExceptionType,
5170 ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
5171 EPI.ExtParameterInfos ? NumArgs : 0,
5173 EPI.FunctionEffects.conditions().size());
5174
5175 auto *FTP = (FunctionProtoType *)Allocate(Size, alignof(FunctionProtoType));
5176 FunctionProtoType::ExtProtoInfo newEPI = EPI;
5177 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
5178 Types.push_back(FTP);
5179 if (!Unique)
5180 FunctionProtoTypes.InsertNode(FTP, InsertPos);
5181 if (!EPI.FunctionEffects.empty())
5182 AnyFunctionEffects = true;
5183 return QualType(FTP, 0);
5184}
5185
5186QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
5187 llvm::FoldingSetNodeID ID;
5188 PipeType::Profile(ID, T, ReadOnly);
5189
5190 void *InsertPos = nullptr;
5191 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
5192 return QualType(PT, 0);
5193
5194 // If the pipe element type isn't canonical, this won't be a canonical type
5195 // either, so fill in the canonical type field.
5196 QualType Canonical;
5197 if (!T.isCanonical()) {
5198 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
5199
5200 // Get the new insert position for the node we care about.
5201 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
5202 assert(!NewIP && "Shouldn't be in the map!");
5203 (void)NewIP;
5204 }
5205 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
5206 Types.push_back(New);
5207 PipeTypes.InsertNode(New, InsertPos);
5208 return QualType(New, 0);
5209}
5210
5212 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
5213 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
5214 : Ty;
5215}
5216
5218 return getPipeType(T, true);
5219}
5220
5222 return getPipeType(T, false);
5223}
5224
5225QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
5226 llvm::FoldingSetNodeID ID;
5227 BitIntType::Profile(ID, IsUnsigned, NumBits);
5228
5229 void *InsertPos = nullptr;
5230 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5231 return QualType(EIT, 0);
5232
5233 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
5234 BitIntTypes.InsertNode(New, InsertPos);
5235 Types.push_back(New);
5236 return QualType(New, 0);
5237}
5238
5240 Expr *NumBitsExpr) const {
5241 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
5242 llvm::FoldingSetNodeID ID;
5243 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
5244
5245 void *InsertPos = nullptr;
5246 if (DependentBitIntType *Existing =
5247 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5248 return QualType(Existing, 0);
5249
5250 auto *New = new (*this, alignof(DependentBitIntType))
5251 DependentBitIntType(IsUnsigned, NumBitsExpr);
5252 DependentBitIntTypes.InsertNode(New, InsertPos);
5253
5254 Types.push_back(New);
5255 return QualType(New, 0);
5256}
5257
5260 using Kind = PredefinedSugarType::Kind;
5261
5262 if (auto *Target = PredefinedSugarTypes[llvm::to_underlying(KD)];
5263 Target != nullptr)
5264 return QualType(Target, 0);
5265
5266 auto getCanonicalType = [](const ASTContext &Ctx, Kind KDI) -> QualType {
5267 switch (KDI) {
5268 // size_t (C99TC3 6.5.3.4), signed size_t (C++23 5.13.2) and
5269 // ptrdiff_t (C99TC3 6.5.6) Although these types are not built-in, they
5270 // are part of the core language and are widely used. Using
5271 // PredefinedSugarType makes these types as named sugar types rather than
5272 // standard integer types, enabling better hints and diagnostics.
5273 case Kind::SizeT:
5274 return Ctx.getFromTargetType(Ctx.Target->getSizeType());
5275 case Kind::SignedSizeT:
5276 return Ctx.getFromTargetType(Ctx.Target->getSignedSizeType());
5277 case Kind::PtrdiffT:
5278 return Ctx.getFromTargetType(Ctx.Target->getPtrDiffType(LangAS::Default));
5279 }
5280 llvm_unreachable("unexpected kind");
5281 };
5282 auto *New = new (*this, alignof(PredefinedSugarType))
5283 PredefinedSugarType(KD, &Idents.get(PredefinedSugarType::getName(KD)),
5284 getCanonicalType(*this, static_cast<Kind>(KD)));
5285 Types.push_back(New);
5286 PredefinedSugarTypes[llvm::to_underlying(KD)] = New;
5287 return QualType(New, 0);
5288}
5289
5291 NestedNameSpecifier Qualifier,
5292 const TypeDecl *Decl) const {
5293 if (auto *Tag = dyn_cast<TagDecl>(Decl))
5294 return getTagType(Keyword, Qualifier, Tag,
5295 /*OwnsTag=*/false);
5296 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
5297 return getTypedefType(Keyword, Qualifier, Typedef);
5298 if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5299 return getUnresolvedUsingType(Keyword, Qualifier, UD);
5300
5302 assert(!Qualifier);
5303 return QualType(Decl->TypeForDecl, 0);
5304}
5305
5307 if (auto *Tag = dyn_cast<TagDecl>(TD))
5308 return getCanonicalTagType(Tag);
5309 if (auto *TN = dyn_cast<TypedefNameDecl>(TD))
5310 return getCanonicalType(TN->getUnderlyingType());
5311 if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD))
5313 assert(TD->TypeForDecl);
5314 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5315}
5316
5318 if (const auto *TD = dyn_cast<TagDecl>(Decl))
5319 return getCanonicalTagType(TD);
5320 if (const auto *TD = dyn_cast<TypedefNameDecl>(Decl);
5321 isa_and_nonnull<TypedefDecl, TypeAliasDecl>(TD))
5323 /*Qualifier=*/std::nullopt, TD);
5324 if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5325 return getCanonicalUnresolvedUsingType(Using);
5326
5327 assert(Decl->TypeForDecl);
5328 return QualType(Decl->TypeForDecl, 0);
5329}
5330
5331/// getTypedefType - Return the unique reference to the type for the
5332/// specified typedef name decl.
5335 NestedNameSpecifier Qualifier,
5336 const TypedefNameDecl *Decl, QualType UnderlyingType,
5337 std::optional<bool> TypeMatchesDeclOrNone) const {
5338 if (!TypeMatchesDeclOrNone) {
5339 QualType DeclUnderlyingType = Decl->getUnderlyingType();
5340 assert(!DeclUnderlyingType.isNull());
5341 if (UnderlyingType.isNull())
5342 UnderlyingType = DeclUnderlyingType;
5343 else
5344 assert(hasSameType(UnderlyingType, DeclUnderlyingType));
5345 TypeMatchesDeclOrNone = UnderlyingType == DeclUnderlyingType;
5346 } else {
5347 // FIXME: This is a workaround for a serialization cycle: assume the decl
5348 // underlying type is not available; don't touch it.
5349 assert(!UnderlyingType.isNull());
5350 }
5351
5352 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier &&
5353 *TypeMatchesDeclOrNone) {
5354 if (Decl->TypeForDecl)
5355 return QualType(Decl->TypeForDecl, 0);
5356
5357 auto *NewType = new (*this, alignof(TypedefType))
5358 TypedefType(Type::Typedef, Keyword, Qualifier, Decl, UnderlyingType,
5359 !*TypeMatchesDeclOrNone);
5360
5361 Types.push_back(NewType);
5362 Decl->TypeForDecl = NewType;
5363 return QualType(NewType, 0);
5364 }
5365
5366 llvm::FoldingSetNodeID ID;
5367 TypedefType::Profile(ID, Keyword, Qualifier, Decl,
5368 *TypeMatchesDeclOrNone ? QualType() : UnderlyingType);
5369
5370 void *InsertPos = nullptr;
5371 if (FoldingSetPlaceholder<TypedefType> *Placeholder =
5372 TypedefTypes.FindNodeOrInsertPos(ID, InsertPos))
5373 return QualType(Placeholder->getType(), 0);
5374
5375 void *Mem =
5376 Allocate(TypedefType::totalSizeToAlloc<FoldingSetPlaceholder<TypedefType>,
5378 1, !!Qualifier, !*TypeMatchesDeclOrNone),
5379 alignof(TypedefType));
5380 auto *NewType =
5381 new (Mem) TypedefType(Type::Typedef, Keyword, Qualifier, Decl,
5382 UnderlyingType, !*TypeMatchesDeclOrNone);
5383 auto *Placeholder = new (NewType->getFoldingSetPlaceholder())
5385 TypedefTypes.InsertNode(Placeholder, InsertPos);
5386 Types.push_back(NewType);
5387 return QualType(NewType, 0);
5388}
5389
5391 NestedNameSpecifier Qualifier,
5392 const UsingShadowDecl *D,
5393 QualType UnderlyingType) const {
5394 // FIXME: This is expensive to compute every time!
5395 if (UnderlyingType.isNull()) {
5396 const auto *UD = cast<UsingDecl>(D->getIntroducer());
5397 UnderlyingType =
5400 UD->getQualifier(), cast<TypeDecl>(D->getTargetDecl()));
5401 }
5402
5403 llvm::FoldingSetNodeID ID;
5404 UsingType::Profile(ID, Keyword, Qualifier, D, UnderlyingType);
5405
5406 void *InsertPos = nullptr;
5407 if (const UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5408 return QualType(T, 0);
5409
5410 assert(!UnderlyingType.hasLocalQualifiers());
5411
5412 assert(
5414 UnderlyingType));
5415
5416 void *Mem =
5417 Allocate(UsingType::totalSizeToAlloc<NestedNameSpecifier>(!!Qualifier),
5418 alignof(UsingType));
5419 UsingType *T = new (Mem) UsingType(Keyword, Qualifier, D, UnderlyingType);
5420 Types.push_back(T);
5421 UsingTypes.InsertNode(T, InsertPos);
5422 return QualType(T, 0);
5423}
5424
5425TagType *ASTContext::getTagTypeInternal(ElaboratedTypeKeyword Keyword,
5426 NestedNameSpecifier Qualifier,
5427 const TagDecl *TD, bool OwnsTag,
5428 bool IsInjected,
5429 const Type *CanonicalType,
5430 bool WithFoldingSetNode) const {
5431 auto [TC, Size] = [&] {
5432 switch (TD->getDeclKind()) {
5433 case Decl::Enum:
5434 static_assert(alignof(EnumType) == alignof(TagType));
5435 return std::make_tuple(Type::Enum, sizeof(EnumType));
5436 case Decl::ClassTemplatePartialSpecialization:
5437 case Decl::ClassTemplateSpecialization:
5438 case Decl::CXXRecord:
5439 static_assert(alignof(RecordType) == alignof(TagType));
5440 static_assert(alignof(InjectedClassNameType) == alignof(TagType));
5441 if (cast<CXXRecordDecl>(TD)->hasInjectedClassType())
5442 return std::make_tuple(Type::InjectedClassName,
5443 sizeof(InjectedClassNameType));
5444 [[fallthrough]];
5445 case Decl::Record:
5446 return std::make_tuple(Type::Record, sizeof(RecordType));
5447 default:
5448 llvm_unreachable("unexpected decl kind");
5449 }
5450 }();
5451
5452 if (Qualifier) {
5453 static_assert(alignof(NestedNameSpecifier) <= alignof(TagType));
5454 Size = llvm::alignTo(Size, alignof(NestedNameSpecifier)) +
5455 sizeof(NestedNameSpecifier);
5456 }
5457 void *Mem;
5458 if (WithFoldingSetNode) {
5459 // FIXME: It would be more profitable to tail allocate the folding set node
5460 // from the type, instead of the other way around, due to the greater
5461 // alignment requirements of the type. But this makes it harder to deal with
5462 // the different type node sizes. This would require either uniquing from
5463 // different folding sets, or having the folding setaccept a
5464 // contextual parameter which is not fixed at construction.
5465 Mem = Allocate(
5466 sizeof(TagTypeFoldingSetPlaceholder) +
5467 TagTypeFoldingSetPlaceholder::getOffset() + Size,
5468 std::max(alignof(TagTypeFoldingSetPlaceholder), alignof(TagType)));
5469 auto *T = new (Mem) TagTypeFoldingSetPlaceholder();
5470 Mem = T->getTagType();
5471 } else {
5472 Mem = Allocate(Size, alignof(TagType));
5473 }
5474
5475 auto *T = [&, TC = TC]() -> TagType * {
5476 switch (TC) {
5477 case Type::Enum: {
5478 assert(isa<EnumDecl>(TD));
5479 auto *T = new (Mem) EnumType(TC, Keyword, Qualifier, TD, OwnsTag,
5480 IsInjected, CanonicalType);
5481 assert(reinterpret_cast<void *>(T) ==
5482 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5483 "TagType must be the first base of EnumType");
5484 return T;
5485 }
5486 case Type::Record: {
5487 assert(isa<RecordDecl>(TD));
5488 auto *T = new (Mem) RecordType(TC, Keyword, Qualifier, TD, OwnsTag,
5489 IsInjected, CanonicalType);
5490 assert(reinterpret_cast<void *>(T) ==
5491 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5492 "TagType must be the first base of RecordType");
5493 return T;
5494 }
5495 case Type::InjectedClassName: {
5496 auto *T = new (Mem) InjectedClassNameType(Keyword, Qualifier, TD,
5497 IsInjected, CanonicalType);
5498 assert(reinterpret_cast<void *>(T) ==
5499 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5500 "TagType must be the first base of InjectedClassNameType");
5501 return T;
5502 }
5503 default:
5504 llvm_unreachable("unexpected type class");
5505 }
5506 }();
5507 assert(T->getKeyword() == Keyword);
5508 assert(T->getQualifier() == Qualifier);
5509 assert(T->getDecl() == TD);
5510 assert(T->isInjected() == IsInjected);
5511 assert(T->isTagOwned() == OwnsTag);
5512 assert((T->isCanonicalUnqualified()
5513 ? QualType()
5514 : T->getCanonicalTypeInternal()) == QualType(CanonicalType, 0));
5515 Types.push_back(T);
5516 return T;
5517}
5518
5519static const TagDecl *getNonInjectedClassName(const TagDecl *TD) {
5520 if (const auto *RD = dyn_cast<CXXRecordDecl>(TD);
5521 RD && RD->isInjectedClassName())
5522 return cast<TagDecl>(RD->getDeclContext());
5523 return TD;
5524}
5525
5528 if (TD->TypeForDecl)
5529 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5530
5531 const Type *CanonicalType = getTagTypeInternal(
5533 /*Qualifier=*/std::nullopt, TD,
5534 /*OwnsTag=*/false, /*IsInjected=*/false, /*CanonicalType=*/nullptr,
5535 /*WithFoldingSetNode=*/false);
5536 TD->TypeForDecl = CanonicalType;
5537 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5538}
5539
5541 NestedNameSpecifier Qualifier,
5542 const TagDecl *TD, bool OwnsTag) const {
5543
5544 const TagDecl *NonInjectedTD = ::getNonInjectedClassName(TD);
5545 bool IsInjected = TD != NonInjectedTD;
5546
5547 ElaboratedTypeKeyword PreferredKeyword =
5550 NonInjectedTD->getTagKind());
5551
5552 if (Keyword == PreferredKeyword && !Qualifier && !OwnsTag) {
5553 if (const Type *T = TD->TypeForDecl; T && !T->isCanonicalUnqualified())
5554 return QualType(T, 0);
5555
5556 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5557 const Type *T =
5558 getTagTypeInternal(Keyword,
5559 /*Qualifier=*/std::nullopt, NonInjectedTD,
5560 /*OwnsTag=*/false, IsInjected, CanonicalType,
5561 /*WithFoldingSetNode=*/false);
5562 TD->TypeForDecl = T;
5563 return QualType(T, 0);
5564 }
5565
5566 llvm::FoldingSetNodeID ID;
5567 TagTypeFoldingSetPlaceholder::Profile(ID, Keyword, Qualifier, NonInjectedTD,
5568 OwnsTag, IsInjected);
5569
5570 void *InsertPos = nullptr;
5571 if (TagTypeFoldingSetPlaceholder *T =
5572 TagTypes.FindNodeOrInsertPos(ID, InsertPos))
5573 return QualType(T->getTagType(), 0);
5574
5575 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5576 TagType *T =
5577 getTagTypeInternal(Keyword, Qualifier, NonInjectedTD, OwnsTag, IsInjected,
5578 CanonicalType, /*WithFoldingSetNode=*/true);
5579 TagTypes.InsertNode(TagTypeFoldingSetPlaceholder::fromTagType(T), InsertPos);
5580 return QualType(T, 0);
5581}
5582
5583bool ASTContext::computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits,
5584 unsigned NumPositiveBits,
5585 QualType &BestType,
5586 QualType &BestPromotionType) {
5587 unsigned IntWidth = Target->getIntWidth();
5588 unsigned CharWidth = Target->getCharWidth();
5589 unsigned ShortWidth = Target->getShortWidth();
5590 bool EnumTooLarge = false;
5591 unsigned BestWidth;
5592 if (NumNegativeBits) {
5593 // If there is a negative value, figure out the smallest integer type (of
5594 // int/long/longlong) that fits.
5595 // If it's packed, check also if it fits a char or a short.
5596 if (IsPacked && NumNegativeBits <= CharWidth &&
5597 NumPositiveBits < CharWidth) {
5598 BestType = SignedCharTy;
5599 BestWidth = CharWidth;
5600 } else if (IsPacked && NumNegativeBits <= ShortWidth &&
5601 NumPositiveBits < ShortWidth) {
5602 BestType = ShortTy;
5603 BestWidth = ShortWidth;
5604 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5605 BestType = IntTy;
5606 BestWidth = IntWidth;
5607 } else {
5608 BestWidth = Target->getLongWidth();
5609
5610 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
5611 BestType = LongTy;
5612 } else {
5613 BestWidth = Target->getLongLongWidth();
5614
5615 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5616 EnumTooLarge = true;
5617 BestType = LongLongTy;
5618 }
5619 }
5620 BestPromotionType = (BestWidth <= IntWidth ? IntTy : BestType);
5621 } else {
5622 // If there is no negative value, figure out the smallest type that fits
5623 // all of the enumerator values.
5624 // If it's packed, check also if it fits a char or a short.
5625 if (IsPacked && NumPositiveBits <= CharWidth) {
5626 BestType = UnsignedCharTy;
5627 BestPromotionType = IntTy;
5628 BestWidth = CharWidth;
5629 } else if (IsPacked && NumPositiveBits <= ShortWidth) {
5630 BestType = UnsignedShortTy;
5631 BestPromotionType = IntTy;
5632 BestWidth = ShortWidth;
5633 } else if (NumPositiveBits <= IntWidth) {
5634 BestType = UnsignedIntTy;
5635 BestWidth = IntWidth;
5636 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5638 : IntTy;
5639 } else if (NumPositiveBits <= (BestWidth = Target->getLongWidth())) {
5640 BestType = UnsignedLongTy;
5641 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5643 : LongTy;
5644 } else {
5645 BestWidth = Target->getLongLongWidth();
5646 if (NumPositiveBits > BestWidth) {
5647 // This can happen with bit-precise integer types, but those are not
5648 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
5649 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
5650 // a 128-bit integer, we should consider doing the same.
5651 EnumTooLarge = true;
5652 }
5653 BestType = UnsignedLongLongTy;
5654 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5656 : LongLongTy;
5657 }
5658 }
5659 return EnumTooLarge;
5660}
5661
5663 assert((T->isIntegralType(*this) || T->isEnumeralType()) &&
5664 "Integral type required!");
5665 unsigned BitWidth = getIntWidth(T);
5666
5667 if (Value.isUnsigned() || Value.isNonNegative()) {
5668 if (T->isSignedIntegerOrEnumerationType())
5669 --BitWidth;
5670 return Value.getActiveBits() <= BitWidth;
5671 }
5672 return Value.getSignificantBits() <= BitWidth;
5673}
5674
5675UnresolvedUsingType *ASTContext::getUnresolvedUsingTypeInternal(
5677 const UnresolvedUsingTypenameDecl *D, void *InsertPos,
5678 const Type *CanonicalType) const {
5679 void *Mem = Allocate(
5680 UnresolvedUsingType::totalSizeToAlloc<
5682 !!InsertPos, !!Qualifier),
5683 alignof(UnresolvedUsingType));
5684 auto *T = new (Mem) UnresolvedUsingType(Keyword, Qualifier, D, CanonicalType);
5685 if (InsertPos) {
5686 auto *Placeholder = new (T->getFoldingSetPlaceholder())
5688 TypedefTypes.InsertNode(Placeholder, InsertPos);
5689 }
5690 Types.push_back(T);
5691 return T;
5692}
5693
5695 const UnresolvedUsingTypenameDecl *D) const {
5696 D = D->getCanonicalDecl();
5697 if (D->TypeForDecl)
5698 return D->TypeForDecl->getCanonicalTypeUnqualified();
5699
5700 const Type *CanonicalType = getUnresolvedUsingTypeInternal(
5702 /*Qualifier=*/std::nullopt, D,
5703 /*InsertPos=*/nullptr, /*CanonicalType=*/nullptr);
5704 D->TypeForDecl = CanonicalType;
5705 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5706}
5707
5710 NestedNameSpecifier Qualifier,
5711 const UnresolvedUsingTypenameDecl *D) const {
5712 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier) {
5713 if (const Type *T = D->TypeForDecl; T && !T->isCanonicalUnqualified())
5714 return QualType(T, 0);
5715
5716 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5717 const Type *T =
5718 getUnresolvedUsingTypeInternal(ElaboratedTypeKeyword::None,
5719 /*Qualifier=*/std::nullopt, D,
5720 /*InsertPos=*/nullptr, CanonicalType);
5721 D->TypeForDecl = T;
5722 return QualType(T, 0);
5723 }
5724
5725 llvm::FoldingSetNodeID ID;
5726 UnresolvedUsingType::Profile(ID, Keyword, Qualifier, D);
5727
5728 void *InsertPos = nullptr;
5730 UnresolvedUsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5731 return QualType(Placeholder->getType(), 0);
5732 assert(InsertPos);
5733
5734 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5735 const Type *T = getUnresolvedUsingTypeInternal(Keyword, Qualifier, D,
5736 InsertPos, CanonicalType);
5737 return QualType(T, 0);
5738}
5739
5741 QualType modifiedType,
5742 QualType equivalentType,
5743 const Attr *attr) const {
5744 llvm::FoldingSetNodeID id;
5745 AttributedType::Profile(id, *this, attrKind, modifiedType, equivalentType,
5746 attr);
5747
5748 void *insertPos = nullptr;
5749 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
5750 if (type) return QualType(type, 0);
5751
5752 assert(!attr || attr->getKind() == attrKind);
5753
5754 QualType canon = getCanonicalType(equivalentType);
5755 type = new (*this, alignof(AttributedType))
5756 AttributedType(canon, attrKind, attr, modifiedType, equivalentType);
5757
5758 Types.push_back(type);
5759 AttributedTypes.InsertNode(type, insertPos);
5760
5761 return QualType(type, 0);
5762}
5763
5765 QualType equivalentType) const {
5766 return getAttributedType(attr->getKind(), modifiedType, equivalentType, attr);
5767}
5768
5770 QualType modifiedType,
5771 QualType equivalentType) {
5772 switch (nullability) {
5774 return getAttributedType(attr::TypeNonNull, modifiedType, equivalentType);
5775
5777 return getAttributedType(attr::TypeNullable, modifiedType, equivalentType);
5778
5780 return getAttributedType(attr::TypeNullableResult, modifiedType,
5781 equivalentType);
5782
5784 return getAttributedType(attr::TypeNullUnspecified, modifiedType,
5785 equivalentType);
5786 }
5787
5788 llvm_unreachable("Unknown nullability kind");
5789}
5790
5791QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
5792 QualType Wrapped) const {
5793 llvm::FoldingSetNodeID ID;
5794 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
5795
5796 void *InsertPos = nullptr;
5797 BTFTagAttributedType *Ty =
5798 BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
5799 if (Ty)
5800 return QualType(Ty, 0);
5801
5802 QualType Canon = getCanonicalType(Wrapped);
5803 Ty = new (*this, alignof(BTFTagAttributedType))
5804 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
5805
5806 Types.push_back(Ty);
5807 BTFTagAttributedTypes.InsertNode(Ty, InsertPos);
5808
5809 return QualType(Ty, 0);
5810}
5811
5813 QualType Underlying) const {
5814 const IdentifierInfo *II = Attr->getBehaviorKind();
5815 StringRef IdentName = II->getName();
5816 OverflowBehaviorType::OverflowBehaviorKind Kind;
5817 if (IdentName == "wrap") {
5818 Kind = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
5819 } else if (IdentName == "trap") {
5820 Kind = OverflowBehaviorType::OverflowBehaviorKind::Trap;
5821 } else {
5822 return Underlying;
5823 }
5824
5825 return getOverflowBehaviorType(Kind, Underlying);
5826}
5827
5829 OverflowBehaviorType::OverflowBehaviorKind Kind,
5830 QualType Underlying) const {
5831 assert(!Underlying->isOverflowBehaviorType() &&
5832 "Cannot have underlying types that are themselves OBTs");
5833 llvm::FoldingSetNodeID ID;
5834 OverflowBehaviorType::Profile(ID, Underlying, Kind);
5835 void *InsertPos = nullptr;
5836
5837 if (OverflowBehaviorType *OBT =
5838 OverflowBehaviorTypes.FindNodeOrInsertPos(ID, InsertPos)) {
5839 return QualType(OBT, 0);
5840 }
5841
5842 QualType Canonical;
5843 if (!Underlying.isCanonical() || Underlying.hasLocalQualifiers()) {
5844 SplitQualType canonSplit = getCanonicalType(Underlying).split();
5845 Canonical = getOverflowBehaviorType(Kind, QualType(canonSplit.Ty, 0));
5846 Canonical = getQualifiedType(Canonical, canonSplit.Quals);
5847 assert(!OverflowBehaviorTypes.FindNodeOrInsertPos(ID, InsertPos) &&
5848 "Shouldn't be in the map");
5849 }
5850
5851 OverflowBehaviorType *Ty = new (*this, alignof(OverflowBehaviorType))
5852 OverflowBehaviorType(Canonical, Underlying, Kind);
5853
5854 Types.push_back(Ty);
5855 OverflowBehaviorTypes.InsertNode(Ty, InsertPos);
5856 return QualType(Ty, 0);
5857}
5858
5860 QualType Wrapped, QualType Contained,
5861 const HLSLAttributedResourceType::Attributes &Attrs) {
5862
5863 llvm::FoldingSetNodeID ID;
5864 HLSLAttributedResourceType::Profile(ID, Wrapped, Contained, Attrs);
5865
5866 void *InsertPos = nullptr;
5867 HLSLAttributedResourceType *Ty =
5868 HLSLAttributedResourceTypes.FindNodeOrInsertPos(ID, InsertPos);
5869 if (Ty)
5870 return QualType(Ty, 0);
5871
5872 Ty = new (*this, alignof(HLSLAttributedResourceType))
5873 HLSLAttributedResourceType(Wrapped, Contained, Attrs);
5874
5875 Types.push_back(Ty);
5876 HLSLAttributedResourceTypes.InsertNode(Ty, InsertPos);
5877
5878 return QualType(Ty, 0);
5879}
5880
5881QualType ASTContext::getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size,
5882 uint32_t Alignment,
5883 ArrayRef<SpirvOperand> Operands) {
5884 llvm::FoldingSetNodeID ID;
5885 HLSLInlineSpirvType::Profile(ID, Opcode, Size, Alignment, Operands);
5886
5887 void *InsertPos = nullptr;
5888 HLSLInlineSpirvType *Ty =
5889 HLSLInlineSpirvTypes.FindNodeOrInsertPos(ID, InsertPos);
5890 if (Ty)
5891 return QualType(Ty, 0);
5892
5893 void *Mem = Allocate(
5894 HLSLInlineSpirvType::totalSizeToAlloc<SpirvOperand>(Operands.size()),
5895 alignof(HLSLInlineSpirvType));
5896
5897 Ty = new (Mem) HLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
5898
5899 Types.push_back(Ty);
5900 HLSLInlineSpirvTypes.InsertNode(Ty, InsertPos);
5901
5902 return QualType(Ty, 0);
5903}
5904
5905/// Retrieve a substitution-result type.
5907 Decl *AssociatedDecl,
5908 unsigned Index,
5909 UnsignedOrNone PackIndex,
5910 bool Final) const {
5911 llvm::FoldingSetNodeID ID;
5912 SubstTemplateTypeParmType::Profile(ID, Replacement, AssociatedDecl, Index,
5913 PackIndex, Final);
5914 void *InsertPos = nullptr;
5915 SubstTemplateTypeParmType *SubstParm =
5916 SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5917
5918 if (!SubstParm) {
5919 void *Mem = Allocate(SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
5920 !Replacement.isCanonical()),
5921 alignof(SubstTemplateTypeParmType));
5922 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
5923 Index, PackIndex, Final);
5924 Types.push_back(SubstParm);
5925 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
5926 }
5927
5928 return QualType(SubstParm, 0);
5929}
5930
5933 unsigned Index, bool Final,
5934 const TemplateArgument &ArgPack) {
5935#ifndef NDEBUG
5936 for (const auto &P : ArgPack.pack_elements())
5937 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
5938#endif
5939
5940 llvm::FoldingSetNodeID ID;
5941 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
5942 ArgPack);
5943 void *InsertPos = nullptr;
5944 if (SubstTemplateTypeParmPackType *SubstParm =
5945 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
5946 return QualType(SubstParm, 0);
5947
5948 QualType Canon;
5949 {
5950 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5951 if (!AssociatedDecl->isCanonicalDecl() ||
5952 !CanonArgPack.structurallyEquals(ArgPack)) {
5954 AssociatedDecl->getCanonicalDecl(), Index, Final, CanonArgPack);
5955 [[maybe_unused]] const auto *Nothing =
5956 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
5957 assert(!Nothing);
5958 }
5959 }
5960
5961 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
5962 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
5963 ArgPack);
5964 Types.push_back(SubstParm);
5965 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
5966 return QualType(SubstParm, 0);
5967}
5968
5971 assert(llvm::all_of(ArgPack.pack_elements(),
5972 [](const auto &P) {
5973 return P.getKind() == TemplateArgument::Type;
5974 }) &&
5975 "Pack contains a non-type");
5976
5977 llvm::FoldingSetNodeID ID;
5978 SubstBuiltinTemplatePackType::Profile(ID, ArgPack);
5979
5980 void *InsertPos = nullptr;
5981 if (auto *T =
5982 SubstBuiltinTemplatePackTypes.FindNodeOrInsertPos(ID, InsertPos))
5983 return QualType(T, 0);
5984
5985 QualType Canon;
5986 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5987 if (!CanonArgPack.structurallyEquals(ArgPack)) {
5988 Canon = getSubstBuiltinTemplatePack(CanonArgPack);
5989 // Refresh InsertPos, in case the recursive call above caused rehashing,
5990 // which would invalidate the bucket pointer.
5991 [[maybe_unused]] const auto *Nothing =
5992 SubstBuiltinTemplatePackTypes.FindNodeOrInsertPos(ID, InsertPos);
5993 assert(!Nothing);
5994 }
5995
5996 auto *PackType = new (*this, alignof(SubstBuiltinTemplatePackType))
5997 SubstBuiltinTemplatePackType(Canon, ArgPack);
5998 Types.push_back(PackType);
5999 SubstBuiltinTemplatePackTypes.InsertNode(PackType, InsertPos);
6000 return QualType(PackType, 0);
6001}
6002
6003/// Retrieve the template type parameter type for a template
6004/// parameter or parameter pack with the given depth, index, and (optionally)
6005/// name.
6007ASTContext::getTemplateTypeParmType(int Depth, int Index, bool ParameterPack,
6008 TemplateTypeParmDecl *TTPDecl) const {
6009 assert(Depth >= 0 && "Depth must be non-negative");
6010 assert(Index >= 0 && "Index must be non-negative");
6011
6012 llvm::FoldingSetNodeID ID;
6013 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
6014 void *InsertPos = nullptr;
6015 TemplateTypeParmType *TypeParm
6016 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
6017
6018 if (TypeParm)
6019 return QualType(TypeParm, 0);
6020
6021 if (TTPDecl) {
6022 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
6023 TypeParm = new (*this, alignof(TemplateTypeParmType))
6024 TemplateTypeParmType(Depth, Index, ParameterPack, TTPDecl, Canon);
6025
6026 TemplateTypeParmType *TypeCheck
6027 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
6028 assert(!TypeCheck && "Template type parameter canonical type broken");
6029 (void)TypeCheck;
6030 } else
6031 TypeParm = new (*this, alignof(TemplateTypeParmType)) TemplateTypeParmType(
6032 Depth, Index, ParameterPack, /*TTPDecl=*/nullptr, /*Canon=*/QualType());
6033
6034 Types.push_back(TypeParm);
6035 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
6036
6037 return QualType(TypeParm, 0);
6038}
6039
6042 switch (Keyword) {
6043 // These are just themselves.
6049 return Keyword;
6050
6051 // These are equivalent.
6054
6055 // These are functionally equivalent, so relying on their equivalence is
6056 // IFNDR. By making them equivalent, we disallow overloading, which at least
6057 // can produce a diagnostic.
6060 }
6061 llvm_unreachable("unexpected keyword kind");
6062}
6063
6065 ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc,
6066 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc,
6067 TemplateName Name, SourceLocation NameLoc,
6068 const TemplateArgumentListInfo &SpecifiedArgs,
6069 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6071 Keyword, Name, SpecifiedArgs.arguments(), CanonicalArgs, Underlying);
6072
6075 ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
6076 SpecifiedArgs);
6077 return TSI;
6078}
6079
6082 ArrayRef<TemplateArgumentLoc> SpecifiedArgs,
6083 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6084 SmallVector<TemplateArgument, 4> SpecifiedArgVec;
6085 SpecifiedArgVec.reserve(SpecifiedArgs.size());
6086 for (const TemplateArgumentLoc &Arg : SpecifiedArgs)
6087 SpecifiedArgVec.push_back(Arg.getArgument());
6088
6089 return getTemplateSpecializationType(Keyword, Template, SpecifiedArgVec,
6090 CanonicalArgs, Underlying);
6091}
6092
6093[[maybe_unused]] static bool
6095 for (const TemplateArgument &Arg : Args)
6096 if (Arg.isPackExpansion())
6097 return true;
6098 return false;
6099}
6100
6103 ArrayRef<TemplateArgument> Args) const {
6104 assert(Template ==
6105 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true));
6107 Template.getAsDependentTemplateName()));
6108#ifndef NDEBUG
6109 for (const auto &Arg : Args)
6110 assert(Arg.structurallyEquals(getCanonicalTemplateArgument(Arg)));
6111#endif
6112
6113 llvm::FoldingSetNodeID ID;
6114 TemplateSpecializationType::Profile(ID, Keyword, Template, Args, QualType(),
6115 *this);
6116 void *InsertPos = nullptr;
6117 if (auto *T = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6118 return QualType(T, 0);
6119
6120 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
6121 sizeof(TemplateArgument) * Args.size(),
6122 alignof(TemplateSpecializationType));
6123 auto *Spec =
6124 new (Mem) TemplateSpecializationType(Keyword, Template,
6125 /*IsAlias=*/false, Args, QualType());
6126 assert(Spec->isDependentType() &&
6127 "canonical template specialization must be dependent");
6128 Types.push_back(Spec);
6129 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
6130 return QualType(Spec, 0);
6131}
6132
6135 ArrayRef<TemplateArgument> SpecifiedArgs,
6136 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6137 const auto *TD = Template.getAsTemplateDecl(/*IgnoreDeduced=*/true);
6138 bool IsTypeAlias = TD && TD->isTypeAlias();
6139 if (Underlying.isNull()) {
6140 TemplateName CanonTemplate =
6141 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true);
6142 ElaboratedTypeKeyword CanonKeyword =
6143 CanonTemplate.getAsDependentTemplateName()
6146 bool NonCanonical = Template != CanonTemplate || Keyword != CanonKeyword;
6148 if (CanonicalArgs.empty()) {
6149 CanonArgsVec = SmallVector<TemplateArgument, 4>(SpecifiedArgs);
6150 NonCanonical |= canonicalizeTemplateArguments(CanonArgsVec);
6151 CanonicalArgs = CanonArgsVec;
6152 } else {
6153 NonCanonical |= !llvm::equal(
6154 SpecifiedArgs, CanonicalArgs,
6155 [](const TemplateArgument &A, const TemplateArgument &B) {
6156 return A.structurallyEquals(B);
6157 });
6158 }
6159
6160 // We can get here with an alias template when the specialization
6161 // contains a pack expansion that does not match up with a parameter
6162 // pack, or a builtin template which cannot be resolved due to dependency.
6163 assert((!isa_and_nonnull<TypeAliasTemplateDecl>(TD) ||
6164 hasAnyPackExpansions(CanonicalArgs)) &&
6165 "Caller must compute aliased type");
6166 IsTypeAlias = false;
6167
6169 CanonKeyword, CanonTemplate, CanonicalArgs);
6170 if (!NonCanonical)
6171 return Underlying;
6172 }
6173 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
6174 sizeof(TemplateArgument) * SpecifiedArgs.size() +
6175 (IsTypeAlias ? sizeof(QualType) : 0),
6176 alignof(TemplateSpecializationType));
6177 auto *Spec = new (Mem) TemplateSpecializationType(
6178 Keyword, Template, IsTypeAlias, SpecifiedArgs, Underlying);
6179 Types.push_back(Spec);
6180 return QualType(Spec, 0);
6181}
6182
6185 llvm::FoldingSetNodeID ID;
6186 ParenType::Profile(ID, InnerType);
6187
6188 void *InsertPos = nullptr;
6189 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6190 if (T)
6191 return QualType(T, 0);
6192
6193 QualType Canon = InnerType;
6194 if (!Canon.isCanonical()) {
6195 Canon = getCanonicalType(InnerType);
6196 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6197 assert(!CheckT && "Paren canonical type broken");
6198 (void)CheckT;
6199 }
6200
6201 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
6202 Types.push_back(T);
6203 ParenTypes.InsertNode(T, InsertPos);
6204 return QualType(T, 0);
6205}
6206
6209 const IdentifierInfo *MacroII) const {
6210 QualType Canon = UnderlyingTy;
6211 if (!Canon.isCanonical())
6212 Canon = getCanonicalType(UnderlyingTy);
6213
6214 auto *newType = new (*this, alignof(MacroQualifiedType))
6215 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
6216 Types.push_back(newType);
6217 return QualType(newType, 0);
6218}
6219
6222 const IdentifierInfo *Name) const {
6223 llvm::FoldingSetNodeID ID;
6224 DependentNameType::Profile(ID, Keyword, NNS, Name);
6225
6226 void *InsertPos = nullptr;
6227 if (DependentNameType *T =
6228 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos))
6229 return QualType(T, 0);
6230
6231 ElaboratedTypeKeyword CanonKeyword =
6233 NestedNameSpecifier CanonNNS = NNS.getCanonical();
6234
6235 QualType Canon;
6236 if (CanonKeyword != Keyword || CanonNNS != NNS) {
6237 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
6238 [[maybe_unused]] DependentNameType *T =
6239 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
6240 assert(!T && "broken canonicalization");
6241 assert(Canon.isCanonical());
6242 }
6243
6244 DependentNameType *T = new (*this, alignof(DependentNameType))
6245 DependentNameType(Keyword, NNS, Name, Canon);
6246 Types.push_back(T);
6247 DependentNameTypes.InsertNode(T, InsertPos);
6248 return QualType(T, 0);
6249}
6250
6252 TemplateArgument Arg;
6253 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6255 if (TTP->isParameterPack())
6256 ArgType = getPackExpansionType(ArgType, std::nullopt);
6257
6259 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6260 QualType T =
6261 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
6262 // For class NTTPs, ensure we include the 'const' so the type matches that
6263 // of a real template argument.
6264 // FIXME: It would be more faithful to model this as something like an
6265 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
6267 if (T->isRecordType()) {
6268 // C++ [temp.param]p8: An id-expression naming a non-type
6269 // template-parameter of class type T denotes a static storage duration
6270 // object of type const T.
6271 T.addConst();
6272 VK = VK_LValue;
6273 } else {
6274 VK = Expr::getValueKindForType(NTTP->getType());
6275 }
6276 Expr *E = new (*this)
6277 DeclRefExpr(*this, NTTP, /*RefersToEnclosingVariableOrCapture=*/false,
6278 T, VK, NTTP->getLocation());
6279
6280 if (NTTP->isParameterPack())
6281 E = new (*this) PackExpansionExpr(E, NTTP->getLocation(), std::nullopt);
6282 Arg = TemplateArgument(E, /*IsCanonical=*/false);
6283 } else {
6284 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
6286 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
6287 TemplateName(TTP));
6288 if (TTP->isParameterPack())
6289 Arg = TemplateArgument(Name, /*NumExpansions=*/std::nullopt);
6290 else
6291 Arg = TemplateArgument(Name);
6292 }
6293
6294 if (Param->isTemplateParameterPack())
6295 Arg =
6296 TemplateArgument::CreatePackCopy(const_cast<ASTContext &>(*this), Arg);
6297
6298 return Arg;
6299}
6300
6302 UnsignedOrNone NumExpansions,
6303 bool ExpectPackInType) const {
6304 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
6305 "Pack expansions must expand one or more parameter packs");
6306
6307 llvm::FoldingSetNodeID ID;
6308 PackExpansionType::Profile(ID, Pattern, NumExpansions);
6309
6310 void *InsertPos = nullptr;
6311 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6312 if (T)
6313 return QualType(T, 0);
6314
6315 QualType Canon;
6316 if (!Pattern.isCanonical()) {
6317 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
6318 /*ExpectPackInType=*/false);
6319
6320 // Find the insert position again, in case we inserted an element into
6321 // PackExpansionTypes and invalidated our insert position.
6322 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6323 }
6324
6325 T = new (*this, alignof(PackExpansionType))
6326 PackExpansionType(Pattern, Canon, NumExpansions);
6327 Types.push_back(T);
6328 PackExpansionTypes.InsertNode(T, InsertPos);
6329 return QualType(T, 0);
6330}
6331
6332/// CmpProtocolNames - Comparison predicate for sorting protocols
6333/// alphabetically.
6334static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
6335 ObjCProtocolDecl *const *RHS) {
6336 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
6337}
6338
6340 if (Protocols.empty()) return true;
6341
6342 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
6343 return false;
6344
6345 for (unsigned i = 1; i != Protocols.size(); ++i)
6346 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
6347 Protocols[i]->getCanonicalDecl() != Protocols[i])
6348 return false;
6349 return true;
6350}
6351
6352static void
6354 // Sort protocols, keyed by name.
6355 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
6356
6357 // Canonicalize.
6358 for (ObjCProtocolDecl *&P : Protocols)
6359 P = P->getCanonicalDecl();
6360
6361 // Remove duplicates.
6362 auto ProtocolsEnd = llvm::unique(Protocols);
6363 Protocols.erase(ProtocolsEnd, Protocols.end());
6364}
6365
6367 ObjCProtocolDecl * const *Protocols,
6368 unsigned NumProtocols) const {
6369 return getObjCObjectType(BaseType, {}, ArrayRef(Protocols, NumProtocols),
6370 /*isKindOf=*/false);
6371}
6372
6374 QualType baseType,
6375 ArrayRef<QualType> typeArgs,
6377 bool isKindOf) const {
6378 // If the base type is an interface and there aren't any protocols or
6379 // type arguments to add, then the interface type will do just fine.
6380 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
6381 isa<ObjCInterfaceType>(baseType))
6382 return baseType;
6383
6384 // Look in the folding set for an existing type.
6385 llvm::FoldingSetNodeID ID;
6386 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
6387 void *InsertPos = nullptr;
6388 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
6389 return QualType(QT, 0);
6390
6391 // Determine the type arguments to be used for canonicalization,
6392 // which may be explicitly specified here or written on the base
6393 // type.
6394 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
6395 if (effectiveTypeArgs.empty()) {
6396 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
6397 effectiveTypeArgs = baseObject->getTypeArgs();
6398 }
6399
6400 // Build the canonical type, which has the canonical base type and a
6401 // sorted-and-uniqued list of protocols and the type arguments
6402 // canonicalized.
6403 QualType canonical;
6404 bool typeArgsAreCanonical = llvm::all_of(
6405 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
6406 bool protocolsSorted = areSortedAndUniqued(protocols);
6407 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
6408 // Determine the canonical type arguments.
6409 ArrayRef<QualType> canonTypeArgs;
6410 SmallVector<QualType, 4> canonTypeArgsVec;
6411 if (!typeArgsAreCanonical) {
6412 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
6413 for (auto typeArg : effectiveTypeArgs)
6414 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
6415 canonTypeArgs = canonTypeArgsVec;
6416 } else {
6417 canonTypeArgs = effectiveTypeArgs;
6418 }
6419
6420 ArrayRef<ObjCProtocolDecl *> canonProtocols;
6421 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
6422 if (!protocolsSorted) {
6423 canonProtocolsVec.append(protocols.begin(), protocols.end());
6424 SortAndUniqueProtocols(canonProtocolsVec);
6425 canonProtocols = canonProtocolsVec;
6426 } else {
6427 canonProtocols = protocols;
6428 }
6429
6430 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
6431 canonProtocols, isKindOf);
6432
6433 // Regenerate InsertPos.
6434 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
6435 }
6436
6437 unsigned size = sizeof(ObjCObjectTypeImpl);
6438 size += typeArgs.size() * sizeof(QualType);
6439 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6440 void *mem = Allocate(size, alignof(ObjCObjectTypeImpl));
6441 auto *T =
6442 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
6443 isKindOf);
6444
6445 Types.push_back(T);
6446 ObjCObjectTypes.InsertNode(T, InsertPos);
6447 return QualType(T, 0);
6448}
6449
6450/// Apply Objective-C protocol qualifiers to the given type.
6451/// If this is for the canonical type of a type parameter, we can apply
6452/// protocol qualifiers on the ObjCObjectPointerType.
6455 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
6456 bool allowOnPointerType) const {
6457 hasError = false;
6458
6459 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
6460 return getObjCTypeParamType(objT->getDecl(), protocols);
6461 }
6462
6463 // Apply protocol qualifiers to ObjCObjectPointerType.
6464 if (allowOnPointerType) {
6465 if (const auto *objPtr =
6466 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
6467 const ObjCObjectType *objT = objPtr->getObjectType();
6468 // Merge protocol lists and construct ObjCObjectType.
6470 protocolsVec.append(objT->qual_begin(),
6471 objT->qual_end());
6472 protocolsVec.append(protocols.begin(), protocols.end());
6473 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
6475 objT->getBaseType(),
6476 objT->getTypeArgsAsWritten(),
6477 protocols,
6478 objT->isKindOfTypeAsWritten());
6480 }
6481 }
6482
6483 // Apply protocol qualifiers to ObjCObjectType.
6484 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
6485 // FIXME: Check for protocols to which the class type is already
6486 // known to conform.
6487
6488 return getObjCObjectType(objT->getBaseType(),
6489 objT->getTypeArgsAsWritten(),
6490 protocols,
6491 objT->isKindOfTypeAsWritten());
6492 }
6493
6494 // If the canonical type is ObjCObjectType, ...
6495 if (type->isObjCObjectType()) {
6496 // Silently overwrite any existing protocol qualifiers.
6497 // TODO: determine whether that's the right thing to do.
6498
6499 // FIXME: Check for protocols to which the class type is already
6500 // known to conform.
6501 return getObjCObjectType(type, {}, protocols, false);
6502 }
6503
6504 // id<protocol-list>
6505 if (type->isObjCIdType()) {
6506 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6507 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
6508 objPtr->isKindOfType());
6510 }
6511
6512 // Class<protocol-list>
6513 if (type->isObjCClassType()) {
6514 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6515 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
6516 objPtr->isKindOfType());
6518 }
6519
6520 hasError = true;
6521 return type;
6522}
6523
6526 ArrayRef<ObjCProtocolDecl *> protocols) const {
6527 // Look in the folding set for an existing type.
6528 llvm::FoldingSetNodeID ID;
6529 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
6530 void *InsertPos = nullptr;
6531 if (ObjCTypeParamType *TypeParam =
6532 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
6533 return QualType(TypeParam, 0);
6534
6535 // We canonicalize to the underlying type.
6536 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
6537 if (!protocols.empty()) {
6538 // Apply the protocol qualifers.
6539 bool hasError;
6541 Canonical, protocols, hasError, true /*allowOnPointerType*/));
6542 assert(!hasError && "Error when apply protocol qualifier to bound type");
6543 }
6544
6545 unsigned size = sizeof(ObjCTypeParamType);
6546 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6547 void *mem = Allocate(size, alignof(ObjCTypeParamType));
6548 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
6549
6550 Types.push_back(newType);
6551 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
6552 return QualType(newType, 0);
6553}
6554
6556 ObjCTypeParamDecl *New) const {
6557 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
6558 // Update TypeForDecl after updating TypeSourceInfo.
6559 auto *NewTypeParamTy = cast<ObjCTypeParamType>(New->TypeForDecl);
6561 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
6562 QualType UpdatedTy = getObjCTypeParamType(New, protocols);
6563 New->TypeForDecl = UpdatedTy.getTypePtr();
6564}
6565
6566/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
6567/// protocol list adopt all protocols in QT's qualified-id protocol
6568/// list.
6570 ObjCInterfaceDecl *IC) {
6571 if (!QT->isObjCQualifiedIdType())
6572 return false;
6573
6574 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
6575 // If both the right and left sides have qualifiers.
6576 for (auto *Proto : OPT->quals()) {
6577 if (!IC->ClassImplementsProtocol(Proto, false))
6578 return false;
6579 }
6580 return true;
6581 }
6582 return false;
6583}
6584
6585/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
6586/// QT's qualified-id protocol list adopt all protocols in IDecl's list
6587/// of protocols.
6589 ObjCInterfaceDecl *IDecl) {
6590 if (!QT->isObjCQualifiedIdType())
6591 return false;
6592 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
6593 if (!OPT)
6594 return false;
6595 if (!IDecl->hasDefinition())
6596 return false;
6598 CollectInheritedProtocols(IDecl, InheritedProtocols);
6599 if (InheritedProtocols.empty())
6600 return false;
6601 // Check that if every protocol in list of id<plist> conforms to a protocol
6602 // of IDecl's, then bridge casting is ok.
6603 bool Conforms = false;
6604 for (auto *Proto : OPT->quals()) {
6605 Conforms = false;
6606 for (auto *PI : InheritedProtocols) {
6607 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
6608 Conforms = true;
6609 break;
6610 }
6611 }
6612 if (!Conforms)
6613 break;
6614 }
6615 if (Conforms)
6616 return true;
6617
6618 for (auto *PI : InheritedProtocols) {
6619 // If both the right and left sides have qualifiers.
6620 bool Adopts = false;
6621 for (auto *Proto : OPT->quals()) {
6622 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
6623 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
6624 break;
6625 }
6626 if (!Adopts)
6627 return false;
6628 }
6629 return true;
6630}
6631
6632/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
6633/// the given object type.
6635 llvm::FoldingSetNodeID ID;
6636 ObjCObjectPointerType::Profile(ID, ObjectT);
6637
6638 void *InsertPos = nullptr;
6639 if (ObjCObjectPointerType *QT =
6640 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
6641 return QualType(QT, 0);
6642
6643 // Find the canonical object type.
6644 QualType Canonical;
6645 if (!ObjectT.isCanonical()) {
6646 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
6647
6648 // Regenerate InsertPos.
6649 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
6650 }
6651
6652 // No match.
6653 void *Mem =
6655 auto *QType =
6656 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
6657
6658 Types.push_back(QType);
6659 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
6660 return QualType(QType, 0);
6661}
6662
6663/// getObjCInterfaceType - Return the unique reference to the type for the
6664/// specified ObjC interface decl. The list of protocols is optional.
6666 ObjCInterfaceDecl *PrevDecl) const {
6667 if (Decl->TypeForDecl)
6668 return QualType(Decl->TypeForDecl, 0);
6669
6670 if (PrevDecl) {
6671 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
6672 Decl->TypeForDecl = PrevDecl->TypeForDecl;
6673 return QualType(PrevDecl->TypeForDecl, 0);
6674 }
6675
6676 // Prefer the definition, if there is one.
6677 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
6678 Decl = Def;
6679
6680 void *Mem = Allocate(sizeof(ObjCInterfaceType), alignof(ObjCInterfaceType));
6681 auto *T = new (Mem) ObjCInterfaceType(Decl);
6682 Decl->TypeForDecl = T;
6683 Types.push_back(T);
6684 return QualType(T, 0);
6685}
6686
6687/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
6688/// TypeOfExprType AST's (since expression's are never shared). For example,
6689/// multiple declarations that refer to "typeof(x)" all contain different
6690/// DeclRefExpr's. This doesn't effect the type checker, since it operates
6691/// on canonical type's (which are always unique).
6693 TypeOfExprType *toe;
6694 if (tofExpr->isTypeDependent()) {
6695 llvm::FoldingSetNodeID ID;
6696 DependentTypeOfExprType::Profile(ID, *this, tofExpr,
6697 Kind == TypeOfKind::Unqualified);
6698
6699 void *InsertPos = nullptr;
6701 DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
6702 if (Canon) {
6703 // We already have a "canonical" version of an identical, dependent
6704 // typeof(expr) type. Use that as our canonical type.
6705 toe = new (*this, alignof(TypeOfExprType)) TypeOfExprType(
6706 *this, tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
6707 } else {
6708 // Build a new, canonical typeof(expr) type.
6709 Canon = new (*this, alignof(DependentTypeOfExprType))
6710 DependentTypeOfExprType(*this, tofExpr, Kind);
6711 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
6712 toe = Canon;
6713 }
6714 } else {
6715 QualType Canonical = getCanonicalType(tofExpr->getType());
6716 toe = new (*this, alignof(TypeOfExprType))
6717 TypeOfExprType(*this, tofExpr, Kind, Canonical);
6718 }
6719 Types.push_back(toe);
6720 return QualType(toe, 0);
6721}
6722
6723/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
6724/// TypeOfType nodes. The only motivation to unique these nodes would be
6725/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
6726/// an issue. This doesn't affect the type checker, since it operates
6727/// on canonical types (which are always unique).
6729 QualType Canonical = getCanonicalType(tofType);
6730 auto *tot = new (*this, alignof(TypeOfType))
6731 TypeOfType(*this, tofType, Canonical, Kind);
6732 Types.push_back(tot);
6733 return QualType(tot, 0);
6734}
6735
6736/// getReferenceQualifiedType - Given an expr, will return the type for
6737/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
6738/// and class member access into account.
6740 // C++11 [dcl.type.simple]p4:
6741 // [...]
6742 QualType T = E->getType();
6743 switch (E->getValueKind()) {
6744 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6745 // type of e;
6746 case VK_XValue:
6747 return getRValueReferenceType(T);
6748 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6749 // type of e;
6750 case VK_LValue:
6751 return getLValueReferenceType(T);
6752 // - otherwise, decltype(e) is the type of e.
6753 case VK_PRValue:
6754 return T;
6755 }
6756 llvm_unreachable("Unknown value kind");
6757}
6758
6759/// Unlike many "get<Type>" functions, we don't unique DecltypeType
6760/// nodes. This would never be helpful, since each such type has its own
6761/// expression, and would not give a significant memory saving, since there
6762/// is an Expr tree under each such type.
6764 // C++11 [temp.type]p2:
6765 // If an expression e involves a template parameter, decltype(e) denotes a
6766 // unique dependent type. Two such decltype-specifiers refer to the same
6767 // type only if their expressions are equivalent (14.5.6.1).
6768 QualType CanonType;
6769 if (!E->isInstantiationDependent()) {
6770 CanonType = getCanonicalType(UnderlyingType);
6771 } else if (!UnderlyingType.isNull()) {
6772 CanonType = getDecltypeType(E, QualType());
6773 } else {
6774 llvm::FoldingSetNodeID ID;
6775 DependentDecltypeType::Profile(ID, *this, E);
6776
6777 void *InsertPos = nullptr;
6778 if (DependentDecltypeType *Canon =
6779 DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos))
6780 return QualType(Canon, 0);
6781
6782 // Build a new, canonical decltype(expr) type.
6783 auto *DT =
6784 new (*this, alignof(DependentDecltypeType)) DependentDecltypeType(E);
6785 DependentDecltypeTypes.InsertNode(DT, InsertPos);
6786 Types.push_back(DT);
6787 return QualType(DT, 0);
6788 }
6789 auto *DT = new (*this, alignof(DecltypeType))
6790 DecltypeType(E, UnderlyingType, CanonType);
6791 Types.push_back(DT);
6792 return QualType(DT, 0);
6793}
6794
6796 bool FullySubstituted,
6797 ArrayRef<QualType> Expansions,
6798 UnsignedOrNone Index) const {
6799 QualType Canonical;
6800 if (FullySubstituted && Index) {
6801 Canonical = getCanonicalType(Expansions[*Index]);
6802 } else {
6803 llvm::FoldingSetNodeID ID;
6804 PackIndexingType::Profile(ID, *this, Pattern.getCanonicalType(), IndexExpr,
6805 FullySubstituted, Expansions);
6806 void *InsertPos = nullptr;
6807 PackIndexingType *Canon =
6808 DependentPackIndexingTypes.FindNodeOrInsertPos(ID, InsertPos);
6809 if (!Canon) {
6810 void *Mem = Allocate(
6811 PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6813 Canon =
6814 new (Mem) PackIndexingType(QualType(), Pattern.getCanonicalType(),
6815 IndexExpr, FullySubstituted, Expansions);
6816 DependentPackIndexingTypes.InsertNode(Canon, InsertPos);
6817 }
6818 Canonical = QualType(Canon, 0);
6819 }
6820
6821 void *Mem =
6822 Allocate(PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6824 auto *T = new (Mem) PackIndexingType(Canonical, Pattern, IndexExpr,
6825 FullySubstituted, Expansions);
6826 Types.push_back(T);
6827 return QualType(T, 0);
6828}
6829
6830/// getUnaryTransformationType - We don't unique these, since the memory
6831/// savings are minimal and these are rare.
6834 UnaryTransformType::UTTKind Kind) const {
6835
6836 llvm::FoldingSetNodeID ID;
6837 UnaryTransformType::Profile(ID, BaseType, UnderlyingType, Kind);
6838
6839 void *InsertPos = nullptr;
6840 if (UnaryTransformType *UT =
6841 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos))
6842 return QualType(UT, 0);
6843
6844 QualType CanonType;
6845 if (!BaseType->isDependentType()) {
6846 CanonType = UnderlyingType.getCanonicalType();
6847 } else {
6848 assert(UnderlyingType.isNull() || BaseType == UnderlyingType);
6849 UnderlyingType = QualType();
6850 if (QualType CanonBase = BaseType.getCanonicalType();
6851 BaseType != CanonBase) {
6852 CanonType = getUnaryTransformType(CanonBase, QualType(), Kind);
6853 assert(CanonType.isCanonical());
6854
6855 // Find the insertion position again.
6856 [[maybe_unused]] UnaryTransformType *UT =
6857 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
6858 assert(!UT && "broken canonicalization");
6859 }
6860 }
6861
6862 auto *UT = new (*this, alignof(UnaryTransformType))
6863 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
6864 UnaryTransformTypes.InsertNode(UT, InsertPos);
6865 Types.push_back(UT);
6866 return QualType(UT, 0);
6867}
6868
6869/// getAutoType - Return the uniqued reference to the 'auto' type which has been
6870/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
6871/// canonical deduced-but-dependent 'auto' type.
6875 TemplateDecl *TypeConstraintConcept,
6876 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
6878 !TypeConstraintConcept) {
6879 assert(DeducedAsType.isNull() && "");
6880 assert(TypeConstraintArgs.empty() && "");
6881 return getAutoDeductType();
6882 }
6883
6884 // Look in the folding set for an existing type.
6885 llvm::FoldingSetNodeID ID;
6886 AutoType::Profile(ID, *this, DK, DeducedAsType, Keyword,
6887 TypeConstraintConcept, TypeConstraintArgs);
6888 if (auto const AT_iter = AutoTypes.find(ID); AT_iter != AutoTypes.end())
6889 return QualType(AT_iter->getSecond(), 0);
6890
6891 if (DK == DeducedKind::Deduced) {
6892 assert(!DeducedAsType.isNull() && "deduced type must be provided");
6893 } else {
6894 assert(DeducedAsType.isNull() && "deduced type must not be provided");
6895 if (TypeConstraintConcept) {
6896 bool AnyNonCanonArgs = false;
6897 auto *CanonicalConcept =
6898 cast<TemplateDecl>(TypeConstraintConcept->getCanonicalDecl());
6899 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
6900 *this, TypeConstraintArgs, AnyNonCanonArgs);
6901 if (TypeConstraintConcept != CanonicalConcept || AnyNonCanonArgs)
6902 DeducedAsType = getAutoType(DK, QualType(), Keyword, CanonicalConcept,
6903 CanonicalConceptArgs);
6904 }
6905 }
6906
6907 void *Mem = Allocate(sizeof(AutoType) +
6908 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
6909 alignof(AutoType));
6910 auto *AT = new (Mem) AutoType(DK, DeducedAsType, Keyword,
6911 TypeConstraintConcept, TypeConstraintArgs);
6912#ifndef NDEBUG
6913 llvm::FoldingSetNodeID InsertedID;
6914 AT->Profile(InsertedID, *this);
6915 assert(InsertedID == ID && "ID does not match");
6916#endif
6917 Types.push_back(AT);
6918 AutoTypes.try_emplace(ID, AT);
6919 return QualType(AT, 0);
6920}
6921
6924
6925 // Remove a type-constraint from a top-level auto or decltype(auto).
6926 if (auto *AT = CanonT->getAs<AutoType>()) {
6927 if (!AT->isConstrained())
6928 return T;
6929 return getQualifiedType(
6930 getAutoType(AT->getDeducedKind(), QualType(), AT->getKeyword()),
6931 T.getQualifiers());
6932 }
6933
6934 // FIXME: We only support constrained auto at the top level in the type of a
6935 // non-type template parameter at the moment. Once we lift that restriction,
6936 // we'll need to recursively build types containing auto here.
6937 assert(!CanonT->getContainedAutoType() ||
6938 !CanonT->getContainedAutoType()->isConstrained());
6939 return T;
6940}
6941
6942/// Return the uniqued reference to the deduced template specialization type
6943/// which has been deduced to the given type, or to the canonical undeduced
6944/// such type, or the canonical deduced-but-dependent such type.
6947 TemplateName Template) const {
6948 // Look in the folding set for an existing type.
6949 void *InsertPos = nullptr;
6950 llvm::FoldingSetNodeID ID;
6951 DeducedTemplateSpecializationType::Profile(ID, DK, DeducedAsType, Keyword,
6952 Template);
6953 if (DeducedTemplateSpecializationType *DTST =
6954 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6955 return QualType(DTST, 0);
6956
6957 if (DK == DeducedKind::Deduced) {
6958 assert(!DeducedAsType.isNull() && "deduced type must be provided");
6959 } else {
6960 assert(DeducedAsType.isNull() && "deduced type must not be provided");
6961 TemplateName CanonTemplateName = getCanonicalTemplateName(Template);
6962 // FIXME: Can this be formed from a DependentTemplateName, such that the
6963 // keyword should be part of the canonical type?
6965 Template != CanonTemplateName) {
6967 DK, QualType(), ElaboratedTypeKeyword::None, CanonTemplateName);
6968 // Find the insertion position again.
6969 [[maybe_unused]] DeducedTemplateSpecializationType *DTST =
6970 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
6971 assert(!DTST && "broken canonicalization");
6972 }
6973 }
6974
6975 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
6976 DeducedTemplateSpecializationType(DK, DeducedAsType, Keyword, Template);
6977
6978#ifndef NDEBUG
6979 llvm::FoldingSetNodeID TempID;
6980 DTST->Profile(TempID);
6981 assert(ID == TempID && "ID does not match");
6982#endif
6983 Types.push_back(DTST);
6984 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
6985 return QualType(DTST, 0);
6986}
6987
6988/// getAtomicType - Return the uniqued reference to the atomic type for
6989/// the given value type.
6991 // Unique pointers, to guarantee there is only one pointer of a particular
6992 // structure.
6993 llvm::FoldingSetNodeID ID;
6994 AtomicType::Profile(ID, T);
6995
6996 void *InsertPos = nullptr;
6997 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
6998 return QualType(AT, 0);
6999
7000 // If the atomic value type isn't canonical, this won't be a canonical type
7001 // either, so fill in the canonical type field.
7002 QualType Canonical;
7003 if (!T.isCanonical()) {
7004 Canonical = getAtomicType(getCanonicalType(T));
7005
7006 // Get the new insert position for the node we care about.
7007 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
7008 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
7009 }
7010 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
7011 Types.push_back(New);
7012 AtomicTypes.InsertNode(New, InsertPos);
7013 return QualType(New, 0);
7014}
7015
7016/// getAutoDeductType - Get type pattern for deducing against 'auto'.
7018 if (AutoDeductTy.isNull())
7019 AutoDeductTy = QualType(new (*this, alignof(AutoType))
7020 AutoType(DeducedKind::Undeduced, QualType(),
7022 /*TypeConstraintConcept=*/nullptr,
7023 /*TypeConstraintArgs=*/{}),
7024 0);
7025 return AutoDeductTy;
7026}
7027
7028/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
7030 if (AutoRRefDeductTy.isNull())
7032 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
7033 return AutoRRefDeductTy;
7034}
7035
7036/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
7037/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
7038/// needs to agree with the definition in <stddef.h>.
7042
7044 return getFromTargetType(Target->getSizeType());
7045}
7046
7047/// Return the unique signed counterpart of the integer type
7048/// corresponding to size_t.
7052
7053/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
7054/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
7058
7059/// Return the unique unsigned counterpart of "ptrdiff_t"
7060/// integer type. The standard (C11 7.21.6.1p7) refers to this type
7061/// in the definition of %tu format specifier.
7063 return getFromTargetType(Target->getUnsignedPtrDiffType(LangAS::Default));
7064}
7065
7066/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
7068 return getFromTargetType(Target->getIntMaxType());
7069}
7070
7071/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
7073 return getFromTargetType(Target->getUIntMaxType());
7074}
7075
7076/// getSignedWCharType - Return the type of "signed wchar_t".
7077/// Used when in C++, as a GCC extension.
7079 // FIXME: derive from "Target" ?
7080 return WCharTy;
7081}
7082
7083/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
7084/// Used when in C++, as a GCC extension.
7086 // FIXME: derive from "Target" ?
7087 return UnsignedIntTy;
7088}
7089
7091 return getFromTargetType(Target->getIntPtrType());
7092}
7093
7097
7098/// Return the unique type for "pid_t" defined in
7099/// <sys/types.h>. We need this to compute the correct type for vfork().
7101 return getFromTargetType(Target->getProcessIDType());
7102}
7103
7104//===----------------------------------------------------------------------===//
7105// Type Operators
7106//===----------------------------------------------------------------------===//
7107
7109 // Push qualifiers into arrays, and then discard any remaining
7110 // qualifiers.
7111 T = getCanonicalType(T);
7113 const Type *Ty = T.getTypePtr();
7117 } else if (isa<ArrayType>(Ty)) {
7119 } else if (isa<FunctionType>(Ty)) {
7120 Result = getPointerType(QualType(Ty, 0));
7121 } else {
7122 Result = QualType(Ty, 0);
7123 }
7124
7126}
7127
7129 Qualifiers &quals) const {
7130 SplitQualType splitType = type.getSplitUnqualifiedType();
7131
7132 // FIXME: getSplitUnqualifiedType() actually walks all the way to
7133 // the unqualified desugared type and then drops it on the floor.
7134 // We then have to strip that sugar back off with
7135 // getUnqualifiedDesugaredType(), which is silly.
7136 const auto *AT =
7137 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
7138
7139 // If we don't have an array, just use the results in splitType.
7140 if (!AT) {
7141 quals = splitType.Quals;
7142 return QualType(splitType.Ty, 0);
7143 }
7144
7145 // Otherwise, recurse on the array's element type.
7146 QualType elementType = AT->getElementType();
7147 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
7148
7149 // If that didn't change the element type, AT has no qualifiers, so we
7150 // can just use the results in splitType.
7151 if (elementType == unqualElementType) {
7152 assert(quals.empty()); // from the recursive call
7153 quals = splitType.Quals;
7154 return QualType(splitType.Ty, 0);
7155 }
7156
7157 // Otherwise, add in the qualifiers from the outermost type, then
7158 // build the type back up.
7159 quals.addConsistentQualifiers(splitType.Quals);
7160
7161 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
7162 return getConstantArrayType(unqualElementType, CAT->getSize(),
7163 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
7164 }
7165
7166 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
7167 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
7168 }
7169
7170 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
7171 return getVariableArrayType(unqualElementType, VAT->getSizeExpr(),
7172 VAT->getSizeModifier(),
7173 VAT->getIndexTypeCVRQualifiers());
7174 }
7175
7176 const auto *DSAT = cast<DependentSizedArrayType>(AT);
7177 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
7178 DSAT->getSizeModifier(), 0);
7179}
7180
7181/// Attempt to unwrap two types that may both be array types with the same bound
7182/// (or both be array types of unknown bound) for the purpose of comparing the
7183/// cv-decomposition of two types per C++ [conv.qual].
7184///
7185/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7186/// C++20 [conv.qual], if permitted by the current language mode.
7188 bool AllowPiMismatch) const {
7189 while (true) {
7190 auto *AT1 = getAsArrayType(T1);
7191 if (!AT1)
7192 return;
7193
7194 auto *AT2 = getAsArrayType(T2);
7195 if (!AT2)
7196 return;
7197
7198 // If we don't have two array types with the same constant bound nor two
7199 // incomplete array types, we've unwrapped everything we can.
7200 // C++20 also permits one type to be a constant array type and the other
7201 // to be an incomplete array type.
7202 // FIXME: Consider also unwrapping array of unknown bound and VLA.
7203 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
7204 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
7205 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
7206 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7208 return;
7209 } else if (isa<IncompleteArrayType>(AT1)) {
7210 if (!(isa<IncompleteArrayType>(AT2) ||
7211 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7213 return;
7214 } else {
7215 return;
7216 }
7217
7218 T1 = AT1->getElementType();
7219 T2 = AT2->getElementType();
7220 }
7221}
7222
7223/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
7224///
7225/// If T1 and T2 are both pointer types of the same kind, or both array types
7226/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
7227/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
7228///
7229/// This function will typically be called in a loop that successively
7230/// "unwraps" pointer and pointer-to-member types to compare them at each
7231/// level.
7232///
7233/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7234/// C++20 [conv.qual], if permitted by the current language mode.
7235///
7236/// \return \c true if a pointer type was unwrapped, \c false if we reached a
7237/// pair of types that can't be unwrapped further.
7239 bool AllowPiMismatch) const {
7240 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
7241
7242 const auto *T1PtrType = T1->getAs<PointerType>();
7243 const auto *T2PtrType = T2->getAs<PointerType>();
7244 if (T1PtrType && T2PtrType) {
7245 T1 = T1PtrType->getPointeeType();
7246 T2 = T2PtrType->getPointeeType();
7247 return true;
7248 }
7249
7250 if (const auto *T1MPType = T1->getAsCanonical<MemberPointerType>(),
7251 *T2MPType = T2->getAsCanonical<MemberPointerType>();
7252 T1MPType && T2MPType) {
7253 // Compare the qualifiers of the canonical type, as the non-canonical type
7254 // may have qualifiers pointing to a base or derived class.
7255 if (T1MPType->getQualifier() != T2MPType->getQualifier())
7256 return false;
7257 // Get the pointee types of the non-canonical type, in order to preserve
7258 // their sugar.
7259 T1 = T1->getAs<MemberPointerType>()->getPointeeType();
7260 T2 = T2->getAs<MemberPointerType>()->getPointeeType();
7261 return true;
7262 }
7263
7264 if (getLangOpts().ObjC) {
7265 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
7266 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
7267 if (T1OPType && T2OPType) {
7268 T1 = T1OPType->getPointeeType();
7269 T2 = T2OPType->getPointeeType();
7270 return true;
7271 }
7272 }
7273
7274 // FIXME: Block pointers, too?
7275
7276 return false;
7277}
7278
7280 while (true) {
7281 Qualifiers Quals;
7282 T1 = getUnqualifiedArrayType(T1, Quals);
7283 T2 = getUnqualifiedArrayType(T2, Quals);
7284 if (hasSameType(T1, T2))
7285 return true;
7286 if (!UnwrapSimilarTypes(T1, T2))
7287 return false;
7288 }
7289}
7290
7292 while (true) {
7293 Qualifiers Quals1, Quals2;
7294 T1 = getUnqualifiedArrayType(T1, Quals1);
7295 T2 = getUnqualifiedArrayType(T2, Quals2);
7296
7297 Quals1.removeCVRQualifiers();
7298 Quals2.removeCVRQualifiers();
7299 if (Quals1 != Quals2)
7300 return false;
7301
7302 if (hasSameType(T1, T2))
7303 return true;
7304
7305 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
7306 return false;
7307 }
7308}
7309
7312 SourceLocation NameLoc) const {
7313 switch (Name.getKind()) {
7316 // DNInfo work in progress: CHECKME: what about DNLoc?
7318 NameLoc);
7319
7322 // DNInfo work in progress: CHECKME: what about DNLoc?
7323 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
7324 }
7325
7328 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
7329 }
7330
7334 DeclarationName DName;
7335 if (const IdentifierInfo *II = TN.getIdentifier()) {
7336 DName = DeclarationNames.getIdentifier(II);
7337 return DeclarationNameInfo(DName, NameLoc);
7338 } else {
7339 DName = DeclarationNames.getCXXOperatorName(TN.getOperator());
7340 // DNInfo work in progress: FIXME: source locations?
7341 DeclarationNameLoc DNLoc =
7343 return DeclarationNameInfo(DName, NameLoc, DNLoc);
7344 }
7345 }
7346
7350 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
7351 NameLoc);
7352 }
7353
7358 NameLoc);
7359 }
7362 NameLoc);
7365 return getNameForTemplate(DTS->getUnderlying(), NameLoc);
7366 }
7367 }
7368
7369 llvm_unreachable("bad template name kind!");
7370}
7371
7372const TemplateArgument *
7374 auto handleParam = [](auto *TP) -> const TemplateArgument * {
7375 if (!TP->hasDefaultArgument())
7376 return nullptr;
7377 return &TP->getDefaultArgument().getArgument();
7378 };
7379 switch (P->getKind()) {
7380 case NamedDecl::TemplateTypeParm:
7381 return handleParam(cast<TemplateTypeParmDecl>(P));
7382 case NamedDecl::NonTypeTemplateParm:
7383 return handleParam(cast<NonTypeTemplateParmDecl>(P));
7384 case NamedDecl::TemplateTemplateParm:
7385 return handleParam(cast<TemplateTemplateParmDecl>(P));
7386 default:
7387 llvm_unreachable("Unexpected template parameter kind");
7388 }
7389}
7390
7392 bool IgnoreDeduced) const {
7393 while (std::optional<TemplateName> UnderlyingOrNone =
7394 Name.desugar(IgnoreDeduced))
7395 Name = *UnderlyingOrNone;
7396
7397 switch (Name.getKind()) {
7400 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
7402
7403 // The canonical template name is the canonical template declaration.
7404 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
7405 }
7406
7408 // An assumed template is just a name, so it is already canonical.
7409 return Name;
7410
7412 llvm_unreachable("cannot canonicalize overloaded template");
7413
7416 assert(DTN && "Non-dependent template names must refer to template decls.");
7417 NestedNameSpecifier Qualifier = DTN->getQualifier();
7418 NestedNameSpecifier CanonQualifier = Qualifier.getCanonical();
7419 if (Qualifier != CanonQualifier || !DTN->hasTemplateKeyword())
7420 return getDependentTemplateName({CanonQualifier, DTN->getName(),
7421 /*HasTemplateKeyword=*/true});
7422 return Name;
7423 }
7424
7428 TemplateArgument canonArgPack =
7431 canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
7432 subst->getIndex(), subst->getFinal());
7433 }
7435 assert(IgnoreDeduced == false);
7437 DefaultArguments DefArgs = DTS->getDefaultArguments();
7438 TemplateName Underlying = DTS->getUnderlying();
7439
7440 TemplateName CanonUnderlying =
7441 getCanonicalTemplateName(Underlying, /*IgnoreDeduced=*/true);
7442 bool NonCanonical = CanonUnderlying != Underlying;
7443 auto CanonArgs =
7444 getCanonicalTemplateArguments(*this, DefArgs.Args, NonCanonical);
7445
7446 ArrayRef<NamedDecl *> Params =
7447 CanonUnderlying.getAsTemplateDecl()->getTemplateParameters()->asArray();
7448 assert(CanonArgs.size() <= Params.size());
7449 // A deduced template name which deduces the same default arguments already
7450 // declared in the underlying template is the same template as the
7451 // underlying template. We need need to note any arguments which differ from
7452 // the corresponding declaration. If any argument differs, we must build a
7453 // deduced template name.
7454 for (int I = CanonArgs.size() - 1; I >= 0; --I) {
7456 if (!A)
7457 break;
7458 auto CanonParamDefArg = getCanonicalTemplateArgument(*A);
7459 TemplateArgument &CanonDefArg = CanonArgs[I];
7460 if (CanonDefArg.structurallyEquals(CanonParamDefArg))
7461 continue;
7462 // Keep popping from the back any deault arguments which are the same.
7463 if (I == int(CanonArgs.size() - 1))
7464 CanonArgs.pop_back();
7465 NonCanonical = true;
7466 }
7467 return NonCanonical ? getDeducedTemplateName(
7468 CanonUnderlying,
7469 /*DefaultArgs=*/{DefArgs.StartPos, CanonArgs})
7470 : Name;
7471 }
7475 llvm_unreachable("always sugar node");
7476 }
7477
7478 llvm_unreachable("bad template name!");
7479}
7480
7482 const TemplateName &Y,
7483 bool IgnoreDeduced) const {
7484 return getCanonicalTemplateName(X, IgnoreDeduced) ==
7485 getCanonicalTemplateName(Y, IgnoreDeduced);
7486}
7487
7489 const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const {
7490 if (ACX.ArgPackSubstIndex != ACY.ArgPackSubstIndex)
7491 return false;
7493 return false;
7494 return true;
7495}
7496
7497bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
7498 if (!XCE != !YCE)
7499 return false;
7500
7501 if (!XCE)
7502 return true;
7503
7504 llvm::FoldingSetNodeID XCEID, YCEID;
7505 XCE->Profile(XCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7506 YCE->Profile(YCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7507 return XCEID == YCEID;
7508}
7509
7511 const TypeConstraint *YTC) const {
7512 if (!XTC != !YTC)
7513 return false;
7514
7515 if (!XTC)
7516 return true;
7517
7518 auto *NCX = XTC->getNamedConcept();
7519 auto *NCY = YTC->getNamedConcept();
7520 if (!NCX || !NCY || !isSameEntity(NCX, NCY))
7521 return false;
7524 return false;
7526 if (XTC->getConceptReference()
7528 ->NumTemplateArgs !=
7530 return false;
7531
7532 // Compare slowly by profiling.
7533 //
7534 // We couldn't compare the profiling result for the template
7535 // args here. Consider the following example in different modules:
7536 //
7537 // template <__integer_like _Tp, C<_Tp> Sentinel>
7538 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
7539 // return __t;
7540 // }
7541 //
7542 // When we compare the profiling result for `C<_Tp>` in different
7543 // modules, it will compare the type of `_Tp` in different modules.
7544 // However, the type of `_Tp` in different modules refer to different
7545 // types here naturally. So we couldn't compare the profiling result
7546 // for the template args directly.
7549}
7550
7552 const NamedDecl *Y) const {
7553 if (X->getKind() != Y->getKind())
7554 return false;
7555
7556 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
7557 auto *TY = cast<TemplateTypeParmDecl>(Y);
7558 if (TX->isParameterPack() != TY->isParameterPack())
7559 return false;
7560 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
7561 return false;
7562 return isSameTypeConstraint(TX->getTypeConstraint(),
7563 TY->getTypeConstraint());
7564 }
7565
7566 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7567 auto *TY = cast<NonTypeTemplateParmDecl>(Y);
7568 return TX->isParameterPack() == TY->isParameterPack() &&
7569 TX->getASTContext().hasSameType(TX->getType(), TY->getType()) &&
7570 isSameConstraintExpr(TX->getPlaceholderTypeConstraint(),
7571 TY->getPlaceholderTypeConstraint());
7572 }
7573
7575 auto *TY = cast<TemplateTemplateParmDecl>(Y);
7576 return TX->isParameterPack() == TY->isParameterPack() &&
7577 isSameTemplateParameterList(TX->getTemplateParameters(),
7578 TY->getTemplateParameters());
7579}
7580
7582 const TemplateParameterList *X, const TemplateParameterList *Y) const {
7583 if (X->size() != Y->size())
7584 return false;
7585
7586 for (unsigned I = 0, N = X->size(); I != N; ++I)
7587 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
7588 return false;
7589
7590 return isSameConstraintExpr(X->getRequiresClause(), Y->getRequiresClause());
7591}
7592
7594 const NamedDecl *Y) const {
7595 // If the type parameter isn't the same already, we don't need to check the
7596 // default argument further.
7597 if (!isSameTemplateParameter(X, Y))
7598 return false;
7599
7600 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(X)) {
7601 auto *TTPY = cast<TemplateTypeParmDecl>(Y);
7602 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7603 return false;
7604
7605 return hasSameType(TTPX->getDefaultArgument().getArgument().getAsType(),
7606 TTPY->getDefaultArgument().getArgument().getAsType());
7607 }
7608
7609 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7610 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Y);
7611 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
7612 return false;
7613
7614 Expr *DefaultArgumentX =
7615 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7616 Expr *DefaultArgumentY =
7617 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7618 llvm::FoldingSetNodeID XID, YID;
7619 DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true);
7620 DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true);
7621 return XID == YID;
7622 }
7623
7624 auto *TTPX = cast<TemplateTemplateParmDecl>(X);
7625 auto *TTPY = cast<TemplateTemplateParmDecl>(Y);
7626
7627 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7628 return false;
7629
7630 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
7631 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
7632 return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate());
7633}
7634
7636 const NestedNameSpecifier Y) {
7637 if (X == Y)
7638 return true;
7639 if (!X || !Y)
7640 return false;
7641
7642 auto Kind = X.getKind();
7643 if (Kind != Y.getKind())
7644 return false;
7645
7646 // FIXME: For namespaces and types, we're permitted to check that the entity
7647 // is named via the same tokens. We should probably do so.
7648 switch (Kind) {
7650 auto [NamespaceX, PrefixX] = X.getAsNamespaceAndPrefix();
7651 auto [NamespaceY, PrefixY] = Y.getAsNamespaceAndPrefix();
7652 if (!declaresSameEntity(NamespaceX->getNamespace(),
7653 NamespaceY->getNamespace()))
7654 return false;
7655 return isSameQualifier(PrefixX, PrefixY);
7656 }
7658 const auto *TX = X.getAsType(), *TY = Y.getAsType();
7659 if (TX->getCanonicalTypeInternal() != TY->getCanonicalTypeInternal())
7660 return false;
7661 return isSameQualifier(TX->getPrefix(), TY->getPrefix());
7662 }
7666 return true;
7667 }
7668 llvm_unreachable("unhandled qualifier kind");
7669}
7670
7671static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B) {
7672 if (!A->getASTContext().getLangOpts().CUDA)
7673 return true; // Target attributes are overloadable in CUDA compilation only.
7674 if (A->hasAttr<CUDADeviceAttr>() != B->hasAttr<CUDADeviceAttr>())
7675 return false;
7676 if (A->hasAttr<CUDADeviceAttr>() && B->hasAttr<CUDADeviceAttr>())
7677 return A->hasAttr<CUDAHostAttr>() == B->hasAttr<CUDAHostAttr>();
7678 return true; // unattributed and __host__ functions are the same.
7679}
7680
7681/// Determine whether the attributes we can overload on are identical for A and
7682/// B. Will ignore any overloadable attrs represented in the type of A and B.
7684 const FunctionDecl *B) {
7685 // Note that pass_object_size attributes are represented in the function's
7686 // ExtParameterInfo, so we don't need to check them here.
7687
7688 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
7689 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
7690 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
7691
7692 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
7693 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
7694 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
7695
7696 // Return false if the number of enable_if attributes is different.
7697 if (!Cand1A || !Cand2A)
7698 return false;
7699
7700 Cand1ID.clear();
7701 Cand2ID.clear();
7702
7703 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
7704 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
7705
7706 // Return false if any of the enable_if expressions of A and B are
7707 // different.
7708 if (Cand1ID != Cand2ID)
7709 return false;
7710 }
7711 return hasSameCudaAttrs(A, B);
7712}
7713
7714bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
7715 // Caution: this function is called by the AST reader during deserialization,
7716 // so it cannot rely on AST invariants being met. Non-trivial accessors
7717 // should be avoided, along with any traversal of redeclaration chains.
7718
7719 if (X == Y)
7720 return true;
7721
7722 if (X->getDeclName() != Y->getDeclName())
7723 return false;
7724
7725 // Must be in the same context.
7726 //
7727 // Note that we can't use DeclContext::Equals here, because the DeclContexts
7728 // could be two different declarations of the same function. (We will fix the
7729 // semantic DC to refer to the primary definition after merging.)
7730 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
7732 return false;
7733
7734 // If either X or Y are local to the owning module, they are only possible to
7735 // be the same entity if they are in the same module.
7736 if (X->isModuleLocal() || Y->isModuleLocal())
7737 if (!isInSameModule(X->getOwningModule(), Y->getOwningModule()))
7738 return false;
7739
7740 // Two typedefs refer to the same entity if they have the same underlying
7741 // type.
7742 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
7743 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
7744 return hasSameType(TypedefX->getUnderlyingType(),
7745 TypedefY->getUnderlyingType());
7746
7747 // Must have the same kind.
7748 if (X->getKind() != Y->getKind())
7749 return false;
7750
7751 // Objective-C classes and protocols with the same name always match.
7753 return true;
7754
7756 // No need to handle these here: we merge them when adding them to the
7757 // template.
7758 return false;
7759 }
7760
7761 // Compatible tags match.
7762 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
7763 const auto *TagY = cast<TagDecl>(Y);
7764 return (TagX->getTagKind() == TagY->getTagKind()) ||
7765 ((TagX->getTagKind() == TagTypeKind::Struct ||
7766 TagX->getTagKind() == TagTypeKind::Class ||
7767 TagX->getTagKind() == TagTypeKind::Interface) &&
7768 (TagY->getTagKind() == TagTypeKind::Struct ||
7769 TagY->getTagKind() == TagTypeKind::Class ||
7770 TagY->getTagKind() == TagTypeKind::Interface));
7771 }
7772
7773 // Functions with the same type and linkage match.
7774 // FIXME: This needs to cope with merging of prototyped/non-prototyped
7775 // functions, etc.
7776 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
7777 const auto *FuncY = cast<FunctionDecl>(Y);
7778 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
7779 const auto *CtorY = cast<CXXConstructorDecl>(Y);
7780 if (CtorX->getInheritedConstructor() &&
7781 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
7782 CtorY->getInheritedConstructor().getConstructor()))
7783 return false;
7784 }
7785
7786 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
7787 return false;
7788
7789 // Multiversioned functions with different feature strings are represented
7790 // as separate declarations.
7791 if (FuncX->isMultiVersion()) {
7792 const auto *TAX = FuncX->getAttr<TargetAttr>();
7793 const auto *TAY = FuncY->getAttr<TargetAttr>();
7794 assert(TAX && TAY && "Multiversion Function without target attribute");
7795
7796 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
7797 return false;
7798 }
7799
7800 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
7801 // not the same entity if they are constrained.
7802 if ((FuncX->isMemberLikeConstrainedFriend() ||
7803 FuncY->isMemberLikeConstrainedFriend()) &&
7804 !FuncX->getLexicalDeclContext()->Equals(
7805 FuncY->getLexicalDeclContext())) {
7806 return false;
7807 }
7808
7809 if (!isSameAssociatedConstraint(FuncX->getTrailingRequiresClause(),
7810 FuncY->getTrailingRequiresClause()))
7811 return false;
7812
7813 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
7814 // Map to the first declaration that we've already merged into this one.
7815 // The TSI of redeclarations might not match (due to calling conventions
7816 // being inherited onto the type but not the TSI), but the TSI type of
7817 // the first declaration of the function should match across modules.
7818 FD = FD->getCanonicalDecl();
7819 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
7820 : FD->getType();
7821 };
7822 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
7823 if (!hasSameType(XT, YT)) {
7824 // We can get functions with different types on the redecl chain in C++17
7825 // if they have differing exception specifications and at least one of
7826 // the excpetion specs is unresolved.
7827 auto *XFPT = XT->getAs<FunctionProtoType>();
7828 auto *YFPT = YT->getAs<FunctionProtoType>();
7829 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
7830 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
7833 return true;
7834 return false;
7835 }
7836
7837 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
7838 hasSameOverloadableAttrs(FuncX, FuncY);
7839 }
7840
7841 // Variables with the same type and linkage match.
7842 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
7843 const auto *VarY = cast<VarDecl>(Y);
7844 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
7845 // During deserialization, we might compare variables before we load
7846 // their types. Assume the types will end up being the same.
7847 if (VarX->getType().isNull() || VarY->getType().isNull())
7848 return true;
7849
7850 if (hasSameType(VarX->getType(), VarY->getType()))
7851 return true;
7852
7853 // We can get decls with different types on the redecl chain. Eg.
7854 // template <typename T> struct S { static T Var[]; }; // #1
7855 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
7856 // Only? happens when completing an incomplete array type. In this case
7857 // when comparing #1 and #2 we should go through their element type.
7858 const ArrayType *VarXTy = getAsArrayType(VarX->getType());
7859 const ArrayType *VarYTy = getAsArrayType(VarY->getType());
7860 if (!VarXTy || !VarYTy)
7861 return false;
7862 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
7863 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
7864 }
7865 return false;
7866 }
7867
7868 // Namespaces with the same name and inlinedness match.
7869 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
7870 const auto *NamespaceY = cast<NamespaceDecl>(Y);
7871 return NamespaceX->isInline() == NamespaceY->isInline();
7872 }
7873
7874 // Identical template names and kinds match if their template parameter lists
7875 // and patterns match.
7876 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
7877 const auto *TemplateY = cast<TemplateDecl>(Y);
7878
7879 // ConceptDecl wouldn't be the same if their constraint expression differs.
7880 if (const auto *ConceptX = dyn_cast<ConceptDecl>(X)) {
7881 const auto *ConceptY = cast<ConceptDecl>(Y);
7882 if (!isSameConstraintExpr(ConceptX->getConstraintExpr(),
7883 ConceptY->getConstraintExpr()))
7884 return false;
7885 }
7886
7887 return isSameEntity(TemplateX->getTemplatedDecl(),
7888 TemplateY->getTemplatedDecl()) &&
7889 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
7890 TemplateY->getTemplateParameters());
7891 }
7892
7893 // Fields with the same name and the same type match.
7894 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
7895 const auto *FDY = cast<FieldDecl>(Y);
7896 // FIXME: Also check the bitwidth is odr-equivalent, if any.
7897 return hasSameType(FDX->getType(), FDY->getType());
7898 }
7899
7900 // Indirect fields with the same target field match.
7901 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
7902 const auto *IFDY = cast<IndirectFieldDecl>(Y);
7903 return IFDX->getAnonField()->getCanonicalDecl() ==
7904 IFDY->getAnonField()->getCanonicalDecl();
7905 }
7906
7907 // Enumerators with the same name match.
7909 // FIXME: Also check the value is odr-equivalent.
7910 return true;
7911
7912 // Using shadow declarations with the same target match.
7913 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
7914 const auto *USY = cast<UsingShadowDecl>(Y);
7915 return declaresSameEntity(USX->getTargetDecl(), USY->getTargetDecl());
7916 }
7917
7918 // Using declarations with the same qualifier match. (We already know that
7919 // the name matches.)
7920 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
7921 const auto *UY = cast<UsingDecl>(Y);
7922 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7923 UX->hasTypename() == UY->hasTypename() &&
7924 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7925 }
7926 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
7927 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
7928 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7929 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7930 }
7931 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
7932 return isSameQualifier(
7933 UX->getQualifier(),
7934 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
7935 }
7936
7937 // Using-pack declarations are only created by instantiation, and match if
7938 // they're instantiated from matching UnresolvedUsing...Decls.
7939 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
7940 return declaresSameEntity(
7941 UX->getInstantiatedFromUsingDecl(),
7942 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
7943 }
7944
7945 // Namespace alias definitions with the same target match.
7946 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
7947 const auto *NAY = cast<NamespaceAliasDecl>(Y);
7948 return NAX->getNamespace()->Equals(NAY->getNamespace());
7949 }
7950
7951 return false;
7952}
7953
7956 switch (Arg.getKind()) {
7958 return Arg;
7959
7961 return TemplateArgument(Arg.getAsExpr(), /*IsCanonical=*/true,
7962 Arg.getIsDefaulted());
7963
7965 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
7967 Arg.getIsDefaulted());
7968 }
7969
7972 /*isNullPtr*/ true, Arg.getIsDefaulted());
7973
7976 Arg.getIsDefaulted());
7977
7979 return TemplateArgument(
7982
7985
7987 return TemplateArgument(*this,
7990
7993 /*isNullPtr*/ false, Arg.getIsDefaulted());
7994
7996 bool AnyNonCanonArgs = false;
7997 auto CanonArgs = ::getCanonicalTemplateArguments(
7998 *this, Arg.pack_elements(), AnyNonCanonArgs);
7999 if (!AnyNonCanonArgs)
8000 return Arg;
8002 const_cast<ASTContext &>(*this), CanonArgs);
8003 NewArg.setIsDefaulted(Arg.getIsDefaulted());
8004 return NewArg;
8005 }
8006 }
8007
8008 // Silence GCC warning
8009 llvm_unreachable("Unhandled template argument kind");
8010}
8011
8013 const TemplateArgument &Arg2) const {
8014 if (Arg1.getKind() != Arg2.getKind())
8015 return false;
8016
8017 switch (Arg1.getKind()) {
8019 llvm_unreachable("Comparing NULL template argument");
8020
8022 return hasSameType(Arg1.getAsType(), Arg2.getAsType());
8023
8025 return Arg1.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl() ==
8027
8029 return hasSameType(Arg1.getNullPtrType(), Arg2.getNullPtrType());
8030
8035
8037 return llvm::APSInt::isSameValue(Arg1.getAsIntegral(),
8038 Arg2.getAsIntegral());
8039
8041 return Arg1.structurallyEquals(Arg2);
8042
8044 llvm::FoldingSetNodeID ID1, ID2;
8045 Arg1.getAsExpr()->Profile(ID1, *this, /*Canonical=*/true);
8046 Arg2.getAsExpr()->Profile(ID2, *this, /*Canonical=*/true);
8047 return ID1 == ID2;
8048 }
8049
8051 return llvm::equal(
8052 Arg1.getPackAsArray(), Arg2.getPackAsArray(),
8053 [&](const TemplateArgument &Arg1, const TemplateArgument &Arg2) {
8054 return isSameTemplateArgument(Arg1, Arg2);
8055 });
8056 }
8057
8058 llvm_unreachable("Unhandled template argument kind");
8059}
8060
8062 // Handle the non-qualified case efficiently.
8063 if (!T.hasLocalQualifiers()) {
8064 // Handle the common positive case fast.
8065 if (const auto *AT = dyn_cast<ArrayType>(T))
8066 return AT;
8067 }
8068
8069 // Handle the common negative case fast.
8070 if (!isa<ArrayType>(T.getCanonicalType()))
8071 return nullptr;
8072
8073 // Apply any qualifiers from the array type to the element type. This
8074 // implements C99 6.7.3p8: "If the specification of an array type includes
8075 // any type qualifiers, the element type is so qualified, not the array type."
8076
8077 // If we get here, we either have type qualifiers on the type, or we have
8078 // sugar such as a typedef in the way. If we have type qualifiers on the type
8079 // we must propagate them down into the element type.
8080
8081 SplitQualType split = T.getSplitDesugaredType();
8082 Qualifiers qs = split.Quals;
8083
8084 // If we have a simple case, just return now.
8085 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
8086 if (!ATy || qs.empty())
8087 return ATy;
8088
8089 // Otherwise, we have an array and we have qualifiers on it. Push the
8090 // qualifiers into the array element type and return a new array type.
8091 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
8092
8093 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
8094 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
8095 CAT->getSizeExpr(),
8096 CAT->getSizeModifier(),
8097 CAT->getIndexTypeCVRQualifiers()));
8098 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
8100 IAT->getSizeModifier(),
8101 IAT->getIndexTypeCVRQualifiers()));
8102
8103 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
8105 NewEltTy, DSAT->getSizeExpr(), DSAT->getSizeModifier(),
8106 DSAT->getIndexTypeCVRQualifiers()));
8107
8108 const auto *VAT = cast<VariableArrayType>(ATy);
8109 return cast<ArrayType>(
8110 getVariableArrayType(NewEltTy, VAT->getSizeExpr(), VAT->getSizeModifier(),
8111 VAT->getIndexTypeCVRQualifiers()));
8112}
8113
8115 if (getLangOpts().HLSL && T.getAddressSpace() == LangAS::hlsl_groupshared)
8116 return getLValueReferenceType(T);
8117 if (getLangOpts().HLSL && T->isConstantArrayType())
8118 return getArrayParameterType(T);
8119 if (T->isArrayType() || T->isFunctionType())
8120 return getDecayedType(T);
8121 return T;
8122}
8123
8127 return T.getUnqualifiedType();
8128}
8129
8131 // C++ [except.throw]p3:
8132 // A throw-expression initializes a temporary object, called the exception
8133 // object, the type of which is determined by removing any top-level
8134 // cv-qualifiers from the static type of the operand of throw and adjusting
8135 // the type from "array of T" or "function returning T" to "pointer to T"
8136 // or "pointer to function returning T", [...]
8138 if (T->isArrayType() || T->isFunctionType())
8139 T = getDecayedType(T);
8140 return T.getUnqualifiedType();
8141}
8142
8143/// getArrayDecayedType - Return the properly qualified result of decaying the
8144/// specified array type to a pointer. This operation is non-trivial when
8145/// handling typedefs etc. The canonical type of "T" must be an array type,
8146/// this returns a pointer to a properly qualified element of the array.
8147///
8148/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
8150 // Get the element type with 'getAsArrayType' so that we don't lose any
8151 // typedefs in the element type of the array. This also handles propagation
8152 // of type qualifiers from the array type into the element type if present
8153 // (C99 6.7.3p8).
8154 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
8155 assert(PrettyArrayType && "Not an array type!");
8156
8157 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
8158
8159 // int x[restrict 4] -> int *restrict
8161 PrettyArrayType->getIndexTypeQualifiers());
8162
8163 // int x[_Nullable] -> int * _Nullable
8164 if (auto Nullability = Ty->getNullability()) {
8165 Result = const_cast<ASTContext *>(this)->getAttributedType(*Nullability,
8166 Result, Result);
8167 }
8168 return Result;
8169}
8170
8172 return getBaseElementType(array->getElementType());
8173}
8174
8176 Qualifiers qs;
8177 while (true) {
8178 SplitQualType split = type.getSplitDesugaredType();
8179 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
8180 if (!array) break;
8181
8182 type = array->getElementType();
8184 }
8185
8186 return getQualifiedType(type, qs);
8187}
8188
8189/// getConstantArrayElementCount - Returns number of constant array elements.
8190uint64_t
8192 uint64_t ElementCount = 1;
8193 do {
8194 ElementCount *= CA->getZExtSize();
8195 CA = dyn_cast_or_null<ConstantArrayType>(
8197 } while (CA);
8198 return ElementCount;
8199}
8200
8202 const ArrayInitLoopExpr *AILE) const {
8203 if (!AILE)
8204 return 0;
8205
8206 uint64_t ElementCount = 1;
8207
8208 do {
8209 ElementCount *= AILE->getArraySize().getZExtValue();
8210 AILE = dyn_cast<ArrayInitLoopExpr>(AILE->getSubExpr());
8211 } while (AILE);
8212
8213 return ElementCount;
8214}
8215
8216/// getFloatingRank - Return a relative rank for floating point types.
8217/// This routine will assert if passed a built-in type that isn't a float.
8219 if (const auto *CT = T->getAs<ComplexType>())
8220 return getFloatingRank(CT->getElementType());
8221
8222 switch (T->castAs<BuiltinType>()->getKind()) {
8223 default: llvm_unreachable("getFloatingRank(): not a floating type");
8224 case BuiltinType::Float16: return Float16Rank;
8225 case BuiltinType::Half: return HalfRank;
8226 case BuiltinType::Float: return FloatRank;
8227 case BuiltinType::Double: return DoubleRank;
8228 case BuiltinType::LongDouble: return LongDoubleRank;
8229 case BuiltinType::Float128: return Float128Rank;
8230 case BuiltinType::BFloat16: return BFloat16Rank;
8231 case BuiltinType::Ibm128: return Ibm128Rank;
8232 }
8233}
8234
8235/// getFloatingTypeOrder - Compare the rank of the two specified floating
8236/// point types, ignoring the domain of the type (i.e. 'double' ==
8237/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
8238/// LHS < RHS, return -1.
8240 FloatingRank LHSR = getFloatingRank(LHS);
8241 FloatingRank RHSR = getFloatingRank(RHS);
8242
8243 if (LHSR == RHSR)
8244 return 0;
8245 if (LHSR > RHSR)
8246 return 1;
8247 return -1;
8248}
8249
8252 return 0;
8253 return getFloatingTypeOrder(LHS, RHS);
8254}
8255
8256/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
8257/// routine will assert if passed a built-in type that isn't an integer or enum,
8258/// or if it is not canonicalized.
8259unsigned ASTContext::getIntegerRank(const Type *T) const {
8260 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
8261
8262 // Results in this 'losing' to any type of the same size, but winning if
8263 // larger.
8264 if (const auto *EIT = dyn_cast<BitIntType>(T))
8265 return 0 + (EIT->getNumBits() << 3);
8266
8267 if (const auto *OBT = dyn_cast<OverflowBehaviorType>(T))
8268 return getIntegerRank(OBT->getUnderlyingType().getTypePtr());
8269
8270 switch (cast<BuiltinType>(T)->getKind()) {
8271 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
8272 case BuiltinType::Bool:
8273 return 1 + (getIntWidth(BoolTy) << 3);
8274 case BuiltinType::Char_S:
8275 case BuiltinType::Char_U:
8276 case BuiltinType::SChar:
8277 case BuiltinType::UChar:
8278 return 2 + (getIntWidth(CharTy) << 3);
8279 case BuiltinType::Short:
8280 case BuiltinType::UShort:
8281 return 3 + (getIntWidth(ShortTy) << 3);
8282 case BuiltinType::Int:
8283 case BuiltinType::UInt:
8284 return 4 + (getIntWidth(IntTy) << 3);
8285 case BuiltinType::Long:
8286 case BuiltinType::ULong:
8287 return 5 + (getIntWidth(LongTy) << 3);
8288 case BuiltinType::LongLong:
8289 case BuiltinType::ULongLong:
8290 return 6 + (getIntWidth(LongLongTy) << 3);
8291 case BuiltinType::Int128:
8292 case BuiltinType::UInt128:
8293 return 7 + (getIntWidth(Int128Ty) << 3);
8294
8295 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
8296 // their underlying types" [c++20 conv.rank]
8297 case BuiltinType::Char8:
8298 return getIntegerRank(UnsignedCharTy.getTypePtr());
8299 case BuiltinType::Char16:
8300 return getIntegerRank(
8301 getFromTargetType(Target->getChar16Type()).getTypePtr());
8302 case BuiltinType::Char32:
8303 return getIntegerRank(
8304 getFromTargetType(Target->getChar32Type()).getTypePtr());
8305 case BuiltinType::WChar_S:
8306 case BuiltinType::WChar_U:
8307 return getIntegerRank(
8308 getFromTargetType(Target->getWCharType()).getTypePtr());
8309 }
8310}
8311
8312/// Whether this is a promotable bitfield reference according
8313/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
8314///
8315/// \returns the type this bit-field will promote to, or NULL if no
8316/// promotion occurs.
8318 if (E->isTypeDependent() || E->isValueDependent())
8319 return {};
8320
8321 // C++ [conv.prom]p5:
8322 // If the bit-field has an enumerated type, it is treated as any other
8323 // value of that type for promotion purposes.
8325 return {};
8326
8327 // FIXME: We should not do this unless E->refersToBitField() is true. This
8328 // matters in C where getSourceBitField() will find bit-fields for various
8329 // cases where the source expression is not a bit-field designator.
8330
8331 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
8332 if (!Field)
8333 return {};
8334
8335 QualType FT = Field->getType();
8336
8337 uint64_t BitWidth = Field->getBitWidthValue();
8338 uint64_t IntSize = getTypeSize(IntTy);
8339 // C++ [conv.prom]p5:
8340 // A prvalue for an integral bit-field can be converted to a prvalue of type
8341 // int if int can represent all the values of the bit-field; otherwise, it
8342 // can be converted to unsigned int if unsigned int can represent all the
8343 // values of the bit-field. If the bit-field is larger yet, no integral
8344 // promotion applies to it.
8345 // C11 6.3.1.1/2:
8346 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
8347 // If an int can represent all values of the original type (as restricted by
8348 // the width, for a bit-field), the value is converted to an int; otherwise,
8349 // it is converted to an unsigned int.
8350 //
8351 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
8352 // We perform that promotion here to match GCC and C++.
8353 // FIXME: C does not permit promotion of an enum bit-field whose rank is
8354 // greater than that of 'int'. We perform that promotion to match GCC.
8355 //
8356 // C23 6.3.1.1p2:
8357 // The value from a bit-field of a bit-precise integer type is converted to
8358 // the corresponding bit-precise integer type. (The rest is the same as in
8359 // C11.)
8360 if (QualType QT = Field->getType(); QT->isBitIntType())
8361 return QT;
8362
8363 if (BitWidth < IntSize)
8364 return IntTy;
8365
8366 if (BitWidth == IntSize)
8367 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
8368
8369 // Bit-fields wider than int are not subject to promotions, and therefore act
8370 // like the base type. GCC has some weird bugs in this area that we
8371 // deliberately do not follow (GCC follows a pre-standard resolution to
8372 // C's DR315 which treats bit-width as being part of the type, and this leaks
8373 // into their semantics in some cases).
8374 return {};
8375}
8376
8377/// getPromotedIntegerType - Returns the type that Promotable will
8378/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
8379/// integer type.
8381 assert(!Promotable.isNull());
8382 assert(isPromotableIntegerType(Promotable));
8383 if (const auto *ED = Promotable->getAsEnumDecl())
8384 return ED->getPromotionType();
8385
8386 // OverflowBehaviorTypes promote their underlying type and preserve OBT
8387 // qualifier.
8388 if (const auto *OBT = Promotable->getAs<OverflowBehaviorType>()) {
8389 QualType PromotedUnderlying =
8390 getPromotedIntegerType(OBT->getUnderlyingType());
8391 return getOverflowBehaviorType(OBT->getBehaviorKind(), PromotedUnderlying);
8392 }
8393
8394 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
8395 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
8396 // (3.9.1) can be converted to a prvalue of the first of the following
8397 // types that can represent all the values of its underlying type:
8398 // int, unsigned int, long int, unsigned long int, long long int, or
8399 // unsigned long long int [...]
8400 // FIXME: Is there some better way to compute this?
8401 if (BT->getKind() == BuiltinType::WChar_S ||
8402 BT->getKind() == BuiltinType::WChar_U ||
8403 BT->getKind() == BuiltinType::Char8 ||
8404 BT->getKind() == BuiltinType::Char16 ||
8405 BT->getKind() == BuiltinType::Char32) {
8406 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
8407 uint64_t FromSize = getTypeSize(BT);
8408 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
8410 for (const auto &PT : PromoteTypes) {
8411 uint64_t ToSize = getTypeSize(PT);
8412 if (FromSize < ToSize ||
8413 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
8414 return PT;
8415 }
8416 llvm_unreachable("char type should fit into long long");
8417 }
8418 }
8419
8420 // At this point, we should have a signed or unsigned integer type.
8421 if (Promotable->isSignedIntegerType())
8422 return IntTy;
8423 uint64_t PromotableSize = getIntWidth(Promotable);
8424 uint64_t IntSize = getIntWidth(IntTy);
8425 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
8426 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
8427}
8428
8429/// Recurses in pointer/array types until it finds an objc retainable
8430/// type and returns its ownership.
8432 while (!T.isNull()) {
8433 if (T.getObjCLifetime() != Qualifiers::OCL_None)
8434 return T.getObjCLifetime();
8435 if (T->isArrayType())
8436 T = getBaseElementType(T);
8437 else if (const auto *PT = T->getAs<PointerType>())
8438 T = PT->getPointeeType();
8439 else if (const auto *RT = T->getAs<ReferenceType>())
8440 T = RT->getPointeeType();
8441 else
8442 break;
8443 }
8444
8445 return Qualifiers::OCL_None;
8446}
8447
8448static const Type *getIntegerTypeForEnum(const EnumType *ET) {
8449 // Incomplete enum types are not treated as integer types.
8450 // FIXME: In C++, enum types are never integer types.
8451 const EnumDecl *ED = ET->getDecl()->getDefinitionOrSelf();
8452 if (ED->isComplete() && !ED->isScoped())
8453 return ED->getIntegerType().getTypePtr();
8454 return nullptr;
8455}
8456
8457/// getIntegerTypeOrder - Returns the highest ranked integer type:
8458/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
8459/// LHS < RHS, return -1.
8461 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
8462 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
8463
8464 // Unwrap enums to their underlying type.
8465 if (const auto *ET = dyn_cast<EnumType>(LHSC))
8466 LHSC = getIntegerTypeForEnum(ET);
8467 if (const auto *ET = dyn_cast<EnumType>(RHSC))
8468 RHSC = getIntegerTypeForEnum(ET);
8469
8470 if (LHSC == RHSC) return 0;
8471
8472 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
8473 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
8474
8475 unsigned LHSRank = getIntegerRank(LHSC);
8476 unsigned RHSRank = getIntegerRank(RHSC);
8477
8478 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
8479 if (LHSRank == RHSRank) return 0;
8480 return LHSRank > RHSRank ? 1 : -1;
8481 }
8482
8483 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
8484 if (LHSUnsigned) {
8485 // If the unsigned [LHS] type is larger, return it.
8486 if (LHSRank >= RHSRank)
8487 return 1;
8488
8489 // If the signed type can represent all values of the unsigned type, it
8490 // wins. Because we are dealing with 2's complement and types that are
8491 // powers of two larger than each other, this is always safe.
8492 return -1;
8493 }
8494
8495 // If the unsigned [RHS] type is larger, return it.
8496 if (RHSRank >= LHSRank)
8497 return -1;
8498
8499 // If the signed type can represent all values of the unsigned type, it
8500 // wins. Because we are dealing with 2's complement and types that are
8501 // powers of two larger than each other, this is always safe.
8502 return 1;
8503}
8504
8506 if (CFConstantStringTypeDecl)
8507 return CFConstantStringTypeDecl;
8508
8509 assert(!CFConstantStringTagDecl &&
8510 "tag and typedef should be initialized together");
8511 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
8512 CFConstantStringTagDecl->startDefinition();
8513
8514 struct {
8515 QualType Type;
8516 const char *Name;
8517 } Fields[5];
8518 unsigned Count = 0;
8519
8520 /// Objective-C ABI
8521 ///
8522 /// typedef struct __NSConstantString_tag {
8523 /// const int *isa;
8524 /// int flags;
8525 /// const char *str;
8526 /// long length;
8527 /// } __NSConstantString;
8528 ///
8529 /// Swift ABI (4.1, 4.2)
8530 ///
8531 /// typedef struct __NSConstantString_tag {
8532 /// uintptr_t _cfisa;
8533 /// uintptr_t _swift_rc;
8534 /// _Atomic(uint64_t) _cfinfoa;
8535 /// const char *_ptr;
8536 /// uint32_t _length;
8537 /// } __NSConstantString;
8538 ///
8539 /// Swift ABI (5.0)
8540 ///
8541 /// typedef struct __NSConstantString_tag {
8542 /// uintptr_t _cfisa;
8543 /// uintptr_t _swift_rc;
8544 /// _Atomic(uint64_t) _cfinfoa;
8545 /// const char *_ptr;
8546 /// uintptr_t _length;
8547 /// } __NSConstantString;
8548
8549 const auto CFRuntime = getLangOpts().CFRuntime;
8550 if (static_cast<unsigned>(CFRuntime) <
8551 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
8552 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
8553 Fields[Count++] = { IntTy, "flags" };
8554 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
8555 Fields[Count++] = { LongTy, "length" };
8556 } else {
8557 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
8558 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
8559 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
8560 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
8563 Fields[Count++] = { IntTy, "_ptr" };
8564 else
8565 Fields[Count++] = { getUIntPtrType(), "_ptr" };
8566 }
8567
8568 // Create fields
8569 for (unsigned i = 0; i < Count; ++i) {
8570 FieldDecl *Field =
8571 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
8572 SourceLocation(), &Idents.get(Fields[i].Name),
8573 Fields[i].Type, /*TInfo=*/nullptr,
8574 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8575 Field->setAccess(AS_public);
8576 CFConstantStringTagDecl->addDecl(Field);
8577 }
8578
8579 CFConstantStringTagDecl->completeDefinition();
8580 // This type is designed to be compatible with NSConstantString, but cannot
8581 // use the same name, since NSConstantString is an interface.
8582 CanQualType tagType = getCanonicalTagType(CFConstantStringTagDecl);
8583 CFConstantStringTypeDecl =
8584 buildImplicitTypedef(tagType, "__NSConstantString");
8585
8586 return CFConstantStringTypeDecl;
8587}
8588
8590 if (!CFConstantStringTagDecl)
8591 getCFConstantStringDecl(); // Build the tag and the typedef.
8592 return CFConstantStringTagDecl;
8593}
8594
8595// getCFConstantStringType - Return the type used for constant CFStrings.
8600
8602 if (ObjCSuperType.isNull()) {
8603 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
8604 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
8605 ObjCSuperType = getCanonicalTagType(ObjCSuperTypeDecl);
8606 }
8607 return ObjCSuperType;
8608}
8609
8611 const auto *TT = T->castAs<TypedefType>();
8612 CFConstantStringTypeDecl = cast<TypedefDecl>(TT->getDecl());
8613 CFConstantStringTagDecl = TT->castAsRecordDecl();
8614}
8615
8617 if (BlockDescriptorType)
8618 return getCanonicalTagType(BlockDescriptorType);
8619
8620 RecordDecl *RD;
8621 // FIXME: Needs the FlagAppleBlock bit.
8622 RD = buildImplicitRecord("__block_descriptor");
8623 RD->startDefinition();
8624
8625 QualType FieldTypes[] = {
8628 };
8629
8630 static const char *const FieldNames[] = {
8631 "reserved",
8632 "Size"
8633 };
8634
8635 for (size_t i = 0; i < 2; ++i) {
8637 *this, RD, SourceLocation(), SourceLocation(),
8638 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8639 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8640 Field->setAccess(AS_public);
8641 RD->addDecl(Field);
8642 }
8643
8644 RD->completeDefinition();
8645
8646 BlockDescriptorType = RD;
8647
8648 return getCanonicalTagType(BlockDescriptorType);
8649}
8650
8652 if (BlockDescriptorExtendedType)
8653 return getCanonicalTagType(BlockDescriptorExtendedType);
8654
8655 RecordDecl *RD;
8656 // FIXME: Needs the FlagAppleBlock bit.
8657 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
8658 RD->startDefinition();
8659
8660 QualType FieldTypes[] = {
8665 };
8666
8667 static const char *const FieldNames[] = {
8668 "reserved",
8669 "Size",
8670 "CopyFuncPtr",
8671 "DestroyFuncPtr"
8672 };
8673
8674 for (size_t i = 0; i < 4; ++i) {
8676 *this, RD, SourceLocation(), SourceLocation(),
8677 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8678 /*BitWidth=*/nullptr,
8679 /*Mutable=*/false, ICIS_NoInit);
8680 Field->setAccess(AS_public);
8681 RD->addDecl(Field);
8682 }
8683
8684 RD->completeDefinition();
8685
8686 BlockDescriptorExtendedType = RD;
8687 return getCanonicalTagType(BlockDescriptorExtendedType);
8688}
8689
8691 const auto *BT = dyn_cast<BuiltinType>(T);
8692
8693 if (!BT) {
8694 if (isa<PipeType>(T))
8695 return OCLTK_Pipe;
8696
8697 return OCLTK_Default;
8698 }
8699
8700 switch (BT->getKind()) {
8701#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8702 case BuiltinType::Id: \
8703 return OCLTK_Image;
8704#include "clang/Basic/OpenCLImageTypes.def"
8705
8706 case BuiltinType::OCLClkEvent:
8707 return OCLTK_ClkEvent;
8708
8709 case BuiltinType::OCLEvent:
8710 return OCLTK_Event;
8711
8712 case BuiltinType::OCLQueue:
8713 return OCLTK_Queue;
8714
8715 case BuiltinType::OCLReserveID:
8716 return OCLTK_ReserveID;
8717
8718 case BuiltinType::OCLSampler:
8719 return OCLTK_Sampler;
8720
8721 default:
8722 return OCLTK_Default;
8723 }
8724}
8725
8727 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
8728}
8729
8730/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
8731/// requires copy/dispose. Note that this must match the logic
8732/// in buildByrefHelpers.
8734 const VarDecl *D) {
8735 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
8736 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
8737 if (!copyExpr && record->hasTrivialDestructor()) return false;
8738
8739 return true;
8740 }
8741
8743 return true;
8744
8745 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
8746 // move or destroy.
8748 return true;
8749
8750 if (!Ty->isObjCRetainableType()) return false;
8751
8752 Qualifiers qs = Ty.getQualifiers();
8753
8754 // If we have lifetime, that dominates.
8755 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
8756 switch (lifetime) {
8757 case Qualifiers::OCL_None: llvm_unreachable("impossible");
8758
8759 // These are just bits as far as the runtime is concerned.
8762 return false;
8763
8764 // These cases should have been taken care of when checking the type's
8765 // non-triviality.
8768 llvm_unreachable("impossible");
8769 }
8770 llvm_unreachable("fell out of lifetime switch!");
8771 }
8772 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
8774}
8775
8777 Qualifiers::ObjCLifetime &LifeTime,
8778 bool &HasByrefExtendedLayout) const {
8779 if (!getLangOpts().ObjC ||
8780 getLangOpts().getGC() != LangOptions::NonGC)
8781 return false;
8782
8783 HasByrefExtendedLayout = false;
8784 if (Ty->isRecordType()) {
8785 HasByrefExtendedLayout = true;
8786 LifeTime = Qualifiers::OCL_None;
8787 } else if ((LifeTime = Ty.getObjCLifetime())) {
8788 // Honor the ARC qualifiers.
8789 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
8790 // The MRR rule.
8792 } else {
8793 LifeTime = Qualifiers::OCL_None;
8794 }
8795 return true;
8796}
8797
8799 assert(Target && "Expected target to be initialized");
8800 const llvm::Triple &T = Target->getTriple();
8801 // Windows is LLP64 rather than LP64
8802 if (T.isOSWindows() && T.isArch64Bit())
8803 return UnsignedLongLongTy;
8804 return UnsignedLongTy;
8805}
8806
8808 assert(Target && "Expected target to be initialized");
8809 const llvm::Triple &T = Target->getTriple();
8810 // Windows is LLP64 rather than LP64
8811 if (T.isOSWindows() && T.isArch64Bit())
8812 return LongLongTy;
8813 return LongTy;
8814}
8815
8817 if (!ObjCInstanceTypeDecl)
8818 ObjCInstanceTypeDecl =
8819 buildImplicitTypedef(getObjCIdType(), "instancetype");
8820 return ObjCInstanceTypeDecl;
8821}
8822
8823// This returns true if a type has been typedefed to BOOL:
8824// typedef <type> BOOL;
8826 if (const auto *TT = dyn_cast<TypedefType>(T))
8827 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
8828 return II->isStr("BOOL");
8829
8830 return false;
8831}
8832
8833/// getObjCEncodingTypeSize returns size of type for objective-c encoding
8834/// purpose.
8836 if (!type->isIncompleteArrayType() && type->isIncompleteType())
8837 return CharUnits::Zero();
8838
8840
8841 // Make all integer and enum types at least as large as an int
8842 if (sz.isPositive() && type->isIntegralOrEnumerationType())
8843 sz = std::max(sz, getTypeSizeInChars(IntTy));
8844 // Treat arrays as pointers, since that's how they're passed in.
8845 else if (type->isArrayType())
8847 return sz;
8848}
8849
8856
8859 if (!VD->isInline())
8861
8862 // In almost all cases, it's a weak definition.
8863 auto *First = VD->getFirstDecl();
8864 if (First->isInlineSpecified() || !First->isStaticDataMember())
8866
8867 // If there's a file-context declaration in this translation unit, it's a
8868 // non-discardable definition.
8869 for (auto *D : VD->redecls())
8871 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
8873
8874 // If we've not seen one yet, we don't know.
8876}
8877
8878static std::string charUnitsToString(const CharUnits &CU) {
8879 return llvm::itostr(CU.getQuantity());
8880}
8881
8882/// getObjCEncodingForBlock - Return the encoded type for this block
8883/// declaration.
8885 std::string S;
8886
8887 const BlockDecl *Decl = Expr->getBlockDecl();
8888 QualType BlockTy =
8890 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
8891 // Encode result type.
8892 if (getLangOpts().EncodeExtendedBlockSig)
8894 true /*Extended*/);
8895 else
8896 getObjCEncodingForType(BlockReturnTy, S);
8897 // Compute size of all parameters.
8898 // Start with computing size of a pointer in number of bytes.
8899 // FIXME: There might(should) be a better way of doing this computation!
8901 CharUnits ParmOffset = PtrSize;
8902 for (auto *PI : Decl->parameters()) {
8903 QualType PType = PI->getType();
8905 if (sz.isZero())
8906 continue;
8907 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
8908 ParmOffset += sz;
8909 }
8910 // Size of the argument frame
8911 S += charUnitsToString(ParmOffset);
8912 // Block pointer and offset.
8913 S += "@?0";
8914
8915 // Argument types.
8916 ParmOffset = PtrSize;
8917 for (auto *PVDecl : Decl->parameters()) {
8918 QualType PType = PVDecl->getOriginalType();
8919 if (const auto *AT =
8920 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8921 // Use array's original type only if it has known number of
8922 // elements.
8923 if (!isa<ConstantArrayType>(AT))
8924 PType = PVDecl->getType();
8925 } else if (PType->isFunctionType())
8926 PType = PVDecl->getType();
8927 if (getLangOpts().EncodeExtendedBlockSig)
8929 S, true /*Extended*/);
8930 else
8931 getObjCEncodingForType(PType, S);
8932 S += charUnitsToString(ParmOffset);
8933 ParmOffset += getObjCEncodingTypeSize(PType);
8934 }
8935
8936 return S;
8937}
8938
8939std::string
8941 std::string S;
8942 // Encode result type.
8943 getObjCEncodingForType(Decl->getReturnType(), S);
8944 CharUnits ParmOffset;
8945 // Compute size of all parameters.
8946 for (auto *PI : Decl->parameters()) {
8947 QualType PType = PI->getType();
8949 if (sz.isZero())
8950 continue;
8951
8952 assert(sz.isPositive() &&
8953 "getObjCEncodingForFunctionDecl - Incomplete param type");
8954 ParmOffset += sz;
8955 }
8956 S += charUnitsToString(ParmOffset);
8957 ParmOffset = CharUnits::Zero();
8958
8959 // Argument types.
8960 for (auto *PVDecl : Decl->parameters()) {
8961 QualType PType = PVDecl->getOriginalType();
8962 if (const auto *AT =
8963 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8964 // Use array's original type only if it has known number of
8965 // elements.
8966 if (!isa<ConstantArrayType>(AT))
8967 PType = PVDecl->getType();
8968 } else if (PType->isFunctionType())
8969 PType = PVDecl->getType();
8970 getObjCEncodingForType(PType, S);
8971 S += charUnitsToString(ParmOffset);
8972 ParmOffset += getObjCEncodingTypeSize(PType);
8973 }
8974
8975 return S;
8976}
8977
8978/// getObjCEncodingForMethodParameter - Return the encoded type for a single
8979/// method parameter or return type. If Extended, include class names and
8980/// block object types.
8982 QualType T, std::string& S,
8983 bool Extended) const {
8984 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
8986 // Encode parameter type.
8987 ObjCEncOptions Options = ObjCEncOptions()
8988 .setExpandPointedToStructures()
8989 .setExpandStructures()
8990 .setIsOutermostType();
8991 if (Extended)
8992 Options.setEncodeBlockParameters().setEncodeClassNames();
8993 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
8994}
8995
8996/// getObjCEncodingForMethodDecl - Return the encoded type for this method
8997/// declaration.
8999 bool Extended) const {
9000 // FIXME: This is not very efficient.
9001 // Encode return type.
9002 std::string S;
9003 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
9004 Decl->getReturnType(), S, Extended);
9005 // Compute size of all parameters.
9006 // Start with computing size of a pointer in number of bytes.
9007 // FIXME: There might(should) be a better way of doing this computation!
9009 // The first two arguments (self and _cmd) are pointers; account for
9010 // their size.
9011 CharUnits ParmOffset = 2 * PtrSize;
9012 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
9013 E = Decl->sel_param_end(); PI != E; ++PI) {
9014 QualType PType = (*PI)->getType();
9016 if (sz.isZero())
9017 continue;
9018
9019 assert(sz.isPositive() &&
9020 "getObjCEncodingForMethodDecl - Incomplete param type");
9021 ParmOffset += sz;
9022 }
9023 S += charUnitsToString(ParmOffset);
9024 S += "@0:";
9025 S += charUnitsToString(PtrSize);
9026
9027 // Argument types.
9028 ParmOffset = 2 * PtrSize;
9029 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
9030 E = Decl->sel_param_end(); PI != E; ++PI) {
9031 const ParmVarDecl *PVDecl = *PI;
9032 QualType PType = PVDecl->getOriginalType();
9033 if (const auto *AT =
9034 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
9035 // Use array's original type only if it has known number of
9036 // elements.
9037 if (!isa<ConstantArrayType>(AT))
9038 PType = PVDecl->getType();
9039 } else if (PType->isFunctionType())
9040 PType = PVDecl->getType();
9042 PType, S, Extended);
9043 S += charUnitsToString(ParmOffset);
9044 ParmOffset += getObjCEncodingTypeSize(PType);
9045 }
9046
9047 return S;
9048}
9049
9052 const ObjCPropertyDecl *PD,
9053 const Decl *Container) const {
9054 if (!Container)
9055 return nullptr;
9056 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
9057 for (auto *PID : CID->property_impls())
9058 if (PID->getPropertyDecl() == PD)
9059 return PID;
9060 } else {
9061 const auto *OID = cast<ObjCImplementationDecl>(Container);
9062 for (auto *PID : OID->property_impls())
9063 if (PID->getPropertyDecl() == PD)
9064 return PID;
9065 }
9066 return nullptr;
9067}
9068
9069/// getObjCEncodingForPropertyDecl - Return the encoded type for this
9070/// property declaration. If non-NULL, Container must be either an
9071/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
9072/// NULL when getting encodings for protocol properties.
9073/// Property attributes are stored as a comma-delimited C string. The simple
9074/// attributes readonly and bycopy are encoded as single characters. The
9075/// parametrized attributes, getter=name, setter=name, and ivar=name, are
9076/// encoded as single characters, followed by an identifier. Property types
9077/// are also encoded as a parametrized attribute. The characters used to encode
9078/// these attributes are defined by the following enumeration:
9079/// @code
9080/// enum PropertyAttributes {
9081/// kPropertyReadOnly = 'R', // property is read-only.
9082/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
9083/// kPropertyByref = '&', // property is a reference to the value last assigned
9084/// kPropertyDynamic = 'D', // property is dynamic
9085/// kPropertyGetter = 'G', // followed by getter selector name
9086/// kPropertySetter = 'S', // followed by setter selector name
9087/// kPropertyInstanceVariable = 'V' // followed by instance variable name
9088/// kPropertyType = 'T' // followed by old-style type encoding.
9089/// kPropertyWeak = 'W' // 'weak' property
9090/// kPropertyStrong = 'P' // property GC'able
9091/// kPropertyNonAtomic = 'N' // property non-atomic
9092/// kPropertyOptional = '?' // property optional
9093/// };
9094/// @endcode
9095std::string
9097 const Decl *Container) const {
9098 // Collect information from the property implementation decl(s).
9099 bool Dynamic = false;
9100 ObjCPropertyImplDecl *SynthesizePID = nullptr;
9101
9102 if (ObjCPropertyImplDecl *PropertyImpDecl =
9104 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
9105 Dynamic = true;
9106 else
9107 SynthesizePID = PropertyImpDecl;
9108 }
9109
9110 // FIXME: This is not very efficient.
9111 std::string S = "T";
9112
9113 // Encode result type.
9114 // GCC has some special rules regarding encoding of properties which
9115 // closely resembles encoding of ivars.
9117
9118 if (PD->isOptional())
9119 S += ",?";
9120
9121 if (PD->isReadOnly()) {
9122 S += ",R";
9124 S += ",C";
9126 S += ",&";
9128 S += ",W";
9129 } else {
9130 switch (PD->getSetterKind()) {
9131 case ObjCPropertyDecl::Assign: break;
9132 case ObjCPropertyDecl::Copy: S += ",C"; break;
9133 case ObjCPropertyDecl::Retain: S += ",&"; break;
9134 case ObjCPropertyDecl::Weak: S += ",W"; break;
9135 }
9136 }
9137
9138 // It really isn't clear at all what this means, since properties
9139 // are "dynamic by default".
9140 if (Dynamic)
9141 S += ",D";
9142
9144 S += ",N";
9145
9147 S += ",G";
9148 S += PD->getGetterName().getAsString();
9149 }
9150
9152 S += ",S";
9153 S += PD->getSetterName().getAsString();
9154 }
9155
9156 if (SynthesizePID) {
9157 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
9158 S += ",V";
9159 S += OID->getNameAsString();
9160 }
9161
9162 // FIXME: OBJCGC: weak & strong
9163 return S;
9164}
9165
9166/// getLegacyIntegralTypeEncoding -
9167/// Another legacy compatibility encoding: 32-bit longs are encoded as
9168/// 'l' or 'L' , but not always. For typedefs, we need to use
9169/// 'i' or 'I' instead if encoding a struct field, or a pointer!
9171 if (PointeeTy->getAs<TypedefType>()) {
9172 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
9173 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
9174 PointeeTy = UnsignedIntTy;
9175 else
9176 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
9177 PointeeTy = IntTy;
9178 }
9179 }
9180}
9181
9183 const FieldDecl *Field,
9184 QualType *NotEncodedT) const {
9185 // We follow the behavior of gcc, expanding structures which are
9186 // directly pointed to, and expanding embedded structures. Note that
9187 // these rules are sufficient to prevent recursive encoding of the
9188 // same type.
9189 getObjCEncodingForTypeImpl(T, S,
9190 ObjCEncOptions()
9191 .setExpandPointedToStructures()
9192 .setExpandStructures()
9193 .setIsOutermostType(),
9194 Field, NotEncodedT);
9195}
9196
9198 std::string& S) const {
9199 // Encode result type.
9200 // GCC has some special rules regarding encoding of properties which
9201 // closely resembles encoding of ivars.
9202 getObjCEncodingForTypeImpl(T, S,
9203 ObjCEncOptions()
9204 .setExpandPointedToStructures()
9205 .setExpandStructures()
9206 .setIsOutermostType()
9207 .setEncodingProperty(),
9208 /*Field=*/nullptr);
9209}
9210
9212 const BuiltinType *BT) {
9214 switch (kind) {
9215 case BuiltinType::Void: return 'v';
9216 case BuiltinType::Bool: return 'B';
9217 case BuiltinType::Char8:
9218 case BuiltinType::Char_U:
9219 case BuiltinType::UChar: return 'C';
9220 case BuiltinType::Char16:
9221 case BuiltinType::UShort: return 'S';
9222 case BuiltinType::Char32:
9223 case BuiltinType::UInt: return 'I';
9224 case BuiltinType::ULong:
9225 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
9226 case BuiltinType::UInt128: return 'T';
9227 case BuiltinType::ULongLong: return 'Q';
9228 case BuiltinType::Char_S:
9229 case BuiltinType::SChar: return 'c';
9230 case BuiltinType::Short: return 's';
9231 case BuiltinType::WChar_S:
9232 case BuiltinType::WChar_U:
9233 case BuiltinType::Int: return 'i';
9234 case BuiltinType::Long:
9235 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
9236 case BuiltinType::LongLong: return 'q';
9237 case BuiltinType::Int128: return 't';
9238 case BuiltinType::Float: return 'f';
9239 case BuiltinType::Double: return 'd';
9240 case BuiltinType::LongDouble: return 'D';
9241 case BuiltinType::NullPtr: return '*'; // like char*
9242
9243 case BuiltinType::BFloat16:
9244 case BuiltinType::Float16:
9245 case BuiltinType::Float128:
9246 case BuiltinType::Ibm128:
9247 case BuiltinType::Half:
9248 case BuiltinType::ShortAccum:
9249 case BuiltinType::Accum:
9250 case BuiltinType::LongAccum:
9251 case BuiltinType::UShortAccum:
9252 case BuiltinType::UAccum:
9253 case BuiltinType::ULongAccum:
9254 case BuiltinType::ShortFract:
9255 case BuiltinType::Fract:
9256 case BuiltinType::LongFract:
9257 case BuiltinType::UShortFract:
9258 case BuiltinType::UFract:
9259 case BuiltinType::ULongFract:
9260 case BuiltinType::SatShortAccum:
9261 case BuiltinType::SatAccum:
9262 case BuiltinType::SatLongAccum:
9263 case BuiltinType::SatUShortAccum:
9264 case BuiltinType::SatUAccum:
9265 case BuiltinType::SatULongAccum:
9266 case BuiltinType::SatShortFract:
9267 case BuiltinType::SatFract:
9268 case BuiltinType::SatLongFract:
9269 case BuiltinType::SatUShortFract:
9270 case BuiltinType::SatUFract:
9271 case BuiltinType::SatULongFract:
9272 // FIXME: potentially need @encodes for these!
9273 return ' ';
9274
9275#define SVE_TYPE(Name, Id, SingletonId) \
9276 case BuiltinType::Id:
9277#include "clang/Basic/AArch64ACLETypes.def"
9278#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9279#include "clang/Basic/RISCVVTypes.def"
9280#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9281#include "clang/Basic/WebAssemblyReferenceTypes.def"
9282#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
9283#include "clang/Basic/AMDGPUTypes.def"
9284 {
9285 DiagnosticsEngine &Diags = C->getDiagnostics();
9286 Diags.Report(diag::err_unsupported_objc_primitive_encoding)
9287 << QualType(BT, 0);
9288 return ' ';
9289 }
9290
9291 case BuiltinType::ObjCId:
9292 case BuiltinType::ObjCClass:
9293 case BuiltinType::ObjCSel:
9294 llvm_unreachable("@encoding ObjC primitive type");
9295
9296 // OpenCL and placeholder types don't need @encodings.
9297#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
9298 case BuiltinType::Id:
9299#include "clang/Basic/OpenCLImageTypes.def"
9300#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9301 case BuiltinType::Id:
9302#include "clang/Basic/OpenCLExtensionTypes.def"
9303 case BuiltinType::OCLEvent:
9304 case BuiltinType::OCLClkEvent:
9305 case BuiltinType::OCLQueue:
9306 case BuiltinType::OCLReserveID:
9307 case BuiltinType::OCLSampler:
9308 case BuiltinType::Dependent:
9309#define PPC_VECTOR_TYPE(Name, Id, Size) \
9310 case BuiltinType::Id:
9311#include "clang/Basic/PPCTypes.def"
9312#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9313#include "clang/Basic/HLSLIntangibleTypes.def"
9314#define BUILTIN_TYPE(KIND, ID)
9315#define PLACEHOLDER_TYPE(KIND, ID) \
9316 case BuiltinType::KIND:
9317#include "clang/AST/BuiltinTypes.def"
9318 llvm_unreachable("invalid builtin type for @encode");
9319 }
9320 llvm_unreachable("invalid BuiltinType::Kind value");
9321}
9322
9323static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED) {
9325
9326 // The encoding of an non-fixed enum type is always 'i', regardless of size.
9327 if (!Enum->isFixed())
9328 return 'i';
9329
9330 // The encoding of a fixed enum type matches its fixed underlying type.
9331 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
9333}
9334
9335static void EncodeBitField(const ASTContext *Ctx, std::string& S,
9336 QualType T, const FieldDecl *FD) {
9337 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
9338 S += 'b';
9339 // The NeXT runtime encodes bit fields as b followed by the number of bits.
9340 // The GNU runtime requires more information; bitfields are encoded as b,
9341 // then the offset (in bits) of the first element, then the type of the
9342 // bitfield, then the size in bits. For example, in this structure:
9343 //
9344 // struct
9345 // {
9346 // int integer;
9347 // int flags:2;
9348 // };
9349 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
9350 // runtime, but b32i2 for the GNU runtime. The reason for this extra
9351 // information is not especially sensible, but we're stuck with it for
9352 // compatibility with GCC, although providing it breaks anything that
9353 // actually uses runtime introspection and wants to work on both runtimes...
9354 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
9355 uint64_t Offset;
9356
9357 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
9358 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), IVD);
9359 } else {
9360 const RecordDecl *RD = FD->getParent();
9361 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
9362 Offset = RL.getFieldOffset(FD->getFieldIndex());
9363 }
9364
9365 S += llvm::utostr(Offset);
9366
9367 if (const auto *ET = T->getAsCanonical<EnumType>())
9368 S += ObjCEncodingForEnumDecl(Ctx, ET->getDecl());
9369 else {
9370 const auto *BT = T->castAs<BuiltinType>();
9371 S += getObjCEncodingForPrimitiveType(Ctx, BT);
9372 }
9373 }
9374 S += llvm::utostr(FD->getBitWidthValue());
9375}
9376
9377// Helper function for determining whether the encoded type string would include
9378// a template specialization type.
9380 bool VisitBasesAndFields) {
9381 T = T->getBaseElementTypeUnsafe();
9382
9383 if (auto *PT = T->getAs<PointerType>())
9385 PT->getPointeeType().getTypePtr(), false);
9386
9387 auto *CXXRD = T->getAsCXXRecordDecl();
9388
9389 if (!CXXRD)
9390 return false;
9391
9393 return true;
9394
9395 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
9396 return false;
9397
9398 for (const auto &B : CXXRD->bases())
9399 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
9400 true))
9401 return true;
9402
9403 for (auto *FD : CXXRD->fields())
9404 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
9405 true))
9406 return true;
9407
9408 return false;
9409}
9410
9411// FIXME: Use SmallString for accumulating string.
9412void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
9413 const ObjCEncOptions Options,
9414 const FieldDecl *FD,
9415 QualType *NotEncodedT) const {
9417 switch (CT->getTypeClass()) {
9418 case Type::Builtin:
9419 case Type::Enum:
9420 if (FD && FD->isBitField())
9421 return EncodeBitField(this, S, T, FD);
9422 if (const auto *BT = dyn_cast<BuiltinType>(CT))
9423 S += getObjCEncodingForPrimitiveType(this, BT);
9424 else
9425 S += ObjCEncodingForEnumDecl(this, cast<EnumType>(CT)->getDecl());
9426 return;
9427
9428 case Type::Complex:
9429 S += 'j';
9430 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
9431 ObjCEncOptions(),
9432 /*Field=*/nullptr);
9433 return;
9434
9435 case Type::Atomic:
9436 S += 'A';
9437 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
9438 ObjCEncOptions(),
9439 /*Field=*/nullptr);
9440 return;
9441
9442 // encoding for pointer or reference types.
9443 case Type::Pointer:
9444 case Type::LValueReference:
9445 case Type::RValueReference: {
9446 QualType PointeeTy;
9447 if (isa<PointerType>(CT)) {
9448 const auto *PT = T->castAs<PointerType>();
9449 if (PT->isObjCSelType()) {
9450 S += ':';
9451 return;
9452 }
9453 PointeeTy = PT->getPointeeType();
9454 } else {
9455 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
9456 }
9457
9458 bool isReadOnly = false;
9459 // For historical/compatibility reasons, the read-only qualifier of the
9460 // pointee gets emitted _before_ the '^'. The read-only qualifier of
9461 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
9462 // Also, do not emit the 'r' for anything but the outermost type!
9463 if (T->getAs<TypedefType>()) {
9464 if (Options.IsOutermostType() && T.isConstQualified()) {
9465 isReadOnly = true;
9466 S += 'r';
9467 }
9468 } else if (Options.IsOutermostType()) {
9469 QualType P = PointeeTy;
9470 while (auto PT = P->getAs<PointerType>())
9471 P = PT->getPointeeType();
9472 if (P.isConstQualified()) {
9473 isReadOnly = true;
9474 S += 'r';
9475 }
9476 }
9477 if (isReadOnly) {
9478 // Another legacy compatibility encoding. Some ObjC qualifier and type
9479 // combinations need to be rearranged.
9480 // Rewrite "in const" from "nr" to "rn"
9481 if (StringRef(S).ends_with("nr"))
9482 S.replace(S.end()-2, S.end(), "rn");
9483 }
9484
9485 if (PointeeTy->isCharType()) {
9486 // char pointer types should be encoded as '*' unless it is a
9487 // type that has been typedef'd to 'BOOL'.
9488 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
9489 S += '*';
9490 return;
9491 }
9492 } else if (const auto *RTy = PointeeTy->getAsCanonical<RecordType>()) {
9493 const IdentifierInfo *II = RTy->getDecl()->getIdentifier();
9494 // GCC binary compat: Need to convert "struct objc_class *" to "#".
9495 if (II == &Idents.get("objc_class")) {
9496 S += '#';
9497 return;
9498 }
9499 // GCC binary compat: Need to convert "struct objc_object *" to "@".
9500 if (II == &Idents.get("objc_object")) {
9501 S += '@';
9502 return;
9503 }
9504 // If the encoded string for the class includes template names, just emit
9505 // "^v" for pointers to the class.
9506 if (getLangOpts().CPlusPlus &&
9507 (!getLangOpts().EncodeCXXClassTemplateSpec &&
9509 RTy, Options.ExpandPointedToStructures()))) {
9510 S += "^v";
9511 return;
9512 }
9513 // fall through...
9514 }
9515 S += '^';
9517
9518 ObjCEncOptions NewOptions;
9519 if (Options.ExpandPointedToStructures())
9520 NewOptions.setExpandStructures();
9521 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
9522 /*Field=*/nullptr, NotEncodedT);
9523 return;
9524 }
9525
9526 case Type::ConstantArray:
9527 case Type::IncompleteArray:
9528 case Type::VariableArray: {
9529 const auto *AT = cast<ArrayType>(CT);
9530
9531 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
9532 // Incomplete arrays are encoded as a pointer to the array element.
9533 S += '^';
9534
9535 getObjCEncodingForTypeImpl(
9536 AT->getElementType(), S,
9537 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
9538 } else {
9539 S += '[';
9540
9541 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
9542 S += llvm::utostr(CAT->getZExtSize());
9543 else {
9544 //Variable length arrays are encoded as a regular array with 0 elements.
9546 "Unknown array type!");
9547 S += '0';
9548 }
9549
9550 getObjCEncodingForTypeImpl(
9551 AT->getElementType(), S,
9552 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
9553 NotEncodedT);
9554 S += ']';
9555 }
9556 return;
9557 }
9558
9559 case Type::FunctionNoProto:
9560 case Type::FunctionProto:
9561 S += '?';
9562 return;
9563
9564 case Type::Record: {
9565 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
9566 S += RDecl->isUnion() ? '(' : '{';
9567 // Anonymous structures print as '?'
9568 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
9569 S += II->getName();
9570 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
9571 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
9572 llvm::raw_string_ostream OS(S);
9573 printTemplateArgumentList(OS, TemplateArgs.asArray(),
9575 }
9576 } else {
9577 S += '?';
9578 }
9579 if (Options.ExpandStructures()) {
9580 S += '=';
9581 if (!RDecl->isUnion()) {
9582 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
9583 } else {
9584 for (const auto *Field : RDecl->fields()) {
9585 if (FD) {
9586 S += '"';
9587 S += Field->getNameAsString();
9588 S += '"';
9589 }
9590
9591 // Special case bit-fields.
9592 if (Field->isBitField()) {
9593 getObjCEncodingForTypeImpl(Field->getType(), S,
9594 ObjCEncOptions().setExpandStructures(),
9595 Field);
9596 } else {
9597 QualType qt = Field->getType();
9599 getObjCEncodingForTypeImpl(
9600 qt, S,
9601 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
9602 NotEncodedT);
9603 }
9604 }
9605 }
9606 }
9607 S += RDecl->isUnion() ? ')' : '}';
9608 return;
9609 }
9610
9611 case Type::BlockPointer: {
9612 const auto *BT = T->castAs<BlockPointerType>();
9613 S += "@?"; // Unlike a pointer-to-function, which is "^?".
9614 if (Options.EncodeBlockParameters()) {
9615 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
9616
9617 S += '<';
9618 // Block return type
9619 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
9620 Options.forComponentType(), FD, NotEncodedT);
9621 // Block self
9622 S += "@?";
9623 // Block parameters
9624 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
9625 for (const auto &I : FPT->param_types())
9626 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
9627 NotEncodedT);
9628 }
9629 S += '>';
9630 }
9631 return;
9632 }
9633
9634 case Type::ObjCObject: {
9635 // hack to match legacy encoding of *id and *Class
9636 QualType Ty = getObjCObjectPointerType(CT);
9637 if (Ty->isObjCIdType()) {
9638 S += "{objc_object=}";
9639 return;
9640 }
9641 else if (Ty->isObjCClassType()) {
9642 S += "{objc_class=}";
9643 return;
9644 }
9645 // TODO: Double check to make sure this intentionally falls through.
9646 [[fallthrough]];
9647 }
9648
9649 case Type::ObjCInterface: {
9650 // Ignore protocol qualifiers when mangling at this level.
9651 // @encode(class_name)
9652 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
9653 S += '{';
9654 S += OI->getObjCRuntimeNameAsString();
9655 if (Options.ExpandStructures()) {
9656 S += '=';
9657 SmallVector<const ObjCIvarDecl*, 32> Ivars;
9658 DeepCollectObjCIvars(OI, true, Ivars);
9659 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
9660 const FieldDecl *Field = Ivars[i];
9661 if (Field->isBitField())
9662 getObjCEncodingForTypeImpl(Field->getType(), S,
9663 ObjCEncOptions().setExpandStructures(),
9664 Field);
9665 else
9666 getObjCEncodingForTypeImpl(Field->getType(), S,
9667 ObjCEncOptions().setExpandStructures(), FD,
9668 NotEncodedT);
9669 }
9670 }
9671 S += '}';
9672 return;
9673 }
9674
9675 case Type::ObjCObjectPointer: {
9676 const auto *OPT = T->castAs<ObjCObjectPointerType>();
9677 if (OPT->isObjCIdType()) {
9678 S += '@';
9679 return;
9680 }
9681
9682 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
9683 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
9684 // Since this is a binary compatibility issue, need to consult with
9685 // runtime folks. Fortunately, this is a *very* obscure construct.
9686 S += '#';
9687 return;
9688 }
9689
9690 if (OPT->isObjCQualifiedIdType()) {
9691 getObjCEncodingForTypeImpl(
9692 getObjCIdType(), S,
9693 Options.keepingOnly(ObjCEncOptions()
9694 .setExpandPointedToStructures()
9695 .setExpandStructures()),
9696 FD);
9697 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
9698 // Note that we do extended encoding of protocol qualifier list
9699 // Only when doing ivar or property encoding.
9700 S += '"';
9701 for (const auto *I : OPT->quals()) {
9702 S += '<';
9703 S += I->getObjCRuntimeNameAsString();
9704 S += '>';
9705 }
9706 S += '"';
9707 }
9708 return;
9709 }
9710
9711 S += '@';
9712 if (OPT->getInterfaceDecl() &&
9713 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
9714 S += '"';
9715 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
9716 for (const auto *I : OPT->quals()) {
9717 S += '<';
9718 S += I->getObjCRuntimeNameAsString();
9719 S += '>';
9720 }
9721 S += '"';
9722 }
9723 return;
9724 }
9725
9726 // gcc just blithely ignores member pointers.
9727 // FIXME: we should do better than that. 'M' is available.
9728 case Type::MemberPointer:
9729 // This matches gcc's encoding, even though technically it is insufficient.
9730 //FIXME. We should do a better job than gcc.
9731 case Type::Vector:
9732 case Type::ExtVector:
9733 // Until we have a coherent encoding of these three types, issue warning.
9734 if (NotEncodedT)
9735 *NotEncodedT = T;
9736 return;
9737
9738 case Type::ConstantMatrix:
9739 if (NotEncodedT)
9740 *NotEncodedT = T;
9741 return;
9742
9743 case Type::BitInt:
9744 if (NotEncodedT)
9745 *NotEncodedT = T;
9746 return;
9747
9748 // We could see an undeduced auto type here during error recovery.
9749 // Just ignore it.
9750 case Type::Auto:
9751 case Type::DeducedTemplateSpecialization:
9752 return;
9753
9754 case Type::HLSLAttributedResource:
9755 case Type::HLSLInlineSpirv:
9756 case Type::OverflowBehavior:
9757 llvm_unreachable("unexpected type");
9758
9759 case Type::ArrayParameter:
9760 case Type::Pipe:
9761#define ABSTRACT_TYPE(KIND, BASE)
9762#define TYPE(KIND, BASE)
9763#define DEPENDENT_TYPE(KIND, BASE) \
9764 case Type::KIND:
9765#define NON_CANONICAL_TYPE(KIND, BASE) \
9766 case Type::KIND:
9767#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
9768 case Type::KIND:
9769#include "clang/AST/TypeNodes.inc"
9770 llvm_unreachable("@encode for dependent type!");
9771 }
9772 llvm_unreachable("bad type kind!");
9773}
9774
9775void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
9776 std::string &S,
9777 const FieldDecl *FD,
9778 bool includeVBases,
9779 QualType *NotEncodedT) const {
9780 assert(RDecl && "Expected non-null RecordDecl");
9781 assert(!RDecl->isUnion() && "Should not be called for unions");
9782 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
9783 return;
9784
9785 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
9786 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
9787 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
9788
9789 if (CXXRec) {
9790 for (const auto &BI : CXXRec->bases()) {
9791 if (!BI.isVirtual()) {
9792 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9793 if (base->isEmpty())
9794 continue;
9795 uint64_t offs = toBits(layout.getBaseClassOffset(base));
9796 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9797 std::make_pair(offs, base));
9798 }
9799 }
9800 }
9801
9802 for (FieldDecl *Field : RDecl->fields()) {
9803 if (!Field->isZeroLengthBitField() && Field->isZeroSize(*this))
9804 continue;
9805 uint64_t offs = layout.getFieldOffset(Field->getFieldIndex());
9806 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9807 std::make_pair(offs, Field));
9808 }
9809
9810 if (CXXRec && includeVBases) {
9811 for (const auto &BI : CXXRec->vbases()) {
9812 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9813 if (base->isEmpty())
9814 continue;
9815 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
9816 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
9817 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
9818 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
9819 std::make_pair(offs, base));
9820 }
9821 }
9822
9823 CharUnits size;
9824 if (CXXRec) {
9825 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
9826 } else {
9827 size = layout.getSize();
9828 }
9829
9830#ifndef NDEBUG
9831 uint64_t CurOffs = 0;
9832#endif
9833 std::multimap<uint64_t, NamedDecl *>::iterator
9834 CurLayObj = FieldOrBaseOffsets.begin();
9835
9836 if (CXXRec && CXXRec->isDynamicClass() &&
9837 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
9838 if (FD) {
9839 S += "\"_vptr$";
9840 std::string recname = CXXRec->getNameAsString();
9841 if (recname.empty()) recname = "?";
9842 S += recname;
9843 S += '"';
9844 }
9845 S += "^^?";
9846#ifndef NDEBUG
9847 CurOffs += getTypeSize(VoidPtrTy);
9848#endif
9849 }
9850
9851 if (!RDecl->hasFlexibleArrayMember()) {
9852 // Mark the end of the structure.
9853 uint64_t offs = toBits(size);
9854 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9855 std::make_pair(offs, nullptr));
9856 }
9857
9858 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
9859#ifndef NDEBUG
9860 assert(CurOffs <= CurLayObj->first);
9861 if (CurOffs < CurLayObj->first) {
9862 uint64_t padding = CurLayObj->first - CurOffs;
9863 // FIXME: There doesn't seem to be a way to indicate in the encoding that
9864 // packing/alignment of members is different that normal, in which case
9865 // the encoding will be out-of-sync with the real layout.
9866 // If the runtime switches to just consider the size of types without
9867 // taking into account alignment, we could make padding explicit in the
9868 // encoding (e.g. using arrays of chars). The encoding strings would be
9869 // longer then though.
9870 CurOffs += padding;
9871 }
9872#endif
9873
9874 NamedDecl *dcl = CurLayObj->second;
9875 if (!dcl)
9876 break; // reached end of structure.
9877
9878 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
9879 // We expand the bases without their virtual bases since those are going
9880 // in the initial structure. Note that this differs from gcc which
9881 // expands virtual bases each time one is encountered in the hierarchy,
9882 // making the encoding type bigger than it really is.
9883 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
9884 NotEncodedT);
9885 assert(!base->isEmpty());
9886#ifndef NDEBUG
9887 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
9888#endif
9889 } else {
9890 const auto *field = cast<FieldDecl>(dcl);
9891 if (FD) {
9892 S += '"';
9893 S += field->getNameAsString();
9894 S += '"';
9895 }
9896
9897 if (field->isBitField()) {
9898 EncodeBitField(this, S, field->getType(), field);
9899#ifndef NDEBUG
9900 CurOffs += field->getBitWidthValue();
9901#endif
9902 } else {
9903 QualType qt = field->getType();
9905 getObjCEncodingForTypeImpl(
9906 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
9907 FD, NotEncodedT);
9908#ifndef NDEBUG
9909 CurOffs += getTypeSize(field->getType());
9910#endif
9911 }
9912 }
9913 }
9914}
9915
9917 std::string& S) const {
9918 if (QT & Decl::OBJC_TQ_In)
9919 S += 'n';
9920 if (QT & Decl::OBJC_TQ_Inout)
9921 S += 'N';
9922 if (QT & Decl::OBJC_TQ_Out)
9923 S += 'o';
9924 if (QT & Decl::OBJC_TQ_Bycopy)
9925 S += 'O';
9926 if (QT & Decl::OBJC_TQ_Byref)
9927 S += 'R';
9928 if (QT & Decl::OBJC_TQ_Oneway)
9929 S += 'V';
9930}
9931
9933 if (!ObjCIdDecl) {
9936 ObjCIdDecl = buildImplicitTypedef(T, "id");
9937 }
9938 return ObjCIdDecl;
9939}
9940
9942 if (!ObjCSelDecl) {
9944 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
9945 }
9946 return ObjCSelDecl;
9947}
9948
9950 if (!ObjCClassDecl) {
9953 ObjCClassDecl = buildImplicitTypedef(T, "Class");
9954 }
9955 return ObjCClassDecl;
9956}
9957
9959 if (!ObjCProtocolClassDecl) {
9960 ObjCProtocolClassDecl
9963 &Idents.get("Protocol"),
9964 /*typeParamList=*/nullptr,
9965 /*PrevDecl=*/nullptr,
9966 SourceLocation(), true);
9967 }
9968
9969 return ObjCProtocolClassDecl;
9970}
9971
9973 if (!getLangOpts().PointerAuthObjcInterfaceSel)
9974 return PointerAuthQualifier();
9976 getLangOpts().PointerAuthObjcInterfaceSelKey,
9977 /*isAddressDiscriminated=*/true, SelPointerConstantDiscriminator,
9979 /*isIsaPointer=*/false,
9980 /*authenticatesNullValues=*/false);
9981}
9982
9983//===----------------------------------------------------------------------===//
9984// __builtin_va_list Construction Functions
9985//===----------------------------------------------------------------------===//
9986
9988 StringRef Name) {
9989 // typedef char* __builtin[_ms]_va_list;
9990 QualType T = Context->getPointerType(Context->CharTy);
9991 return Context->buildImplicitTypedef(T, Name);
9992}
9993
9995 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
9996}
9997
9999 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
10000}
10001
10003 // typedef void* __builtin_va_list;
10004 QualType T = Context->getPointerType(Context->VoidTy);
10005 return Context->buildImplicitTypedef(T, "__builtin_va_list");
10006}
10007
10008static TypedefDecl *
10010 // struct __va_list
10011 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
10012 if (Context->getLangOpts().CPlusPlus) {
10013 // namespace std { struct __va_list {
10014 auto *NS = NamespaceDecl::Create(
10015 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
10016 /*Inline=*/false, SourceLocation(), SourceLocation(),
10017 &Context->Idents.get("std"),
10018 /*PrevDecl=*/nullptr, /*Nested=*/false);
10019 NS->setImplicit();
10021 }
10022
10023 VaListTagDecl->startDefinition();
10024
10025 const size_t NumFields = 5;
10026 QualType FieldTypes[NumFields];
10027 const char *FieldNames[NumFields];
10028
10029 // void *__stack;
10030 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
10031 FieldNames[0] = "__stack";
10032
10033 // void *__gr_top;
10034 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
10035 FieldNames[1] = "__gr_top";
10036
10037 // void *__vr_top;
10038 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10039 FieldNames[2] = "__vr_top";
10040
10041 // int __gr_offs;
10042 FieldTypes[3] = Context->IntTy;
10043 FieldNames[3] = "__gr_offs";
10044
10045 // int __vr_offs;
10046 FieldTypes[4] = Context->IntTy;
10047 FieldNames[4] = "__vr_offs";
10048
10049 // Create fields
10050 for (unsigned i = 0; i < NumFields; ++i) {
10051 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10055 &Context->Idents.get(FieldNames[i]),
10056 FieldTypes[i], /*TInfo=*/nullptr,
10057 /*BitWidth=*/nullptr,
10058 /*Mutable=*/false,
10059 ICIS_NoInit);
10060 Field->setAccess(AS_public);
10061 VaListTagDecl->addDecl(Field);
10062 }
10063 VaListTagDecl->completeDefinition();
10064 Context->VaListTagDecl = VaListTagDecl;
10065 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10066
10067 // } __builtin_va_list;
10068 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10069}
10070
10072 // typedef struct __va_list_tag {
10074
10075 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10076 VaListTagDecl->startDefinition();
10077
10078 const size_t NumFields = 5;
10079 QualType FieldTypes[NumFields];
10080 const char *FieldNames[NumFields];
10081
10082 // unsigned char gpr;
10083 FieldTypes[0] = Context->UnsignedCharTy;
10084 FieldNames[0] = "gpr";
10085
10086 // unsigned char fpr;
10087 FieldTypes[1] = Context->UnsignedCharTy;
10088 FieldNames[1] = "fpr";
10089
10090 // unsigned short reserved;
10091 FieldTypes[2] = Context->UnsignedShortTy;
10092 FieldNames[2] = "reserved";
10093
10094 // void* overflow_arg_area;
10095 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10096 FieldNames[3] = "overflow_arg_area";
10097
10098 // void* reg_save_area;
10099 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
10100 FieldNames[4] = "reg_save_area";
10101
10102 // Create fields
10103 for (unsigned i = 0; i < NumFields; ++i) {
10104 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
10107 &Context->Idents.get(FieldNames[i]),
10108 FieldTypes[i], /*TInfo=*/nullptr,
10109 /*BitWidth=*/nullptr,
10110 /*Mutable=*/false,
10111 ICIS_NoInit);
10112 Field->setAccess(AS_public);
10113 VaListTagDecl->addDecl(Field);
10114 }
10115 VaListTagDecl->completeDefinition();
10116 Context->VaListTagDecl = VaListTagDecl;
10117 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10118
10119 // } __va_list_tag;
10120 TypedefDecl *VaListTagTypedefDecl =
10121 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10122
10123 QualType VaListTagTypedefType =
10124 Context->getTypedefType(ElaboratedTypeKeyword::None,
10125 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10126
10127 // typedef __va_list_tag __builtin_va_list[1];
10128 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10129 QualType VaListTagArrayType = Context->getConstantArrayType(
10130 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10131 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10132}
10133
10134static TypedefDecl *
10136 // struct __va_list_tag {
10138 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10139 VaListTagDecl->startDefinition();
10140
10141 const size_t NumFields = 4;
10142 QualType FieldTypes[NumFields];
10143 const char *FieldNames[NumFields];
10144
10145 // unsigned gp_offset;
10146 FieldTypes[0] = Context->UnsignedIntTy;
10147 FieldNames[0] = "gp_offset";
10148
10149 // unsigned fp_offset;
10150 FieldTypes[1] = Context->UnsignedIntTy;
10151 FieldNames[1] = "fp_offset";
10152
10153 // void* overflow_arg_area;
10154 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10155 FieldNames[2] = "overflow_arg_area";
10156
10157 // void* reg_save_area;
10158 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10159 FieldNames[3] = "reg_save_area";
10160
10161 // Create fields
10162 for (unsigned i = 0; i < NumFields; ++i) {
10163 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10167 &Context->Idents.get(FieldNames[i]),
10168 FieldTypes[i], /*TInfo=*/nullptr,
10169 /*BitWidth=*/nullptr,
10170 /*Mutable=*/false,
10171 ICIS_NoInit);
10172 Field->setAccess(AS_public);
10173 VaListTagDecl->addDecl(Field);
10174 }
10175 VaListTagDecl->completeDefinition();
10176 Context->VaListTagDecl = VaListTagDecl;
10177 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10178
10179 // };
10180
10181 // typedef struct __va_list_tag __builtin_va_list[1];
10182 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10183 QualType VaListTagArrayType = Context->getConstantArrayType(
10184 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10185 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10186}
10187
10188static TypedefDecl *
10190 // struct __va_list
10191 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
10192 if (Context->getLangOpts().CPlusPlus) {
10193 // namespace std { struct __va_list {
10194 NamespaceDecl *NS;
10195 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
10196 Context->getTranslationUnitDecl(),
10197 /*Inline=*/false, SourceLocation(),
10198 SourceLocation(), &Context->Idents.get("std"),
10199 /*PrevDecl=*/nullptr, /*Nested=*/false);
10200 NS->setImplicit();
10201 VaListDecl->setDeclContext(NS);
10202 }
10203
10204 VaListDecl->startDefinition();
10205
10206 // void * __ap;
10207 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10208 VaListDecl,
10211 &Context->Idents.get("__ap"),
10212 Context->getPointerType(Context->VoidTy),
10213 /*TInfo=*/nullptr,
10214 /*BitWidth=*/nullptr,
10215 /*Mutable=*/false,
10216 ICIS_NoInit);
10217 Field->setAccess(AS_public);
10218 VaListDecl->addDecl(Field);
10219
10220 // };
10221 VaListDecl->completeDefinition();
10222 Context->VaListTagDecl = VaListDecl;
10223
10224 // typedef struct __va_list __builtin_va_list;
10225 CanQualType T = Context->getCanonicalTagType(VaListDecl);
10226 return Context->buildImplicitTypedef(T, "__builtin_va_list");
10227}
10228
10229static TypedefDecl *
10231 // struct __va_list_tag {
10233 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10234 VaListTagDecl->startDefinition();
10235
10236 const size_t NumFields = 4;
10237 QualType FieldTypes[NumFields];
10238 const char *FieldNames[NumFields];
10239
10240 // long __gpr;
10241 FieldTypes[0] = Context->LongTy;
10242 FieldNames[0] = "__gpr";
10243
10244 // long __fpr;
10245 FieldTypes[1] = Context->LongTy;
10246 FieldNames[1] = "__fpr";
10247
10248 // void *__overflow_arg_area;
10249 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10250 FieldNames[2] = "__overflow_arg_area";
10251
10252 // void *__reg_save_area;
10253 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10254 FieldNames[3] = "__reg_save_area";
10255
10256 // Create fields
10257 for (unsigned i = 0; i < NumFields; ++i) {
10258 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10262 &Context->Idents.get(FieldNames[i]),
10263 FieldTypes[i], /*TInfo=*/nullptr,
10264 /*BitWidth=*/nullptr,
10265 /*Mutable=*/false,
10266 ICIS_NoInit);
10267 Field->setAccess(AS_public);
10268 VaListTagDecl->addDecl(Field);
10269 }
10270 VaListTagDecl->completeDefinition();
10271 Context->VaListTagDecl = VaListTagDecl;
10272 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10273
10274 // };
10275
10276 // typedef __va_list_tag __builtin_va_list[1];
10277 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10278 QualType VaListTagArrayType = Context->getConstantArrayType(
10279 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10280
10281 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10282}
10283
10285 // typedef struct __va_list_tag {
10287 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10288 VaListTagDecl->startDefinition();
10289
10290 const size_t NumFields = 3;
10291 QualType FieldTypes[NumFields];
10292 const char *FieldNames[NumFields];
10293
10294 // void *CurrentSavedRegisterArea;
10295 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
10296 FieldNames[0] = "__current_saved_reg_area_pointer";
10297
10298 // void *SavedRegAreaEnd;
10299 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
10300 FieldNames[1] = "__saved_reg_area_end_pointer";
10301
10302 // void *OverflowArea;
10303 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10304 FieldNames[2] = "__overflow_area_pointer";
10305
10306 // Create fields
10307 for (unsigned i = 0; i < NumFields; ++i) {
10309 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
10310 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
10311 /*TInfo=*/nullptr,
10312 /*BitWidth=*/nullptr,
10313 /*Mutable=*/false, ICIS_NoInit);
10314 Field->setAccess(AS_public);
10315 VaListTagDecl->addDecl(Field);
10316 }
10317 VaListTagDecl->completeDefinition();
10318 Context->VaListTagDecl = VaListTagDecl;
10319 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10320
10321 // } __va_list_tag;
10322 TypedefDecl *VaListTagTypedefDecl =
10323 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10324
10325 QualType VaListTagTypedefType =
10326 Context->getTypedefType(ElaboratedTypeKeyword::None,
10327 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10328
10329 // typedef __va_list_tag __builtin_va_list[1];
10330 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10331 QualType VaListTagArrayType = Context->getConstantArrayType(
10332 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10333
10334 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10335}
10336
10337static TypedefDecl *
10339 // typedef struct __va_list_tag {
10340 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10341
10342 VaListTagDecl->startDefinition();
10343
10344 // int* __va_stk;
10345 // int* __va_reg;
10346 // int __va_ndx;
10347 constexpr size_t NumFields = 3;
10348 QualType FieldTypes[NumFields] = {Context->getPointerType(Context->IntTy),
10349 Context->getPointerType(Context->IntTy),
10350 Context->IntTy};
10351 const char *FieldNames[NumFields] = {"__va_stk", "__va_reg", "__va_ndx"};
10352
10353 // Create fields
10354 for (unsigned i = 0; i < NumFields; ++i) {
10357 &Context->Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
10358 /*BitWidth=*/nullptr,
10359 /*Mutable=*/false, ICIS_NoInit);
10360 Field->setAccess(AS_public);
10361 VaListTagDecl->addDecl(Field);
10362 }
10363 VaListTagDecl->completeDefinition();
10364 Context->VaListTagDecl = VaListTagDecl;
10365 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10366
10367 // } __va_list_tag;
10368 TypedefDecl *VaListTagTypedefDecl =
10369 Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10370
10371 return VaListTagTypedefDecl;
10372}
10373
10376 switch (Kind) {
10378 return CreateCharPtrBuiltinVaListDecl(Context);
10380 return CreateVoidPtrBuiltinVaListDecl(Context);
10382 return CreateAArch64ABIBuiltinVaListDecl(Context);
10384 return CreatePowerABIBuiltinVaListDecl(Context);
10386 return CreateX86_64ABIBuiltinVaListDecl(Context);
10388 return CreateAAPCSABIBuiltinVaListDecl(Context);
10390 return CreateSystemZBuiltinVaListDecl(Context);
10392 return CreateHexagonBuiltinVaListDecl(Context);
10394 return CreateXtensaABIBuiltinVaListDecl(Context);
10395 }
10396
10397 llvm_unreachable("Unhandled __builtin_va_list type kind");
10398}
10399
10401 if (!BuiltinVaListDecl) {
10402 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
10403 assert(BuiltinVaListDecl->isImplicit());
10404 }
10405
10406 return BuiltinVaListDecl;
10407}
10408
10410 // Force the creation of VaListTagDecl by building the __builtin_va_list
10411 // declaration.
10412 if (!VaListTagDecl)
10413 (void)getBuiltinVaListDecl();
10414
10415 return VaListTagDecl;
10416}
10417
10419 if (!BuiltinMSVaListDecl)
10420 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
10421
10422 return BuiltinMSVaListDecl;
10423}
10424
10426 // Allow redecl custom type checking builtin for HLSL.
10427 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
10428 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10429 return true;
10430 // Allow redecl custom type checking builtin for SPIR-V.
10431 if (getTargetInfo().getTriple().isSPIROrSPIRV() &&
10432 BuiltinInfo.isTSBuiltin(FD->getBuiltinID()) &&
10433 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10434 return true;
10435 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
10436}
10437
10439 assert(ObjCConstantStringType.isNull() &&
10440 "'NSConstantString' type already set!");
10441
10442 ObjCConstantStringType = getObjCInterfaceType(Decl);
10443}
10444
10445/// Retrieve the template name that corresponds to a non-empty
10446/// lookup.
10449 UnresolvedSetIterator End) const {
10450 unsigned size = End - Begin;
10451 assert(size > 1 && "set is not overloaded!");
10452
10453 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
10454 size * sizeof(FunctionTemplateDecl*));
10455 auto *OT = new (memory) OverloadedTemplateStorage(size);
10456
10457 NamedDecl **Storage = OT->getStorage();
10458 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
10459 NamedDecl *D = *I;
10460 assert(isa<FunctionTemplateDecl>(D) ||
10464 *Storage++ = D;
10465 }
10466
10467 return TemplateName(OT);
10468}
10469
10470/// Retrieve a template name representing an unqualified-id that has been
10471/// assumed to name a template for ADL purposes.
10473 auto *OT = new (*this) AssumedTemplateStorage(Name);
10474 return TemplateName(OT);
10475}
10476
10477/// Retrieve the template name that represents a qualified
10478/// template name such as \c std::vector.
10480 bool TemplateKeyword,
10481 TemplateName Template) const {
10482 assert(Template.getKind() == TemplateName::Template ||
10484
10485 if (Template.getAsTemplateDecl()->getKind() == Decl::TemplateTemplateParm) {
10486 assert(!Qualifier && "unexpected qualified template template parameter");
10487 assert(TemplateKeyword == false);
10488 return Template;
10489 }
10490
10491 // FIXME: Canonicalization?
10492 llvm::FoldingSetNodeID ID;
10493 QualifiedTemplateName::Profile(ID, Qualifier, TemplateKeyword, Template);
10494
10495 void *InsertPos = nullptr;
10497 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
10498 if (!QTN) {
10499 QTN = new (*this, alignof(QualifiedTemplateName))
10500 QualifiedTemplateName(Qualifier, TemplateKeyword, Template);
10501 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
10502 }
10503
10504 return TemplateName(QTN);
10505}
10506
10507/// Retrieve the template name that represents a dependent
10508/// template name such as \c MetaFun::template operator+.
10511 llvm::FoldingSetNodeID ID;
10512 S.Profile(ID);
10513
10514 void *InsertPos = nullptr;
10515 if (DependentTemplateName *QTN =
10516 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos))
10517 return TemplateName(QTN);
10518
10520 new (*this, alignof(DependentTemplateName)) DependentTemplateName(S);
10521 DependentTemplateNames.InsertNode(QTN, InsertPos);
10522 return TemplateName(QTN);
10523}
10524
10526 Decl *AssociatedDecl,
10527 unsigned Index,
10528 UnsignedOrNone PackIndex,
10529 bool Final) const {
10530 llvm::FoldingSetNodeID ID;
10531 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
10532 Index, PackIndex, Final);
10533
10534 void *insertPos = nullptr;
10536 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
10537
10538 if (!subst) {
10539 subst = new (*this) SubstTemplateTemplateParmStorage(
10540 Replacement, AssociatedDecl, Index, PackIndex, Final);
10541 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
10542 }
10543
10544 return TemplateName(subst);
10545}
10546
10549 Decl *AssociatedDecl,
10550 unsigned Index, bool Final) const {
10551 auto &Self = const_cast<ASTContext &>(*this);
10552 llvm::FoldingSetNodeID ID;
10554 AssociatedDecl, Index, Final);
10555
10556 void *InsertPos = nullptr;
10558 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
10559
10560 if (!Subst) {
10561 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
10562 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
10563 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
10564 }
10565
10566 return TemplateName(Subst);
10567}
10568
10569/// Retrieve the template name that represents a template name
10570/// deduced from a specialization.
10573 DefaultArguments DefaultArgs) const {
10574 if (!DefaultArgs)
10575 return Underlying;
10576
10577 llvm::FoldingSetNodeID ID;
10578 DeducedTemplateStorage::Profile(ID, *this, Underlying, DefaultArgs);
10579
10580 void *InsertPos = nullptr;
10582 DeducedTemplates.FindNodeOrInsertPos(ID, InsertPos);
10583 if (!DTS) {
10584 void *Mem = Allocate(sizeof(DeducedTemplateStorage) +
10585 sizeof(TemplateArgument) * DefaultArgs.Args.size(),
10586 alignof(DeducedTemplateStorage));
10587 DTS = new (Mem) DeducedTemplateStorage(Underlying, DefaultArgs);
10588 DeducedTemplates.InsertNode(DTS, InsertPos);
10589 }
10590 return TemplateName(DTS);
10591}
10592
10593/// getFromTargetType - Given one of the integer types provided by
10594/// TargetInfo, produce the corresponding type. The unsigned @p Type
10595/// is actually a value of type @c TargetInfo::IntType.
10596CanQualType ASTContext::getFromTargetType(unsigned Type) const {
10597 switch (Type) {
10598 case TargetInfo::NoInt: return {};
10601 case TargetInfo::SignedShort: return ShortTy;
10603 case TargetInfo::SignedInt: return IntTy;
10605 case TargetInfo::SignedLong: return LongTy;
10609 }
10610
10611 llvm_unreachable("Unhandled TargetInfo::IntType value");
10612}
10613
10614//===----------------------------------------------------------------------===//
10615// Type Predicates.
10616//===----------------------------------------------------------------------===//
10617
10618/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
10619/// garbage collection attribute.
10620///
10622 if (getLangOpts().getGC() == LangOptions::NonGC)
10623 return Qualifiers::GCNone;
10624
10625 assert(getLangOpts().ObjC);
10626 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
10627
10628 // Default behaviour under objective-C's gc is for ObjC pointers
10629 // (or pointers to them) be treated as though they were declared
10630 // as __strong.
10631 if (GCAttrs == Qualifiers::GCNone) {
10633 return Qualifiers::Strong;
10634 else if (Ty->isPointerType())
10636 } else {
10637 // It's not valid to set GC attributes on anything that isn't a
10638 // pointer.
10639#ifndef NDEBUG
10641 while (const auto *AT = dyn_cast<ArrayType>(CT))
10642 CT = AT->getElementType();
10643 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
10644#endif
10645 }
10646 return GCAttrs;
10647}
10648
10649//===----------------------------------------------------------------------===//
10650// Type Compatibility Testing
10651//===----------------------------------------------------------------------===//
10652
10653/// areCompatVectorTypes - Return true if the two specified vector types are
10654/// compatible.
10655static bool areCompatVectorTypes(const VectorType *LHS,
10656 const VectorType *RHS) {
10657 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10658 return LHS->getElementType() == RHS->getElementType() &&
10659 LHS->getNumElements() == RHS->getNumElements();
10660}
10661
10662/// areCompatMatrixTypes - Return true if the two specified matrix types are
10663/// compatible.
10665 const ConstantMatrixType *RHS) {
10666 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10667 return LHS->getElementType() == RHS->getElementType() &&
10668 LHS->getNumRows() == RHS->getNumRows() &&
10669 LHS->getNumColumns() == RHS->getNumColumns();
10670}
10671
10673 QualType SecondVec) {
10674 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
10675 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
10676
10677 if (hasSameUnqualifiedType(FirstVec, SecondVec))
10678 return true;
10679
10680 // Treat Neon vector types and most AltiVec vector types as if they are the
10681 // equivalent GCC vector types.
10682 const auto *First = FirstVec->castAs<VectorType>();
10683 const auto *Second = SecondVec->castAs<VectorType>();
10684 if (First->getNumElements() == Second->getNumElements() &&
10685 hasSameType(First->getElementType(), Second->getElementType()) &&
10686 First->getVectorKind() != VectorKind::AltiVecPixel &&
10687 First->getVectorKind() != VectorKind::AltiVecBool &&
10690 First->getVectorKind() != VectorKind::SveFixedLengthData &&
10691 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10694 First->getVectorKind() != VectorKind::RVVFixedLengthData &&
10696 First->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10698 First->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10700 First->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10702 First->getVectorKind() != VectorKind::RVVFixedLengthMask_4 &&
10704 return true;
10705
10706 // In OpenCL, treat half and _Float16 vector types as compatible.
10707 if (getLangOpts().OpenCL &&
10708 First->getNumElements() == Second->getNumElements()) {
10709 QualType FirstElt = First->getElementType();
10710 QualType SecondElt = Second->getElementType();
10711
10712 if ((FirstElt->isFloat16Type() && SecondElt->isHalfType()) ||
10713 (FirstElt->isHalfType() && SecondElt->isFloat16Type())) {
10714 if (First->getVectorKind() != VectorKind::AltiVecPixel &&
10715 First->getVectorKind() != VectorKind::AltiVecBool &&
10718 return true;
10719 }
10720 }
10721 return false;
10722}
10723
10729
10732 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
10733 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
10734
10735 if (!LHSOBT && !RHSOBT)
10737
10738 if (LHSOBT && RHSOBT) {
10739 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
10742 }
10743
10744 QualType LHSUnderlying = LHSOBT ? LHSOBT->desugar() : LHS;
10745 QualType RHSUnderlying = RHSOBT ? RHSOBT->desugar() : RHS;
10746
10747 if (RHSOBT && !LHSOBT) {
10748 if (LHSUnderlying->isIntegerType() && RHSUnderlying->isIntegerType())
10750 }
10751
10753}
10754
10755/// getRVVTypeSize - Return RVV vector register size.
10756static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
10757 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
10758 auto VScale = Context.getTargetInfo().getVScaleRange(
10759 Context.getLangOpts(), TargetInfo::ArmStreamingKind::NotStreaming);
10760 if (!VScale)
10761 return 0;
10762
10763 ASTContext::BuiltinVectorTypeInfo Info = Context.getBuiltinVectorTypeInfo(Ty);
10764
10765 uint64_t EltSize = Context.getTypeSize(Info.ElementType);
10766 if (Info.ElementType == Context.BoolTy)
10767 EltSize = 1;
10768
10769 uint64_t MinElts = Info.EC.getKnownMinValue();
10770 return VScale->first * MinElts * EltSize;
10771}
10772
10774 QualType SecondType) {
10775 assert(
10776 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10777 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10778 "Expected RVV builtin type and vector type!");
10779
10780 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10781 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10782 if (const auto *VT = SecondType->getAs<VectorType>()) {
10783 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10785 return FirstType->isRVVVLSBuiltinType() &&
10786 Info.ElementType == BoolTy &&
10787 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)));
10788 }
10789 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1) {
10791 return FirstType->isRVVVLSBuiltinType() &&
10792 Info.ElementType == BoolTy &&
10793 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT) * 8));
10794 }
10795 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2) {
10797 return FirstType->isRVVVLSBuiltinType() &&
10798 Info.ElementType == BoolTy &&
10799 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 4);
10800 }
10801 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10803 return FirstType->isRVVVLSBuiltinType() &&
10804 Info.ElementType == BoolTy &&
10805 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 2);
10806 }
10807 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
10808 VT->getVectorKind() == VectorKind::Generic)
10809 return FirstType->isRVVVLSBuiltinType() &&
10810 getTypeSize(SecondType) == getRVVTypeSize(*this, BT) &&
10811 hasSameType(VT->getElementType(),
10812 getBuiltinVectorTypeInfo(BT).ElementType);
10813 }
10814 }
10815 return false;
10816 };
10817
10818 return IsValidCast(FirstType, SecondType) ||
10819 IsValidCast(SecondType, FirstType);
10820}
10821
10823 QualType SecondType) {
10824 assert(
10825 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10826 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10827 "Expected RVV builtin type and vector type!");
10828
10829 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10830 const auto *BT = FirstType->getAs<BuiltinType>();
10831 if (!BT)
10832 return false;
10833
10834 if (!BT->isRVVVLSBuiltinType())
10835 return false;
10836
10837 const auto *VecTy = SecondType->getAs<VectorType>();
10838 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
10840 getLangOpts().getLaxVectorConversions();
10841
10842 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
10843 if (getTypeSize(SecondType) != getRVVTypeSize(*this, BT))
10844 return false;
10845
10846 // If -flax-vector-conversions=all is specified, the types are
10847 // certainly compatible.
10849 return true;
10850
10851 // If -flax-vector-conversions=integer is specified, the types are
10852 // compatible if the elements are integer types.
10854 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10855 FirstType->getRVVEltType(*this)->isIntegerType();
10856 }
10857
10858 return false;
10859 };
10860
10861 return IsLaxCompatible(FirstType, SecondType) ||
10862 IsLaxCompatible(SecondType, FirstType);
10863}
10864
10866 while (true) {
10867 // __strong id
10868 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
10869 if (Attr->getAttrKind() == attr::ObjCOwnership)
10870 return true;
10871
10872 Ty = Attr->getModifiedType();
10873
10874 // X *__strong (...)
10875 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
10876 Ty = Paren->getInnerType();
10877
10878 // We do not want to look through typedefs, typeof(expr),
10879 // typeof(type), or any other way that the type is somehow
10880 // abstracted.
10881 } else {
10882 return false;
10883 }
10884 }
10885}
10886
10887//===----------------------------------------------------------------------===//
10888// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
10889//===----------------------------------------------------------------------===//
10890
10891/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
10892/// inheritance hierarchy of 'rProto'.
10893bool
10895 ObjCProtocolDecl *rProto) const {
10896 if (declaresSameEntity(lProto, rProto))
10897 return true;
10898 for (auto *PI : rProto->protocols())
10899 if (ProtocolCompatibleWithProtocol(lProto, PI))
10900 return true;
10901 return false;
10902}
10903
10904/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
10905/// Class<pr1, ...>.
10907 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
10908 for (auto *lhsProto : lhs->quals()) {
10909 bool match = false;
10910 for (auto *rhsProto : rhs->quals()) {
10911 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
10912 match = true;
10913 break;
10914 }
10915 }
10916 if (!match)
10917 return false;
10918 }
10919 return true;
10920}
10921
10922/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
10923/// ObjCQualifiedIDType.
10925 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
10926 bool compare) {
10927 // Allow id<P..> and an 'id' in all cases.
10928 if (lhs->isObjCIdType() || rhs->isObjCIdType())
10929 return true;
10930
10931 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
10932 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
10934 return false;
10935
10936 if (lhs->isObjCQualifiedIdType()) {
10937 if (rhs->qual_empty()) {
10938 // If the RHS is a unqualified interface pointer "NSString*",
10939 // make sure we check the class hierarchy.
10940 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10941 for (auto *I : lhs->quals()) {
10942 // when comparing an id<P> on lhs with a static type on rhs,
10943 // see if static class implements all of id's protocols, directly or
10944 // through its super class and categories.
10945 if (!rhsID->ClassImplementsProtocol(I, true))
10946 return false;
10947 }
10948 }
10949 // If there are no qualifiers and no interface, we have an 'id'.
10950 return true;
10951 }
10952 // Both the right and left sides have qualifiers.
10953 for (auto *lhsProto : lhs->quals()) {
10954 bool match = false;
10955
10956 // when comparing an id<P> on lhs with a static type on rhs,
10957 // see if static class implements all of id's protocols, directly or
10958 // through its super class and categories.
10959 for (auto *rhsProto : rhs->quals()) {
10960 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10961 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10962 match = true;
10963 break;
10964 }
10965 }
10966 // If the RHS is a qualified interface pointer "NSString<P>*",
10967 // make sure we check the class hierarchy.
10968 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10969 for (auto *I : lhs->quals()) {
10970 // when comparing an id<P> on lhs with a static type on rhs,
10971 // see if static class implements all of id's protocols, directly or
10972 // through its super class and categories.
10973 if (rhsID->ClassImplementsProtocol(I, true)) {
10974 match = true;
10975 break;
10976 }
10977 }
10978 }
10979 if (!match)
10980 return false;
10981 }
10982
10983 return true;
10984 }
10985
10986 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
10987
10988 if (lhs->getInterfaceType()) {
10989 // If both the right and left sides have qualifiers.
10990 for (auto *lhsProto : lhs->quals()) {
10991 bool match = false;
10992
10993 // when comparing an id<P> on rhs with a static type on lhs,
10994 // see if static class implements all of id's protocols, directly or
10995 // through its super class and categories.
10996 // First, lhs protocols in the qualifier list must be found, direct
10997 // or indirect in rhs's qualifier list or it is a mismatch.
10998 for (auto *rhsProto : rhs->quals()) {
10999 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
11000 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
11001 match = true;
11002 break;
11003 }
11004 }
11005 if (!match)
11006 return false;
11007 }
11008
11009 // Static class's protocols, or its super class or category protocols
11010 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
11011 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
11012 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
11013 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
11014 // This is rather dubious but matches gcc's behavior. If lhs has
11015 // no type qualifier and its class has no static protocol(s)
11016 // assume that it is mismatch.
11017 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
11018 return false;
11019 for (auto *lhsProto : LHSInheritedProtocols) {
11020 bool match = false;
11021 for (auto *rhsProto : rhs->quals()) {
11022 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
11023 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
11024 match = true;
11025 break;
11026 }
11027 }
11028 if (!match)
11029 return false;
11030 }
11031 }
11032 return true;
11033 }
11034 return false;
11035}
11036
11037/// canAssignObjCInterfaces - Return true if the two interface types are
11038/// compatible for assignment from RHS to LHS. This handles validation of any
11039/// protocol qualifiers on the LHS or RHS.
11041 const ObjCObjectPointerType *RHSOPT) {
11042 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11043 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11044
11045 // If either type represents the built-in 'id' type, return true.
11046 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
11047 return true;
11048
11049 // Function object that propagates a successful result or handles
11050 // __kindof types.
11051 auto finish = [&](bool succeeded) -> bool {
11052 if (succeeded)
11053 return true;
11054
11055 if (!RHS->isKindOfType())
11056 return false;
11057
11058 // Strip off __kindof and protocol qualifiers, then check whether
11059 // we can assign the other way.
11061 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
11062 };
11063
11064 // Casts from or to id<P> are allowed when the other side has compatible
11065 // protocols.
11066 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
11067 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
11068 }
11069
11070 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
11071 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
11072 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
11073 }
11074
11075 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
11076 if (LHS->isObjCClass() && RHS->isObjCClass()) {
11077 return true;
11078 }
11079
11080 // If we have 2 user-defined types, fall into that path.
11081 if (LHS->getInterface() && RHS->getInterface()) {
11082 return finish(canAssignObjCInterfaces(LHS, RHS));
11083 }
11084
11085 return false;
11086}
11087
11088/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
11089/// for providing type-safety for objective-c pointers used to pass/return
11090/// arguments in block literals. When passed as arguments, passing 'A*' where
11091/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
11092/// not OK. For the return type, the opposite is not OK.
11094 const ObjCObjectPointerType *LHSOPT,
11095 const ObjCObjectPointerType *RHSOPT,
11096 bool BlockReturnType) {
11097
11098 // Function object that propagates a successful result or handles
11099 // __kindof types.
11100 auto finish = [&](bool succeeded) -> bool {
11101 if (succeeded)
11102 return true;
11103
11104 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
11105 if (!Expected->isKindOfType())
11106 return false;
11107
11108 // Strip off __kindof and protocol qualifiers, then check whether
11109 // we can assign the other way.
11111 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
11112 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
11113 BlockReturnType);
11114 };
11115
11116 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
11117 return true;
11118
11119 if (LHSOPT->isObjCBuiltinType()) {
11120 return finish(RHSOPT->isObjCBuiltinType() ||
11121 RHSOPT->isObjCQualifiedIdType());
11122 }
11123
11124 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
11125 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
11126 // Use for block parameters previous type checking for compatibility.
11127 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
11128 // Or corrected type checking as in non-compat mode.
11129 (!BlockReturnType &&
11130 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
11131 else
11133 (BlockReturnType ? LHSOPT : RHSOPT),
11134 (BlockReturnType ? RHSOPT : LHSOPT), false));
11135 }
11136
11137 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
11138 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
11139 if (LHS && RHS) { // We have 2 user-defined types.
11140 if (LHS != RHS) {
11141 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
11142 return finish(BlockReturnType);
11143 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
11144 return finish(!BlockReturnType);
11145 }
11146 else
11147 return true;
11148 }
11149 return false;
11150}
11151
11152/// Comparison routine for Objective-C protocols to be used with
11153/// llvm::array_pod_sort.
11155 ObjCProtocolDecl * const *rhs) {
11156 return (*lhs)->getName().compare((*rhs)->getName());
11157}
11158
11159/// getIntersectionOfProtocols - This routine finds the intersection of set
11160/// of protocols inherited from two distinct objective-c pointer objects with
11161/// the given common base.
11162/// It is used to build composite qualifier list of the composite type of
11163/// the conditional expression involving two objective-c pointer objects.
11164static
11166 const ObjCInterfaceDecl *CommonBase,
11167 const ObjCObjectPointerType *LHSOPT,
11168 const ObjCObjectPointerType *RHSOPT,
11169 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
11170
11171 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11172 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11173 assert(LHS->getInterface() && "LHS must have an interface base");
11174 assert(RHS->getInterface() && "RHS must have an interface base");
11175
11176 // Add all of the protocols for the LHS.
11178
11179 // Start with the protocol qualifiers.
11180 for (auto *proto : LHS->quals()) {
11181 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
11182 }
11183
11184 // Also add the protocols associated with the LHS interface.
11185 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
11186
11187 // Add all of the protocols for the RHS.
11189
11190 // Start with the protocol qualifiers.
11191 for (auto *proto : RHS->quals()) {
11192 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
11193 }
11194
11195 // Also add the protocols associated with the RHS interface.
11196 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
11197
11198 // Compute the intersection of the collected protocol sets.
11199 for (auto *proto : LHSProtocolSet) {
11200 if (RHSProtocolSet.count(proto))
11201 IntersectionSet.push_back(proto);
11202 }
11203
11204 // Compute the set of protocols that is implied by either the common type or
11205 // the protocols within the intersection.
11207 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
11208
11209 // Remove any implied protocols from the list of inherited protocols.
11210 if (!ImpliedProtocols.empty()) {
11211 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
11212 return ImpliedProtocols.contains(proto);
11213 });
11214 }
11215
11216 // Sort the remaining protocols by name.
11217 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
11219}
11220
11221/// Determine whether the first type is a subtype of the second.
11223 QualType rhs) {
11224 // Common case: two object pointers.
11225 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
11226 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
11227 if (lhsOPT && rhsOPT)
11228 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
11229
11230 // Two block pointers.
11231 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
11232 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
11233 if (lhsBlock && rhsBlock)
11234 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
11235
11236 // If either is an unqualified 'id' and the other is a block, it's
11237 // acceptable.
11238 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
11239 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
11240 return true;
11241
11242 return false;
11243}
11244
11245// Check that the given Objective-C type argument lists are equivalent.
11247 const ObjCInterfaceDecl *iface,
11248 ArrayRef<QualType> lhsArgs,
11249 ArrayRef<QualType> rhsArgs,
11250 bool stripKindOf) {
11251 if (lhsArgs.size() != rhsArgs.size())
11252 return false;
11253
11254 ObjCTypeParamList *typeParams = iface->getTypeParamList();
11255 if (!typeParams)
11256 return false;
11257
11258 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
11259 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
11260 continue;
11261
11262 switch (typeParams->begin()[i]->getVariance()) {
11264 if (!stripKindOf ||
11265 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
11266 rhsArgs[i].stripObjCKindOfType(ctx))) {
11267 return false;
11268 }
11269 break;
11270
11272 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
11273 return false;
11274 break;
11275
11277 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
11278 return false;
11279 break;
11280 }
11281 }
11282
11283 return true;
11284}
11285
11287 const ObjCObjectPointerType *Lptr,
11288 const ObjCObjectPointerType *Rptr) {
11289 const ObjCObjectType *LHS = Lptr->getObjectType();
11290 const ObjCObjectType *RHS = Rptr->getObjectType();
11291 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
11292 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
11293
11294 if (!LDecl || !RDecl)
11295 return {};
11296
11297 // When either LHS or RHS is a kindof type, we should return a kindof type.
11298 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
11299 // kindof(A).
11300 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
11301
11302 // Follow the left-hand side up the class hierarchy until we either hit a
11303 // root or find the RHS. Record the ancestors in case we don't find it.
11304 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
11305 LHSAncestors;
11306 while (true) {
11307 // Record this ancestor. We'll need this if the common type isn't in the
11308 // path from the LHS to the root.
11309 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
11310
11311 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
11312 // Get the type arguments.
11313 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
11314 bool anyChanges = false;
11315 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11316 // Both have type arguments, compare them.
11317 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11318 LHS->getTypeArgs(), RHS->getTypeArgs(),
11319 /*stripKindOf=*/true))
11320 return {};
11321 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11322 // If only one has type arguments, the result will not have type
11323 // arguments.
11324 LHSTypeArgs = {};
11325 anyChanges = true;
11326 }
11327
11328 // Compute the intersection of protocols.
11330 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
11331 Protocols);
11332 if (!Protocols.empty())
11333 anyChanges = true;
11334
11335 // If anything in the LHS will have changed, build a new result type.
11336 // If we need to return a kindof type but LHS is not a kindof type, we
11337 // build a new result type.
11338 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
11339 QualType Result = getObjCInterfaceType(LHS->getInterface());
11340 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
11341 anyKindOf || LHS->isKindOfType());
11343 }
11344
11345 return getObjCObjectPointerType(QualType(LHS, 0));
11346 }
11347
11348 // Find the superclass.
11349 QualType LHSSuperType = LHS->getSuperClassType();
11350 if (LHSSuperType.isNull())
11351 break;
11352
11353 LHS = LHSSuperType->castAs<ObjCObjectType>();
11354 }
11355
11356 // We didn't find anything by following the LHS to its root; now check
11357 // the RHS against the cached set of ancestors.
11358 while (true) {
11359 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
11360 if (KnownLHS != LHSAncestors.end()) {
11361 LHS = KnownLHS->second;
11362
11363 // Get the type arguments.
11364 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
11365 bool anyChanges = false;
11366 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11367 // Both have type arguments, compare them.
11368 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11369 LHS->getTypeArgs(), RHS->getTypeArgs(),
11370 /*stripKindOf=*/true))
11371 return {};
11372 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11373 // If only one has type arguments, the result will not have type
11374 // arguments.
11375 RHSTypeArgs = {};
11376 anyChanges = true;
11377 }
11378
11379 // Compute the intersection of protocols.
11381 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
11382 Protocols);
11383 if (!Protocols.empty())
11384 anyChanges = true;
11385
11386 // If we need to return a kindof type but RHS is not a kindof type, we
11387 // build a new result type.
11388 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
11389 QualType Result = getObjCInterfaceType(RHS->getInterface());
11390 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
11391 anyKindOf || RHS->isKindOfType());
11393 }
11394
11395 return getObjCObjectPointerType(QualType(RHS, 0));
11396 }
11397
11398 // Find the superclass of the RHS.
11399 QualType RHSSuperType = RHS->getSuperClassType();
11400 if (RHSSuperType.isNull())
11401 break;
11402
11403 RHS = RHSSuperType->castAs<ObjCObjectType>();
11404 }
11405
11406 return {};
11407}
11408
11410 const ObjCObjectType *RHS) {
11411 assert(LHS->getInterface() && "LHS is not an interface type");
11412 assert(RHS->getInterface() && "RHS is not an interface type");
11413
11414 // Verify that the base decls are compatible: the RHS must be a subclass of
11415 // the LHS.
11416 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
11417 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
11418 if (!IsSuperClass)
11419 return false;
11420
11421 // If the LHS has protocol qualifiers, determine whether all of them are
11422 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
11423 // LHS).
11424 if (LHS->getNumProtocols() > 0) {
11425 // OK if conversion of LHS to SuperClass results in narrowing of types
11426 // ; i.e., SuperClass may implement at least one of the protocols
11427 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
11428 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
11429 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
11430 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
11431 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
11432 // qualifiers.
11433 for (auto *RHSPI : RHS->quals())
11434 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
11435 // If there is no protocols associated with RHS, it is not a match.
11436 if (SuperClassInheritedProtocols.empty())
11437 return false;
11438
11439 for (const auto *LHSProto : LHS->quals()) {
11440 bool SuperImplementsProtocol = false;
11441 for (auto *SuperClassProto : SuperClassInheritedProtocols)
11442 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
11443 SuperImplementsProtocol = true;
11444 break;
11445 }
11446 if (!SuperImplementsProtocol)
11447 return false;
11448 }
11449 }
11450
11451 // If the LHS is specialized, we may need to check type arguments.
11452 if (LHS->isSpecialized()) {
11453 // Follow the superclass chain until we've matched the LHS class in the
11454 // hierarchy. This substitutes type arguments through.
11455 const ObjCObjectType *RHSSuper = RHS;
11456 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
11457 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
11458
11459 // If the RHS is specializd, compare type arguments.
11460 if (RHSSuper->isSpecialized() &&
11461 !sameObjCTypeArgs(*this, LHS->getInterface(),
11462 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
11463 /*stripKindOf=*/true)) {
11464 return false;
11465 }
11466 }
11467
11468 return true;
11469}
11470
11472 // get the "pointed to" types
11473 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
11474 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
11475
11476 if (!LHSOPT || !RHSOPT)
11477 return false;
11478
11479 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
11480 canAssignObjCInterfaces(RHSOPT, LHSOPT);
11481}
11482
11485 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
11486 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
11487}
11488
11489/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
11490/// both shall have the identically qualified version of a compatible type.
11491/// C99 6.2.7p1: Two types have compatible types if their types are the
11492/// same. See 6.7.[2,3,5] for additional rules.
11494 bool CompareUnqualified) {
11495 if (getLangOpts().CPlusPlus)
11496 return hasSameType(LHS, RHS);
11497
11498 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
11499}
11500
11502 return typesAreCompatible(LHS, RHS);
11503}
11504
11506 return !mergeTypes(LHS, RHS, true).isNull();
11507}
11508
11509/// mergeTransparentUnionType - if T is a transparent union type and a member
11510/// of T is compatible with SubType, return the merged type, else return
11511/// QualType()
11513 bool OfBlockPointer,
11514 bool Unqualified) {
11515 if (const RecordType *UT = T->getAsUnionType()) {
11516 RecordDecl *UD = UT->getDecl()->getMostRecentDecl();
11517 if (UD->hasAttr<TransparentUnionAttr>()) {
11518 for (const auto *I : UD->fields()) {
11519 QualType ET = I->getType().getUnqualifiedType();
11520 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
11521 if (!MT.isNull())
11522 return MT;
11523 }
11524 }
11525 }
11526
11527 return {};
11528}
11529
11530/// mergeFunctionParameterTypes - merge two types which appear as function
11531/// parameter types
11533 bool OfBlockPointer,
11534 bool Unqualified) {
11535 // GNU extension: two types are compatible if they appear as a function
11536 // argument, one of the types is a transparent union type and the other
11537 // type is compatible with a union member
11538 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
11539 Unqualified);
11540 if (!lmerge.isNull())
11541 return lmerge;
11542
11543 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
11544 Unqualified);
11545 if (!rmerge.isNull())
11546 return rmerge;
11547
11548 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
11549}
11550
11552 bool OfBlockPointer, bool Unqualified,
11553 bool AllowCXX,
11554 bool IsConditionalOperator) {
11555 const auto *lbase = lhs->castAs<FunctionType>();
11556 const auto *rbase = rhs->castAs<FunctionType>();
11557 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
11558 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
11559 bool allLTypes = true;
11560 bool allRTypes = true;
11561
11562 // Check return type
11563 QualType retType;
11564 if (OfBlockPointer) {
11565 QualType RHS = rbase->getReturnType();
11566 QualType LHS = lbase->getReturnType();
11567 bool UnqualifiedResult = Unqualified;
11568 if (!UnqualifiedResult)
11569 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
11570 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
11571 }
11572 else
11573 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
11574 Unqualified);
11575 if (retType.isNull())
11576 return {};
11577
11578 if (Unqualified)
11579 retType = retType.getUnqualifiedType();
11580
11581 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
11582 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
11583 if (Unqualified) {
11584 LRetType = LRetType.getUnqualifiedType();
11585 RRetType = RRetType.getUnqualifiedType();
11586 }
11587
11588 if (getCanonicalType(retType) != LRetType)
11589 allLTypes = false;
11590 if (getCanonicalType(retType) != RRetType)
11591 allRTypes = false;
11592
11593 // FIXME: double check this
11594 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
11595 // rbase->getRegParmAttr() != 0 &&
11596 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
11597 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
11598 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
11599
11600 // Compatible functions must have compatible calling conventions
11601 if (lbaseInfo.getCC() != rbaseInfo.getCC())
11602 return {};
11603
11604 // Regparm is part of the calling convention.
11605 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
11606 return {};
11607 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
11608 return {};
11609
11610 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
11611 return {};
11612 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
11613 return {};
11614 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
11615 return {};
11616
11617 // When merging declarations, it's common for supplemental information like
11618 // attributes to only be present in one of the declarations, and we generally
11619 // want type merging to preserve the union of information. So a merged
11620 // function type should be noreturn if it was noreturn in *either* operand
11621 // type.
11622 //
11623 // But for the conditional operator, this is backwards. The result of the
11624 // operator could be either operand, and its type should conservatively
11625 // reflect that. So a function type in a composite type is noreturn only
11626 // if it's noreturn in *both* operand types.
11627 //
11628 // Arguably, noreturn is a kind of subtype, and the conditional operator
11629 // ought to produce the most specific common supertype of its operand types.
11630 // That would differ from this rule in contravariant positions. However,
11631 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
11632 // as a practical matter, it would only affect C code that does abstraction of
11633 // higher-order functions (taking noreturn callbacks!), which is uncommon to
11634 // say the least. So we use the simpler rule.
11635 bool NoReturn = IsConditionalOperator
11636 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
11637 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
11638 if (lbaseInfo.getNoReturn() != NoReturn)
11639 allLTypes = false;
11640 if (rbaseInfo.getNoReturn() != NoReturn)
11641 allRTypes = false;
11642
11643 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
11644
11645 std::optional<FunctionEffectSet> MergedFX;
11646
11647 if (lproto && rproto) { // two C99 style function prototypes
11648 assert((AllowCXX ||
11649 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
11650 "C++ shouldn't be here");
11651 // Compatible functions must have the same number of parameters
11652 if (lproto->getNumParams() != rproto->getNumParams())
11653 return {};
11654
11655 // Variadic and non-variadic functions aren't compatible
11656 if (lproto->isVariadic() != rproto->isVariadic())
11657 return {};
11658
11659 if (lproto->getMethodQuals() != rproto->getMethodQuals())
11660 return {};
11661
11662 // Function protos with different 'cfi_salt' values aren't compatible.
11663 if (lproto->getExtraAttributeInfo().CFISalt !=
11664 rproto->getExtraAttributeInfo().CFISalt)
11665 return {};
11666
11667 // Function effects are handled similarly to noreturn, see above.
11668 FunctionEffectsRef LHSFX = lproto->getFunctionEffects();
11669 FunctionEffectsRef RHSFX = rproto->getFunctionEffects();
11670 if (LHSFX != RHSFX) {
11671 if (IsConditionalOperator)
11672 MergedFX = FunctionEffectSet::getIntersection(LHSFX, RHSFX);
11673 else {
11675 MergedFX = FunctionEffectSet::getUnion(LHSFX, RHSFX, Errs);
11676 // Here we're discarding a possible error due to conflicts in the effect
11677 // sets. But we're not in a context where we can report it. The
11678 // operation does however guarantee maintenance of invariants.
11679 }
11680 if (*MergedFX != LHSFX)
11681 allLTypes = false;
11682 if (*MergedFX != RHSFX)
11683 allRTypes = false;
11684 }
11685
11687 bool canUseLeft, canUseRight;
11688 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
11689 newParamInfos))
11690 return {};
11691
11692 if (!canUseLeft)
11693 allLTypes = false;
11694 if (!canUseRight)
11695 allRTypes = false;
11696
11697 // Check parameter type compatibility
11699 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
11700 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
11701 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
11703 lParamType, rParamType, OfBlockPointer, Unqualified);
11704 if (paramType.isNull())
11705 return {};
11706
11707 if (Unqualified)
11708 paramType = paramType.getUnqualifiedType();
11709
11710 types.push_back(paramType);
11711 if (Unqualified) {
11712 lParamType = lParamType.getUnqualifiedType();
11713 rParamType = rParamType.getUnqualifiedType();
11714 }
11715
11716 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
11717 allLTypes = false;
11718 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
11719 allRTypes = false;
11720 }
11721
11722 if (allLTypes) return lhs;
11723 if (allRTypes) return rhs;
11724
11725 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
11726 EPI.ExtInfo = einfo;
11727 EPI.ExtParameterInfos =
11728 newParamInfos.empty() ? nullptr : newParamInfos.data();
11729 if (MergedFX)
11730 EPI.FunctionEffects = *MergedFX;
11731 return getFunctionType(retType, types, EPI);
11732 }
11733
11734 if (lproto) allRTypes = false;
11735 if (rproto) allLTypes = false;
11736
11737 const FunctionProtoType *proto = lproto ? lproto : rproto;
11738 if (proto) {
11739 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
11740 if (proto->isVariadic())
11741 return {};
11742 // Check that the types are compatible with the types that
11743 // would result from default argument promotions (C99 6.7.5.3p15).
11744 // The only types actually affected are promotable integer
11745 // types and floats, which would be passed as a different
11746 // type depending on whether the prototype is visible.
11747 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
11748 QualType paramTy = proto->getParamType(i);
11749
11750 // Look at the converted type of enum types, since that is the type used
11751 // to pass enum values.
11752 if (const auto *ED = paramTy->getAsEnumDecl()) {
11753 paramTy = ED->getIntegerType();
11754 if (paramTy.isNull())
11755 return {};
11756 }
11757
11758 if (isPromotableIntegerType(paramTy) ||
11759 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
11760 return {};
11761 }
11762
11763 if (allLTypes) return lhs;
11764 if (allRTypes) return rhs;
11765
11767 EPI.ExtInfo = einfo;
11768 if (MergedFX)
11769 EPI.FunctionEffects = *MergedFX;
11770 return getFunctionType(retType, proto->getParamTypes(), EPI);
11771 }
11772
11773 if (allLTypes) return lhs;
11774 if (allRTypes) return rhs;
11775 return getFunctionNoProtoType(retType, einfo);
11776}
11777
11778/// Given that we have an enum type and a non-enum type, try to merge them.
11779static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
11780 QualType other, bool isBlockReturnType) {
11781 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
11782 // a signed integer type, or an unsigned integer type.
11783 // Compatibility is based on the underlying type, not the promotion
11784 // type.
11785 QualType underlyingType =
11786 ET->getDecl()->getDefinitionOrSelf()->getIntegerType();
11787 if (underlyingType.isNull())
11788 return {};
11789 if (Context.hasSameType(underlyingType, other))
11790 return other;
11791
11792 // In block return types, we're more permissive and accept any
11793 // integral type of the same size.
11794 if (isBlockReturnType && other->isIntegerType() &&
11795 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
11796 return other;
11797
11798 return {};
11799}
11800
11802 // C17 and earlier and C++ disallow two tag definitions within the same TU
11803 // from being compatible.
11804 if (LangOpts.CPlusPlus || !LangOpts.C23)
11805 return {};
11806
11807 // Nameless tags are comparable only within outer definitions. At the top
11808 // level they are not comparable.
11809 const TagDecl *LTagD = LHS->castAsTagDecl(), *RTagD = RHS->castAsTagDecl();
11810 if (!LTagD->getIdentifier() || !RTagD->getIdentifier())
11811 return {};
11812
11813 // C23, on the other hand, requires the members to be "the same enough", so
11814 // we use a structural equivalence check.
11817 getLangOpts(), *this, *this, NonEquivalentDecls,
11818 StructuralEquivalenceKind::Default, /*StrictTypeSpelling=*/false,
11819 /*Complain=*/false, /*ErrorOnTagTypeMismatch=*/true);
11820 return Ctx.IsEquivalent(LHS, RHS) ? LHS : QualType{};
11821}
11822
11824 QualType LHS, QualType RHS, bool OfBlockPointer, bool Unqualified,
11825 bool BlockReturnType, bool IsConditionalOperator) {
11826 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
11827 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
11828
11829 if (!LHSOBT && !RHSOBT)
11830 return std::nullopt;
11831
11832 if (LHSOBT) {
11833 if (RHSOBT) {
11834 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
11835 return QualType();
11836
11837 QualType MergedUnderlying = mergeTypes(
11838 LHSOBT->getUnderlyingType(), RHSOBT->getUnderlyingType(),
11839 OfBlockPointer, Unqualified, BlockReturnType, IsConditionalOperator);
11840
11841 if (MergedUnderlying.isNull())
11842 return QualType();
11843
11844 if (getCanonicalType(LHSOBT) == getCanonicalType(RHSOBT)) {
11845 if (LHSOBT->getUnderlyingType() == RHSOBT->getUnderlyingType())
11846 return getCommonSugaredType(LHS, RHS);
11848 LHSOBT->getBehaviorKind(),
11849 getCanonicalType(LHSOBT->getUnderlyingType()));
11850 }
11851
11852 // For different underlying types that successfully merge, wrap the
11853 // merged underlying type with the common overflow behavior
11854 return getOverflowBehaviorType(LHSOBT->getBehaviorKind(),
11855 MergedUnderlying);
11856 }
11857 return mergeTypes(LHSOBT->getUnderlyingType(), RHS, OfBlockPointer,
11858 Unqualified, BlockReturnType, IsConditionalOperator);
11859 }
11860
11861 return mergeTypes(LHS, RHSOBT->getUnderlyingType(), OfBlockPointer,
11862 Unqualified, BlockReturnType, IsConditionalOperator);
11863}
11864
11865QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
11866 bool Unqualified, bool BlockReturnType,
11867 bool IsConditionalOperator) {
11868 // For C++ we will not reach this code with reference types (see below),
11869 // for OpenMP variant call overloading we might.
11870 //
11871 // C++ [expr]: If an expression initially has the type "reference to T", the
11872 // type is adjusted to "T" prior to any further analysis, the expression
11873 // designates the object or function denoted by the reference, and the
11874 // expression is an lvalue unless the reference is an rvalue reference and
11875 // the expression is a function call (possibly inside parentheses).
11876 auto *LHSRefTy = LHS->getAs<ReferenceType>();
11877 auto *RHSRefTy = RHS->getAs<ReferenceType>();
11878 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
11879 LHS->getTypeClass() == RHS->getTypeClass())
11880 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
11881 OfBlockPointer, Unqualified, BlockReturnType);
11882 if (LHSRefTy || RHSRefTy)
11883 return {};
11884
11885 if (std::optional<QualType> MergedOBT =
11886 tryMergeOverflowBehaviorTypes(LHS, RHS, OfBlockPointer, Unqualified,
11887 BlockReturnType, IsConditionalOperator))
11888 return *MergedOBT;
11889
11890 if (Unqualified) {
11891 LHS = LHS.getUnqualifiedType();
11892 RHS = RHS.getUnqualifiedType();
11893 }
11894
11895 QualType LHSCan = getCanonicalType(LHS),
11896 RHSCan = getCanonicalType(RHS);
11897
11898 // If two types are identical, they are compatible.
11899 if (LHSCan == RHSCan)
11900 return LHS;
11901
11902 // If the qualifiers are different, the types aren't compatible... mostly.
11903 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11904 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11905 if (LQuals != RQuals) {
11906 // If any of these qualifiers are different, we have a type
11907 // mismatch.
11908 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11909 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
11910 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
11911 !LQuals.getPointerAuth().isEquivalent(RQuals.getPointerAuth()) ||
11912 LQuals.hasUnaligned() != RQuals.hasUnaligned())
11913 return {};
11914
11915 // Exactly one GC qualifier difference is allowed: __strong is
11916 // okay if the other type has no GC qualifier but is an Objective
11917 // C object pointer (i.e. implicitly strong by default). We fix
11918 // this by pretending that the unqualified type was actually
11919 // qualified __strong.
11920 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11921 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11922 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11923
11924 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11925 return {};
11926
11927 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
11929 }
11930 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
11932 }
11933 return {};
11934 }
11935
11936 // Okay, qualifiers are equal.
11937
11938 Type::TypeClass LHSClass = LHSCan->getTypeClass();
11939 Type::TypeClass RHSClass = RHSCan->getTypeClass();
11940
11941 // We want to consider the two function types to be the same for these
11942 // comparisons, just force one to the other.
11943 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
11944 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
11945
11946 // Same as above for arrays
11947 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
11948 LHSClass = Type::ConstantArray;
11949 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
11950 RHSClass = Type::ConstantArray;
11951
11952 // ObjCInterfaces are just specialized ObjCObjects.
11953 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
11954 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
11955
11956 // Canonicalize ExtVector -> Vector.
11957 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
11958 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
11959
11960 // If the canonical type classes don't match.
11961 if (LHSClass != RHSClass) {
11962 // Note that we only have special rules for turning block enum
11963 // returns into block int returns, not vice-versa.
11964 if (const auto *ETy = LHS->getAsCanonical<EnumType>()) {
11965 return mergeEnumWithInteger(*this, ETy, RHS, false);
11966 }
11967 if (const EnumType *ETy = RHS->getAsCanonical<EnumType>()) {
11968 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
11969 }
11970 // allow block pointer type to match an 'id' type.
11971 if (OfBlockPointer && !BlockReturnType) {
11972 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
11973 return LHS;
11974 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
11975 return RHS;
11976 }
11977 // Allow __auto_type to match anything; it merges to the type with more
11978 // information.
11979 if (const auto *AT = LHS->getAs<AutoType>()) {
11980 if (!AT->isDeduced() && AT->isGNUAutoType())
11981 return RHS;
11982 }
11983 if (const auto *AT = RHS->getAs<AutoType>()) {
11984 if (!AT->isDeduced() && AT->isGNUAutoType())
11985 return LHS;
11986 }
11987 return {};
11988 }
11989
11990 // The canonical type classes match.
11991 switch (LHSClass) {
11992#define TYPE(Class, Base)
11993#define ABSTRACT_TYPE(Class, Base)
11994#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
11995#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
11996#define DEPENDENT_TYPE(Class, Base) case Type::Class:
11997#include "clang/AST/TypeNodes.inc"
11998 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
11999
12000 case Type::Auto:
12001 case Type::DeducedTemplateSpecialization:
12002 case Type::LValueReference:
12003 case Type::RValueReference:
12004 case Type::MemberPointer:
12005 llvm_unreachable("C++ should never be in mergeTypes");
12006
12007 case Type::ObjCInterface:
12008 case Type::IncompleteArray:
12009 case Type::VariableArray:
12010 case Type::FunctionProto:
12011 case Type::ExtVector:
12012 case Type::OverflowBehavior:
12013 llvm_unreachable("Types are eliminated above");
12014
12015 case Type::Pointer:
12016 {
12017 // Merge two pointer types, while trying to preserve typedef info
12018 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
12019 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
12020 if (Unqualified) {
12021 LHSPointee = LHSPointee.getUnqualifiedType();
12022 RHSPointee = RHSPointee.getUnqualifiedType();
12023 }
12024 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
12025 Unqualified);
12026 if (ResultType.isNull())
12027 return {};
12028 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
12029 return LHS;
12030 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
12031 return RHS;
12032 return getPointerType(ResultType);
12033 }
12034 case Type::BlockPointer:
12035 {
12036 // Merge two block pointer types, while trying to preserve typedef info
12037 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
12038 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
12039 if (Unqualified) {
12040 LHSPointee = LHSPointee.getUnqualifiedType();
12041 RHSPointee = RHSPointee.getUnqualifiedType();
12042 }
12043 if (getLangOpts().OpenCL) {
12044 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
12045 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
12046 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
12047 // 6.12.5) thus the following check is asymmetric.
12048 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual, *this))
12049 return {};
12050 LHSPteeQual.removeAddressSpace();
12051 RHSPteeQual.removeAddressSpace();
12052 LHSPointee =
12053 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
12054 RHSPointee =
12055 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
12056 }
12057 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
12058 Unqualified);
12059 if (ResultType.isNull())
12060 return {};
12061 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
12062 return LHS;
12063 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
12064 return RHS;
12065 return getBlockPointerType(ResultType);
12066 }
12067 case Type::Atomic:
12068 {
12069 // Merge two pointer types, while trying to preserve typedef info
12070 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
12071 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
12072 if (Unqualified) {
12073 LHSValue = LHSValue.getUnqualifiedType();
12074 RHSValue = RHSValue.getUnqualifiedType();
12075 }
12076 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
12077 Unqualified);
12078 if (ResultType.isNull())
12079 return {};
12080 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
12081 return LHS;
12082 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
12083 return RHS;
12084 return getAtomicType(ResultType);
12085 }
12086 case Type::ConstantArray:
12087 {
12088 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
12089 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
12090 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
12091 return {};
12092
12093 QualType LHSElem = getAsArrayType(LHS)->getElementType();
12094 QualType RHSElem = getAsArrayType(RHS)->getElementType();
12095 if (Unqualified) {
12096 LHSElem = LHSElem.getUnqualifiedType();
12097 RHSElem = RHSElem.getUnqualifiedType();
12098 }
12099
12100 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
12101 if (ResultType.isNull())
12102 return {};
12103
12104 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
12105 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
12106
12107 // If either side is a variable array, and both are complete, check whether
12108 // the current dimension is definite.
12109 if (LVAT || RVAT) {
12110 auto SizeFetch = [this](const VariableArrayType* VAT,
12111 const ConstantArrayType* CAT)
12112 -> std::pair<bool,llvm::APInt> {
12113 if (VAT) {
12114 std::optional<llvm::APSInt> TheInt;
12115 Expr *E = VAT->getSizeExpr();
12116 if (E && (TheInt = E->getIntegerConstantExpr(*this)))
12117 return std::make_pair(true, *TheInt);
12118 return std::make_pair(false, llvm::APSInt());
12119 }
12120 if (CAT)
12121 return std::make_pair(true, CAT->getSize());
12122 return std::make_pair(false, llvm::APInt());
12123 };
12124
12125 bool HaveLSize, HaveRSize;
12126 llvm::APInt LSize, RSize;
12127 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
12128 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
12129 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
12130 return {}; // Definite, but unequal, array dimension
12131 }
12132
12133 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
12134 return LHS;
12135 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
12136 return RHS;
12137 if (LCAT)
12138 return getConstantArrayType(ResultType, LCAT->getSize(),
12139 LCAT->getSizeExpr(), ArraySizeModifier(), 0);
12140 if (RCAT)
12141 return getConstantArrayType(ResultType, RCAT->getSize(),
12142 RCAT->getSizeExpr(), ArraySizeModifier(), 0);
12143 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
12144 return LHS;
12145 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
12146 return RHS;
12147 if (LVAT) {
12148 // FIXME: This isn't correct! But tricky to implement because
12149 // the array's size has to be the size of LHS, but the type
12150 // has to be different.
12151 return LHS;
12152 }
12153 if (RVAT) {
12154 // FIXME: This isn't correct! But tricky to implement because
12155 // the array's size has to be the size of RHS, but the type
12156 // has to be different.
12157 return RHS;
12158 }
12159 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
12160 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
12161 return getIncompleteArrayType(ResultType, ArraySizeModifier(), 0);
12162 }
12163 case Type::FunctionNoProto:
12164 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified,
12165 /*AllowCXX=*/false, IsConditionalOperator);
12166 case Type::Record:
12167 case Type::Enum:
12168 return mergeTagDefinitions(LHS, RHS);
12169 case Type::Builtin:
12170 // Only exactly equal builtin types are compatible, which is tested above.
12171 return {};
12172 case Type::Complex:
12173 // Distinct complex types are incompatible.
12174 return {};
12175 case Type::Vector:
12176 // FIXME: The merged type should be an ExtVector!
12177 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
12178 RHSCan->castAs<VectorType>()))
12179 return LHS;
12180 return {};
12181 case Type::ConstantMatrix:
12183 RHSCan->castAs<ConstantMatrixType>()))
12184 return LHS;
12185 return {};
12186 case Type::ObjCObject: {
12187 // Check if the types are assignment compatible.
12188 // FIXME: This should be type compatibility, e.g. whether
12189 // "LHS x; RHS x;" at global scope is legal.
12191 RHS->castAs<ObjCObjectType>()))
12192 return LHS;
12193 return {};
12194 }
12195 case Type::ObjCObjectPointer:
12196 if (OfBlockPointer) {
12199 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
12200 return LHS;
12201 return {};
12202 }
12205 return LHS;
12206 return {};
12207 case Type::Pipe:
12208 assert(LHS != RHS &&
12209 "Equivalent pipe types should have already been handled!");
12210 return {};
12211 case Type::ArrayParameter:
12212 assert(LHS != RHS &&
12213 "Equivalent ArrayParameter types should have already been handled!");
12214 return {};
12215 case Type::BitInt: {
12216 // Merge two bit-precise int types, while trying to preserve typedef info.
12217 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
12218 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
12219 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
12220 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
12221
12222 // Like unsigned/int, shouldn't have a type if they don't match.
12223 if (LHSUnsigned != RHSUnsigned)
12224 return {};
12225
12226 if (LHSBits != RHSBits)
12227 return {};
12228 return LHS;
12229 }
12230 case Type::HLSLAttributedResource: {
12231 const HLSLAttributedResourceType *LHSTy =
12232 LHS->castAs<HLSLAttributedResourceType>();
12233 const HLSLAttributedResourceType *RHSTy =
12234 RHS->castAs<HLSLAttributedResourceType>();
12235 assert(LHSTy->getWrappedType() == RHSTy->getWrappedType() &&
12236 LHSTy->getWrappedType()->isHLSLResourceType() &&
12237 "HLSLAttributedResourceType should always wrap __hlsl_resource_t");
12238
12239 if (LHSTy->getAttrs() == RHSTy->getAttrs() &&
12240 LHSTy->getContainedType() == RHSTy->getContainedType())
12241 return LHS;
12242 return {};
12243 }
12244 case Type::HLSLInlineSpirv:
12245 const HLSLInlineSpirvType *LHSTy = LHS->castAs<HLSLInlineSpirvType>();
12246 const HLSLInlineSpirvType *RHSTy = RHS->castAs<HLSLInlineSpirvType>();
12247
12248 if (LHSTy->getOpcode() == RHSTy->getOpcode() &&
12249 LHSTy->getSize() == RHSTy->getSize() &&
12250 LHSTy->getAlignment() == RHSTy->getAlignment()) {
12251 for (size_t I = 0; I < LHSTy->getOperands().size(); I++)
12252 if (LHSTy->getOperands()[I] != RHSTy->getOperands()[I])
12253 return {};
12254
12255 return LHS;
12256 }
12257 return {};
12258 }
12259
12260 llvm_unreachable("Invalid Type::Class!");
12261}
12262
12264 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
12265 bool &CanUseFirst, bool &CanUseSecond,
12267 assert(NewParamInfos.empty() && "param info list not empty");
12268 CanUseFirst = CanUseSecond = true;
12269 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
12270 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
12271
12272 // Fast path: if the first type doesn't have ext parameter infos,
12273 // we match if and only if the second type also doesn't have them.
12274 if (!FirstHasInfo && !SecondHasInfo)
12275 return true;
12276
12277 bool NeedParamInfo = false;
12278 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
12279 : SecondFnType->getExtParameterInfos().size();
12280
12281 for (size_t I = 0; I < E; ++I) {
12282 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
12283 if (FirstHasInfo)
12284 FirstParam = FirstFnType->getExtParameterInfo(I);
12285 if (SecondHasInfo)
12286 SecondParam = SecondFnType->getExtParameterInfo(I);
12287
12288 // Cannot merge unless everything except the noescape flag matches.
12289 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
12290 return false;
12291
12292 bool FirstNoEscape = FirstParam.isNoEscape();
12293 bool SecondNoEscape = SecondParam.isNoEscape();
12294 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
12295 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
12296 if (NewParamInfos.back().getOpaqueValue())
12297 NeedParamInfo = true;
12298 if (FirstNoEscape != IsNoEscape)
12299 CanUseFirst = false;
12300 if (SecondNoEscape != IsNoEscape)
12301 CanUseSecond = false;
12302 }
12303
12304 if (!NeedParamInfo)
12305 NewParamInfos.clear();
12306
12307 return true;
12308}
12309
12311 if (auto It = ObjCLayouts.find(D); It != ObjCLayouts.end()) {
12312 It->second = nullptr;
12313 for (auto *SubClass : ObjCSubClasses.lookup(D))
12314 ResetObjCLayout(SubClass);
12315 }
12316}
12317
12318/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
12319/// 'RHS' attributes and returns the merged version; including for function
12320/// return types.
12322 QualType LHSCan = getCanonicalType(LHS),
12323 RHSCan = getCanonicalType(RHS);
12324 // If two types are identical, they are compatible.
12325 if (LHSCan == RHSCan)
12326 return LHS;
12327 if (RHSCan->isFunctionType()) {
12328 if (!LHSCan->isFunctionType())
12329 return {};
12330 QualType OldReturnType =
12331 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
12332 QualType NewReturnType =
12333 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
12334 QualType ResReturnType =
12335 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
12336 if (ResReturnType.isNull())
12337 return {};
12338 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
12339 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
12340 // In either case, use OldReturnType to build the new function type.
12341 const auto *F = LHS->castAs<FunctionType>();
12342 if (const auto *FPT = cast<FunctionProtoType>(F)) {
12343 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12344 EPI.ExtInfo = getFunctionExtInfo(LHS);
12345 QualType ResultType =
12346 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
12347 return ResultType;
12348 }
12349 }
12350 return {};
12351 }
12352
12353 // If the qualifiers are different, the types can still be merged.
12354 Qualifiers LQuals = LHSCan.getLocalQualifiers();
12355 Qualifiers RQuals = RHSCan.getLocalQualifiers();
12356 if (LQuals != RQuals) {
12357 // If any of these qualifiers are different, we have a type mismatch.
12358 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
12359 LQuals.getAddressSpace() != RQuals.getAddressSpace())
12360 return {};
12361
12362 // Exactly one GC qualifier difference is allowed: __strong is
12363 // okay if the other type has no GC qualifier but is an Objective
12364 // C object pointer (i.e. implicitly strong by default). We fix
12365 // this by pretending that the unqualified type was actually
12366 // qualified __strong.
12367 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
12368 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
12369 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
12370
12371 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
12372 return {};
12373
12374 if (GC_L == Qualifiers::Strong)
12375 return LHS;
12376 if (GC_R == Qualifiers::Strong)
12377 return RHS;
12378 return {};
12379 }
12380
12381 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
12382 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12383 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12384 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
12385 if (ResQT == LHSBaseQT)
12386 return LHS;
12387 if (ResQT == RHSBaseQT)
12388 return RHS;
12389 }
12390 return {};
12391}
12392
12393//===----------------------------------------------------------------------===//
12394// Integer Predicates
12395//===----------------------------------------------------------------------===//
12396
12398 if (const auto *ED = T->getAsEnumDecl())
12399 T = ED->getIntegerType();
12400 if (T->isBooleanType())
12401 return 1;
12402 if (const auto *EIT = T->getAs<BitIntType>())
12403 return EIT->getNumBits();
12404 // For builtin types, just use the standard type sizing method
12405 return (unsigned)getTypeSize(T);
12406}
12407
12409 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12410 T->isFixedPointType()) &&
12411 "Unexpected type");
12412
12413 // Turn <4 x signed int> -> <4 x unsigned int>
12414 if (const auto *VTy = T->getAs<VectorType>())
12415 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
12416 VTy->getNumElements(), VTy->getVectorKind());
12417
12418 // For _BitInt, return an unsigned _BitInt with same width.
12419 if (const auto *EITy = T->getAs<BitIntType>())
12420 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
12421
12422 // For the overflow behavior types, construct a new unsigned variant
12423 if (const auto *OBT = T->getAs<OverflowBehaviorType>())
12425 OBT->getBehaviorKind(),
12426 getCorrespondingUnsignedType(OBT->getUnderlyingType()));
12427
12428 // For enums, get the underlying integer type of the enum, and let the general
12429 // integer type signchanging code handle it.
12430 if (const auto *ED = T->getAsEnumDecl())
12431 T = ED->getIntegerType();
12432
12433 switch (T->castAs<BuiltinType>()->getKind()) {
12434 case BuiltinType::Char_U:
12435 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
12436 case BuiltinType::Char_S:
12437 case BuiltinType::SChar:
12438 case BuiltinType::Char8:
12439 return UnsignedCharTy;
12440 case BuiltinType::Short:
12441 return UnsignedShortTy;
12442 case BuiltinType::Int:
12443 return UnsignedIntTy;
12444 case BuiltinType::Long:
12445 return UnsignedLongTy;
12446 case BuiltinType::LongLong:
12447 return UnsignedLongLongTy;
12448 case BuiltinType::Int128:
12449 return UnsignedInt128Ty;
12450 // wchar_t is special. It is either signed or not, but when it's signed,
12451 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
12452 // version of its underlying type instead.
12453 case BuiltinType::WChar_S:
12454 return getUnsignedWCharType();
12455
12456 case BuiltinType::ShortAccum:
12457 return UnsignedShortAccumTy;
12458 case BuiltinType::Accum:
12459 return UnsignedAccumTy;
12460 case BuiltinType::LongAccum:
12461 return UnsignedLongAccumTy;
12462 case BuiltinType::SatShortAccum:
12464 case BuiltinType::SatAccum:
12465 return SatUnsignedAccumTy;
12466 case BuiltinType::SatLongAccum:
12468 case BuiltinType::ShortFract:
12469 return UnsignedShortFractTy;
12470 case BuiltinType::Fract:
12471 return UnsignedFractTy;
12472 case BuiltinType::LongFract:
12473 return UnsignedLongFractTy;
12474 case BuiltinType::SatShortFract:
12476 case BuiltinType::SatFract:
12477 return SatUnsignedFractTy;
12478 case BuiltinType::SatLongFract:
12480 default:
12481 assert((T->hasUnsignedIntegerRepresentation() ||
12482 T->isUnsignedFixedPointType()) &&
12483 "Unexpected signed integer or fixed point type");
12484 return T;
12485 }
12486}
12487
12489 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12490 T->isFixedPointType()) &&
12491 "Unexpected type");
12492
12493 // Turn <4 x unsigned int> -> <4 x signed int>
12494 if (const auto *VTy = T->getAs<VectorType>())
12495 return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
12496 VTy->getNumElements(), VTy->getVectorKind());
12497
12498 // For _BitInt, return a signed _BitInt with same width.
12499 if (const auto *EITy = T->getAs<BitIntType>())
12500 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
12501
12502 // For enums, get the underlying integer type of the enum, and let the general
12503 // integer type signchanging code handle it.
12504 if (const auto *ED = T->getAsEnumDecl())
12505 T = ED->getIntegerType();
12506
12507 switch (T->castAs<BuiltinType>()->getKind()) {
12508 case BuiltinType::Char_S:
12509 // Plain `char` is mapped to `signed char` even if it's already signed
12510 case BuiltinType::Char_U:
12511 case BuiltinType::UChar:
12512 case BuiltinType::Char8:
12513 return SignedCharTy;
12514 case BuiltinType::UShort:
12515 return ShortTy;
12516 case BuiltinType::UInt:
12517 return IntTy;
12518 case BuiltinType::ULong:
12519 return LongTy;
12520 case BuiltinType::ULongLong:
12521 return LongLongTy;
12522 case BuiltinType::UInt128:
12523 return Int128Ty;
12524 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
12525 // there's no matching "signed wchar_t". Therefore we return the signed
12526 // version of its underlying type instead.
12527 case BuiltinType::WChar_U:
12528 return getSignedWCharType();
12529
12530 case BuiltinType::UShortAccum:
12531 return ShortAccumTy;
12532 case BuiltinType::UAccum:
12533 return AccumTy;
12534 case BuiltinType::ULongAccum:
12535 return LongAccumTy;
12536 case BuiltinType::SatUShortAccum:
12537 return SatShortAccumTy;
12538 case BuiltinType::SatUAccum:
12539 return SatAccumTy;
12540 case BuiltinType::SatULongAccum:
12541 return SatLongAccumTy;
12542 case BuiltinType::UShortFract:
12543 return ShortFractTy;
12544 case BuiltinType::UFract:
12545 return FractTy;
12546 case BuiltinType::ULongFract:
12547 return LongFractTy;
12548 case BuiltinType::SatUShortFract:
12549 return SatShortFractTy;
12550 case BuiltinType::SatUFract:
12551 return SatFractTy;
12552 case BuiltinType::SatULongFract:
12553 return SatLongFractTy;
12554 default:
12555 assert(
12556 (T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
12557 "Unexpected signed integer or fixed point type");
12558 return T;
12559 }
12560}
12561
12563
12566
12567//===----------------------------------------------------------------------===//
12568// Builtin Type Computation
12569//===----------------------------------------------------------------------===//
12570
12571/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
12572/// pointer over the consumed characters. This returns the resultant type. If
12573/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
12574/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
12575/// a vector of "i*".
12576///
12577/// RequiresICE is filled in on return to indicate whether the value is required
12578/// to be an Integer Constant Expression.
12579static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
12581 bool &RequiresICE,
12582 bool AllowTypeModifiers) {
12583 // Modifiers.
12584 int HowLong = 0;
12585 bool Signed = false, Unsigned = false;
12586 bool IsChar = false, IsShort = false;
12587 RequiresICE = false;
12588
12589 // Read the prefixed modifiers first.
12590 bool Done = false;
12591 #ifndef NDEBUG
12592 bool IsSpecial = false;
12593 #endif
12594 while (!Done) {
12595 switch (*Str++) {
12596 default: Done = true; --Str; break;
12597 case 'I':
12598 RequiresICE = true;
12599 break;
12600 case 'S':
12601 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
12602 assert(!Signed && "Can't use 'S' modifier multiple times!");
12603 Signed = true;
12604 break;
12605 case 'U':
12606 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
12607 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
12608 Unsigned = true;
12609 break;
12610 case 'B':
12611 // This modifier represents int8 type (byte-width).
12612 assert(!IsSpecial &&
12613 "Can't use two 'N', 'W', 'Z', 'O', 'B', or 'T' modifiers!");
12614 assert(HowLong == 0 && "Can't use both 'L' and 'B' modifiers!");
12615#ifndef NDEBUG
12616 IsSpecial = true;
12617#endif
12618 IsChar = true;
12619 break;
12620 case 'T':
12621 // This modifier represents int16 type (short-width).
12622 assert(!IsSpecial &&
12623 "Can't use two 'N', 'W', 'Z', 'O', 'B', or 'T' modifiers!");
12624 assert(HowLong == 0 && "Can't use both 'L' and 'T' modifiers!");
12625#ifndef NDEBUG
12626 IsSpecial = true;
12627#endif
12628 IsShort = true;
12629 break;
12630 case 'L':
12631 assert(!IsSpecial &&
12632 "Can't use 'L' with 'W', 'N', 'Z', 'O', 'B', or 'T' modifiers");
12633 assert(HowLong <= 2 && "Can't have LLLL modifier");
12634 ++HowLong;
12635 break;
12636 case 'N':
12637 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
12638 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12639 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
12640 #ifndef NDEBUG
12641 IsSpecial = true;
12642 #endif
12643 if (Context.getTargetInfo().getLongWidth() == 32)
12644 ++HowLong;
12645 break;
12646 case 'W':
12647 // This modifier represents int64 type.
12648 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12649 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
12650 #ifndef NDEBUG
12651 IsSpecial = true;
12652 #endif
12653 switch (Context.getTargetInfo().getInt64Type()) {
12654 default:
12655 llvm_unreachable("Unexpected integer type");
12657 HowLong = 1;
12658 break;
12660 HowLong = 2;
12661 break;
12662 }
12663 break;
12664 case 'Z':
12665 // This modifier represents int32 type.
12666 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12667 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
12668 #ifndef NDEBUG
12669 IsSpecial = true;
12670 #endif
12671 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
12672 default:
12673 llvm_unreachable("Unexpected integer type");
12675 HowLong = 0;
12676 break;
12678 HowLong = 1;
12679 break;
12681 HowLong = 2;
12682 break;
12683 }
12684 break;
12685 case 'O':
12686 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12687 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
12688 #ifndef NDEBUG
12689 IsSpecial = true;
12690 #endif
12691 if (Context.getLangOpts().OpenCL)
12692 HowLong = 1;
12693 else
12694 HowLong = 2;
12695 break;
12696 }
12697 }
12698
12699 QualType Type;
12700
12701 // Read the base type.
12702 switch (*Str++) {
12703 default:
12704 llvm_unreachable("Unknown builtin type letter!");
12705 case 'x':
12706 assert(HowLong == 0 && !Signed && !Unsigned &&
12707 "Bad modifiers used with 'x'!");
12708 Type = Context.Float16Ty;
12709 break;
12710 case 'y':
12711 assert(HowLong == 0 && !Signed && !Unsigned &&
12712 "Bad modifiers used with 'y'!");
12713 Type = Context.BFloat16Ty;
12714 break;
12715 case 'v':
12716 assert(HowLong == 0 && !Signed && !Unsigned &&
12717 "Bad modifiers used with 'v'!");
12718 Type = Context.VoidTy;
12719 break;
12720 case 'h':
12721 assert(HowLong == 0 && !Signed && !Unsigned &&
12722 "Bad modifiers used with 'h'!");
12723 Type = Context.HalfTy;
12724 break;
12725 case 'f':
12726 assert(HowLong == 0 && !Signed && !Unsigned &&
12727 "Bad modifiers used with 'f'!");
12728 Type = Context.FloatTy;
12729 break;
12730 case 'd':
12731 assert(HowLong < 3 && !Signed && !Unsigned &&
12732 "Bad modifiers used with 'd'!");
12733 if (HowLong == 1)
12734 Type = Context.LongDoubleTy;
12735 else if (HowLong == 2)
12736 Type = Context.Float128Ty;
12737 else
12738 Type = Context.DoubleTy;
12739 break;
12740 case 's':
12741 assert(HowLong == 0 && "Bad modifiers used with 's'!");
12742 if (Unsigned)
12743 Type = Context.UnsignedShortTy;
12744 else
12745 Type = Context.ShortTy;
12746 break;
12747 case 'i':
12748 if (IsChar)
12749 Type = Unsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
12750 else if (IsShort)
12751 Type = Unsigned ? Context.UnsignedShortTy : Context.ShortTy;
12752 else if (HowLong == 3)
12753 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
12754 else if (HowLong == 2)
12755 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
12756 else if (HowLong == 1)
12757 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
12758 else
12759 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
12760 break;
12761 case 'c':
12762 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
12763 if (Signed)
12764 Type = Context.SignedCharTy;
12765 else if (Unsigned)
12766 Type = Context.UnsignedCharTy;
12767 else
12768 Type = Context.CharTy;
12769 break;
12770 case 'b': // boolean
12771 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
12772 Type = Context.BoolTy;
12773 break;
12774 case 'z': // size_t.
12775 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
12776 Type = Context.getSizeType();
12777 break;
12778 case 'w': // wchar_t.
12779 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
12780 Type = Context.getWideCharType();
12781 break;
12782 case 'F':
12783 Type = Context.getCFConstantStringType();
12784 break;
12785 case 'G':
12786 Type = Context.getObjCIdType();
12787 break;
12788 case 'H':
12789 Type = Context.getObjCSelType();
12790 break;
12791 case 'M':
12792 Type = Context.getObjCSuperType();
12793 break;
12794 case 'a':
12795 Type = Context.getBuiltinVaListType();
12796 assert(!Type.isNull() && "builtin va list type not initialized!");
12797 break;
12798 case 'A':
12799 // This is a "reference" to a va_list; however, what exactly
12800 // this means depends on how va_list is defined. There are two
12801 // different kinds of va_list: ones passed by value, and ones
12802 // passed by reference. An example of a by-value va_list is
12803 // x86, where va_list is a char*. An example of by-ref va_list
12804 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
12805 // we want this argument to be a char*&; for x86-64, we want
12806 // it to be a __va_list_tag*.
12807 Type = Context.getBuiltinVaListType();
12808 assert(!Type.isNull() && "builtin va list type not initialized!");
12809 if (Type->isArrayType())
12810 Type = Context.getArrayDecayedType(Type);
12811 else
12812 Type = Context.getLValueReferenceType(Type);
12813 break;
12814 case 'q': {
12815 char *End;
12816 unsigned NumElements = strtoul(Str, &End, 10);
12817 assert(End != Str && "Missing vector size");
12818 Str = End;
12819
12820 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12821 RequiresICE, false);
12822 assert(!RequiresICE && "Can't require vector ICE");
12823
12824 Type = Context.getScalableVectorType(ElementType, NumElements);
12825 break;
12826 }
12827 case 'Q': {
12828 switch (*Str++) {
12829 case 'a': {
12830 Type = Context.SveCountTy;
12831 break;
12832 }
12833 case 'b': {
12834 Type = Context.AMDGPUBufferRsrcTy;
12835 break;
12836 }
12837 case 'c': {
12838 Type = Context.AMDGPUFeaturePredicateTy;
12839 break;
12840 }
12841 case 't': {
12842 Type = Context.AMDGPUTextureTy;
12843 break;
12844 }
12845 case 'r': {
12846 Type = Context.HLSLResourceTy;
12847 break;
12848 }
12849 default:
12850 llvm_unreachable("Unexpected target builtin type");
12851 }
12852 break;
12853 }
12854 case 'V': {
12855 char *End;
12856 unsigned NumElements = strtoul(Str, &End, 10);
12857 assert(End != Str && "Missing vector size");
12858 Str = End;
12859
12860 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12861 RequiresICE, false);
12862 assert(!RequiresICE && "Can't require vector ICE");
12863
12864 // TODO: No way to make AltiVec vectors in builtins yet.
12865 Type = Context.getVectorType(ElementType, NumElements, VectorKind::Generic);
12866 break;
12867 }
12868 case 'E': {
12869 char *End;
12870
12871 unsigned NumElements = strtoul(Str, &End, 10);
12872 assert(End != Str && "Missing vector size");
12873
12874 Str = End;
12875
12876 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12877 false);
12878 Type = Context.getExtVectorType(ElementType, NumElements);
12879 break;
12880 }
12881 case 'X': {
12882 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12883 false);
12884 assert(!RequiresICE && "Can't require complex ICE");
12885 Type = Context.getComplexType(ElementType);
12886 break;
12887 }
12888 case 'Y':
12889 Type = Context.getPointerDiffType();
12890 break;
12891 case 'P':
12892 Type = Context.getFILEType();
12893 if (Type.isNull()) {
12895 return {};
12896 }
12897 break;
12898 case 'J':
12899 if (Signed)
12900 Type = Context.getsigjmp_bufType();
12901 else
12902 Type = Context.getjmp_bufType();
12903
12904 if (Type.isNull()) {
12906 return {};
12907 }
12908 break;
12909 case 'K':
12910 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
12911 Type = Context.getucontext_tType();
12912
12913 if (Type.isNull()) {
12915 return {};
12916 }
12917 break;
12918 case 'p':
12919 Type = Context.getProcessIDType();
12920 break;
12921 case 'm':
12922 Type = Context.MFloat8Ty;
12923 break;
12924 }
12925
12926 // If there are modifiers and if we're allowed to parse them, go for it.
12927 Done = !AllowTypeModifiers;
12928 while (!Done) {
12929 switch (char c = *Str++) {
12930 default: Done = true; --Str; break;
12931 case '*':
12932 case '&': {
12933 // Both pointers and references can have their pointee types
12934 // qualified with an address space.
12935 char *End;
12936 unsigned AddrSpace = strtoul(Str, &End, 10);
12937 if (End != Str) {
12938 // Note AddrSpace == 0 is not the same as an unspecified address space.
12939 Type = Context.getAddrSpaceQualType(
12940 Type,
12941 Context.getLangASForBuiltinAddressSpace(AddrSpace));
12942 Str = End;
12943 }
12944 if (c == '*')
12945 Type = Context.getPointerType(Type);
12946 else
12947 Type = Context.getLValueReferenceType(Type);
12948 break;
12949 }
12950 // FIXME: There's no way to have a built-in with an rvalue ref arg.
12951 case 'C':
12952 Type = Type.withConst();
12953 break;
12954 case 'D':
12955 Type = Context.getVolatileType(Type);
12956 break;
12957 case 'R':
12958 Type = Type.withRestrict();
12959 break;
12960 }
12961 }
12962
12963 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
12964 "Integer constant 'I' type must be an integer");
12965
12966 return Type;
12967}
12968
12969// On some targets such as PowerPC, some of the builtins are defined with custom
12970// type descriptors for target-dependent types. These descriptors are decoded in
12971// other functions, but it may be useful to be able to fall back to default
12972// descriptor decoding to define builtins mixing target-dependent and target-
12973// independent types. This function allows decoding one type descriptor with
12974// default decoding.
12975QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
12976 GetBuiltinTypeError &Error, bool &RequireICE,
12977 bool AllowTypeModifiers) const {
12978 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
12979}
12980
12981/// GetBuiltinType - Return the type for the specified builtin.
12984 unsigned *IntegerConstantArgs) const {
12985 const char *TypeStr = BuiltinInfo.getTypeString(Id);
12986 if (TypeStr[0] == '\0') {
12988 return {};
12989 }
12990
12991 SmallVector<QualType, 8> ArgTypes;
12992
12993 bool RequiresICE = false;
12994 Error = GE_None;
12995 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
12996 RequiresICE, true);
12997 if (Error != GE_None)
12998 return {};
12999
13000 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
13001
13002 while (TypeStr[0] && TypeStr[0] != '.') {
13003 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
13004 if (Error != GE_None)
13005 return {};
13006
13007 // If this argument is required to be an IntegerConstantExpression and the
13008 // caller cares, fill in the bitmask we return.
13009 if (RequiresICE && IntegerConstantArgs)
13010 *IntegerConstantArgs |= 1 << ArgTypes.size();
13011
13012 // Do array -> pointer decay. The builtin should use the decayed type.
13013 if (Ty->isArrayType())
13014 Ty = getArrayDecayedType(Ty);
13015
13016 ArgTypes.push_back(Ty);
13017 }
13018
13019 if (Id == Builtin::BI__GetExceptionInfo)
13020 return {};
13021
13022 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
13023 "'.' should only occur at end of builtin type list!");
13024
13025 bool Variadic = (TypeStr[0] == '.');
13026
13027 FunctionType::ExtInfo EI(Target->getDefaultCallingConv());
13028 if (BuiltinInfo.isNoReturn(Id))
13029 EI = EI.withNoReturn(true);
13030
13031 // We really shouldn't be making a no-proto type here.
13032 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
13033 return getFunctionNoProtoType(ResType, EI);
13034
13036 EPI.ExtInfo = EI;
13037 EPI.Variadic = Variadic;
13038 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
13039 EPI.ExceptionSpec.Type =
13041
13042 return getFunctionType(ResType, ArgTypes, EPI);
13043}
13044
13046 const FunctionDecl *FD) {
13047 if (!FD->isExternallyVisible())
13048 return GVA_Internal;
13049
13050 // Non-user-provided functions get emitted as weak definitions with every
13051 // use, no matter whether they've been explicitly instantiated etc.
13052 if (!FD->isUserProvided())
13053 return GVA_DiscardableODR;
13054
13056 switch (FD->getTemplateSpecializationKind()) {
13057 case TSK_Undeclared:
13060 break;
13061
13063 return GVA_StrongODR;
13064
13065 // C++11 [temp.explicit]p10:
13066 // [ Note: The intent is that an inline function that is the subject of
13067 // an explicit instantiation declaration will still be implicitly
13068 // instantiated when used so that the body can be considered for
13069 // inlining, but that no out-of-line copy of the inline function would be
13070 // generated in the translation unit. -- end note ]
13073
13076 break;
13077 }
13078
13079 if (!FD->isInlined())
13080 return External;
13081
13082 if ((!Context.getLangOpts().CPlusPlus &&
13083 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13084 !FD->hasAttr<DLLExportAttr>()) ||
13085 FD->hasAttr<GNUInlineAttr>()) {
13086 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
13087
13088 // GNU or C99 inline semantics. Determine whether this symbol should be
13089 // externally visible.
13090 if (auto *Def = FD->getDefinition();
13092 return External;
13093
13094 // C99 inline semantics, where the symbol is not externally visible.
13096 }
13097
13098 // Functions specified with extern and inline in -fms-compatibility mode
13099 // forcibly get emitted. While the body of the function cannot be later
13100 // replaced, the function definition cannot be discarded.
13101 if (FD->isMSExternInline())
13102 return GVA_StrongODR;
13103
13104 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13106 cast<CXXConstructorDecl>(FD)->isInheritingConstructor() &&
13107 !FD->hasAttr<DLLExportAttr>()) {
13108 // Both Clang and MSVC implement inherited constructors as forwarding
13109 // thunks that delegate to the base constructor. Keep non-dllexport
13110 // inheriting constructor thunks internal since they are not needed
13111 // outside the translation unit.
13112 //
13113 // dllexport inherited constructors are exempted so they are externally
13114 // visible, matching MSVC's export behavior. Inherited constructors
13115 // whose parameters prevent ABI-compatible forwarding (e.g. callee-
13116 // cleanup types) are excluded from export in Sema to avoid silent
13117 // runtime mismatches.
13118 return GVA_Internal;
13119 }
13120
13121 return GVA_DiscardableODR;
13122}
13123
13125 const Decl *D, GVALinkage L) {
13126 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
13127 // dllexport/dllimport on inline functions.
13128 if (D->hasAttr<DLLImportAttr>()) {
13129 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
13131 } else if (D->hasAttr<DLLExportAttr>()) {
13132 if (L == GVA_DiscardableODR)
13133 return GVA_StrongODR;
13134 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
13135 // Device-side functions with __global__ attribute must always be
13136 // visible externally so they can be launched from host.
13137 if (D->hasAttr<CUDAGlobalAttr>() &&
13138 (L == GVA_DiscardableODR || L == GVA_Internal))
13139 return GVA_StrongODR;
13140 // Single source offloading languages like CUDA/HIP need to be able to
13141 // access static device variables from host code of the same compilation
13142 // unit. This is done by externalizing the static variable with a shared
13143 // name between the host and device compilation which is the same for the
13144 // same compilation unit whereas different among different compilation
13145 // units.
13146 if (Context.shouldExternalize(D))
13147 return GVA_StrongExternal;
13148 }
13149 return L;
13150}
13151
13152/// Adjust the GVALinkage for a declaration based on what an external AST source
13153/// knows about whether there can be other definitions of this declaration.
13154static GVALinkage
13156 GVALinkage L) {
13157 ExternalASTSource *Source = Ctx.getExternalSource();
13158 if (!Source)
13159 return L;
13160
13161 switch (Source->hasExternalDefinitions(D)) {
13163 // Other translation units rely on us to provide the definition.
13164 if (L == GVA_DiscardableODR)
13165 return GVA_StrongODR;
13166 break;
13167
13170
13172 break;
13173 }
13174 return L;
13175}
13176
13182
13184 const VarDecl *VD) {
13185 // As an extension for interactive REPLs, make sure constant variables are
13186 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
13187 // marking them as internal.
13188 if (Context.getLangOpts().CPlusPlus &&
13189 Context.getLangOpts().IncrementalExtensions &&
13190 VD->getType().isConstQualified() &&
13191 !VD->getType().isVolatileQualified() && !VD->isInline() &&
13193 return GVA_DiscardableODR;
13194
13195 if (!VD->isExternallyVisible())
13196 return GVA_Internal;
13197
13198 if (VD->isStaticLocal()) {
13199 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
13200 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
13201 LexicalContext = LexicalContext->getLexicalParent();
13202
13203 // ObjC Blocks can create local variables that don't have a FunctionDecl
13204 // LexicalContext.
13205 if (!LexicalContext)
13206 return GVA_DiscardableODR;
13207
13208 // Otherwise, let the static local variable inherit its linkage from the
13209 // nearest enclosing function.
13210 auto StaticLocalLinkage =
13211 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
13212
13213 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
13214 // be emitted in any object with references to the symbol for the object it
13215 // contains, whether inline or out-of-line."
13216 // Similar behavior is observed with MSVC. An alternative ABI could use
13217 // StrongODR/AvailableExternally to match the function, but none are
13218 // known/supported currently.
13219 if (StaticLocalLinkage == GVA_StrongODR ||
13220 StaticLocalLinkage == GVA_AvailableExternally)
13221 return GVA_DiscardableODR;
13222 return StaticLocalLinkage;
13223 }
13224
13225 // MSVC treats in-class initialized static data members as definitions.
13226 // By giving them non-strong linkage, out-of-line definitions won't
13227 // cause link errors.
13228 if (Context.isMSStaticDataMemberInlineDefinition(VD))
13229 return GVA_DiscardableODR;
13230
13231 // Most non-template variables have strong linkage; inline variables are
13232 // linkonce_odr or (occasionally, for compatibility) weak_odr.
13233 GVALinkage StrongLinkage;
13234 switch (Context.getInlineVariableDefinitionKind(VD)) {
13236 StrongLinkage = GVA_StrongExternal;
13237 break;
13240 StrongLinkage = GVA_DiscardableODR;
13241 break;
13243 StrongLinkage = GVA_StrongODR;
13244 break;
13245 }
13246
13247 switch (VD->getTemplateSpecializationKind()) {
13248 case TSK_Undeclared:
13249 return StrongLinkage;
13250
13252 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13253 VD->isStaticDataMember()
13255 : StrongLinkage;
13256
13258 return GVA_StrongODR;
13259
13262
13264 return GVA_DiscardableODR;
13265 }
13266
13267 llvm_unreachable("Invalid Linkage!");
13268}
13269
13275
13277 if (const auto *VD = dyn_cast<VarDecl>(D)) {
13278 if (!VD->isFileVarDecl())
13279 return false;
13280 // Global named register variables (GNU extension) are never emitted.
13281 if (VD->getStorageClass() == SC_Register)
13282 return false;
13283 if (VD->getDescribedVarTemplate() ||
13285 return false;
13286 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13287 // We never need to emit an uninstantiated function template.
13288 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13289 return false;
13290 } else if (isa<PragmaCommentDecl>(D))
13291 return true;
13293 return true;
13294 else if (isa<OMPRequiresDecl>(D))
13295 return true;
13296 else if (isa<OMPThreadPrivateDecl>(D))
13297 return !D->getDeclContext()->isDependentContext();
13298 else if (isa<OMPAllocateDecl>(D))
13299 return !D->getDeclContext()->isDependentContext();
13301 return !D->getDeclContext()->isDependentContext();
13302 else if (isa<ImportDecl>(D))
13303 return true;
13304 else
13305 return false;
13306
13307 // If this is a member of a class template, we do not need to emit it.
13309 return false;
13310
13311 // Weak references don't produce any output by themselves.
13312 if (D->hasAttr<WeakRefAttr>())
13313 return false;
13314
13315 // SYCL device compilation requires that functions defined with the
13316 // sycl_kernel_entry_point or sycl_external attributes be emitted. All
13317 // other entities are emitted only if they are used by a function
13318 // defined with one of those attributes.
13319 if (LangOpts.SYCLIsDevice)
13320 return isa<FunctionDecl>(D) && (D->hasAttr<SYCLKernelEntryPointAttr>() ||
13321 D->hasAttr<SYCLExternalAttr>());
13322
13323 // Aliases and used decls are required.
13324 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
13325 return true;
13326
13327 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13328 // Forward declarations aren't required.
13329 if (!FD->doesThisDeclarationHaveABody())
13330 return FD->doesDeclarationForceExternallyVisibleDefinition();
13331
13332 // Constructors and destructors are required.
13333 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
13334 return true;
13335
13336 // The key function for a class is required. This rule only comes
13337 // into play when inline functions can be key functions, though.
13338 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13339 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13340 const CXXRecordDecl *RD = MD->getParent();
13341 if (MD->isOutOfLine() && RD->isDynamicClass()) {
13342 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
13343 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
13344 return true;
13345 }
13346 }
13347 }
13348
13350
13351 // static, static inline, always_inline, and extern inline functions can
13352 // always be deferred. Normal inline functions can be deferred in C99/C++.
13353 // Implicit template instantiations can also be deferred in C++.
13355 }
13356
13357 const auto *VD = cast<VarDecl>(D);
13358 assert(VD->isFileVarDecl() && "Expected file scoped var");
13359
13360 // If the decl is marked as `declare target to`, it should be emitted for the
13361 // host and for the device.
13362 if (LangOpts.OpenMP &&
13363 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
13364 return true;
13365
13366 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
13368 return false;
13369
13370 if (VD->shouldEmitInExternalSource())
13371 return false;
13372
13373 // Variables that can be needed in other TUs are required.
13376 return true;
13377
13378 // We never need to emit a variable that is available in another TU.
13380 return false;
13381
13382 // Variables that have destruction with side-effects are required.
13383 if (VD->needsDestruction(*this))
13384 return true;
13385
13386 // Variables that have initialization with side-effects are required.
13387 if (VD->hasInitWithSideEffects())
13388 return true;
13389
13390 // Likewise, variables with tuple-like bindings are required if their
13391 // bindings have side-effects.
13392 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) {
13393 for (const auto *BD : DD->flat_bindings())
13394 if (const auto *BindingVD = BD->getHoldingVar())
13395 if (DeclMustBeEmitted(BindingVD))
13396 return true;
13397 }
13398
13399 return false;
13400}
13401
13403 const FunctionDecl *FD,
13404 llvm::function_ref<void(FunctionDecl *)> Pred) const {
13405 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
13406 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
13407 FD = FD->getMostRecentDecl();
13408 // FIXME: The order of traversal here matters and depends on the order of
13409 // lookup results, which happens to be (mostly) oldest-to-newest, but we
13410 // shouldn't rely on that.
13411 for (auto *CurDecl :
13413 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
13414 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
13415 SeenDecls.insert(CurFD).second) {
13416 Pred(CurFD);
13417 }
13418 }
13419}
13420
13422 bool IsCXXMethod) const {
13423 // Pass through to the C++ ABI object
13424 if (IsCXXMethod)
13425 return ABI->getDefaultMethodCallConv(IsVariadic);
13426
13427 switch (LangOpts.getDefaultCallingConv()) {
13429 break;
13431 return CC_C;
13433 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
13434 return CC_X86FastCall;
13435 break;
13437 if (!IsVariadic)
13438 return CC_X86StdCall;
13439 break;
13441 // __vectorcall cannot be applied to variadic functions.
13442 if (!IsVariadic)
13443 return CC_X86VectorCall;
13444 break;
13446 // __regcall cannot be applied to variadic functions.
13447 if (!IsVariadic)
13448 return CC_X86RegCall;
13449 break;
13451 if (!IsVariadic)
13452 return CC_M68kRTD;
13453 break;
13454 }
13455 return Target->getDefaultCallingConv();
13456}
13457
13459 // Pass through to the C++ ABI object
13460 return ABI->isNearlyEmpty(RD);
13461}
13462
13464 if (!VTContext) {
13465 auto ABI = Target->getCXXABI();
13466 if (ABI.isMicrosoft())
13467 VTContext.reset(new MicrosoftVTableContext(*this));
13468 else {
13469 VTContext.reset(new ItaniumVTableContext(*this));
13470 }
13471 }
13472 return VTContext.get();
13473}
13474
13476 if (!T)
13477 T = Target;
13478 switch (T->getCXXABI().getKind()) {
13479 case TargetCXXABI::AppleARM64:
13480 case TargetCXXABI::Fuchsia:
13481 case TargetCXXABI::GenericAArch64:
13482 case TargetCXXABI::GenericItanium:
13483 case TargetCXXABI::GenericARM:
13484 case TargetCXXABI::GenericMIPS:
13485 case TargetCXXABI::iOS:
13486 case TargetCXXABI::WebAssembly:
13487 case TargetCXXABI::WatchOS:
13488 case TargetCXXABI::XL:
13490 case TargetCXXABI::Microsoft:
13492 }
13493 llvm_unreachable("Unsupported ABI");
13494}
13495
13497 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
13498 "Device mangle context does not support Microsoft mangling.");
13499 switch (T.getCXXABI().getKind()) {
13500 case TargetCXXABI::AppleARM64:
13501 case TargetCXXABI::Fuchsia:
13502 case TargetCXXABI::GenericAArch64:
13503 case TargetCXXABI::GenericItanium:
13504 case TargetCXXABI::GenericARM:
13505 case TargetCXXABI::GenericMIPS:
13506 case TargetCXXABI::iOS:
13507 case TargetCXXABI::WebAssembly:
13508 case TargetCXXABI::WatchOS:
13509 case TargetCXXABI::XL:
13511 *this, getDiagnostics(),
13512 [](ASTContext &, const NamedDecl *ND) -> UnsignedOrNone {
13513 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
13514 return RD->getDeviceLambdaManglingNumber();
13515 return std::nullopt;
13516 },
13517 /*IsAux=*/true);
13518 case TargetCXXABI::Microsoft:
13520 /*IsAux=*/true);
13521 }
13522 llvm_unreachable("Unsupported ABI");
13523}
13524
13526 // If the host and device have different C++ ABIs, mark it as the device
13527 // mangle context so that the mangling needs to retrieve the additional
13528 // device lambda mangling number instead of the regular host one.
13529 if (getAuxTargetInfo() && getTargetInfo().getCXXABI().isMicrosoft() &&
13530 getAuxTargetInfo()->getCXXABI().isItaniumFamily()) {
13532 }
13533
13535}
13536
13537CXXABI::~CXXABI() = default;
13538
13540 return ASTRecordLayouts.getMemorySize() +
13541 llvm::capacity_in_bytes(ObjCLayouts) +
13542 llvm::capacity_in_bytes(KeyFunctions) +
13543 llvm::capacity_in_bytes(ObjCImpls) +
13544 llvm::capacity_in_bytes(BlockVarCopyInits) +
13545 llvm::capacity_in_bytes(DeclAttrs) +
13546 llvm::capacity_in_bytes(TemplateOrInstantiation) +
13547 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
13548 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
13549 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
13550 llvm::capacity_in_bytes(OverriddenMethods) +
13551 llvm::capacity_in_bytes(Types) +
13552 llvm::capacity_in_bytes(VariableArrayTypes);
13553}
13554
13555/// getIntTypeForBitwidth -
13556/// sets integer QualTy according to specified details:
13557/// bitwidth, signed/unsigned.
13558/// Returns empty type if there is no appropriate target types.
13560 unsigned Signed) const {
13562 CanQualType QualTy = getFromTargetType(Ty);
13563 if (!QualTy && DestWidth == 128)
13564 return Signed ? Int128Ty : UnsignedInt128Ty;
13565 return QualTy;
13566}
13567
13569 unsigned Signed) const {
13570 return getFromTargetType(
13571 getTargetInfo().getLeastIntTypeByWidth(DestWidth, Signed));
13572}
13573
13574/// getRealTypeForBitwidth -
13575/// sets floating point QualTy according to specified bitwidth.
13576/// Returns empty type if there is no appropriate target types.
13578 FloatModeKind ExplicitType) const {
13579 FloatModeKind Ty =
13580 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
13581 switch (Ty) {
13583 return HalfTy;
13585 return FloatTy;
13587 return DoubleTy;
13589 return LongDoubleTy;
13591 return Float128Ty;
13593 return Ibm128Ty;
13595 return {};
13596 }
13597
13598 llvm_unreachable("Unhandled TargetInfo::RealType value");
13599}
13600
13601void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
13602 if (Number <= 1)
13603 return;
13604
13605 MangleNumbers[ND] = Number;
13606
13607 if (Listener)
13608 Listener->AddedManglingNumber(ND, Number);
13609}
13610
13612 bool ForAuxTarget) const {
13613 auto I = MangleNumbers.find(ND);
13614 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
13615 // CUDA/HIP host compilation encodes host and device mangling numbers
13616 // as lower and upper half of 32 bit integer.
13617 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
13618 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
13619 } else {
13620 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
13621 "number for aux target");
13622 }
13623 return Res > 1 ? Res : 1;
13624}
13625
13626void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
13627 if (Number <= 1)
13628 return;
13629
13630 StaticLocalNumbers[VD] = Number;
13631
13632 if (Listener)
13633 Listener->AddedStaticLocalNumbers(VD, Number);
13634}
13635
13637 auto I = StaticLocalNumbers.find(VD);
13638 return I != StaticLocalNumbers.end() ? I->second : 1;
13639}
13640
13642 bool IsDestroying) {
13643 if (!IsDestroying) {
13644 assert(!DestroyingOperatorDeletes.contains(FD->getCanonicalDecl()));
13645 return;
13646 }
13647 DestroyingOperatorDeletes.insert(FD->getCanonicalDecl());
13648}
13649
13651 return DestroyingOperatorDeletes.contains(FD->getCanonicalDecl());
13652}
13653
13655 bool IsTypeAware) {
13656 if (!IsTypeAware) {
13657 assert(!TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl()));
13658 return;
13659 }
13660 TypeAwareOperatorNewAndDeletes.insert(FD->getCanonicalDecl());
13661}
13662
13664 return TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl());
13665}
13666
13668 FunctionDecl *OperatorDelete,
13669 OperatorDeleteKind K) const {
13670 switch (K) {
13672 OperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] = OperatorDelete;
13673 break;
13675 GlobalOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13676 OperatorDelete;
13677 break;
13679 ArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13680 OperatorDelete;
13681 break;
13683 GlobalArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13684 OperatorDelete;
13685 break;
13686 }
13687}
13688
13690 OperatorDeleteKind K) const {
13691 switch (K) {
13693 return OperatorDeletesForVirtualDtor.contains(Dtor->getCanonicalDecl());
13695 return GlobalOperatorDeletesForVirtualDtor.contains(
13696 Dtor->getCanonicalDecl());
13698 return ArrayOperatorDeletesForVirtualDtor.contains(
13699 Dtor->getCanonicalDecl());
13701 return GlobalArrayOperatorDeletesForVirtualDtor.contains(
13702 Dtor->getCanonicalDecl());
13703 }
13704 return false;
13705}
13706
13709 OperatorDeleteKind K) const {
13710 const CXXDestructorDecl *Canon = Dtor->getCanonicalDecl();
13711 switch (K) {
13713 if (OperatorDeletesForVirtualDtor.contains(Canon))
13714 return OperatorDeletesForVirtualDtor[Canon];
13715 return nullptr;
13717 if (GlobalOperatorDeletesForVirtualDtor.contains(Canon))
13718 return GlobalOperatorDeletesForVirtualDtor[Canon];
13719 return nullptr;
13721 if (ArrayOperatorDeletesForVirtualDtor.contains(Canon))
13722 return ArrayOperatorDeletesForVirtualDtor[Canon];
13723 return nullptr;
13725 if (GlobalArrayOperatorDeletesForVirtualDtor.contains(Canon))
13726 return GlobalArrayOperatorDeletesForVirtualDtor[Canon];
13727 return nullptr;
13728 }
13729 return nullptr;
13730}
13731
13733 const CXXRecordDecl *RD) {
13734 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13735 return false;
13736
13737 return MaybeRequireVectorDeletingDtor.count(RD);
13738}
13739
13741 const CXXRecordDecl *RD) {
13742 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13743 return;
13744
13745 MaybeRequireVectorDeletingDtor.insert(RD);
13746}
13747
13750 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13751 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
13752 if (!MCtx)
13754 return *MCtx;
13755}
13756
13759 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13760 std::unique_ptr<MangleNumberingContext> &MCtx =
13761 ExtraMangleNumberingContexts[D];
13762 if (!MCtx)
13764 return *MCtx;
13765}
13766
13767std::unique_ptr<MangleNumberingContext>
13769 return ABI->createMangleNumberingContext();
13770}
13771
13772const CXXConstructorDecl *
13774 return ABI->getCopyConstructorForExceptionObject(
13776}
13777
13779 CXXConstructorDecl *CD) {
13780 return ABI->addCopyConstructorForExceptionObject(
13783}
13784
13786 TypedefNameDecl *DD) {
13787 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
13788}
13789
13792 return ABI->getTypedefNameForUnnamedTagDecl(TD);
13793}
13794
13796 DeclaratorDecl *DD) {
13797 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
13798}
13799
13801 return ABI->getDeclaratorForUnnamedTagDecl(TD);
13802}
13803
13805 ParamIndices[D] = index;
13806}
13807
13809 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
13810 assert(I != ParamIndices.end() &&
13811 "ParmIndices lacks entry set by ParmVarDecl");
13812 return I->second;
13813}
13814
13816 unsigned Length) const {
13817 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
13818 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
13819 EltTy = EltTy.withConst();
13820
13821 EltTy = adjustStringLiteralBaseType(EltTy);
13822
13823 // Get an array type for the string, according to C99 6.4.5. This includes
13824 // the null terminator character.
13825 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
13826 ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
13827}
13828
13831 StringLiteral *&Result = StringLiteralCache[Key];
13832 if (!Result)
13834 *this, Key, StringLiteralKind::Ordinary,
13835 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
13836 SourceLocation());
13837 return Result;
13838}
13839
13840MSGuidDecl *
13842 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
13843
13844 llvm::FoldingSetNodeID ID;
13845 MSGuidDecl::Profile(ID, Parts);
13846
13847 void *InsertPos;
13848 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
13849 return Existing;
13850
13851 QualType GUIDType = getMSGuidType().withConst();
13852 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
13853 MSGuidDecls.InsertNode(New, InsertPos);
13854 return New;
13855}
13856
13859 const APValue &APVal) const {
13860 llvm::FoldingSetNodeID ID;
13862
13863 void *InsertPos;
13864 if (UnnamedGlobalConstantDecl *Existing =
13865 UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos))
13866 return Existing;
13867
13869 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
13870 UnnamedGlobalConstantDecls.InsertNode(New, InsertPos);
13871 return New;
13872}
13873
13876 assert(T->isRecordType() && "template param object of unexpected type");
13877
13878 // C++ [temp.param]p8:
13879 // [...] a static storage duration object of type 'const T' [...]
13880 T.addConst();
13881
13882 llvm::FoldingSetNodeID ID;
13884
13885 void *InsertPos;
13886 if (TemplateParamObjectDecl *Existing =
13887 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
13888 return Existing;
13889
13890 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
13891 TemplateParamObjectDecls.InsertNode(New, InsertPos);
13892 return New;
13893}
13894
13896 const llvm::Triple &T = getTargetInfo().getTriple();
13897 if (!T.isOSDarwin())
13898 return false;
13899
13900 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
13901 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
13902 return false;
13903
13904 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
13905 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
13906 uint64_t Size = sizeChars.getQuantity();
13907 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
13908 unsigned Align = alignChars.getQuantity();
13909 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
13910 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
13911}
13912
13913bool
13915 const ObjCMethodDecl *MethodImpl) {
13916 // No point trying to match an unavailable/deprecated mothod.
13917 if (MethodDecl->hasAttr<UnavailableAttr>()
13918 || MethodDecl->hasAttr<DeprecatedAttr>())
13919 return false;
13920 if (MethodDecl->getObjCDeclQualifier() !=
13921 MethodImpl->getObjCDeclQualifier())
13922 return false;
13923 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
13924 return false;
13925
13926 if (MethodDecl->param_size() != MethodImpl->param_size())
13927 return false;
13928
13929 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
13930 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
13931 EF = MethodDecl->param_end();
13932 IM != EM && IF != EF; ++IM, ++IF) {
13933 const ParmVarDecl *DeclVar = (*IF);
13934 const ParmVarDecl *ImplVar = (*IM);
13935 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
13936 return false;
13937 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
13938 return false;
13939 }
13940
13941 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
13942}
13943
13945 LangAS AS;
13947 AS = LangAS::Default;
13948 else
13949 AS = QT->getPointeeType().getAddressSpace();
13950
13952}
13953
13956}
13957
13958bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
13959 if (X == Y)
13960 return true;
13961 if (!X || !Y)
13962 return false;
13963 llvm::FoldingSetNodeID IDX, IDY;
13964 X->Profile(IDX, *this, /*Canonical=*/true);
13965 Y->Profile(IDY, *this, /*Canonical=*/true);
13966 return IDX == IDY;
13967}
13968
13969// The getCommon* helpers return, for given 'same' X and Y entities given as
13970// inputs, another entity which is also the 'same' as the inputs, but which
13971// is closer to the canonical form of the inputs, each according to a given
13972// criteria.
13973// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
13974// the regular ones.
13975
13977 if (!declaresSameEntity(X, Y))
13978 return nullptr;
13979 for (const Decl *DX : X->redecls()) {
13980 // If we reach Y before reaching the first decl, that means X is older.
13981 if (DX == Y)
13982 return X;
13983 // If we reach the first decl, then Y is older.
13984 if (DX->isFirstDecl())
13985 return Y;
13986 }
13987 llvm_unreachable("Corrupt redecls chain");
13988}
13989
13990template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13991static T *getCommonDecl(T *X, T *Y) {
13992 return cast_or_null<T>(
13993 getCommonDecl(const_cast<Decl *>(cast_or_null<Decl>(X)),
13994 const_cast<Decl *>(cast_or_null<Decl>(Y))));
13995}
13996
13997template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13998static T *getCommonDeclChecked(T *X, T *Y) {
13999 return cast<T>(getCommonDecl(const_cast<Decl *>(cast<Decl>(X)),
14000 const_cast<Decl *>(cast<Decl>(Y))));
14001}
14002
14004 TemplateName Y,
14005 bool IgnoreDeduced = false) {
14006 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
14007 return X;
14008 // FIXME: There are cases here where we could find a common template name
14009 // with more sugar. For example one could be a SubstTemplateTemplate*
14010 // replacing the other.
14011 TemplateName CX = Ctx.getCanonicalTemplateName(X, IgnoreDeduced);
14012 if (CX.getAsVoidPointer() !=
14014 return TemplateName();
14015 return CX;
14016}
14017
14020 bool IgnoreDeduced) {
14021 TemplateName R = getCommonTemplateName(Ctx, X, Y, IgnoreDeduced);
14022 assert(R.getAsVoidPointer() != nullptr);
14023 return R;
14024}
14025
14027 ArrayRef<QualType> Ys, bool Unqualified = false) {
14028 assert(Xs.size() == Ys.size());
14029 SmallVector<QualType, 8> Rs(Xs.size());
14030 for (size_t I = 0; I < Rs.size(); ++I)
14031 Rs[I] = Ctx.getCommonSugaredType(Xs[I], Ys[I], Unqualified);
14032 return Rs;
14033}
14034
14035template <class T>
14036static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
14037 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
14038 : SourceLocation();
14039}
14040
14042 const TemplateArgument &X,
14043 const TemplateArgument &Y) {
14044 if (X.getKind() != Y.getKind())
14045 return TemplateArgument();
14046
14047 switch (X.getKind()) {
14049 if (!Ctx.hasSameType(X.getAsType(), Y.getAsType()))
14050 return TemplateArgument();
14051 return TemplateArgument(
14052 Ctx.getCommonSugaredType(X.getAsType(), Y.getAsType()));
14054 if (!Ctx.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
14055 return TemplateArgument();
14056 return TemplateArgument(
14057 Ctx.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
14058 /*Unqualified=*/true);
14060 if (!Ctx.hasSameType(X.getAsExpr()->getType(), Y.getAsExpr()->getType()))
14061 return TemplateArgument();
14062 // FIXME: Try to keep the common sugar.
14063 return X;
14065 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
14066 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
14067 if (!CTN.getAsVoidPointer())
14068 return TemplateArgument();
14069 return TemplateArgument(CTN);
14070 }
14072 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
14074 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
14075 if (!CTN.getAsVoidPointer())
14076 return TemplateName();
14077 auto NExpX = X.getNumTemplateExpansions();
14078 assert(NExpX == Y.getNumTemplateExpansions());
14079 return TemplateArgument(CTN, NExpX);
14080 }
14081 default:
14082 // FIXME: Handle the other argument kinds.
14083 return X;
14084 }
14085}
14086
14091 if (Xs.size() != Ys.size())
14092 return true;
14093 R.resize(Xs.size());
14094 for (size_t I = 0; I < R.size(); ++I) {
14095 R[I] = getCommonTemplateArgument(Ctx, Xs[I], Ys[I]);
14096 if (R[I].isNull())
14097 return true;
14098 }
14099 return false;
14100}
14101
14106 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
14107 assert(!Different);
14108 (void)Different;
14109 return R;
14110}
14111
14112template <class T>
14114 bool IsSame) {
14115 ElaboratedTypeKeyword KX = X->getKeyword(), KY = Y->getKeyword();
14116 if (KX == KY)
14117 return KX;
14119 assert(!IsSame || KX == getCanonicalElaboratedTypeKeyword(KY));
14120 return KX;
14121}
14122
14123/// Returns a NestedNameSpecifier which has only the common sugar
14124/// present in both NNS1 and NNS2.
14127 NestedNameSpecifier NNS2, bool IsSame) {
14128 // If they are identical, all sugar is common.
14129 if (NNS1 == NNS2)
14130 return NNS1;
14131
14132 // IsSame implies both Qualifiers are equivalent.
14133 NestedNameSpecifier Canon = NNS1.getCanonical();
14134 if (Canon != NNS2.getCanonical()) {
14135 assert(!IsSame && "Should be the same NestedNameSpecifier");
14136 // If they are not the same, there is nothing to unify.
14137 return std::nullopt;
14138 }
14139
14140 NestedNameSpecifier R = std::nullopt;
14141 NestedNameSpecifier::Kind Kind = NNS1.getKind();
14142 assert(Kind == NNS2.getKind());
14143 switch (Kind) {
14145 auto [Namespace1, Prefix1] = NNS1.getAsNamespaceAndPrefix();
14146 auto [Namespace2, Prefix2] = NNS2.getAsNamespaceAndPrefix();
14147 auto Kind = Namespace1->getKind();
14148 if (Kind != Namespace2->getKind() ||
14149 (Kind == Decl::NamespaceAlias &&
14150 !declaresSameEntity(Namespace1, Namespace2))) {
14152 Ctx,
14153 ::getCommonDeclChecked(Namespace1->getNamespace(),
14154 Namespace2->getNamespace()),
14155 /*Prefix=*/std::nullopt);
14156 break;
14157 }
14158 // The prefixes for namespaces are not significant, its declaration
14159 // identifies it uniquely.
14160 NestedNameSpecifier Prefix = ::getCommonNNS(Ctx, Prefix1, Prefix2,
14161 /*IsSame=*/false);
14162 R = NestedNameSpecifier(Ctx, ::getCommonDeclChecked(Namespace1, Namespace2),
14163 Prefix);
14164 break;
14165 }
14167 const Type *T1 = NNS1.getAsType(), *T2 = NNS2.getAsType();
14168 const Type *T = Ctx.getCommonSugaredType(QualType(T1, 0), QualType(T2, 0),
14169 /*Unqualified=*/true)
14170 .getTypePtr();
14171 R = NestedNameSpecifier(T);
14172 break;
14173 }
14175 // FIXME: Can __super even be used with data members?
14176 // If it's only usable in functions, we will never see it here,
14177 // unless we save the qualifiers used in function types.
14178 // In that case, it might be possible NNS2 is a type,
14179 // in which case we should degrade the result to
14180 // a CXXRecordType.
14182 NNS2.getAsMicrosoftSuper()));
14183 break;
14184 }
14187 // These are singletons.
14188 llvm_unreachable("singletons did not compare equal");
14189 }
14190 assert(R.getCanonical() == Canon);
14191 return R;
14192}
14193
14194template <class T>
14196 const T *Y, bool IsSame) {
14197 return ::getCommonNNS(Ctx, X->getQualifier(), Y->getQualifier(), IsSame);
14198}
14199
14200template <class T>
14201static QualType getCommonElementType(const ASTContext &Ctx, const T *X,
14202 const T *Y) {
14203 return Ctx.getCommonSugaredType(X->getElementType(), Y->getElementType());
14204}
14205
14207 QualType X, QualType Y,
14208 Qualifiers &QX,
14209 Qualifiers &QY) {
14210 QualType R = Ctx.getCommonSugaredType(X, Y,
14211 /*Unqualified=*/true);
14212 // Qualifiers common to both element types.
14213 Qualifiers RQ = R.getQualifiers();
14214 // For each side, move to the top level any qualifiers which are not common to
14215 // both element types. The caller must assume top level qualifiers might
14216 // be different, even if they are the same type, and can be treated as sugar.
14217 QX += X.getQualifiers() - RQ;
14218 QY += Y.getQualifiers() - RQ;
14219 return R;
14220}
14221
14222template <class T>
14224 Qualifiers &QX, const T *Y,
14225 Qualifiers &QY) {
14226 return getCommonTypeWithQualifierLifting(Ctx, X->getElementType(),
14227 Y->getElementType(), QX, QY);
14228}
14229
14230template <class T>
14231static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X,
14232 const T *Y) {
14233 return Ctx.getCommonSugaredType(X->getPointeeType(), Y->getPointeeType());
14234}
14235
14236template <class T>
14237static auto *getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y) {
14238 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
14239 return X->getSizeExpr();
14240}
14241
14242static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
14243 assert(X->getSizeModifier() == Y->getSizeModifier());
14244 return X->getSizeModifier();
14245}
14246
14248 const ArrayType *Y) {
14249 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
14250 return X->getIndexTypeCVRQualifiers();
14251}
14252
14253// Merges two type lists such that the resulting vector will contain
14254// each type (in a canonical sense) only once, in the order they appear
14255// from X to Y. If they occur in both X and Y, the result will contain
14256// the common sugared type between them.
14257static void mergeTypeLists(const ASTContext &Ctx,
14260 llvm::DenseMap<QualType, unsigned> Found;
14261 for (auto Ts : {X, Y}) {
14262 for (QualType T : Ts) {
14263 auto Res = Found.try_emplace(Ctx.getCanonicalType(T), Out.size());
14264 if (!Res.second) {
14265 QualType &U = Out[Res.first->second];
14266 U = Ctx.getCommonSugaredType(U, T);
14267 } else {
14268 Out.emplace_back(T);
14269 }
14270 }
14271 }
14272}
14273
14274FunctionProtoType::ExceptionSpecInfo
14277 SmallVectorImpl<QualType> &ExceptionTypeStorage,
14278 bool AcceptDependent) const {
14279 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
14280
14281 // If either of them can throw anything, that is the result.
14282 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
14283 if (EST1 == I)
14284 return ESI1;
14285 if (EST2 == I)
14286 return ESI2;
14287 }
14288
14289 // If either of them is non-throwing, the result is the other.
14290 for (auto I :
14292 if (EST1 == I)
14293 return ESI2;
14294 if (EST2 == I)
14295 return ESI1;
14296 }
14297
14298 // If we're left with value-dependent computed noexcept expressions, we're
14299 // stuck. Before C++17, we can just drop the exception specification entirely,
14300 // since it's not actually part of the canonical type. And this should never
14301 // happen in C++17, because it would mean we were computing the composite
14302 // pointer type of dependent types, which should never happen.
14303 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
14304 assert(AcceptDependent &&
14305 "computing composite pointer type of dependent types");
14307 }
14308
14309 // Switch over the possibilities so that people adding new values know to
14310 // update this function.
14311 switch (EST1) {
14312 case EST_None:
14313 case EST_DynamicNone:
14314 case EST_MSAny:
14315 case EST_BasicNoexcept:
14317 case EST_NoexceptFalse:
14318 case EST_NoexceptTrue:
14319 case EST_NoThrow:
14320 llvm_unreachable("These ESTs should be handled above");
14321
14322 case EST_Dynamic: {
14323 // This is the fun case: both exception specifications are dynamic. Form
14324 // the union of the two lists.
14325 assert(EST2 == EST_Dynamic && "other cases should already be handled");
14326 mergeTypeLists(*this, ExceptionTypeStorage, ESI1.Exceptions,
14327 ESI2.Exceptions);
14329 Result.Exceptions = ExceptionTypeStorage;
14330 return Result;
14331 }
14332
14333 case EST_Unevaluated:
14334 case EST_Uninstantiated:
14335 case EST_Unparsed:
14336 llvm_unreachable("shouldn't see unresolved exception specifications here");
14337 }
14338
14339 llvm_unreachable("invalid ExceptionSpecificationType");
14340}
14341
14343 Qualifiers &QX, const Type *Y,
14344 Qualifiers &QY) {
14345 Type::TypeClass TC = X->getTypeClass();
14346 assert(TC == Y->getTypeClass());
14347 switch (TC) {
14348#define UNEXPECTED_TYPE(Class, Kind) \
14349 case Type::Class: \
14350 llvm_unreachable("Unexpected " Kind ": " #Class);
14351
14352#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
14353#define TYPE(Class, Base)
14354#include "clang/AST/TypeNodes.inc"
14355
14356#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
14358 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
14359 SUGAR_FREE_TYPE(DependentBitInt)
14361 SUGAR_FREE_TYPE(ObjCInterface)
14362 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
14363 SUGAR_FREE_TYPE(SubstBuiltinTemplatePack)
14364 SUGAR_FREE_TYPE(UnresolvedUsing)
14365 SUGAR_FREE_TYPE(HLSLAttributedResource)
14366 SUGAR_FREE_TYPE(HLSLInlineSpirv)
14367#undef SUGAR_FREE_TYPE
14368#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
14369 NON_UNIQUE_TYPE(TypeOfExpr)
14370 NON_UNIQUE_TYPE(VariableArray)
14371#undef NON_UNIQUE_TYPE
14372
14373 UNEXPECTED_TYPE(TypeOf, "sugar")
14374
14375#undef UNEXPECTED_TYPE
14376
14377 case Type::Auto: {
14378 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14379 assert(AX->getDeducedKind() == AY->getDeducedKind());
14380 assert(AX->getDeducedKind() != DeducedKind::Deduced);
14381 assert(AX->getKeyword() == AY->getKeyword());
14382 TemplateDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(),
14383 AY->getTypeConstraintConcept());
14385 if (CD &&
14386 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
14387 AY->getTypeConstraintArguments())) {
14388 CD = nullptr; // The arguments differ, so make it unconstrained.
14389 As.clear();
14390 }
14391 return Ctx.getAutoType(AX->getDeducedKind(), QualType(), AX->getKeyword(),
14392 CD, As);
14393 }
14394 case Type::IncompleteArray: {
14395 const auto *AX = cast<IncompleteArrayType>(X),
14397 return Ctx.getIncompleteArrayType(
14398 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14400 }
14401 case Type::DependentSizedArray: {
14402 const auto *AX = cast<DependentSizedArrayType>(X),
14404 return Ctx.getDependentSizedArrayType(
14405 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14406 getCommonSizeExpr(Ctx, AX, AY), getCommonSizeModifier(AX, AY),
14408 }
14409 case Type::ConstantArray: {
14410 const auto *AX = cast<ConstantArrayType>(X),
14411 *AY = cast<ConstantArrayType>(Y);
14412 assert(AX->getSize() == AY->getSize());
14413 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14414 ? AX->getSizeExpr()
14415 : nullptr;
14416 return Ctx.getConstantArrayType(
14417 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14419 }
14420 case Type::ArrayParameter: {
14421 const auto *AX = cast<ArrayParameterType>(X),
14422 *AY = cast<ArrayParameterType>(Y);
14423 assert(AX->getSize() == AY->getSize());
14424 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14425 ? AX->getSizeExpr()
14426 : nullptr;
14427 auto ArrayTy = Ctx.getConstantArrayType(
14428 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14430 return Ctx.getArrayParameterType(ArrayTy);
14431 }
14432 case Type::Atomic: {
14433 const auto *AX = cast<AtomicType>(X), *AY = cast<AtomicType>(Y);
14434 return Ctx.getAtomicType(
14435 Ctx.getCommonSugaredType(AX->getValueType(), AY->getValueType()));
14436 }
14437 case Type::Complex: {
14438 const auto *CX = cast<ComplexType>(X), *CY = cast<ComplexType>(Y);
14439 return Ctx.getComplexType(getCommonArrayElementType(Ctx, CX, QX, CY, QY));
14440 }
14441 case Type::Pointer: {
14442 const auto *PX = cast<PointerType>(X), *PY = cast<PointerType>(Y);
14443 return Ctx.getPointerType(getCommonPointeeType(Ctx, PX, PY));
14444 }
14445 case Type::BlockPointer: {
14446 const auto *PX = cast<BlockPointerType>(X), *PY = cast<BlockPointerType>(Y);
14447 return Ctx.getBlockPointerType(getCommonPointeeType(Ctx, PX, PY));
14448 }
14449 case Type::ObjCObjectPointer: {
14450 const auto *PX = cast<ObjCObjectPointerType>(X),
14452 return Ctx.getObjCObjectPointerType(getCommonPointeeType(Ctx, PX, PY));
14453 }
14454 case Type::MemberPointer: {
14455 const auto *PX = cast<MemberPointerType>(X),
14456 *PY = cast<MemberPointerType>(Y);
14457 assert(declaresSameEntity(PX->getMostRecentCXXRecordDecl(),
14458 PY->getMostRecentCXXRecordDecl()));
14459 return Ctx.getMemberPointerType(
14460 getCommonPointeeType(Ctx, PX, PY),
14461 getCommonQualifier(Ctx, PX, PY, /*IsSame=*/true),
14462 PX->getMostRecentCXXRecordDecl());
14463 }
14464 case Type::LValueReference: {
14465 const auto *PX = cast<LValueReferenceType>(X),
14467 // FIXME: Preserve PointeeTypeAsWritten.
14468 return Ctx.getLValueReferenceType(getCommonPointeeType(Ctx, PX, PY),
14469 PX->isSpelledAsLValue() ||
14470 PY->isSpelledAsLValue());
14471 }
14472 case Type::RValueReference: {
14473 const auto *PX = cast<RValueReferenceType>(X),
14475 // FIXME: Preserve PointeeTypeAsWritten.
14476 return Ctx.getRValueReferenceType(getCommonPointeeType(Ctx, PX, PY));
14477 }
14478 case Type::DependentAddressSpace: {
14479 const auto *PX = cast<DependentAddressSpaceType>(X),
14481 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
14482 return Ctx.getDependentAddressSpaceType(getCommonPointeeType(Ctx, PX, PY),
14483 PX->getAddrSpaceExpr(),
14484 getCommonAttrLoc(PX, PY));
14485 }
14486 case Type::FunctionNoProto: {
14487 const auto *FX = cast<FunctionNoProtoType>(X),
14489 assert(FX->getExtInfo() == FY->getExtInfo());
14490 return Ctx.getFunctionNoProtoType(
14491 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType()),
14492 FX->getExtInfo());
14493 }
14494 case Type::FunctionProto: {
14495 const auto *FX = cast<FunctionProtoType>(X),
14496 *FY = cast<FunctionProtoType>(Y);
14497 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
14498 EPIY = FY->getExtProtoInfo();
14499 assert(EPIX.ExtInfo == EPIY.ExtInfo);
14500 assert(!EPIX.ExtParameterInfos == !EPIY.ExtParameterInfos);
14501 assert(!EPIX.ExtParameterInfos ||
14502 llvm::equal(
14503 llvm::ArrayRef(EPIX.ExtParameterInfos, FX->getNumParams()),
14504 llvm::ArrayRef(EPIY.ExtParameterInfos, FY->getNumParams())));
14505 assert(EPIX.RefQualifier == EPIY.RefQualifier);
14506 assert(EPIX.TypeQuals == EPIY.TypeQuals);
14507 assert(EPIX.Variadic == EPIY.Variadic);
14508
14509 // FIXME: Can we handle an empty EllipsisLoc?
14510 // Use emtpy EllipsisLoc if X and Y differ.
14511
14512 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
14513
14514 QualType R =
14515 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType());
14516 auto P = getCommonTypes(Ctx, FX->param_types(), FY->param_types(),
14517 /*Unqualified=*/true);
14518
14519 SmallVector<QualType, 8> Exceptions;
14521 EPIX.ExceptionSpec, EPIY.ExceptionSpec, Exceptions, true);
14522 return Ctx.getFunctionType(R, P, EPIX);
14523 }
14524 case Type::ObjCObject: {
14525 const auto *OX = cast<ObjCObjectType>(X), *OY = cast<ObjCObjectType>(Y);
14526 assert(
14527 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
14528 OY->getProtocols().begin(), OY->getProtocols().end(),
14529 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
14530 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
14531 }) &&
14532 "protocol lists must be the same");
14533 auto TAs = getCommonTypes(Ctx, OX->getTypeArgsAsWritten(),
14534 OY->getTypeArgsAsWritten());
14535 return Ctx.getObjCObjectType(
14536 Ctx.getCommonSugaredType(OX->getBaseType(), OY->getBaseType()), TAs,
14537 OX->getProtocols(),
14538 OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
14539 }
14540 case Type::ConstantMatrix: {
14541 const auto *MX = cast<ConstantMatrixType>(X),
14542 *MY = cast<ConstantMatrixType>(Y);
14543 assert(MX->getNumRows() == MY->getNumRows());
14544 assert(MX->getNumColumns() == MY->getNumColumns());
14545 return Ctx.getConstantMatrixType(getCommonElementType(Ctx, MX, MY),
14546 MX->getNumRows(), MX->getNumColumns());
14547 }
14548 case Type::DependentSizedMatrix: {
14549 const auto *MX = cast<DependentSizedMatrixType>(X),
14551 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
14552 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
14553 return Ctx.getDependentSizedMatrixType(
14554 getCommonElementType(Ctx, MX, MY), MX->getRowExpr(),
14555 MX->getColumnExpr(), getCommonAttrLoc(MX, MY));
14556 }
14557 case Type::Vector: {
14558 const auto *VX = cast<VectorType>(X), *VY = cast<VectorType>(Y);
14559 assert(VX->getNumElements() == VY->getNumElements());
14560 assert(VX->getVectorKind() == VY->getVectorKind());
14561 return Ctx.getVectorType(getCommonElementType(Ctx, VX, VY),
14562 VX->getNumElements(), VX->getVectorKind());
14563 }
14564 case Type::ExtVector: {
14565 const auto *VX = cast<ExtVectorType>(X), *VY = cast<ExtVectorType>(Y);
14566 assert(VX->getNumElements() == VY->getNumElements());
14567 return Ctx.getExtVectorType(getCommonElementType(Ctx, VX, VY),
14568 VX->getNumElements());
14569 }
14570 case Type::DependentSizedExtVector: {
14571 const auto *VX = cast<DependentSizedExtVectorType>(X),
14574 getCommonSizeExpr(Ctx, VX, VY),
14575 getCommonAttrLoc(VX, VY));
14576 }
14577 case Type::DependentVector: {
14578 const auto *VX = cast<DependentVectorType>(X),
14580 assert(VX->getVectorKind() == VY->getVectorKind());
14581 return Ctx.getDependentVectorType(
14582 getCommonElementType(Ctx, VX, VY), getCommonSizeExpr(Ctx, VX, VY),
14583 getCommonAttrLoc(VX, VY), VX->getVectorKind());
14584 }
14585 case Type::Enum:
14586 case Type::Record:
14587 case Type::InjectedClassName: {
14588 const auto *TX = cast<TagType>(X), *TY = cast<TagType>(Y);
14589 return Ctx.getTagType(::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14590 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false),
14591 ::getCommonDeclChecked(TX->getDecl(), TY->getDecl()),
14592 /*OwnedTag=*/false);
14593 }
14594 case Type::TemplateSpecialization: {
14595 const auto *TX = cast<TemplateSpecializationType>(X),
14597 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
14598 TY->template_arguments());
14600 getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14601 ::getCommonTemplateNameChecked(Ctx, TX->getTemplateName(),
14602 TY->getTemplateName(),
14603 /*IgnoreDeduced=*/true),
14604 As, /*CanonicalArgs=*/{}, X->getCanonicalTypeInternal());
14605 }
14606 case Type::Decltype: {
14607 const auto *DX = cast<DecltypeType>(X);
14608 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Y);
14609 assert(DX->isDependentType());
14610 assert(DY->isDependentType());
14611 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
14612 // As Decltype is not uniqued, building a common type would be wasteful.
14613 return QualType(DX, 0);
14614 }
14615 case Type::PackIndexing: {
14616 const auto *DX = cast<PackIndexingType>(X);
14617 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Y);
14618 assert(DX->isDependentType());
14619 assert(DY->isDependentType());
14620 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
14621 return QualType(DX, 0);
14622 }
14623 case Type::DependentName: {
14624 const auto *NX = cast<DependentNameType>(X),
14625 *NY = cast<DependentNameType>(Y);
14626 assert(NX->getIdentifier() == NY->getIdentifier());
14627 return Ctx.getDependentNameType(
14628 getCommonTypeKeyword(NX, NY, /*IsSame=*/true),
14629 getCommonQualifier(Ctx, NX, NY, /*IsSame=*/true), NX->getIdentifier());
14630 }
14631 case Type::OverflowBehavior: {
14632 const auto *NX = cast<OverflowBehaviorType>(X),
14634 assert(NX->getBehaviorKind() == NY->getBehaviorKind());
14635 return Ctx.getOverflowBehaviorType(
14636 NX->getBehaviorKind(),
14637 getCommonTypeWithQualifierLifting(Ctx, NX->getUnderlyingType(),
14638 NY->getUnderlyingType(), QX, QY));
14639 }
14640 case Type::UnaryTransform: {
14641 const auto *TX = cast<UnaryTransformType>(X),
14642 *TY = cast<UnaryTransformType>(Y);
14643 assert(TX->getUTTKind() == TY->getUTTKind());
14644 return Ctx.getUnaryTransformType(
14645 Ctx.getCommonSugaredType(TX->getBaseType(), TY->getBaseType()),
14646 Ctx.getCommonSugaredType(TX->getUnderlyingType(),
14647 TY->getUnderlyingType()),
14648 TX->getUTTKind());
14649 }
14650 case Type::PackExpansion: {
14651 const auto *PX = cast<PackExpansionType>(X),
14652 *PY = cast<PackExpansionType>(Y);
14653 assert(PX->getNumExpansions() == PY->getNumExpansions());
14654 return Ctx.getPackExpansionType(
14655 Ctx.getCommonSugaredType(PX->getPattern(), PY->getPattern()),
14656 PX->getNumExpansions(), false);
14657 }
14658 case Type::Pipe: {
14659 const auto *PX = cast<PipeType>(X), *PY = cast<PipeType>(Y);
14660 assert(PX->isReadOnly() == PY->isReadOnly());
14661 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
14663 return (Ctx.*MP)(getCommonElementType(Ctx, PX, PY));
14664 }
14665 case Type::TemplateTypeParm: {
14666 const auto *TX = cast<TemplateTypeParmType>(X),
14668 assert(TX->getDepth() == TY->getDepth());
14669 assert(TX->getIndex() == TY->getIndex());
14670 assert(TX->isParameterPack() == TY->isParameterPack());
14671 return Ctx.getTemplateTypeParmType(
14672 TX->getDepth(), TX->getIndex(), TX->isParameterPack(),
14673 getCommonDecl(TX->getDecl(), TY->getDecl()));
14674 }
14675 }
14676 llvm_unreachable("Unknown Type Class");
14677}
14678
14680 const Type *Y,
14681 SplitQualType Underlying) {
14682 Type::TypeClass TC = X->getTypeClass();
14683 if (TC != Y->getTypeClass())
14684 return QualType();
14685 switch (TC) {
14686#define UNEXPECTED_TYPE(Class, Kind) \
14687 case Type::Class: \
14688 llvm_unreachable("Unexpected " Kind ": " #Class);
14689#define TYPE(Class, Base)
14690#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
14691#include "clang/AST/TypeNodes.inc"
14692
14693#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
14696 CANONICAL_TYPE(BlockPointer)
14699 CANONICAL_TYPE(ConstantArray)
14700 CANONICAL_TYPE(ArrayParameter)
14701 CANONICAL_TYPE(ConstantMatrix)
14703 CANONICAL_TYPE(ExtVector)
14704 CANONICAL_TYPE(FunctionNoProto)
14705 CANONICAL_TYPE(FunctionProto)
14706 CANONICAL_TYPE(IncompleteArray)
14707 CANONICAL_TYPE(HLSLAttributedResource)
14708 CANONICAL_TYPE(HLSLInlineSpirv)
14709 CANONICAL_TYPE(LValueReference)
14710 CANONICAL_TYPE(ObjCInterface)
14711 CANONICAL_TYPE(ObjCObject)
14712 CANONICAL_TYPE(ObjCObjectPointer)
14713 CANONICAL_TYPE(OverflowBehavior)
14717 CANONICAL_TYPE(RValueReference)
14718 CANONICAL_TYPE(VariableArray)
14720#undef CANONICAL_TYPE
14721
14722#undef UNEXPECTED_TYPE
14723
14724 case Type::Adjusted: {
14725 const auto *AX = cast<AdjustedType>(X), *AY = cast<AdjustedType>(Y);
14726 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
14727 if (!Ctx.hasSameType(OX, OY))
14728 return QualType();
14729 // FIXME: It's inefficient to have to unify the original types.
14730 return Ctx.getAdjustedType(Ctx.getCommonSugaredType(OX, OY),
14731 Ctx.getQualifiedType(Underlying));
14732 }
14733 case Type::Decayed: {
14734 const auto *DX = cast<DecayedType>(X), *DY = cast<DecayedType>(Y);
14735 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
14736 if (!Ctx.hasSameType(OX, OY))
14737 return QualType();
14738 // FIXME: It's inefficient to have to unify the original types.
14739 return Ctx.getDecayedType(Ctx.getCommonSugaredType(OX, OY),
14740 Ctx.getQualifiedType(Underlying));
14741 }
14742 case Type::Attributed: {
14743 const auto *AX = cast<AttributedType>(X), *AY = cast<AttributedType>(Y);
14744 AttributedType::Kind Kind = AX->getAttrKind();
14745 if (Kind != AY->getAttrKind())
14746 return QualType();
14747 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
14748 if (!Ctx.hasSameType(MX, MY))
14749 return QualType();
14750 // FIXME: It's inefficient to have to unify the modified types.
14751 return Ctx.getAttributedType(Kind, Ctx.getCommonSugaredType(MX, MY),
14752 Ctx.getQualifiedType(Underlying),
14753 AX->getAttr());
14754 }
14755 case Type::BTFTagAttributed: {
14756 const auto *BX = cast<BTFTagAttributedType>(X);
14757 const BTFTypeTagAttr *AX = BX->getAttr();
14758 // The attribute is not uniqued, so just compare the tag.
14759 if (AX->getBTFTypeTag() !=
14760 cast<BTFTagAttributedType>(Y)->getAttr()->getBTFTypeTag())
14761 return QualType();
14762 return Ctx.getBTFTagAttributedType(AX, Ctx.getQualifiedType(Underlying));
14763 }
14764 case Type::Auto: {
14765 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14766 assert(AX->getDeducedKind() == DeducedKind::Deduced);
14767 assert(AY->getDeducedKind() == DeducedKind::Deduced);
14768
14769 AutoTypeKeyword KW = AX->getKeyword();
14770 if (KW != AY->getKeyword())
14771 return QualType();
14772
14773 TemplateDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(),
14774 AY->getTypeConstraintConcept());
14776 if (CD &&
14777 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
14778 AY->getTypeConstraintArguments())) {
14779 CD = nullptr; // The arguments differ, so make it unconstrained.
14780 As.clear();
14781 }
14782
14783 // Both auto types can't be dependent, otherwise they wouldn't have been
14784 // sugar. This implies they can't contain unexpanded packs either.
14786 Ctx.getQualifiedType(Underlying), AX->getKeyword(),
14787 CD, As);
14788 }
14789 case Type::PackIndexing:
14790 case Type::Decltype:
14791 return QualType();
14792 case Type::DeducedTemplateSpecialization:
14793 // FIXME: Try to merge these.
14794 return QualType();
14795 case Type::MacroQualified: {
14796 const auto *MX = cast<MacroQualifiedType>(X),
14797 *MY = cast<MacroQualifiedType>(Y);
14798 const IdentifierInfo *IX = MX->getMacroIdentifier();
14799 if (IX != MY->getMacroIdentifier())
14800 return QualType();
14801 return Ctx.getMacroQualifiedType(Ctx.getQualifiedType(Underlying), IX);
14802 }
14803 case Type::SubstTemplateTypeParm: {
14804 const auto *SX = cast<SubstTemplateTypeParmType>(X),
14806 Decl *CD =
14807 ::getCommonDecl(SX->getAssociatedDecl(), SY->getAssociatedDecl());
14808 if (!CD)
14809 return QualType();
14810 unsigned Index = SX->getIndex();
14811 if (Index != SY->getIndex())
14812 return QualType();
14813 auto PackIndex = SX->getPackIndex();
14814 if (PackIndex != SY->getPackIndex())
14815 return QualType();
14816 return Ctx.getSubstTemplateTypeParmType(Ctx.getQualifiedType(Underlying),
14817 CD, Index, PackIndex,
14818 SX->getFinal() && SY->getFinal());
14819 }
14820 case Type::ObjCTypeParam:
14821 // FIXME: Try to merge these.
14822 return QualType();
14823 case Type::Paren:
14824 return Ctx.getParenType(Ctx.getQualifiedType(Underlying));
14825
14826 case Type::TemplateSpecialization: {
14827 const auto *TX = cast<TemplateSpecializationType>(X),
14829 TemplateName CTN =
14830 ::getCommonTemplateName(Ctx, TX->getTemplateName(),
14831 TY->getTemplateName(), /*IgnoreDeduced=*/true);
14832 if (!CTN.getAsVoidPointer())
14833 return QualType();
14835 if (getCommonTemplateArguments(Ctx, As, TX->template_arguments(),
14836 TY->template_arguments()))
14837 return QualType();
14839 getCommonTypeKeyword(TX, TY, /*IsSame=*/false), CTN, As,
14840 /*CanonicalArgs=*/{}, Ctx.getQualifiedType(Underlying));
14841 }
14842 case Type::Typedef: {
14843 const auto *TX = cast<TypedefType>(X), *TY = cast<TypedefType>(Y);
14844 const TypedefNameDecl *CD = ::getCommonDecl(TX->getDecl(), TY->getDecl());
14845 if (!CD)
14846 return QualType();
14847 return Ctx.getTypedefType(
14848 ::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14849 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false), CD,
14850 Ctx.getQualifiedType(Underlying));
14851 }
14852 case Type::TypeOf: {
14853 // The common sugar between two typeof expressions, where one is
14854 // potentially a typeof_unqual and the other is not, we unify to the
14855 // qualified type as that retains the most information along with the type.
14856 // We only return a typeof_unqual type when both types are unqual types.
14861 return Ctx.getTypeOfType(Ctx.getQualifiedType(Underlying), Kind);
14862 }
14863 case Type::TypeOfExpr:
14864 return QualType();
14865
14866 case Type::UnaryTransform: {
14867 const auto *UX = cast<UnaryTransformType>(X),
14868 *UY = cast<UnaryTransformType>(Y);
14869 UnaryTransformType::UTTKind KX = UX->getUTTKind();
14870 if (KX != UY->getUTTKind())
14871 return QualType();
14872 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
14873 if (!Ctx.hasSameType(BX, BY))
14874 return QualType();
14875 // FIXME: It's inefficient to have to unify the base types.
14876 return Ctx.getUnaryTransformType(Ctx.getCommonSugaredType(BX, BY),
14877 Ctx.getQualifiedType(Underlying), KX);
14878 }
14879 case Type::Using: {
14880 const auto *UX = cast<UsingType>(X), *UY = cast<UsingType>(Y);
14881 const UsingShadowDecl *CD = ::getCommonDecl(UX->getDecl(), UY->getDecl());
14882 if (!CD)
14883 return QualType();
14884 return Ctx.getUsingType(::getCommonTypeKeyword(UX, UY, /*IsSame=*/false),
14885 ::getCommonQualifier(Ctx, UX, UY, /*IsSame=*/false),
14886 CD, Ctx.getQualifiedType(Underlying));
14887 }
14888 case Type::MemberPointer: {
14889 const auto *PX = cast<MemberPointerType>(X),
14890 *PY = cast<MemberPointerType>(Y);
14891 CXXRecordDecl *Cls = PX->getMostRecentCXXRecordDecl();
14892 assert(Cls == PY->getMostRecentCXXRecordDecl());
14893 return Ctx.getMemberPointerType(
14894 ::getCommonPointeeType(Ctx, PX, PY),
14895 ::getCommonQualifier(Ctx, PX, PY, /*IsSame=*/false), Cls);
14896 }
14897 case Type::CountAttributed: {
14898 const auto *DX = cast<CountAttributedType>(X),
14900 if (DX->isCountInBytes() != DY->isCountInBytes())
14901 return QualType();
14902 if (DX->isOrNull() != DY->isOrNull())
14903 return QualType();
14904 Expr *CEX = DX->getCountExpr();
14905 Expr *CEY = DY->getCountExpr();
14906 ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
14907 if (Ctx.hasSameExpr(CEX, CEY))
14908 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14909 DX->isCountInBytes(), DX->isOrNull(),
14910 CDX);
14911 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
14912 return QualType();
14913 // Two declarations with the same integer constant may still differ in their
14914 // expression pointers, so we need to evaluate them.
14915 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
14916 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
14917 if (VX != VY)
14918 return QualType();
14919 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14920 DX->isCountInBytes(), DX->isOrNull(),
14921 CDX);
14922 }
14923 case Type::PredefinedSugar:
14924 assert(cast<PredefinedSugarType>(X)->getKind() !=
14926 return QualType();
14927 }
14928 llvm_unreachable("Unhandled Type Class");
14929}
14930
14931static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
14933 while (true) {
14934 QTotal.addConsistentQualifiers(T.Quals);
14936 if (NT == QualType(T.Ty, 0))
14937 break;
14938 R.push_back(T);
14939 T = NT.split();
14940 }
14941 return R;
14942}
14943
14945 bool Unqualified) const {
14946 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
14947 if (X == Y)
14948 return X;
14949 if (!Unqualified) {
14950 if (X.isCanonical())
14951 return X;
14952 if (Y.isCanonical())
14953 return Y;
14954 }
14955
14956 SplitQualType SX = X.split(), SY = Y.split();
14957 Qualifiers QX, QY;
14958 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
14959 // until we reach their underlying "canonical nodes". Note these are not
14960 // necessarily canonical types, as they may still have sugared properties.
14961 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
14962 auto Xs = ::unwrapSugar(SX, QX), Ys = ::unwrapSugar(SY, QY);
14963
14964 // If this is an ArrayType, the element qualifiers are interchangeable with
14965 // the top level qualifiers.
14966 // * In case the canonical nodes are the same, the elements types are already
14967 // the same.
14968 // * Otherwise, the element types will be made the same, and any different
14969 // element qualifiers will be moved up to the top level qualifiers, per
14970 // 'getCommonArrayElementType'.
14971 // In both cases, this means there may be top level qualifiers which differ
14972 // between X and Y. If so, these differing qualifiers are redundant with the
14973 // element qualifiers, and can be removed without changing the canonical type.
14974 // The desired behaviour is the same as for the 'Unqualified' case here:
14975 // treat the redundant qualifiers as sugar, remove the ones which are not
14976 // common to both sides.
14977 bool KeepCommonQualifiers =
14979
14980 if (SX.Ty != SY.Ty) {
14981 // The canonical nodes differ. Build a common canonical node out of the two,
14982 // unifying their sugar. This may recurse back here.
14983 SX.Ty =
14984 ::getCommonNonSugarTypeNode(*this, SX.Ty, QX, SY.Ty, QY).getTypePtr();
14985 } else {
14986 // The canonical nodes were identical: We may have desugared too much.
14987 // Add any common sugar back in.
14988 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
14989 QX -= SX.Quals;
14990 QY -= SY.Quals;
14991 SX = Xs.pop_back_val();
14992 SY = Ys.pop_back_val();
14993 }
14994 }
14995 if (KeepCommonQualifiers)
14997 else
14998 assert(QX == QY);
14999
15000 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
15001 // related. Walk up these nodes, unifying them and adding the result.
15002 while (!Xs.empty() && !Ys.empty()) {
15003 auto Underlying = SplitQualType(
15004 SX.Ty, Qualifiers::removeCommonQualifiers(SX.Quals, SY.Quals));
15005 SX = Xs.pop_back_val();
15006 SY = Ys.pop_back_val();
15007 SX.Ty = ::getCommonSugarTypeNode(*this, SX.Ty, SY.Ty, Underlying)
15009 // Stop at the first pair which is unrelated.
15010 if (!SX.Ty) {
15011 SX.Ty = Underlying.Ty;
15012 break;
15013 }
15014 QX -= Underlying.Quals;
15015 };
15016
15017 // Add back the missing accumulated qualifiers, which were stripped off
15018 // with the sugar nodes we could not unify.
15019 QualType R = getQualifiedType(SX.Ty, QX);
15020 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
15021 return R;
15022}
15023
15025 assert(Ty->isFixedPointType());
15026
15028 return Ty;
15029
15030 switch (Ty->castAs<BuiltinType>()->getKind()) {
15031 default:
15032 llvm_unreachable("Not a saturated fixed point type!");
15033 case BuiltinType::SatShortAccum:
15034 return ShortAccumTy;
15035 case BuiltinType::SatAccum:
15036 return AccumTy;
15037 case BuiltinType::SatLongAccum:
15038 return LongAccumTy;
15039 case BuiltinType::SatUShortAccum:
15040 return UnsignedShortAccumTy;
15041 case BuiltinType::SatUAccum:
15042 return UnsignedAccumTy;
15043 case BuiltinType::SatULongAccum:
15044 return UnsignedLongAccumTy;
15045 case BuiltinType::SatShortFract:
15046 return ShortFractTy;
15047 case BuiltinType::SatFract:
15048 return FractTy;
15049 case BuiltinType::SatLongFract:
15050 return LongFractTy;
15051 case BuiltinType::SatUShortFract:
15052 return UnsignedShortFractTy;
15053 case BuiltinType::SatUFract:
15054 return UnsignedFractTy;
15055 case BuiltinType::SatULongFract:
15056 return UnsignedLongFractTy;
15057 }
15058}
15059
15061 assert(Ty->isFixedPointType());
15062
15063 if (Ty->isSaturatedFixedPointType()) return Ty;
15064
15065 switch (Ty->castAs<BuiltinType>()->getKind()) {
15066 default:
15067 llvm_unreachable("Not a fixed point type!");
15068 case BuiltinType::ShortAccum:
15069 return SatShortAccumTy;
15070 case BuiltinType::Accum:
15071 return SatAccumTy;
15072 case BuiltinType::LongAccum:
15073 return SatLongAccumTy;
15074 case BuiltinType::UShortAccum:
15076 case BuiltinType::UAccum:
15077 return SatUnsignedAccumTy;
15078 case BuiltinType::ULongAccum:
15080 case BuiltinType::ShortFract:
15081 return SatShortFractTy;
15082 case BuiltinType::Fract:
15083 return SatFractTy;
15084 case BuiltinType::LongFract:
15085 return SatLongFractTy;
15086 case BuiltinType::UShortFract:
15088 case BuiltinType::UFract:
15089 return SatUnsignedFractTy;
15090 case BuiltinType::ULongFract:
15092 }
15093}
15094
15096 if (LangOpts.OpenCL)
15098
15099 if (LangOpts.CUDA)
15101
15102 return getLangASFromTargetAS(AS);
15103}
15104
15105// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
15106// doesn't include ASTContext.h
15107template
15109 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
15111 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
15112 const clang::ASTContext &Ctx, Decl *Value);
15113
15115 assert(Ty->isFixedPointType());
15116
15117 const TargetInfo &Target = getTargetInfo();
15118 switch (Ty->castAs<BuiltinType>()->getKind()) {
15119 default:
15120 llvm_unreachable("Not a fixed point type!");
15121 case BuiltinType::ShortAccum:
15122 case BuiltinType::SatShortAccum:
15123 return Target.getShortAccumScale();
15124 case BuiltinType::Accum:
15125 case BuiltinType::SatAccum:
15126 return Target.getAccumScale();
15127 case BuiltinType::LongAccum:
15128 case BuiltinType::SatLongAccum:
15129 return Target.getLongAccumScale();
15130 case BuiltinType::UShortAccum:
15131 case BuiltinType::SatUShortAccum:
15132 return Target.getUnsignedShortAccumScale();
15133 case BuiltinType::UAccum:
15134 case BuiltinType::SatUAccum:
15135 return Target.getUnsignedAccumScale();
15136 case BuiltinType::ULongAccum:
15137 case BuiltinType::SatULongAccum:
15138 return Target.getUnsignedLongAccumScale();
15139 case BuiltinType::ShortFract:
15140 case BuiltinType::SatShortFract:
15141 return Target.getShortFractScale();
15142 case BuiltinType::Fract:
15143 case BuiltinType::SatFract:
15144 return Target.getFractScale();
15145 case BuiltinType::LongFract:
15146 case BuiltinType::SatLongFract:
15147 return Target.getLongFractScale();
15148 case BuiltinType::UShortFract:
15149 case BuiltinType::SatUShortFract:
15150 return Target.getUnsignedShortFractScale();
15151 case BuiltinType::UFract:
15152 case BuiltinType::SatUFract:
15153 return Target.getUnsignedFractScale();
15154 case BuiltinType::ULongFract:
15155 case BuiltinType::SatULongFract:
15156 return Target.getUnsignedLongFractScale();
15157 }
15158}
15159
15161 assert(Ty->isFixedPointType());
15162
15163 const TargetInfo &Target = getTargetInfo();
15164 switch (Ty->castAs<BuiltinType>()->getKind()) {
15165 default:
15166 llvm_unreachable("Not a fixed point type!");
15167 case BuiltinType::ShortAccum:
15168 case BuiltinType::SatShortAccum:
15169 return Target.getShortAccumIBits();
15170 case BuiltinType::Accum:
15171 case BuiltinType::SatAccum:
15172 return Target.getAccumIBits();
15173 case BuiltinType::LongAccum:
15174 case BuiltinType::SatLongAccum:
15175 return Target.getLongAccumIBits();
15176 case BuiltinType::UShortAccum:
15177 case BuiltinType::SatUShortAccum:
15178 return Target.getUnsignedShortAccumIBits();
15179 case BuiltinType::UAccum:
15180 case BuiltinType::SatUAccum:
15181 return Target.getUnsignedAccumIBits();
15182 case BuiltinType::ULongAccum:
15183 case BuiltinType::SatULongAccum:
15184 return Target.getUnsignedLongAccumIBits();
15185 case BuiltinType::ShortFract:
15186 case BuiltinType::SatShortFract:
15187 case BuiltinType::Fract:
15188 case BuiltinType::SatFract:
15189 case BuiltinType::LongFract:
15190 case BuiltinType::SatLongFract:
15191 case BuiltinType::UShortFract:
15192 case BuiltinType::SatUShortFract:
15193 case BuiltinType::UFract:
15194 case BuiltinType::SatUFract:
15195 case BuiltinType::ULongFract:
15196 case BuiltinType::SatULongFract:
15197 return 0;
15198 }
15199}
15200
15201llvm::FixedPointSemantics
15203 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
15204 "Can only get the fixed point semantics for a "
15205 "fixed point or integer type.");
15206 if (Ty->isIntegerType())
15207 return llvm::FixedPointSemantics::GetIntegerSemantics(
15208 getIntWidth(Ty), Ty->isSignedIntegerType());
15209
15210 bool isSigned = Ty->isSignedFixedPointType();
15211 return llvm::FixedPointSemantics(
15212 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
15214 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
15215}
15216
15217llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
15218 assert(Ty->isFixedPointType());
15219 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
15220}
15221
15222llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
15223 assert(Ty->isFixedPointType());
15224 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
15225}
15226
15228 assert(Ty->isUnsignedFixedPointType() &&
15229 "Expected unsigned fixed point type");
15230
15231 switch (Ty->castAs<BuiltinType>()->getKind()) {
15232 case BuiltinType::UShortAccum:
15233 return ShortAccumTy;
15234 case BuiltinType::UAccum:
15235 return AccumTy;
15236 case BuiltinType::ULongAccum:
15237 return LongAccumTy;
15238 case BuiltinType::SatUShortAccum:
15239 return SatShortAccumTy;
15240 case BuiltinType::SatUAccum:
15241 return SatAccumTy;
15242 case BuiltinType::SatULongAccum:
15243 return SatLongAccumTy;
15244 case BuiltinType::UShortFract:
15245 return ShortFractTy;
15246 case BuiltinType::UFract:
15247 return FractTy;
15248 case BuiltinType::ULongFract:
15249 return LongFractTy;
15250 case BuiltinType::SatUShortFract:
15251 return SatShortFractTy;
15252 case BuiltinType::SatUFract:
15253 return SatFractTy;
15254 case BuiltinType::SatULongFract:
15255 return SatLongFractTy;
15256 default:
15257 llvm_unreachable("Unexpected unsigned fixed point type");
15258 }
15259}
15260
15261// Given a list of FMV features, return a concatenated list of the
15262// corresponding backend features (which may contain duplicates).
15263static std::vector<std::string> getFMVBackendFeaturesFor(
15264 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) {
15265 std::vector<std::string> BackendFeats;
15266 llvm::AArch64::ExtensionSet FeatureBits;
15267 for (StringRef F : FMVFeatStrings)
15268 if (auto FMVExt = llvm::AArch64::parseFMVExtension(F))
15269 if (FMVExt->ID)
15270 FeatureBits.enable(*FMVExt->ID);
15271 FeatureBits.toLLVMFeatureList(BackendFeats);
15272 return BackendFeats;
15273}
15274
15275ParsedTargetAttr
15276ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
15277 assert(TD != nullptr);
15278 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TD->getFeaturesStr());
15279
15280 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
15281 return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
15282 });
15283 return ParsedAttr;
15284}
15285
15286void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15287 const FunctionDecl *FD) const {
15288 if (FD)
15289 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
15290 else
15291 Target->initFeatureMap(FeatureMap, getDiagnostics(),
15292 Target->getTargetOpts().CPU,
15293 Target->getTargetOpts().Features);
15294}
15295
15296// Fills in the supplied string map with the set of target features for the
15297// passed in function.
15298void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15299 GlobalDecl GD) const {
15300 StringRef TargetCPU = Target->getTargetOpts().CPU;
15301 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
15302 if (const auto *TD = FD->getAttr<TargetAttr>()) {
15304
15305 // Make a copy of the features as passed on the command line into the
15306 // beginning of the additional features from the function to override.
15307 // AArch64 handles command line option features in parseTargetAttr().
15308 if (!Target->getTriple().isAArch64())
15309 ParsedAttr.Features.insert(
15310 ParsedAttr.Features.begin(),
15311 Target->getTargetOpts().FeaturesAsWritten.begin(),
15312 Target->getTargetOpts().FeaturesAsWritten.end());
15313
15314 if (ParsedAttr.CPU != "" && Target->isValidCPUName(ParsedAttr.CPU))
15315 TargetCPU = ParsedAttr.CPU;
15316
15317 // Now populate the feature map, first with the TargetCPU which is either
15318 // the default or a new one from the target attribute string. Then we'll use
15319 // the passed in features (FeaturesAsWritten) along with the new ones from
15320 // the attribute.
15321 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
15322 ParsedAttr.Features);
15323 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
15325 Target->getCPUSpecificCPUDispatchFeatures(
15326 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
15327 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
15328 Features.insert(Features.begin(),
15329 Target->getTargetOpts().FeaturesAsWritten.begin(),
15330 Target->getTargetOpts().FeaturesAsWritten.end());
15331 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15332 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
15333 if (Target->getTriple().isAArch64()) {
15335 TC->getFeatures(Feats, GD.getMultiVersionIndex());
15336 std::vector<std::string> Features = getFMVBackendFeaturesFor(Feats);
15337 Features.insert(Features.begin(),
15338 Target->getTargetOpts().FeaturesAsWritten.begin(),
15339 Target->getTargetOpts().FeaturesAsWritten.end());
15340 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15341 } else if (Target->getTriple().isRISCV()) {
15342 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15343 std::vector<std::string> Features;
15344 if (VersionStr != "default") {
15345 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(VersionStr);
15346 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
15347 ParsedAttr.Features.end());
15348 }
15349 Features.insert(Features.begin(),
15350 Target->getTargetOpts().FeaturesAsWritten.begin(),
15351 Target->getTargetOpts().FeaturesAsWritten.end());
15352 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15353 } else if (Target->getTriple().isOSAIX()) {
15354 std::vector<std::string> Features;
15355 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15356 if (VersionStr.starts_with("cpu="))
15357 TargetCPU = VersionStr.drop_front(sizeof("cpu=") - 1);
15358 else
15359 assert(VersionStr == "default");
15360 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15361 } else {
15362 std::vector<std::string> Features;
15363 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15364 if (VersionStr.starts_with("arch="))
15365 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
15366 else if (VersionStr != "default")
15367 Features.push_back((StringRef{"+"} + VersionStr).str());
15368 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15369 }
15370 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
15371 std::vector<std::string> Features;
15372 if (Target->getTriple().isRISCV()) {
15373 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TV->getName());
15374 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
15375 ParsedAttr.Features.end());
15376 } else {
15377 assert(Target->getTriple().isAArch64());
15379 TV->getFeatures(Feats);
15380 Features = getFMVBackendFeaturesFor(Feats);
15381 }
15382 Features.insert(Features.begin(),
15383 Target->getTargetOpts().FeaturesAsWritten.begin(),
15384 Target->getTargetOpts().FeaturesAsWritten.end());
15385 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15386 } else {
15387 FeatureMap = Target->getTargetOpts().FeatureMap;
15388 }
15389}
15390
15392 CanQualType KernelNameType,
15393 const FunctionDecl *FD) {
15394 // Host and device compilation may use different ABIs and different ABIs
15395 // may allocate name mangling discriminators differently. A discriminator
15396 // override is used to ensure consistent discriminator allocation across
15397 // host and device compilation.
15398 auto DeviceDiscriminatorOverrider =
15399 [](ASTContext &Ctx, const NamedDecl *ND) -> UnsignedOrNone {
15400 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
15401 if (RD->isLambda())
15402 return RD->getDeviceLambdaManglingNumber();
15403 return std::nullopt;
15404 };
15405 std::unique_ptr<MangleContext> MC{ItaniumMangleContext::create(
15406 Context, Context.getDiagnostics(), DeviceDiscriminatorOverrider)};
15407
15408 // Construct a mangled name for the SYCL kernel caller offload entry point.
15409 // FIXME: The Itanium typeinfo mangling (_ZTS<type>) is currently used to
15410 // name the SYCL kernel caller offload entry point function. This mangling
15411 // does not suffice to clearly identify symbols that correspond to SYCL
15412 // kernel caller functions, nor is this mangling natural for targets that
15413 // use a non-Itanium ABI.
15414 std::string Buffer;
15415 Buffer.reserve(128);
15416 llvm::raw_string_ostream Out(Buffer);
15417 MC->mangleCanonicalTypeName(KernelNameType, Out);
15418 std::string KernelName = Out.str();
15419
15420 return {KernelNameType, FD, KernelName};
15421}
15422
15424 // If the function declaration to register is invalid or dependent, the
15425 // registration attempt is ignored.
15426 if (FD->isInvalidDecl() || FD->isTemplated())
15427 return;
15428
15429 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
15430 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
15431
15432 // Be tolerant of multiple registration attempts so long as each attempt
15433 // is for the same entity. Callers are obligated to detect and diagnose
15434 // conflicting kernel names prior to calling this function.
15435 CanQualType KernelNameType = getCanonicalType(SKEPAttr->getKernelName());
15436 auto IT = SYCLKernels.find(KernelNameType);
15437 assert((IT == SYCLKernels.end() ||
15438 declaresSameEntity(FD, IT->second.getKernelEntryPointDecl())) &&
15439 "SYCL kernel name conflict");
15440 (void)IT;
15441 SYCLKernels.insert(std::make_pair(
15442 KernelNameType, BuildSYCLKernelInfo(*this, KernelNameType, FD)));
15443}
15444
15446 CanQualType KernelNameType = getCanonicalType(T);
15447 return SYCLKernels.at(KernelNameType);
15448}
15449
15451 CanQualType KernelNameType = getCanonicalType(T);
15452 auto IT = SYCLKernels.find(KernelNameType);
15453 if (IT != SYCLKernels.end())
15454 return &IT->second;
15455 return nullptr;
15456}
15457
15459 OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
15460 return *OMPTraitInfoVector.back();
15461}
15462
15465 const ASTContext::SectionInfo &Section) {
15466 if (Section.Decl)
15467 return DB << Section.Decl;
15468 return DB << "a prior #pragma section";
15469}
15470
15471bool ASTContext::mayExternalize(const Decl *D) const {
15472 bool IsInternalVar =
15473 isa<VarDecl>(D) &&
15475 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
15476 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
15477 (D->hasAttr<CUDAConstantAttr>() &&
15478 !D->getAttr<CUDAConstantAttr>()->isImplicit());
15479 // CUDA/HIP: managed variables need to be externalized since it is
15480 // a declaration in IR, therefore cannot have internal linkage. Kernels in
15481 // anonymous name space needs to be externalized to avoid duplicate symbols.
15482 return (IsInternalVar &&
15483 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
15484 (D->hasAttr<CUDAGlobalAttr>() &&
15486 GVA_Internal);
15487}
15488
15490 return mayExternalize(D) &&
15491 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
15493}
15494
15495StringRef ASTContext::getCUIDHash() const {
15496 if (!CUIDHash.empty())
15497 return CUIDHash;
15498 if (LangOpts.CUID.empty())
15499 return StringRef();
15500 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
15501 return CUIDHash;
15502}
15503
15504const CXXRecordDecl *
15506 assert(ThisClass);
15507 assert(ThisClass->isPolymorphic());
15508 const CXXRecordDecl *PrimaryBase = ThisClass;
15509 while (1) {
15510 assert(PrimaryBase);
15511 assert(PrimaryBase->isPolymorphic());
15512 auto &Layout = getASTRecordLayout(PrimaryBase);
15513 auto Base = Layout.getPrimaryBase();
15514 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
15515 break;
15516 PrimaryBase = Base;
15517 }
15518 return PrimaryBase;
15519}
15520
15522 StringRef MangledName) {
15523 auto *Method = cast<CXXMethodDecl>(VirtualMethodDecl.getDecl());
15524 assert(Method->isVirtual());
15525 bool DefaultIncludesPointerAuth =
15526 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics;
15527
15528 if (!DefaultIncludesPointerAuth)
15529 return true;
15530
15531 auto Existing = ThunksToBeAbbreviated.find(VirtualMethodDecl);
15532 if (Existing != ThunksToBeAbbreviated.end())
15533 return Existing->second.contains(MangledName.str());
15534
15535 std::unique_ptr<MangleContext> Mangler(createMangleContext());
15536 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks;
15537 auto VtableContext = getVTableContext();
15538 if (const auto *ThunkInfos = VtableContext->getThunkInfo(VirtualMethodDecl)) {
15539 auto *Destructor = dyn_cast<CXXDestructorDecl>(Method);
15540 for (const auto &Thunk : *ThunkInfos) {
15541 SmallString<256> ElidedName;
15542 llvm::raw_svector_ostream ElidedNameStream(ElidedName);
15543 if (Destructor)
15544 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15545 Thunk, /* elideOverrideInfo */ true,
15546 ElidedNameStream);
15547 else
15548 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ true,
15549 ElidedNameStream);
15550 SmallString<256> MangledName;
15551 llvm::raw_svector_ostream mangledNameStream(MangledName);
15552 if (Destructor)
15553 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15554 Thunk, /* elideOverrideInfo */ false,
15555 mangledNameStream);
15556 else
15557 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ false,
15558 mangledNameStream);
15559
15560 Thunks[ElidedName].push_back(std::string(MangledName));
15561 }
15562 }
15563 llvm::StringSet<> SimplifiedThunkNames;
15564 for (auto &ThunkList : Thunks) {
15565 llvm::sort(ThunkList.second);
15566 SimplifiedThunkNames.insert(ThunkList.second[0]);
15567 }
15568 bool Result = SimplifiedThunkNames.contains(MangledName);
15569 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames);
15570 return Result;
15571}
15572
15574 // Check for trivially-destructible here because non-trivially-destructible
15575 // types will always cause the type and any types derived from it to be
15576 // considered non-trivially-copyable. The same cannot be said for
15577 // trivially-copyable because deleting special members of a type derived from
15578 // a non-trivially-copyable type can cause the derived type to be considered
15579 // trivially copyable.
15580 if (getLangOpts().PointerFieldProtectionTagged)
15581 return !isa<CXXRecordDecl>(RD) ||
15582 cast<CXXRecordDecl>(RD)->hasTrivialDestructor();
15583 return true;
15584}
15585
15586static void findPFPFields(const ASTContext &Ctx, QualType Ty, CharUnits Offset,
15587 std::vector<PFPField> &Fields, bool IncludeVBases) {
15588 if (auto *AT = Ctx.getAsConstantArrayType(Ty)) {
15589 if (auto *ElemDecl = AT->getElementType()->getAsCXXRecordDecl()) {
15590 const ASTRecordLayout &ElemRL = Ctx.getASTRecordLayout(ElemDecl);
15591 for (unsigned i = 0; i != AT->getSize(); ++i)
15592 findPFPFields(Ctx, AT->getElementType(), Offset + i * ElemRL.getSize(),
15593 Fields, true);
15594 }
15595 }
15596 auto *Decl = Ty->getAsCXXRecordDecl();
15597 // isPFPType() is inherited from bases and members (including via arrays), so
15598 // we can early exit if it is false. Unions are excluded per the API
15599 // documentation.
15600 if (!Decl || !Decl->isPFPType() || Decl->isUnion())
15601 return;
15602 const ASTRecordLayout &RL = Ctx.getASTRecordLayout(Decl);
15603 for (FieldDecl *Field : Decl->fields()) {
15604 CharUnits FieldOffset =
15605 Offset +
15606 Ctx.toCharUnitsFromBits(RL.getFieldOffset(Field->getFieldIndex()));
15607 if (Ctx.isPFPField(Field))
15608 Fields.push_back({FieldOffset, Field});
15609 findPFPFields(Ctx, Field->getType(), FieldOffset, Fields,
15610 /*IncludeVBases=*/true);
15611 }
15612 // Pass false for IncludeVBases below because vbases are only included in
15613 // layout for top-level types, i.e. not bases or vbases.
15614 for (CXXBaseSpecifier &Base : Decl->bases()) {
15615 if (Base.isVirtual())
15616 continue;
15617 CharUnits BaseOffset =
15618 Offset + RL.getBaseClassOffset(Base.getType()->getAsCXXRecordDecl());
15619 findPFPFields(Ctx, Base.getType(), BaseOffset, Fields,
15620 /*IncludeVBases=*/false);
15621 }
15622 if (IncludeVBases) {
15623 for (CXXBaseSpecifier &Base : Decl->vbases()) {
15624 CharUnits BaseOffset =
15625 Offset + RL.getVBaseClassOffset(Base.getType()->getAsCXXRecordDecl());
15626 findPFPFields(Ctx, Base.getType(), BaseOffset, Fields,
15627 /*IncludeVBases=*/false);
15628 }
15629 }
15630}
15631
15632std::vector<PFPField> ASTContext::findPFPFields(QualType Ty) const {
15633 std::vector<PFPField> PFPFields;
15634 ::findPFPFields(*this, Ty, CharUnits::Zero(), PFPFields, true);
15635 return PFPFields;
15636}
15637
15639 return !findPFPFields(Ty).empty();
15640}
15641
15642bool ASTContext::isPFPField(const FieldDecl *FD) const {
15643 if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getParent()))
15644 return RD->isPFPType() && FD->getType()->isPointerType() &&
15645 !FD->hasAttr<NoFieldProtectionAttr>();
15646 return false;
15647}
15648
15650 auto *FD = dyn_cast<FieldDecl>(VD);
15651 if (!FD)
15652 FD = cast<FieldDecl>(cast<IndirectFieldDecl>(VD)->chain().back());
15653 if (isPFPField(FD))
15655}
15656
15658 if (E->getNumComponents() == 0)
15659 return;
15660 OffsetOfNode Comp = E->getComponent(E->getNumComponents() - 1);
15661 if (Comp.getKind() != OffsetOfNode::Field)
15662 return;
15663 if (FieldDecl *FD = Comp.getField(); isPFPField(FD))
15665}
This file provides AST data structures related to concepts.
static void SortAndUniqueProtocols(SmallVectorImpl< ObjCProtocolDecl * > &Protocols)
static bool isCanonicalExceptionSpecification(const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType)
static SourceLocation getCommonAttrLoc(const T *X, const T *Y)
static auto getCanonicalTemplateArguments(const ASTContext &C, ArrayRef< TemplateArgument > Args, bool &AnyNonCanonArgs)
static char getObjCEncodingForPrimitiveType(const ASTContext *C, const BuiltinType *BT)
static bool isSameQualifier(const NestedNameSpecifier X, const NestedNameSpecifier Y)
static bool unionHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD, bool CheckIfTriviallyCopyable)
static TypedefDecl * CreateHexagonBuiltinVaListDecl(const ASTContext *Context)
#define CANONICAL_TYPE(Class)
static ElaboratedTypeKeyword getCommonTypeKeyword(const T *X, const T *Y, bool IsSame)
static Decl * getCommonDecl(Decl *X, Decl *Y)
static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, const Decl *D, GVALinkage L)
static bool isTypeTypedefedAsBOOL(QualType T)
static void EncodeBitField(const ASTContext *Ctx, std::string &S, QualType T, const FieldDecl *FD)
static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, const VarDecl *VD)
static QualType getCommonArrayElementType(const ASTContext &Ctx, const T *X, Qualifiers &QX, const T *Y, Qualifiers &QY)
#define SUGAR_FREE_TYPE(Class)
static SYCLKernelInfo BuildSYCLKernelInfo(ASTContext &Context, CanQualType KernelNameType, const FunctionDecl *FD)
static bool hasTemplateSpecializationInEncodedString(const Type *T, bool VisitBasesAndFields)
static void getIntersectionOfProtocols(ASTContext &Context, const ObjCInterfaceDecl *CommonBase, const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT, SmallVectorImpl< ObjCProtocolDecl * > &IntersectionSet)
getIntersectionOfProtocols - This routine finds the intersection of set of protocols inherited from t...
static bool areCompatMatrixTypes(const ConstantMatrixType *LHS, const ConstantMatrixType *RHS)
areCompatMatrixTypes - Return true if the two specified matrix types are compatible.
static TypedefDecl * CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context)
static bool sameObjCTypeArgs(ASTContext &ctx, const ObjCInterfaceDecl *iface, ArrayRef< QualType > lhsArgs, ArrayRef< QualType > rhsArgs, bool stripKindOf)
static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs, QualType rhs)
Determine whether the first type is a subtype of the second.
static const Type * getIntegerTypeForEnum(const EnumType *ET)
static SmallVector< SourceLocation, 2 > getLocsForCommentSearch(ASTContext::RawCommentLookupKey Key, SourceManager &SourceMgr)
static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B)
static TemplateName getCommonTemplateName(const ASTContext &Ctx, TemplateName X, TemplateName Y, bool IgnoreDeduced=false)
static int CmpProtocolNames(ObjCProtocolDecl *const *LHS, ObjCProtocolDecl *const *RHS)
CmpProtocolNames - Comparison predicate for sorting protocols alphabetically.
static auto * getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y)
static TypedefDecl * CreatePowerABIBuiltinVaListDecl(const ASTContext *Context)
static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y)
static TemplateArgument getCommonTemplateArgument(const ASTContext &Ctx, const TemplateArgument &X, const TemplateArgument &Y)
static std::optional< int64_t > structHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD, bool CheckIfTriviallyCopyable)
static bool hasSameOverloadableAttrs(const FunctionDecl *A, const FunctionDecl *B)
Determine whether the attributes we can overload on are identical for A and B.
static T * getCommonDeclChecked(T *X, T *Y)
static NestedNameSpecifier getCommonNNS(const ASTContext &Ctx, NestedNameSpecifier NNS1, NestedNameSpecifier NNS2, bool IsSame)
Returns a NestedNameSpecifier which has only the common sugar present in both NNS1 and NNS2.
static TypedefDecl * CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context)
static int64_t getSubobjectOffset(const FieldDecl *Field, const ASTContext &Context, const clang::ASTRecordLayout &)
static QualType getCommonSugarTypeNode(const ASTContext &Ctx, const Type *X, const Type *Y, SplitQualType Underlying)
static TypedefDecl * CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context)
static QualType getCommonNonSugarTypeNode(const ASTContext &Ctx, const Type *X, Qualifiers &QX, const Type *Y, Qualifiers &QY)
static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, QualType other, bool isBlockReturnType)
Given that we have an enum type and a non-enum type, try to merge them.
static GVALinkage adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D, GVALinkage L)
Adjust the GVALinkage for a declaration based on what an external AST source knows about whether ther...
static TypedefDecl * CreateSystemZBuiltinVaListDecl(const ASTContext *Context)
static std::optional< int64_t > getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context, bool CheckIfTriviallyCopyable)
static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, const FunctionDecl *FD)
#define NON_UNIQUE_TYPE(Class)
static TypedefDecl * CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context)
static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI, const LangOptions &LangOpts)
static ElaboratedTypeKeyword getCanonicalElaboratedTypeKeyword(ElaboratedTypeKeyword Keyword)
static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X, const T *Y)
static auto getCommonIndexTypeCVRQualifiers(const ArrayType *X, const ArrayType *Y)
static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, ASTContext::GetBuiltinTypeError &Error, bool &RequiresICE, bool AllowTypeModifiers)
DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the pointer over the consume...
FloatingRank
@ FloatRank
@ LongDoubleRank
@ Float16Rank
@ Ibm128Rank
@ Float128Rank
@ BFloat16Rank
@ HalfRank
@ DoubleRank
static TypedefDecl * CreateCharPtrBuiltinVaListDecl(const ASTContext *Context)
static bool areSortedAndUniqued(ArrayRef< ObjCProtocolDecl * > Protocols)
static TypeInfoChars getConstantArrayInfoInChars(const ASTContext &Context, const ConstantArrayType *CAT)
getConstantArrayInfoInChars - Performing the computation in CharUnits instead of in bits prevents ove...
static FloatingRank getFloatingRank(QualType T)
getFloatingRank - Return a relative rank for floating point types.
static bool getCommonTemplateArguments(const ASTContext &Ctx, SmallVectorImpl< TemplateArgument > &R, ArrayRef< TemplateArgument > Xs, ArrayRef< TemplateArgument > Ys)
static TypedefDecl * CreateXtensaABIBuiltinVaListDecl(const ASTContext *Context)
static QualType getCommonElementType(const ASTContext &Ctx, const T *X, const T *Y)
static void mergeTypeLists(const ASTContext &Ctx, SmallVectorImpl< QualType > &Out, ArrayRef< QualType > X, ArrayRef< QualType > Y)
static bool matchesPostDecrInWhile(const UnaryOperator *UO, ASTContext &Ctx)
For the purposes of overflow pattern exclusion, does this match the while(i–) pattern?
static void encodeTypeForFunctionPointerAuth(const ASTContext &Ctx, raw_ostream &OS, QualType QT)
Encode a function type for use in the discriminator of a function pointer type.
static std::optional< int64_t > structSubobjectsHaveUniqueObjectRepresentations(const RangeT &Subobjects, int64_t CurOffsetInBits, const ASTContext &Context, const clang::ASTRecordLayout &Layout, bool CheckIfTriviallyCopyable)
static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty)
getRVVTypeSize - Return RVV vector register size.
static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal)
static TemplateName getCommonTemplateNameChecked(const ASTContext &Ctx, TemplateName X, TemplateName Y, bool IgnoreDeduced)
static int compareObjCProtocolsByName(ObjCProtocolDecl *const *lhs, ObjCProtocolDecl *const *rhs)
Comparison routine for Objective-C protocols to be used with llvm::array_pod_sort.
static std::string charUnitsToString(const CharUnits &CU)
static const TagDecl * getNonInjectedClassName(const TagDecl *TD)
static bool hasAnyPackExpansions(ArrayRef< TemplateArgument > Args)
static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED)
static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod, SmallVectorImpl< const NamedDecl * > &Redeclared)
static QualType getCommonTypeWithQualifierLifting(const ASTContext &Ctx, QualType X, QualType Y, Qualifiers &QX, Qualifiers &QY)
static auto getCommonTypes(const ASTContext &Ctx, ArrayRef< QualType > Xs, ArrayRef< QualType > Ys, bool Unqualified=false)
static bool isCanonicalResultType(QualType T)
Determine whether T is canonical as the result type of a function.
static TypedefDecl * CreateMSVaListDecl(const ASTContext *Context)
static bool areCompatVectorTypes(const VectorType *LHS, const VectorType *RHS)
areCompatVectorTypes - Return true if the two specified vector types are compatible.
static TypedefDecl * CreateCharPtrNamedVaListDecl(const ASTContext *Context, StringRef Name)
static NestedNameSpecifier getCommonQualifier(const ASTContext &Ctx, const T *X, const T *Y, bool IsSame)
#define UNEXPECTED_TYPE(Class, Kind)
static TypedefDecl * CreateVaListDecl(const ASTContext *Context, TargetInfo::BuiltinVaListKind Kind)
static bool primaryBaseHaseAddressDiscriminatedVTableAuthentication(const ASTContext &Context, const CXXRecordDecl *Class)
static std::vector< std::string > getFMVBackendFeaturesFor(const llvm::SmallVectorImpl< StringRef > &FMVFeatStrings)
Defines the clang::ASTContext interface.
#define V(N, I)
#define BuiltinTemplate(BTName)
Definition ASTContext.h:472
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:806
comments::FullComment * cloneFullComment(comments::FullComment *FC, const Decl *D) const
CharUnits getObjCEncodingTypeSize(QualType T) const
Return the size of type T for Objective-C encoding purpose, in characters.
int getIntegerTypeOrder(QualType LHS, QualType RHS) const
Return the highest ranked integer type, see C99 6.3.1.8p1.
const TemplateArgument * getDefaultTemplateArgumentOrNone(const NamedDecl *P) const
Return the default argument of a template parameter, if one exists.
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType, const Attr *attr=nullptr) const
TypedefDecl * getObjCIdDecl() const
Retrieve the typedef corresponding to the predefined id type in Objective-C.
void setCurrentNamedModule(Module *M)
Set the (C++20) module we are building.
QualType getProcessIDType() const
Return the unique type for "pid_t" defined in <sys/types.h>.
CharUnits getMemberPointerPathAdjustment(const APValue &MP) const
Find the 'this' offset for the member path in a pointer-to-member APValue.
bool mayExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel may be externalized.
std::unique_ptr< MangleNumberingContext > createMangleNumberingContext() const
CanQualType SatAccumTy
QualType getUnsignedPointerDiffType() const
Return the unique unsigned counterpart of "ptrdiff_t" integer type.
QualType getScalableVectorType(QualType EltTy, unsigned NumElts, unsigned NumFields=1) const
Return the unique reference to a scalable vector type of the specified element type and scalable numb...
bool hasSameExpr(const Expr *X, const Expr *Y) const
Determine whether the given expressions X and Y are equivalent.
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
MangleContext * createMangleContext(const TargetInfo *T=nullptr)
If T is null pointer, assume the target in ASTContext.
RawComment * getRawCommentNoCache(RawCommentLookupKey Key) const
Return the documentation comment attached to a given declaration or macro, without looking into cache...
QualType getRealTypeForBitwidth(unsigned DestWidth, FloatModeKind ExplicitType) const
getRealTypeForBitwidth - sets floating point QualTy according to specified bitwidth.
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
CanQualType ShortAccumTy
ASTMutationListener * getASTMutationListener() const
Retrieve a pointer to the AST mutation listener associated with this AST context, if any.
unsigned NumImplicitCopyAssignmentOperatorsDeclared
The number of implicitly-declared copy assignment operators for which declarations were built.
uint64_t getTargetNullPointerValue(QualType QT) const
Get target-dependent integer value for null pointer which is used for constant folding.
unsigned getTypeUnadjustedAlign(QualType T) const
Return the ABI-specified natural alignment of a (complete) type T, before alignment adjustments,...
unsigned char getFixedPointIBits(QualType Ty) const
QualType getSubstBuiltinTemplatePack(const TemplateArgument &ArgPack)
QualType getCorrespondingSignedFixedPointType(QualType Ty) const
IntrusiveRefCntPtr< ExternalASTSource > ExternalSource
Definition ASTContext.h:807
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:802
Builtin::Context & BuiltinInfo
Definition ASTContext.h:804
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:959
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:803
bool isTypeIgnoredBySanitizer(const SanitizerMask &Mask, const QualType &Ty) const
Check if a type can have its sanitizer instrumentation elided based on its presence within an ignorel...
unsigned getMinGlobalAlignOfVar(uint64_t Size, const VarDecl *VD) const
Return the minimum alignment as specified by the target.
RawCommentList Comments
All comments in this translation unit.
Definition ASTContext.h:994
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:922
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:580
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:805
CanQualType UnsignedLongAccumTy
QualType AutoRRefDeductTy
RawComment * getRawCommentNoCacheImpl(RawCommentLookupKey Key, const SourceLocation RepresentativeLoc, const std::map< unsigned, RawComment * > &CommentsInFile) const
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
CanQualType ShortFractTy
QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const
Return a type for a constant array for a string literal of the specified element type and length.
QualType getCorrespondingSaturatedType(QualType Ty) const
bool arePFPFieldsTriviallyCopyable(const RecordDecl *RD) const
Returns whether this record's PFP fields (if any) are trivially copyable (i.e.
bool isSameEntity(const NamedDecl *X, const NamedDecl *Y) const
Determine whether the two declarations refer to the same entity.
QualType getSubstTemplateTypeParmPackType(Decl *AssociatedDecl, unsigned Index, bool Final, const TemplateArgument &ArgPack)
CanQualType BoundMemberTy
CanQualType SatUnsignedShortFractTy
CanQualType CharTy
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
bool hasSameFunctionTypeIgnoringParamABI(QualType T, QualType U) const
Determine if two function types are the same, ignoring parameter ABI annotations.
TypedefDecl * getInt128Decl() const
Retrieve the declaration for the 128-bit signed integer type.
unsigned getOpenMPDefaultSimdAlign(QualType T) const
Get default simd alignment of the specified complete type in bits.
QualType getObjCSuperType() const
Returns the C struct type for objc_super.
QualType getBlockDescriptorType() const
Gets the struct used to keep track of the descriptor for pointer to blocks.
bool CommentsLoaded
True if comments are already loaded from ExternalASTSource.
Definition ASTContext.h:997
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:808
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:855
void ResetObjCLayout(const ObjCInterfaceDecl *D)
ArrayRef< Module * > getModulesWithMergedDefinition(const NamedDecl *Def)
Get the additional modules in which the definition Def has been merged.
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
CanQualType SatUnsignedShortAccumTy
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false, bool IsConditionalOperator=false)
CharUnits getAlignOfGlobalVarInChars(QualType T, const VarDecl *VD) const
Return the alignment in characters that should be given to a global variable with type T.
const ObjCMethodDecl * getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const
Get the duplicate declaration of a ObjCMethod in the same interface, or null if none exists.
QualType getPackIndexingType(QualType Pattern, Expr *IndexExpr, bool FullySubstituted=false, ArrayRef< QualType > Expansions={}, UnsignedOrNone Index=std::nullopt) const
static bool isObjCNSObjectType(QualType Ty)
Return true if this is an NSObject object with its NSObject attribute set.
GVALinkage GetGVALinkageForVariable(const VarDecl *VD) const
llvm::PointerUnion< VarTemplateDecl *, MemberSpecializationInfo * > TemplateOrSpecializationInfo
A type synonym for the TemplateOrInstantiation mapping.
Definition ASTContext.h:572
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:876
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:921
void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl)
CanQualType OCLQueueTy
CanQualType LongFractTy
OBTAssignResult checkOBTAssignmentCompatibility(QualType LHS, QualType RHS)
Check overflow behavior type compatibility for assignments.
CanQualType SatShortAccumTy
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CanQualType BFloat16Ty
unsigned NumImplicitCopyConstructors
The number of implicitly-declared copy constructors.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
void addExplicitInstantiationDecl(const NamedDecl *Spec, ExplicitInstantiationDecl *EID)
Add an ExplicitInstantiationDecl for a given specialization.
QualType getOverflowBehaviorType(const OverflowBehaviorAttr *Attr, QualType Wrapped) const
CanQualType IncompleteMatrixIdxTy
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
CanQualType getNSIntegerType() const
QualType getCorrespondingUnsignedType(QualType T) const
void setBlockVarCopyInit(const VarDecl *VD, Expr *CopyExpr, bool CanThrow)
Set the copy initialization expression of a block var decl.
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const
Retrieve the template name that corresponds to a non-empty lookup.
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
TemplateName getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack, Decl *AssociatedDecl, unsigned Index, bool Final) const
TargetCXXABI::Kind getCXXABIKind() const
Return the C++ ABI kind that should be used.
QualType getHLSLAttributedResourceType(QualType Wrapped, QualType Contained, const HLSLAttributedResourceType::Attributes &Attrs)
bool UnwrapSimilarTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true) const
Attempt to unwrap two types that may be similar (C++ [conv.qual]).
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
QualType getSignedSizeType() const
Return the unique signed counterpart of the integer type corresponding to size_t.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const
Return number of constant array elements.
CanQualType SatUnsignedLongAccumTy
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
CanQualType LongLongTy
CanQualType getCanonicalTagType(const TagDecl *TD) const
bool isSameTemplateArgument(const TemplateArgument &Arg1, const TemplateArgument &Arg2) const
Determine whether the given template arguments Arg1 and Arg2 are equivalent.
QualType getTypeOfType(QualType QT, TypeOfKind Kind) const
getTypeOfType - Unlike many "get<Type>" functions, we don't unique TypeOfType nodes.
QualType getCorrespondingSignedType(QualType T) const
QualType mergeObjCGCQualifiers(QualType, QualType)
mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 'RHS' attributes and ret...
llvm::DenseMap< const Decl *, const Decl * > CommentlessRedeclChains
Keeps track of redeclaration chains that don't have any comment attached.
uint64_t getArrayInitLoopExprElementCount(const ArrayInitLoopExpr *AILE) const
Return number of elements initialized in an ArrayInitLoopExpr.
unsigned getTargetAddressSpace(LangAS AS) const
std::vector< PFPField > findPFPFields(QualType Ty) const
Returns a list of PFP fields for the given type, including subfields in bases or other fields,...
QualType getIntPtrType() const
Return a type compatible with "intptr_t" (C99 7.18.1.4), as defined by the target.
void mergeDefinitionIntoModule(NamedDecl *ND, Module *M, bool NotifyListeners=true)
Note that the definition ND has been merged into module M, and should be visible whenever M is visibl...
QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a non-unique reference to the type for a dependently-sized array of the specified element type...
void addTranslationUnitDecl()
CanQualType WCharTy
void getObjCEncodingForPropertyType(QualType T, std::string &S) const
Emit the Objective-C property type encoding for the given type T into S.
unsigned NumImplicitCopyAssignmentOperators
The number of implicitly-declared copy assignment operators.
void CollectInheritedProtocols(const Decl *CDecl, llvm::SmallPtrSet< ObjCProtocolDecl *, 8 > &Protocols)
CollectInheritedProtocols - Collect all protocols in current class and those inherited by it.
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
llvm::DenseMap< const Decl *, const Decl * > RedeclChainComments
Mapping from canonical declaration to the first redeclaration in chain that has a comment attached.
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const
Return the uniqued reference to the type for an Objective-C gc-qualified type.
QualType getDecltypeType(Expr *e, QualType UnderlyingType) const
C++11 decltype.
std::optional< CXXRecordDeclRelocationInfo > getRelocationInfoForCXXRecord(const CXXRecordDecl *) const
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
InlineVariableDefinitionKind getInlineVariableDefinitionKind(const VarDecl *VD) const
Determine whether a definition of this inline variable should be treated as a weak or strong definiti...
const RawComment * getRawCommentForAnyRedecl(RawCommentLookupKey Key, const Decl **OriginalDecl=nullptr) const
Return the documentation comment attached to a given declaration or macro.
TemplateName getSubstTemplateTemplateParm(TemplateName replacement, Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex, bool Final) const
CanQualType getUIntMaxType() const
Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in <stdint.h>.
friend class DeclContext
uint16_t getPointerAuthVTablePointerDiscriminator(const CXXRecordDecl *RD)
Return the "other" discriminator used for the pointer auth schema used for vtable pointers in instanc...
CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const
Loading virtual member pointers using the virtual inheritance model always results in an adjustment u...
LangAS getLangASForBuiltinAddressSpace(unsigned AS) const
bool hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U)
Determine whether two function types are the same, ignoring pointer sizes in the return type and para...
void addOperatorDeleteForVDtor(const CXXDestructorDecl *Dtor, FunctionDecl *OperatorDelete, OperatorDeleteKind K) const
unsigned char getFixedPointScale(QualType Ty) const
QualType getIncompleteArrayType(QualType EltTy, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a unique reference to the type for an incomplete array of the specified element type.
QualType getDependentSizedExtVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc) const
QualType DecodeTypeStr(const char *&Str, const ASTContext &Context, ASTContext::GetBuiltinTypeError &Error, bool &RequireICE, bool AllowTypeModifiers) const
TemplateName getAssumedTemplateName(DeclarationName Name) const
Retrieve a template name representing an unqualified-id that has been assumed to name a template for ...
@ GE_None
No error.
@ GE_Missing_type
Missing a type.
QualType adjustStringLiteralBaseType(QualType StrLTy) const
uint16_t getPointerAuthTypeDiscriminator(QualType T)
Return the "other" type-specific discriminator for the given type.
llvm::SetVector< const FieldDecl * > PFPFieldsWithEvaluatedOffset
bool canonicalizeTemplateArguments(MutableArrayRef< TemplateArgument > Args) const
Canonicalize the given template argument list.
QualType getTypeOfExprType(Expr *E, TypeOfKind Kind) const
C23 feature and GCC extension.
CanQualType Char8Ty
bool isUnaryOverflowPatternExcluded(const UnaryOperator *UO)
QualType getSignedWCharType() const
Return the type of "signed wchar_t".
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
bool hasCvrSimilarType(QualType T1, QualType T2)
Determine if two types are similar, ignoring only CVR qualifiers.
TemplateName getDeducedTemplateName(TemplateName Underlying, DefaultArguments DefaultArgs) const
Represents a TemplateName which had some of its default arguments deduced.
ObjCImplementationDecl * getObjCImplementation(ObjCInterfaceDecl *D)
Get the implementation of the ObjCInterfaceDecl D, or nullptr if none exists.
CanQualType HalfTy
CanQualType UnsignedAccumTy
void setObjCMethodRedeclaration(const ObjCMethodDecl *MD, const ObjCMethodDecl *Redecl)
void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND)
QualType getConstantMatrixType(QualType ElementType, unsigned NumRows, unsigned NumColumns) const
Return the unique reference to the matrix type of the specified element type and size.
const CXXRecordDecl * baseForVTableAuthentication(const CXXRecordDecl *ThisClass) const
Resolve the root record to be used to derive the vtable pointer authentication policy for the specifi...
void cacheRawComment(RawCommentLookupKey Original, const RawComment &Comment) const
Attaches Comment to Original (a declaration or macro), and to its redeclaration chain when Original i...
QualType getVariableArrayDecayedType(QualType Ty) const
Returns a vla type where known sizes are replaced with [*].
void setCFConstantStringType(QualType T)
const SYCLKernelInfo * findSYCLKernelInfo(QualType T) const
Returns a pointer to the metadata generated from the corresponding SYCLkernel entry point if the prov...
unsigned getParameterIndex(const ParmVarDecl *D) const
Used by ParmVarDecl to retrieve on the side the index of the parameter when it exceeds the size of th...
QualType getCommonSugaredType(QualType X, QualType Y, bool Unqualified=false) const
CanQualType OCLEventTy
void AddDeallocation(void(*Callback)(void *), void *Data) const
Add a deallocation callback that will be invoked when the ASTContext is destroyed.
AttrVec & getDeclAttrs(const Decl *D)
Retrieve the attributes for the given declaration.
QualType getDeducedTemplateSpecializationType(DeducedKind DK, QualType DeducedAsType, ElaboratedTypeKeyword Keyword, TemplateName Template) const
C++17 deduced class template specialization type.
CXXMethodVector::const_iterator overridden_cxx_method_iterator
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
QualType mergeTransparentUnionType(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false)
mergeTransparentUnionType - if T is a transparent union type and a member of T is compatible with Sub...
QualType isPromotableBitField(Expr *E) const
Whether this is a promotable bitfield reference according to C99 6.3.1.1p2, bullet 2 (and GCC extensi...
bool isSentinelNullExpr(const Expr *E)
CanQualType getNSUIntegerType() const
void setIsDestroyingOperatorDelete(const FunctionDecl *FD, bool IsDestroying)
void recordMemberDataPointerEvaluation(const ValueDecl *VD)
uint64_t getCharWidth() const
Return the size of the character type, in bits.
QualType getBitIntType(bool Unsigned, unsigned NumBits) const
Return a bit-precise integer type with the specified signedness and bit count.
unsigned NumImplicitMoveAssignmentOperators
The number of implicitly-declared move assignment operators.
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
virtual void DeducedReturnType(const FunctionDecl *FD, QualType ReturnType)
A function's return type has been deduced.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
CharUnits getAlignment() const
getAlignment - Get the record alignment in characters.
const CXXRecordDecl * getBaseSharingVBPtr() const
CharUnits getSize() const
getSize - Get the record size in characters.
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
CharUnits getDataSize() const
getDataSize() - Get the record data size, which is the record size without tail padding,...
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getNonVirtualSize() const
getNonVirtualSize - Get the non-virtual size (in chars) of an object, which is the size of the object...
CharUnits getUnadjustedAlignment() const
getUnadjustedAlignment - Get the record alignment in characters, before alignment adjustment.
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition TypeBase.h:3553
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3574
Represents a loop initializing the elements of an array.
Definition Expr.h:5971
llvm::APInt getArraySize() const
Definition Expr.h:5993
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:5991
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:6931
Expr * getPtr() const
Definition Expr.h:6962
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:4694
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6675
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:2895
CXXDestructorDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2943
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:1462
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2122
bool isFileContext() const
Definition DeclBase.h:2193
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2138
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void addDecl(Decl *D)
Add the declaration D into this context.
Decl::Kind getDeclKind() const
Definition DeclBase.h:2115
A reference to a declared variable, function, enum, etc.
Definition Expr.h: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:867
static Decl * castFromDeclContext(const DeclContext *)
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp:308
bool isCanonicalDecl() const
Whether this particular Decl is a canonical one.
Definition DeclBase.h:997
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:850
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
ObjCDeclQualifier
ObjCDeclQualifier - 'Qualifiers' written next to the return and parameter types in method declaration...
Definition DeclBase.h:198
bool isInvalidDecl() const
Definition DeclBase.h:596
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:567
void setImplicit(bool I=true)
Definition DeclBase.h:602
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition DeclBase.h:1062
DeclContext * getDeclContext()
Definition DeclBase.h:456
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition DeclBase.cpp:382
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:931
bool hasAttr() const
Definition DeclBase.h:585
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:991
Kind getKind() const
Definition DeclBase.h:450
DeclarationNameLoc - Additional source/type location info for a declaration name.
static DeclarationNameLoc makeCXXOperatorNameLoc(SourceLocation BeginLoc, SourceLocation EndLoc)
Construct location information for a non-literal C++ operator.
The name of a declaration.
static int compare(DeclarationName LHS, DeclarationName RHS)
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:780
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
TemplateName getUnderlying() const
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) const
DefaultArguments getDefaultArguments() const
Represents an extended address space qualifier where the input address space value is dependent.
Definition TypeBase.h: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:233
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
A dynamically typed AST node container.
Represents an enum.
Definition Decl.h:4033
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4251
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4265
EnumDecl * getDefinitionOrSelf() const
Definition Decl.h:4149
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4206
Represents an explicit instantiation of a template entity in source code.
This represents one expression.
Definition Expr.h:112
bool isIntegerConstantExpr(const ASTContext &Ctx) const
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp: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:5544
Abstract interface for external sources of AST nodes.
virtual void CompleteRedeclChain(const Decl *D)
Gives the external AST source an opportunity to complete the redeclaration chain for a declaration.
Represents a member of a struct/union/class.
Definition Decl.h:3182
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3285
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4748
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3267
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3418
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition Decl.cpp:4696
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Represents a function declaration or definition.
Definition Decl.h:2018
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2707
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3738
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2939
bool isMSExternInline() const
The combination of the extern and inline keywords under MSVC forces the function to be required.
Definition Decl.cpp:3867
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3723
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition Decl.h:2300
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4393
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition Decl.h:2428
bool isInlineDefinitionExternallyVisible() const
For an inline function definition in C, or for a gnu_inline function in C++, determine whether the de...
Definition Decl.cpp:4054
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:5854
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition Type.cpp:5892
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:4082
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:5075
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:4416
static void Profile(llvm::FoldingSetNodeID &ID, Parts P)
Definition DeclCXX.h:4453
MSGuidDeclParts Parts
Definition DeclCXX.h:4418
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:3362
A C++ nested-name-specifier augmented with source location information.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NestedNameSpecifier getCanonical() const
Retrieves the "canonical" nested name specifier for a given nested name specifier.
CXXRecordDecl * getAsMicrosoftSuper() const
NamespaceAndPrefix getAsNamespaceAndPrefix() const
Kind
The kind of specifier that completes this nested name specifier.
@ MicrosoftSuper
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace-like entity, stored as a NamespaceBaseDecl*.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, int D, int P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
ObjCCategoryDecl - Represents a category declaration.
Definition DeclObjC.h:2329
ObjCCategoryImplDecl - An object of this class encapsulates a category @implementation declaration.
Definition DeclObjC.h:2545
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition DeclObjC.h:2597
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
ObjCTypeParamList * getTypeParamList() const
Retrieve the type parameters of this class.
Definition DeclObjC.cpp:319
static ObjCInterfaceDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation atLoc, const IdentifierInfo *Id, ObjCTypeParamList *typeParamList, ObjCInterfaceDecl *PrevDecl, SourceLocation ClassLoc=SourceLocation(), bool isInternal=false)
bool hasDefinition() const
Determine whether this class has been defined.
Definition DeclObjC.h:1528
ivar_range ivars() const
Definition DeclObjC.h:1451
bool ClassImplementsProtocol(ObjCProtocolDecl *lProto, bool lookupCategory, bool RHSIsQualifiedID=false)
ClassImplementsProtocol - Checks that 'lProto' protocol has been implemented in IDecl class,...
StringRef getObjCRuntimeNameAsString() const
Produce a name to be used for class's metadata.
ObjCImplementationDecl * getImplementation() const
ObjCInterfaceDecl * getSuperClass() const
Definition DeclObjC.cpp:349
bool isSuperClassOf(const ObjCInterfaceDecl *I) const
isSuperClassOf - Return true if this class is the specified class or is a super class of the specifie...
Definition DeclObjC.h:1810
known_extensions_range known_extensions() const
Definition DeclObjC.h:1762
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h: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:1808
ObjCDeclQualifier getObjCDeclQualifier() const
Definition Decl.h:1872
QualType getOriginalType() const
Definition Decl.cpp:2942
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:2966
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:3675
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:3109
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:4347
bool isLambda() const
Determine whether this record is a class describing a lambda function object.
Definition Decl.cpp:5242
bool hasFlexibleArrayMember() const
Definition Decl.h:4380
field_range fields() const
Definition Decl.h:4550
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition Decl.cpp:5228
RecordDecl * getMostRecentDecl()
Definition Decl.h:4373
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition Decl.cpp:5287
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4531
bool field_empty() const
Definition Decl.h:4558
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h: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:3739
TagTypeKind TagKind
Definition Decl.h:3744
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition Decl.h:3976
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4902
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4895
bool isUnion() const
Definition Decl.h:3950
TagKind getTagKind() const
Definition Decl.h:3939
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Kind
The basic C++ ABI kind.
static Kind getKind(StringRef Name)
Exposes information about the current target.
Definition TargetInfo.h:227
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
unsigned getMaxAtomicInlineWidth() const
Return the maximum width lock-free atomic operation which can be inlined given the supported features...
Definition TargetInfo.h:859
virtual LangAS getCUDABuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
virtual LangAS getOpenCLBuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
unsigned getDefaultAlignForAttributeAligned() const
Return the default alignment for attribute((aligned)) on this target, to be used if no alignment valu...
Definition TargetInfo.h:752
BuiltinVaListKind
The different kinds of __builtin_va_list types defined by the target implementation.
Definition TargetInfo.h:334
@ AArch64ABIBuiltinVaList
__builtin_va_list as defined by the AArch64 ABI http://infocenter.arm.com/help/topic/com....
Definition TargetInfo.h:343
@ PowerABIBuiltinVaList
__builtin_va_list as defined by the Power ABI: https://www.power.org /resources/downloads/Power-Arch-...
Definition TargetInfo.h:348
@ AAPCSABIBuiltinVaList
__builtin_va_list as defined by ARM AAPCS ABI http://infocenter.arm.com
Definition TargetInfo.h:357
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition TargetInfo.h:336
@ VoidPtrBuiltinVaList
typedef void* __builtin_va_list;
Definition TargetInfo.h:339
@ X86_64ABIBuiltinVaList
__builtin_va_list as defined by the x86-64 ABI: http://refspecs.linuxbase.org/elf/x86_64-abi-0....
Definition TargetInfo.h:352
virtual uint64_t getNullPointerValue(LangAS AddrSpace) const
Get integer value for null pointer.
Definition TargetInfo.h:506
static bool isTypeSigned(IntType T)
Returns true if the type is signed; false otherwise.
IntType getPtrDiffType(LangAS AddrSpace) const
Definition TargetInfo.h:408
IntType getSizeType() const
Definition TargetInfo.h:389
FloatModeKind getRealTypeByWidth(unsigned BitWidth, FloatModeKind ExplicitType) const
Return floating point type with specified width.
virtual IntType getIntTypeByWidth(unsigned BitWidth, bool IsSigned) const
Return integer type with specified width.
unsigned getMaxAlignedAttribute() const
Get the maximum alignment in bits for a static variable with aligned attribute.
Definition TargetInfo.h:979
virtual unsigned getMinGlobalAlign(uint64_t Size, bool HasNonWeakDef) const
getMinGlobalAlign - Return the minimum alignment of a global variable, unless its alignment is explic...
Definition TargetInfo.h:760
unsigned getTargetAddressSpace(LangAS AS) const
IntType getSignedSizeType() const
Definition TargetInfo.h:390
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
bool useAddressSpaceMapMangling() const
Specify if mangling based on address space map should be used or not for language specific address sp...
A convenient class for passing around template argument information.
ArrayRef< TemplateArgumentLoc > arguments() const
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Location wrapper for a TemplateArgument.
Represents a template argument.
ArrayRef< TemplateArgument > getPackAsArray() const
Return the array of arguments in this template argument pack.
QualType getStructuralValueType() const
Get the type of a StructuralValue.
QualType getParamTypeForDecl() const
Expr * getAsExpr() const
Retrieve the template argument as an expression.
UnsignedOrNone getNumTemplateExpansions() const
Retrieve the number of expansions that a template template argument expansion will produce,...
QualType getAsType() const
Retrieve the type for a type template argument.
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
static TemplateArgument CreatePackCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument pack by copying the given set of template arguments.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
bool structurallyEquals(const TemplateArgument &Other) const
Determines whether two template arguments are superficially the same.
QualType getIntegralType() const
Retrieve the type of the integral value.
bool getIsDefaulted() const
If returns 'true', this TemplateArgument corresponds to a default template parameter.
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
ArrayRef< TemplateArgument > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
@ Template
The template argument is a template name that was provided for a template template parameter.
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
@ Pack
The template argument is actually a parameter pack.
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
@ Type
The template argument is a type.
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
ArgKind getKind() const
Return the kind of stored template argument.
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
The base class of all kinds of template declarations (e.g., class, function, etc.).
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
DeducedTemplateStorage * getAsDeducedTemplateName() const
Retrieve the deduced template info, if any.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
std::optional< TemplateName > desugar(bool IgnoreDeduced) const
OverloadedTemplateStorage * getAsOverloadedTemplate() const
Retrieve the underlying, overloaded function template declarations that this template name refers to,...
AssumedTemplateStorage * getAsAssumedTemplateName() const
Retrieve information on a name that has been assumed to be a template-name in order to permit a call ...
NameKind getKind() const
void * getAsVoidPointer() const
Retrieve the template name as a void pointer.
@ UsingTemplate
A template name that refers to a template declaration found through a specific using shadow declarati...
@ OverloadedTemplate
A set of overloaded template declarations.
@ Template
A single template declaration.
@ DependentTemplate
A dependent template name that has not been resolved to a template (or set of templates).
@ SubstTemplateTemplateParm
A template template parameter that has been substituted for some other template name.
@ SubstTemplateTemplateParmPack
A template template parameter pack that has been substituted for a template template argument pack,...
@ DeducedTemplate
A template name that refers to another TemplateName with deduced default arguments.
@ QualifiedTemplate
A qualified template name, where the qualification is kept to describe the source code as written.
@ AssumedTemplate
An unqualified-id that has been assumed to name a function template that will be found by ADL.
UsingShadowDecl * getAsUsingShadowDecl() const
Retrieve the using shadow declaration through which the underlying template declaration is introduced...
SubstTemplateTemplateParmPackStorage * getAsSubstTemplateTemplateParmPack() const
Retrieve the substituted template template parameter pack, if known.
SubstTemplateTemplateParmStorage * getAsSubstTemplateTemplateParm() const
Retrieve the substituted template template parameter, if known.
A template parameter object.
static void Profile(llvm::FoldingSetNodeID &ID, QualType T, const APValue &V)
Stores a list of template parameters for a TemplateDecl and its derived classes.
NamedDecl * getParam(unsigned Idx)
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
NamedDecl *const * const_iterator
Iterates through the template parameters in this list.
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
ArrayRef< NamedDecl * > asArray()
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
TemplateNameKind templateParameterKind() const
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
bool isParameterPack() const
Whether this template template parameter is a template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, int D, int P, bool ParameterPack, IdentifierInfo *Id, TemplateNameKind ParameterKind, bool Typename, TemplateParameterList *Params)
unsigned getDepth() const
Get the nesting depth of the template parameter.
Declaration of a template type parameter.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, int D, int P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, UnsignedOrNone NumExpanded=std::nullopt)
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition ASTConcept.h:227
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition ASTConcept.h:244
TemplateDecl * getNamedConcept() const
Definition ASTConcept.h:254
ConceptReference * getConceptReference() const
Definition ASTConcept.h:248
Represents a declaration of a type.
Definition Decl.h:3535
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition TypeLoc.h:78
static unsigned getFullDataSizeForType(QualType Ty)
Returns the size of type source info data block for the given type.
Definition TypeLoc.cpp:95
void initialize(ASTContext &Context, SourceLocation Loc) const
Initializes this to state that every location in this type is the given location.
Definition TypeLoc.h:211
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition TypeBase.h: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:2771
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:2266
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:2517
bool isArrayType() const
Definition TypeBase.h:8783
bool isCharType() const
Definition Type.cpp:2193
QualType getLocallyUnqualifiedSingleStepDesugaredType() const
Pull a single level of sugar off of this locally-unqualified type.
Definition Type.cpp:558
bool isPointerType() const
Definition TypeBase.h: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:2527
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:2753
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2688
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h: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:2332
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:5431
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5152
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3689
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5762
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3584
QualType getUnderlyingType() const
Definition Decl.h:3639
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType Underlying)
Definition TypeBase.h: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:4473
static void Profile(llvm::FoldingSetNodeID &ID, QualType Ty, const APValue &APVal)
Definition DeclCXX.h:4501
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:4055
UnresolvedUsingTypenameDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this declaration.
Definition DeclCXX.h:4120
Represents a C++ using-enum-declaration.
Definition DeclCXX.h:3810
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3417
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3481
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition DeclCXX.cpp:3475
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UsingShadowDecl *D, QualType UnderlyingType)
Definition TypeBase.h: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:5577
void clear()
Definition Value.cpp:217
Represents a variable declaration or definition.
Definition Decl.h:924
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2770
bool hasInit() const
Definition Decl.cpp:2377
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a static data member.
Definition Decl.cpp:2440
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1296
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1206
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1564
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1308
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2354
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition Decl.cpp:2739
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:1106
ArrayRef< BlockContentComment * > getBlocks() const
Definition Comment.h:1144
const DeclInfo * getDeclInfo() const LLVM_READONLY
Definition Comment.h:1138
const Decl * getDecl() const LLVM_READONLY
Definition Comment.h:1134
Holds all information required to evaluate constexpr code in a module.
Definition Context.h:47
Defines the Linkage enumeration and various utility functions.
Defines the clang::TargetInfo interface.
Definition SPIR.cpp:47
mlir::Type getBaseType(mlir::Value varPtr)
const AstTypeMatcher< TagType > tagType
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ArrayType > arrayType
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus17
GVALinkage
A more specific kind of linkage than enum Linkage.
Definition Linkage.h:72
@ GVA_StrongODR
Definition Linkage.h:77
@ GVA_StrongExternal
Definition Linkage.h:76
@ GVA_AvailableExternally
Definition Linkage.h:74
@ GVA_DiscardableODR
Definition Linkage.h:75
@ GVA_Internal
Definition Linkage.h:73
AutoTypeKeyword
Which keyword(s) were used to create an AutoType.
Definition TypeBase.h:1834
OpenCLTypeKind
OpenCL type kinds.
Definition TargetInfo.h:213
@ OCLTK_ReserveID
Definition TargetInfo.h:220
@ OCLTK_Sampler
Definition TargetInfo.h:221
@ OCLTK_Pipe
Definition TargetInfo.h:218
@ OCLTK_ClkEvent
Definition TargetInfo.h:215
@ OCLTK_Event
Definition TargetInfo.h:216
@ OCLTK_Default
Definition TargetInfo.h:214
@ OCLTK_Queue
Definition TargetInfo.h:219
FunctionType::ExtInfo getFunctionExtInfo(const Type &t)
Definition TypeBase.h: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:1301
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ConceptReference *C)
Insertion operator for diagnostics.
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:189
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:207
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:203
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:199
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:195
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:192
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:279
@ CC_M68kRTD
Definition Specifiers.h:300
@ CC_X86RegCall
Definition Specifiers.h:288
@ CC_X86VectorCall
Definition Specifiers.h:284
@ CC_X86StdCall
Definition Specifiers.h:281
@ CC_X86FastCall
Definition Specifiers.h:282
@ Invariant
The parameter is invariant: must match exactly.
Definition DeclObjC.h:555
@ Contravariant
The parameter is contravariant, e.g., X<T> is a subtype of X when the type parameter is covariant and...
Definition DeclObjC.h:563
@ Covariant
The parameter is covariant, e.g., X<T> is a subtype of X when the type parameter is covariant and T i...
Definition DeclObjC.h:559
@ AltiVecBool
is AltiVec 'vector bool ...'
Definition TypeBase.h: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
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:6721
Expr * getCopyExpr() const
Definition Expr.h:6728
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:3385
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:983
const TemplateParameterList * TemplateParameters
Template parameters that can be referenced by \tparam if CommentDecl is a template (IsTemplateDecl or...
Definition Comment.h:1009
const Decl * CommentDecl
Declaration the comment is actually attached to (in the source).
Definition Comment.h:986