clang 20.0.0git
ASTContext.cpp
Go to the documentation of this file.
1//===- ASTContext.cpp - Context to hold long-lived AST nodes --------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the ASTContext interface.
10//
11//===----------------------------------------------------------------------===//
12
14#include "ByteCode/Context.h"
15#include "CXXABI.h"
16#include "clang/AST/APValue.h"
20#include "clang/AST/Attr.h"
22#include "clang/AST/CharUnits.h"
23#include "clang/AST/Comment.h"
24#include "clang/AST/Decl.h"
25#include "clang/AST/DeclBase.h"
26#include "clang/AST/DeclCXX.h"
28#include "clang/AST/DeclObjC.h"
33#include "clang/AST/Expr.h"
34#include "clang/AST/ExprCXX.h"
36#include "clang/AST/Mangle.h"
42#include "clang/AST/Stmt.h"
45#include "clang/AST/Type.h"
46#include "clang/AST/TypeLoc.h"
54#include "clang/Basic/LLVM.h"
56#include "clang/Basic/Linkage.h"
57#include "clang/Basic/Module.h"
67#include "llvm/ADT/APFixedPoint.h"
68#include "llvm/ADT/APInt.h"
69#include "llvm/ADT/APSInt.h"
70#include "llvm/ADT/ArrayRef.h"
71#include "llvm/ADT/DenseMap.h"
72#include "llvm/ADT/DenseSet.h"
73#include "llvm/ADT/FoldingSet.h"
74#include "llvm/ADT/PointerUnion.h"
75#include "llvm/ADT/STLExtras.h"
76#include "llvm/ADT/SmallPtrSet.h"
77#include "llvm/ADT/SmallVector.h"
78#include "llvm/ADT/StringExtras.h"
79#include "llvm/ADT/StringRef.h"
80#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
81#include "llvm/Support/Capacity.h"
82#include "llvm/Support/Compiler.h"
83#include "llvm/Support/ErrorHandling.h"
84#include "llvm/Support/MD5.h"
85#include "llvm/Support/MathExtras.h"
86#include "llvm/Support/SipHash.h"
87#include "llvm/Support/raw_ostream.h"
88#include "llvm/TargetParser/AArch64TargetParser.h"
89#include "llvm/TargetParser/Triple.h"
90#include <algorithm>
91#include <cassert>
92#include <cstddef>
93#include <cstdint>
94#include <cstdlib>
95#include <map>
96#include <memory>
97#include <optional>
98#include <string>
99#include <tuple>
100#include <utility>
101
102using namespace clang;
103
114
115template <> struct llvm::DenseMapInfo<llvm::FoldingSetNodeID> {
116 static FoldingSetNodeID getEmptyKey() { return FoldingSetNodeID{}; }
117
118 static FoldingSetNodeID getTombstoneKey() {
119 FoldingSetNodeID id;
120 for (size_t i = 0; i < sizeof(id) / sizeof(unsigned); ++i) {
121 id.AddInteger(std::numeric_limits<unsigned>::max());
122 }
123 return id;
124 }
125
126 static unsigned getHashValue(const FoldingSetNodeID &Val) {
127 return Val.ComputeHash();
128 }
129
130 static bool isEqual(const FoldingSetNodeID &LHS,
131 const FoldingSetNodeID &RHS) {
132 return LHS == RHS;
133 }
134};
135
136/// \returns The locations that are relevant when searching for Doc comments
137/// related to \p D.
140 assert(D);
141
142 // User can not attach documentation to implicit declarations.
143 if (D->isImplicit())
144 return {};
145
146 // User can not attach documentation to implicit instantiations.
147 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
148 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
149 return {};
150 }
151
152 if (const auto *VD = dyn_cast<VarDecl>(D)) {
153 if (VD->isStaticDataMember() &&
154 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
155 return {};
156 }
157
158 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
159 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
160 return {};
161 }
162
163 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
164 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
165 if (TSK == TSK_ImplicitInstantiation ||
166 TSK == TSK_Undeclared)
167 return {};
168 }
169
170 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
171 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
172 return {};
173 }
174 if (const auto *TD = dyn_cast<TagDecl>(D)) {
175 // When tag declaration (but not definition!) is part of the
176 // decl-specifier-seq of some other declaration, it doesn't get comment
177 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
178 return {};
179 }
180 // TODO: handle comments for function parameters properly.
181 if (isa<ParmVarDecl>(D))
182 return {};
183
184 // TODO: we could look up template parameter documentation in the template
185 // documentation.
186 if (isa<TemplateTypeParmDecl>(D) ||
187 isa<NonTypeTemplateParmDecl>(D) ||
188 isa<TemplateTemplateParmDecl>(D))
189 return {};
190
192 // Find declaration location.
193 // For Objective-C declarations we generally don't expect to have multiple
194 // declarators, thus use declaration starting location as the "declaration
195 // location".
196 // For all other declarations multiple declarators are used quite frequently,
197 // so we use the location of the identifier as the "declaration location".
198 SourceLocation BaseLocation;
199 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
200 isa<ObjCPropertyDecl>(D) || isa<RedeclarableTemplateDecl>(D) ||
201 isa<ClassTemplateSpecializationDecl>(D) ||
202 // Allow association with Y across {} in `typedef struct X {} Y`.
203 isa<TypedefDecl>(D))
204 BaseLocation = D->getBeginLoc();
205 else
206 BaseLocation = D->getLocation();
207
208 if (!D->getLocation().isMacroID()) {
209 Locations.emplace_back(BaseLocation);
210 } else {
211 const auto *DeclCtx = D->getDeclContext();
212
213 // When encountering definitions generated from a macro (that are not
214 // contained by another declaration in the macro) we need to try and find
215 // the comment at the location of the expansion but if there is no comment
216 // there we should retry to see if there is a comment inside the macro as
217 // well. To this end we return first BaseLocation to first look at the
218 // expansion site, the second value is the spelling location of the
219 // beginning of the declaration defined inside the macro.
220 if (!(DeclCtx &&
221 Decl::castFromDeclContext(DeclCtx)->getLocation().isMacroID())) {
222 Locations.emplace_back(SourceMgr.getExpansionLoc(BaseLocation));
223 }
224
225 // We use Decl::getBeginLoc() and not just BaseLocation here to ensure that
226 // we don't refer to the macro argument location at the expansion site (this
227 // can happen if the name's spelling is provided via macro argument), and
228 // always to the declaration itself.
229 Locations.emplace_back(SourceMgr.getSpellingLoc(D->getBeginLoc()));
230 }
231
232 return Locations;
233}
234
236 const Decl *D, const SourceLocation RepresentativeLocForDecl,
237 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
238 // If the declaration doesn't map directly to a location in a file, we
239 // can't find the comment.
240 if (RepresentativeLocForDecl.isInvalid() ||
241 !RepresentativeLocForDecl.isFileID())
242 return nullptr;
243
244 // If there are no comments anywhere, we won't find anything.
245 if (CommentsInTheFile.empty())
246 return nullptr;
247
248 // Decompose the location for the declaration and find the beginning of the
249 // file buffer.
250 const std::pair<FileID, unsigned> DeclLocDecomp =
251 SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
252
253 // Slow path.
254 auto OffsetCommentBehindDecl =
255 CommentsInTheFile.lower_bound(DeclLocDecomp.second);
256
257 // First check whether we have a trailing comment.
258 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
259 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
260 if ((CommentBehindDecl->isDocumentation() ||
261 LangOpts.CommentOpts.ParseAllComments) &&
262 CommentBehindDecl->isTrailingComment() &&
263 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
264 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
265
266 // Check that Doxygen trailing comment comes after the declaration, starts
267 // on the same line and in the same file as the declaration.
268 if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
269 Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
270 OffsetCommentBehindDecl->first)) {
271 return CommentBehindDecl;
272 }
273 }
274 }
275
276 // The comment just after the declaration was not a trailing comment.
277 // Let's look at the previous comment.
278 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
279 return nullptr;
280
281 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
282 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
283
284 // Check that we actually have a non-member Doxygen comment.
285 if (!(CommentBeforeDecl->isDocumentation() ||
286 LangOpts.CommentOpts.ParseAllComments) ||
287 CommentBeforeDecl->isTrailingComment())
288 return nullptr;
289
290 // Decompose the end of the comment.
291 const unsigned CommentEndOffset =
292 Comments.getCommentEndOffset(CommentBeforeDecl);
293
294 // Get the corresponding buffer.
295 bool Invalid = false;
296 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
297 &Invalid).data();
298 if (Invalid)
299 return nullptr;
300
301 // Extract text between the comment and declaration.
302 StringRef Text(Buffer + CommentEndOffset,
303 DeclLocDecomp.second - CommentEndOffset);
304
305 // There should be no other declarations or preprocessor directives between
306 // comment and declaration.
307 if (Text.find_last_of(";{}#@") != StringRef::npos)
308 return nullptr;
309
310 return CommentBeforeDecl;
311}
312
314 const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr);
315
316 for (const auto DeclLoc : DeclLocs) {
317 // If the declaration doesn't map directly to a location in a file, we
318 // can't find the comment.
319 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
320 continue;
321
324 CommentsLoaded = true;
325 }
326
327 if (Comments.empty())
328 continue;
329
330 const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
331 if (!File.isValid())
332 continue;
333
334 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
335 if (!CommentsInThisFile || CommentsInThisFile->empty())
336 continue;
337
338 if (RawComment *Comment =
339 getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile))
340 return Comment;
341 }
342
343 return nullptr;
344}
345
347 assert(LangOpts.RetainCommentsFromSystemHeaders ||
348 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
349 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
350}
351
352/// If we have a 'templated' declaration for a template, adjust 'D' to
353/// refer to the actual template.
354/// If we have an implicit instantiation, adjust 'D' to refer to template.
355static const Decl &adjustDeclToTemplate(const Decl &D) {
356 if (const auto *FD = dyn_cast<FunctionDecl>(&D)) {
357 // Is this function declaration part of a function template?
358 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
359 return *FTD;
360
361 // Nothing to do if function is not an implicit instantiation.
362 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
363 return D;
364
365 // Function is an implicit instantiation of a function template?
366 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
367 return *FTD;
368
369 // Function is instantiated from a member definition of a class template?
370 if (const FunctionDecl *MemberDecl =
372 return *MemberDecl;
373
374 return D;
375 }
376 if (const auto *VD = dyn_cast<VarDecl>(&D)) {
377 // Static data member is instantiated from a member definition of a class
378 // template?
379 if (VD->isStaticDataMember())
380 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
381 return *MemberDecl;
382
383 return D;
384 }
385 if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) {
386 // Is this class declaration part of a class template?
387 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
388 return *CTD;
389
390 // Class is an implicit instantiation of a class template or partial
391 // specialization?
392 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
393 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
394 return D;
395 llvm::PointerUnion<ClassTemplateDecl *,
398 return isa<ClassTemplateDecl *>(PU)
399 ? *static_cast<const Decl *>(cast<ClassTemplateDecl *>(PU))
400 : *static_cast<const Decl *>(
401 cast<ClassTemplatePartialSpecializationDecl *>(PU));
402 }
403
404 // Class is instantiated from a member definition of a class template?
405 if (const MemberSpecializationInfo *Info =
406 CRD->getMemberSpecializationInfo())
407 return *Info->getInstantiatedFrom();
408
409 return D;
410 }
411 if (const auto *ED = dyn_cast<EnumDecl>(&D)) {
412 // Enum is instantiated from a member definition of a class template?
413 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
414 return *MemberDecl;
415
416 return D;
417 }
418 // FIXME: Adjust alias templates?
419 return D;
420}
421
423 const Decl *D,
424 const Decl **OriginalDecl) const {
425 if (!D) {
426 if (OriginalDecl)
427 OriginalDecl = nullptr;
428 return nullptr;
429 }
430
432
433 // Any comment directly attached to D?
434 {
435 auto DeclComment = DeclRawComments.find(D);
436 if (DeclComment != DeclRawComments.end()) {
437 if (OriginalDecl)
438 *OriginalDecl = D;
439 return DeclComment->second;
440 }
441 }
442
443 // Any comment attached to any redeclaration of D?
444 const Decl *CanonicalD = D->getCanonicalDecl();
445 if (!CanonicalD)
446 return nullptr;
447
448 {
449 auto RedeclComment = RedeclChainComments.find(CanonicalD);
450 if (RedeclComment != RedeclChainComments.end()) {
451 if (OriginalDecl)
452 *OriginalDecl = RedeclComment->second;
453 auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
454 assert(CommentAtRedecl != DeclRawComments.end() &&
455 "This decl is supposed to have comment attached.");
456 return CommentAtRedecl->second;
457 }
458 }
459
460 // Any redeclarations of D that we haven't checked for comments yet?
461 const Decl *LastCheckedRedecl = [&]() {
462 const Decl *LastChecked = CommentlessRedeclChains.lookup(CanonicalD);
463 bool CanUseCommentlessCache = false;
464 if (LastChecked) {
465 for (auto *Redecl : CanonicalD->redecls()) {
466 if (Redecl == D) {
467 CanUseCommentlessCache = true;
468 break;
469 }
470 if (Redecl == LastChecked)
471 break;
472 }
473 }
474 // FIXME: This could be improved so that even if CanUseCommentlessCache
475 // is false, once we've traversed past CanonicalD we still skip ahead
476 // LastChecked.
477 return CanUseCommentlessCache ? LastChecked : nullptr;
478 }();
479
480 for (const Decl *Redecl : D->redecls()) {
481 assert(Redecl);
482 // Skip all redeclarations that have been checked previously.
483 if (LastCheckedRedecl) {
484 if (LastCheckedRedecl == Redecl) {
485 LastCheckedRedecl = nullptr;
486 }
487 continue;
488 }
489 const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
490 if (RedeclComment) {
491 cacheRawCommentForDecl(*Redecl, *RedeclComment);
492 if (OriginalDecl)
493 *OriginalDecl = Redecl;
494 return RedeclComment;
495 }
496 CommentlessRedeclChains[CanonicalD] = Redecl;
497 }
498
499 if (OriginalDecl)
500 *OriginalDecl = nullptr;
501 return nullptr;
502}
503
505 const RawComment &Comment) const {
506 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
507 DeclRawComments.try_emplace(&OriginalD, &Comment);
508 const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
509 RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
510 CommentlessRedeclChains.erase(CanonicalDecl);
511}
512
513static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
515 const DeclContext *DC = ObjCMethod->getDeclContext();
516 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
517 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
518 if (!ID)
519 return;
520 // Add redeclared method here.
521 for (const auto *Ext : ID->known_extensions()) {
522 if (ObjCMethodDecl *RedeclaredMethod =
523 Ext->getMethod(ObjCMethod->getSelector(),
524 ObjCMethod->isInstanceMethod()))
525 Redeclared.push_back(RedeclaredMethod);
526 }
527 }
528}
529
531 const Preprocessor *PP) {
532 if (Comments.empty() || Decls.empty())
533 return;
534
535 FileID File;
536 for (const Decl *D : Decls) {
537 if (D->isInvalidDecl())
538 continue;
539
542 if (Loc.isValid()) {
543 // See if there are any new comments that are not attached to a decl.
544 // The location doesn't have to be precise - we care only about the file.
545 File = SourceMgr.getDecomposedLoc(Loc).first;
546 break;
547 }
548 }
549
550 if (File.isInvalid())
551 return;
552
553 auto CommentsInThisFile = Comments.getCommentsInFile(File);
554 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
555 CommentsInThisFile->rbegin()->second->isAttached())
556 return;
557
558 // There is at least one comment not attached to a decl.
559 // Maybe it should be attached to one of Decls?
560 //
561 // Note that this way we pick up not only comments that precede the
562 // declaration, but also comments that *follow* the declaration -- thanks to
563 // the lookahead in the lexer: we've consumed the semicolon and looked
564 // ahead through comments.
565 for (const Decl *D : Decls) {
566 assert(D);
567 if (D->isInvalidDecl())
568 continue;
569
571
572 if (DeclRawComments.count(D) > 0)
573 continue;
574
575 const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr);
576
577 for (const auto DeclLoc : DeclLocs) {
578 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
579 continue;
580
581 if (RawComment *const DocComment = getRawCommentForDeclNoCacheImpl(
582 D, DeclLoc, *CommentsInThisFile)) {
583 cacheRawCommentForDecl(*D, *DocComment);
584 comments::FullComment *FC = DocComment->parse(*this, PP, D);
586 break;
587 }
588 }
589 }
590}
591
593 const Decl *D) const {
594 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
595 ThisDeclInfo->CommentDecl = D;
596 ThisDeclInfo->IsFilled = false;
597 ThisDeclInfo->fill();
598 ThisDeclInfo->CommentDecl = FC->getDecl();
599 if (!ThisDeclInfo->TemplateParameters)
600 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
602 new (*this) comments::FullComment(FC->getBlocks(),
603 ThisDeclInfo);
604 return CFC;
605}
606
609 return RC ? RC->parse(*this, nullptr, D) : nullptr;
610}
611
613 const Decl *D,
614 const Preprocessor *PP) const {
615 if (!D || D->isInvalidDecl())
616 return nullptr;
618
619 const Decl *Canonical = D->getCanonicalDecl();
620 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
621 ParsedComments.find(Canonical);
622
623 if (Pos != ParsedComments.end()) {
624 if (Canonical != D) {
625 comments::FullComment *FC = Pos->second;
627 return CFC;
628 }
629 return Pos->second;
630 }
631
632 const Decl *OriginalDecl = nullptr;
633
634 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
635 if (!RC) {
636 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
638 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
639 if (OMD && OMD->isPropertyAccessor())
640 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
641 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
642 return cloneFullComment(FC, D);
643 if (OMD)
644 addRedeclaredMethods(OMD, Overridden);
645 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
646 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
647 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
648 return cloneFullComment(FC, D);
649 }
650 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
651 // Attach any tag type's documentation to its typedef if latter
652 // does not have one of its own.
653 QualType QT = TD->getUnderlyingType();
654 if (const auto *TT = QT->getAs<TagType>())
655 if (const Decl *TD = TT->getDecl())
657 return cloneFullComment(FC, D);
658 }
659 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
660 while (IC->getSuperClass()) {
661 IC = IC->getSuperClass();
663 return cloneFullComment(FC, D);
664 }
665 }
666 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
667 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
669 return cloneFullComment(FC, D);
670 }
671 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
672 if (!(RD = RD->getDefinition()))
673 return nullptr;
674 // Check non-virtual bases.
675 for (const auto &I : RD->bases()) {
676 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
677 continue;
678 QualType Ty = I.getType();
679 if (Ty.isNull())
680 continue;
682 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
683 continue;
684
686 return cloneFullComment(FC, D);
687 }
688 }
689 // Check virtual bases.
690 for (const auto &I : RD->vbases()) {
691 if (I.getAccessSpecifier() != AS_public)
692 continue;
693 QualType Ty = I.getType();
694 if (Ty.isNull())
695 continue;
696 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
697 if (!(VirtualBase= VirtualBase->getDefinition()))
698 continue;
700 return cloneFullComment(FC, D);
701 }
702 }
703 }
704 return nullptr;
705 }
706
707 // If the RawComment was attached to other redeclaration of this Decl, we
708 // should parse the comment in context of that other Decl. This is important
709 // because comments can contain references to parameter names which can be
710 // different across redeclarations.
711 if (D != OriginalDecl && OriginalDecl)
712 return getCommentForDecl(OriginalDecl, PP);
713
714 comments::FullComment *FC = RC->parse(*this, PP, D);
715 ParsedComments[Canonical] = FC;
716 return FC;
717}
718
719void
720ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
721 const ASTContext &C,
723 ID.AddInteger(Parm->getDepth());
724 ID.AddInteger(Parm->getPosition());
725 ID.AddBoolean(Parm->isParameterPack());
726
728 ID.AddInteger(Params->size());
730 PEnd = Params->end();
731 P != PEnd; ++P) {
732 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
733 ID.AddInteger(0);
734 ID.AddBoolean(TTP->isParameterPack());
735 if (TTP->isExpandedParameterPack()) {
736 ID.AddBoolean(true);
737 ID.AddInteger(TTP->getNumExpansionParameters());
738 } else
739 ID.AddBoolean(false);
740 continue;
741 }
742
743 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
744 ID.AddInteger(1);
745 ID.AddBoolean(NTTP->isParameterPack());
746 ID.AddPointer(C.getUnconstrainedType(C.getCanonicalType(NTTP->getType()))
747 .getAsOpaquePtr());
748 if (NTTP->isExpandedParameterPack()) {
749 ID.AddBoolean(true);
750 ID.AddInteger(NTTP->getNumExpansionTypes());
751 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
752 QualType T = NTTP->getExpansionType(I);
753 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
754 }
755 } else
756 ID.AddBoolean(false);
757 continue;
758 }
759
760 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
761 ID.AddInteger(2);
762 Profile(ID, C, TTP);
763 }
764}
765
767ASTContext::getCanonicalTemplateTemplateParmDecl(
768 TemplateTemplateParmDecl *TTP) const {
769 // Check if we already have a canonical template template parameter.
770 llvm::FoldingSetNodeID ID;
771 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
772 void *InsertPos = nullptr;
773 CanonicalTemplateTemplateParm *Canonical
774 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
775 if (Canonical)
776 return Canonical->getParam();
777
778 // Build a canonical template parameter list.
780 SmallVector<NamedDecl *, 4> CanonParams;
781 CanonParams.reserve(Params->size());
783 PEnd = Params->end();
784 P != PEnd; ++P) {
785 // Note that, per C++20 [temp.over.link]/6, when determining whether
786 // template-parameters are equivalent, constraints are ignored.
787 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
790 TTP->getDepth(), TTP->getIndex(), nullptr, false,
791 TTP->isParameterPack(), /*HasTypeConstraint=*/false,
793 ? std::optional<unsigned>(TTP->getNumExpansionParameters())
794 : std::nullopt);
795 CanonParams.push_back(NewTTP);
796 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
800 if (NTTP->isExpandedParameterPack()) {
801 SmallVector<QualType, 2> ExpandedTypes;
803 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
804 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
805 ExpandedTInfos.push_back(
806 getTrivialTypeSourceInfo(ExpandedTypes.back()));
807 }
808
812 NTTP->getDepth(),
813 NTTP->getPosition(), nullptr,
814 T,
815 TInfo,
816 ExpandedTypes,
817 ExpandedTInfos);
818 } else {
822 NTTP->getDepth(),
823 NTTP->getPosition(), nullptr,
824 T,
825 NTTP->isParameterPack(),
826 TInfo);
827 }
828 CanonParams.push_back(Param);
829 } else
830 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
831 cast<TemplateTemplateParmDecl>(*P)));
832 }
833
836 TTP->getPosition(), TTP->isParameterPack(), nullptr, /*Typename=*/false,
838 CanonParams, SourceLocation(),
839 /*RequiresClause=*/nullptr));
840
841 // Get the new insert position for the node we care about.
842 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
843 assert(!Canonical && "Shouldn't be in the map!");
844 (void)Canonical;
845
846 // Create the canonical template template parameter entry.
847 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
848 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
849 return CanonTTP;
850}
851
852/// Check if a type can have its sanitizer instrumentation elided based on its
853/// presence within an ignorelist.
855 const QualType &Ty) const {
856 std::string TyName = Ty.getUnqualifiedType().getAsString(getPrintingPolicy());
857 return NoSanitizeL->containsType(Mask, TyName) &&
858 !NoSanitizeL->containsType(Mask, TyName, "sanitize");
859}
860
862 auto Kind = getTargetInfo().getCXXABI().getKind();
863 return getLangOpts().CXXABI.value_or(Kind);
864}
865
866CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
867 if (!LangOpts.CPlusPlus) return nullptr;
868
869 switch (getCXXABIKind()) {
870 case TargetCXXABI::AppleARM64:
871 case TargetCXXABI::Fuchsia:
872 case TargetCXXABI::GenericARM: // Same as Itanium at this level
873 case TargetCXXABI::iOS:
874 case TargetCXXABI::WatchOS:
875 case TargetCXXABI::GenericAArch64:
876 case TargetCXXABI::GenericMIPS:
877 case TargetCXXABI::GenericItanium:
878 case TargetCXXABI::WebAssembly:
879 case TargetCXXABI::XL:
880 return CreateItaniumCXXABI(*this);
881 case TargetCXXABI::Microsoft:
882 return CreateMicrosoftCXXABI(*this);
883 }
884 llvm_unreachable("Invalid CXXABI type!");
885}
886
888 if (!InterpContext) {
889 InterpContext.reset(new interp::Context(*this));
890 }
891 return *InterpContext.get();
892}
893
895 if (!ParentMapCtx)
896 ParentMapCtx.reset(new ParentMapContext(*this));
897 return *ParentMapCtx.get();
898}
899
901 const LangOptions &LangOpts) {
902 switch (LangOpts.getAddressSpaceMapMangling()) {
904 return TI.useAddressSpaceMapMangling();
906 return true;
908 return false;
909 }
910 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
911}
912
914 IdentifierTable &idents, SelectorTable &sels,
915 Builtin::Context &builtins, TranslationUnitKind TUKind)
916 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize),
917 DependentSizedArrayTypes(this_()), DependentSizedExtVectorTypes(this_()),
918 DependentAddressSpaceTypes(this_()), DependentVectorTypes(this_()),
919 DependentSizedMatrixTypes(this_()),
920 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize),
921 DependentTypeOfExprTypes(this_()), DependentDecltypeTypes(this_()),
922 TemplateSpecializationTypes(this_()),
923 DependentTemplateSpecializationTypes(this_()),
924 DependentBitIntTypes(this_()), SubstTemplateTemplateParmPacks(this_()),
925 DeducedTemplates(this_()), ArrayParameterTypes(this_()),
926 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
927 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
928 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
929 LangOpts.XRayNeverInstrumentFiles,
930 LangOpts.XRayAttrListFiles, SM)),
931 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
932 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
933 BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this),
934 Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
935 CompCategories(this_()), LastSDM(nullptr, 0) {
937}
938
940 // Release the DenseMaps associated with DeclContext objects.
941 // FIXME: Is this the ideal solution?
942 ReleaseDeclContextMaps();
943
944 // Call all of the deallocation functions on all of their targets.
945 for (auto &Pair : Deallocations)
946 (Pair.first)(Pair.second);
947 Deallocations.clear();
948
949 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
950 // because they can contain DenseMaps.
951 for (llvm::DenseMap<const ObjCContainerDecl*,
952 const ASTRecordLayout*>::iterator
953 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
954 // Increment in loop to prevent using deallocated memory.
955 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
956 R->Destroy(*this);
957 ObjCLayouts.clear();
958
959 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
960 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
961 // Increment in loop to prevent using deallocated memory.
962 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
963 R->Destroy(*this);
964 }
965 ASTRecordLayouts.clear();
966
967 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
968 AEnd = DeclAttrs.end();
969 A != AEnd; ++A)
970 A->second->~AttrVec();
971 DeclAttrs.clear();
972
973 for (const auto &Value : ModuleInitializers)
974 Value.second->~PerModuleInitializers();
975 ModuleInitializers.clear();
976}
977
979
980void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
981 TraversalScope = TopLevelDecls;
983}
984
985void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
986 Deallocations.push_back({Callback, Data});
987}
988
989void
991 ExternalSource = std::move(Source);
992}
993
995 llvm::errs() << "\n*** AST Context Stats:\n";
996 llvm::errs() << " " << Types.size() << " types total.\n";
997
998 unsigned counts[] = {
999#define TYPE(Name, Parent) 0,
1000#define ABSTRACT_TYPE(Name, Parent)
1001#include "clang/AST/TypeNodes.inc"
1002 0 // Extra
1003 };
1004
1005 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1006 Type *T = Types[i];
1007 counts[(unsigned)T->getTypeClass()]++;
1008 }
1009
1010 unsigned Idx = 0;
1011 unsigned TotalBytes = 0;
1012#define TYPE(Name, Parent) \
1013 if (counts[Idx]) \
1014 llvm::errs() << " " << counts[Idx] << " " << #Name \
1015 << " types, " << sizeof(Name##Type) << " each " \
1016 << "(" << counts[Idx] * sizeof(Name##Type) \
1017 << " bytes)\n"; \
1018 TotalBytes += counts[Idx] * sizeof(Name##Type); \
1019 ++Idx;
1020#define ABSTRACT_TYPE(Name, Parent)
1021#include "clang/AST/TypeNodes.inc"
1022
1023 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1024
1025 // Implicit special member functions.
1026 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1028 << " implicit default constructors created\n";
1029 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1031 << " implicit copy constructors created\n";
1032 if (getLangOpts().CPlusPlus)
1033 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1035 << " implicit move constructors created\n";
1036 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1038 << " implicit copy assignment operators created\n";
1039 if (getLangOpts().CPlusPlus)
1040 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1042 << " implicit move assignment operators created\n";
1043 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1045 << " implicit destructors created\n";
1046
1047 if (ExternalSource) {
1048 llvm::errs() << "\n";
1050 }
1051
1052 BumpAlloc.PrintStats();
1053}
1054
1056 bool NotifyListeners) {
1057 if (NotifyListeners)
1058 if (auto *Listener = getASTMutationListener())
1060
1061 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1062}
1063
1065 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1066 if (It == MergedDefModules.end())
1067 return;
1068
1069 auto &Merged = It->second;
1070 llvm::DenseSet<Module*> Found;
1071 for (Module *&M : Merged)
1072 if (!Found.insert(M).second)
1073 M = nullptr;
1074 llvm::erase(Merged, nullptr);
1075}
1076
1079 auto MergedIt =
1080 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1081 if (MergedIt == MergedDefModules.end())
1082 return {};
1083 return MergedIt->second;
1084}
1085
1086void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1087 if (LazyInitializers.empty())
1088 return;
1089
1090 auto *Source = Ctx.getExternalSource();
1091 assert(Source && "lazy initializers but no external source");
1092
1093 auto LazyInits = std::move(LazyInitializers);
1094 LazyInitializers.clear();
1095
1096 for (auto ID : LazyInits)
1097 Initializers.push_back(Source->GetExternalDecl(ID));
1098
1099 assert(LazyInitializers.empty() &&
1100 "GetExternalDecl for lazy module initializer added more inits");
1101}
1102
1104 // One special case: if we add a module initializer that imports another
1105 // module, and that module's only initializer is an ImportDecl, simplify.
1106 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1107 auto It = ModuleInitializers.find(ID->getImportedModule());
1108
1109 // Maybe the ImportDecl does nothing at all. (Common case.)
1110 if (It == ModuleInitializers.end())
1111 return;
1112
1113 // Maybe the ImportDecl only imports another ImportDecl.
1114 auto &Imported = *It->second;
1115 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1116 Imported.resolve(*this);
1117 auto *OnlyDecl = Imported.Initializers.front();
1118 if (isa<ImportDecl>(OnlyDecl))
1119 D = OnlyDecl;
1120 }
1121 }
1122
1123 auto *&Inits = ModuleInitializers[M];
1124 if (!Inits)
1125 Inits = new (*this) PerModuleInitializers;
1126 Inits->Initializers.push_back(D);
1127}
1128
1131 auto *&Inits = ModuleInitializers[M];
1132 if (!Inits)
1133 Inits = new (*this) PerModuleInitializers;
1134 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1135 IDs.begin(), IDs.end());
1136}
1137
1139 auto It = ModuleInitializers.find(M);
1140 if (It == ModuleInitializers.end())
1141 return {};
1142
1143 auto *Inits = It->second;
1144 Inits->resolve(*this);
1145 return Inits->Initializers;
1146}
1147
1149 assert(M->isNamedModule());
1150 assert(!CurrentCXXNamedModule &&
1151 "We should set named module for ASTContext for only once");
1152 CurrentCXXNamedModule = M;
1153}
1154
1155bool ASTContext::isInSameModule(const Module *M1, const Module *M2) {
1156 if (!M1 != !M2)
1157 return false;
1158
1159 /// Get the representative module for M. The representative module is the
1160 /// first module unit for a specific primary module name. So that the module
1161 /// units have the same representative module belongs to the same module.
1162 ///
1163 /// The process is helpful to reduce the expensive string operations.
1164 auto GetRepresentativeModule = [this](const Module *M) {
1165 auto Iter = SameModuleLookupSet.find(M);
1166 if (Iter != SameModuleLookupSet.end())
1167 return Iter->second;
1168
1169 const Module *RepresentativeModule =
1170 PrimaryModuleNameMap.try_emplace(M->getPrimaryModuleInterfaceName(), M)
1171 .first->second;
1172 SameModuleLookupSet[M] = RepresentativeModule;
1173 return RepresentativeModule;
1174 };
1175
1176 assert(M1 && "Shouldn't call `isInSameModule` if both M1 and M2 are none.");
1177 return GetRepresentativeModule(M1) == GetRepresentativeModule(M2);
1178}
1179
1181 if (!ExternCContext)
1182 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1183
1184 return ExternCContext;
1185}
1186
1189 const IdentifierInfo *II) const {
1190 auto *BuiltinTemplate =
1192 BuiltinTemplate->setImplicit();
1193 getTranslationUnitDecl()->addDecl(BuiltinTemplate);
1194
1195 return BuiltinTemplate;
1196}
1197
1200 if (!MakeIntegerSeqDecl)
1203 return MakeIntegerSeqDecl;
1204}
1205
1208 if (!TypePackElementDecl)
1211 return TypePackElementDecl;
1212}
1213
1215 if (!BuiltinCommonTypeDecl)
1216 BuiltinCommonTypeDecl = buildBuiltinTemplateDecl(
1218 return BuiltinCommonTypeDecl;
1219}
1220
1222 RecordDecl::TagKind TK) const {
1224 RecordDecl *NewDecl;
1225 if (getLangOpts().CPlusPlus)
1226 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1227 Loc, &Idents.get(Name));
1228 else
1229 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1230 &Idents.get(Name));
1231 NewDecl->setImplicit();
1232 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1233 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1234 return NewDecl;
1235}
1236
1238 StringRef Name) const {
1241 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1242 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1243 NewDecl->setImplicit();
1244 return NewDecl;
1245}
1246
1248 if (!Int128Decl)
1249 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1250 return Int128Decl;
1251}
1252
1254 if (!UInt128Decl)
1255 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1256 return UInt128Decl;
1257}
1258
1259void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1260 auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K);
1262 Types.push_back(Ty);
1263}
1264
1266 const TargetInfo *AuxTarget) {
1267 assert((!this->Target || this->Target == &Target) &&
1268 "Incorrect target reinitialization");
1269 assert(VoidTy.isNull() && "Context reinitialized?");
1270
1271 this->Target = &Target;
1272 this->AuxTarget = AuxTarget;
1273
1274 ABI.reset(createCXXABI(Target));
1275 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1276
1277 // C99 6.2.5p19.
1278 InitBuiltinType(VoidTy, BuiltinType::Void);
1279
1280 // C99 6.2.5p2.
1281 InitBuiltinType(BoolTy, BuiltinType::Bool);
1282 // C99 6.2.5p3.
1283 if (LangOpts.CharIsSigned)
1284 InitBuiltinType(CharTy, BuiltinType::Char_S);
1285 else
1286 InitBuiltinType(CharTy, BuiltinType::Char_U);
1287 // C99 6.2.5p4.
1288 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1289 InitBuiltinType(ShortTy, BuiltinType::Short);
1290 InitBuiltinType(IntTy, BuiltinType::Int);
1291 InitBuiltinType(LongTy, BuiltinType::Long);
1292 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1293
1294 // C99 6.2.5p6.
1295 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1296 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1297 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1298 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1299 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1300
1301 // C99 6.2.5p10.
1302 InitBuiltinType(FloatTy, BuiltinType::Float);
1303 InitBuiltinType(DoubleTy, BuiltinType::Double);
1304 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1305
1306 // GNU extension, __float128 for IEEE quadruple precision
1307 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1308
1309 // __ibm128 for IBM extended precision
1310 InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128);
1311
1312 // C11 extension ISO/IEC TS 18661-3
1313 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1314
1315 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1316 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1317 InitBuiltinType(AccumTy, BuiltinType::Accum);
1318 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1319 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1320 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1321 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1322 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1323 InitBuiltinType(FractTy, BuiltinType::Fract);
1324 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1325 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1326 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1327 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1328 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1329 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1330 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1331 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1332 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1333 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1334 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1335 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1336 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1337 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1338 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1339 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
1340
1341 // GNU extension, 128-bit integers.
1342 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1343 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1344
1345 // C++ 3.9.1p5
1346 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1347 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1348 else // -fshort-wchar makes wchar_t be unsigned.
1349 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1350 if (LangOpts.CPlusPlus && LangOpts.WChar)
1352 else {
1353 // C99 (or C++ using -fno-wchar).
1354 WideCharTy = getFromTargetType(Target.getWCharType());
1355 }
1356
1357 WIntTy = getFromTargetType(Target.getWIntType());
1358
1359 // C++20 (proposed)
1360 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1361
1362 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1363 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1364 else // C99
1365 Char16Ty = getFromTargetType(Target.getChar16Type());
1366
1367 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1368 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1369 else // C99
1370 Char32Ty = getFromTargetType(Target.getChar32Type());
1371
1372 // Placeholder type for type-dependent expressions whose type is
1373 // completely unknown. No code should ever check a type against
1374 // DependentTy and users should never see it; however, it is here to
1375 // help diagnose failures to properly check for type-dependent
1376 // expressions.
1377 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1378
1379 // Placeholder type for functions.
1380 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1381
1382 // Placeholder type for bound members.
1383 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1384
1385 // Placeholder type for unresolved templates.
1386 InitBuiltinType(UnresolvedTemplateTy, BuiltinType::UnresolvedTemplate);
1387
1388 // Placeholder type for pseudo-objects.
1389 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1390
1391 // "any" type; useful for debugger-like clients.
1392 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1393
1394 // Placeholder type for unbridged ARC casts.
1395 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1396
1397 // Placeholder type for builtin functions.
1398 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1399
1400 // Placeholder type for OMP array sections.
1401 if (LangOpts.OpenMP) {
1402 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1403 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1404 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1405 }
1406 // Placeholder type for OpenACC array sections, if we are ALSO in OMP mode,
1407 // don't bother, as we're just using the same type as OMP.
1408 if (LangOpts.OpenACC && !LangOpts.OpenMP) {
1409 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1410 }
1411 if (LangOpts.MatrixTypes)
1412 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1413
1414 // Builtin types for 'id', 'Class', and 'SEL'.
1415 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1416 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1417 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1418
1419 if (LangOpts.OpenCL) {
1420#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1421 InitBuiltinType(SingletonId, BuiltinType::Id);
1422#include "clang/Basic/OpenCLImageTypes.def"
1423
1424 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1425 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1426 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1427 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1428 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1429
1430#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1431 InitBuiltinType(Id##Ty, BuiltinType::Id);
1432#include "clang/Basic/OpenCLExtensionTypes.def"
1433 }
1434
1435 if (LangOpts.HLSL) {
1436#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1437 InitBuiltinType(SingletonId, BuiltinType::Id);
1438#include "clang/Basic/HLSLIntangibleTypes.def"
1439 }
1440
1441 if (Target.hasAArch64SVETypes() ||
1442 (AuxTarget && AuxTarget->hasAArch64SVETypes())) {
1443#define SVE_TYPE(Name, Id, SingletonId) \
1444 InitBuiltinType(SingletonId, BuiltinType::Id);
1445#include "clang/Basic/AArch64SVEACLETypes.def"
1446 }
1447
1448 if (Target.getTriple().isPPC64()) {
1449#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1450 InitBuiltinType(Id##Ty, BuiltinType::Id);
1451#include "clang/Basic/PPCTypes.def"
1452#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1453 InitBuiltinType(Id##Ty, BuiltinType::Id);
1454#include "clang/Basic/PPCTypes.def"
1455 }
1456
1457 if (Target.hasRISCVVTypes()) {
1458#define RVV_TYPE(Name, Id, SingletonId) \
1459 InitBuiltinType(SingletonId, BuiltinType::Id);
1460#include "clang/Basic/RISCVVTypes.def"
1461 }
1462
1463 if (Target.getTriple().isWasm() && Target.hasFeature("reference-types")) {
1464#define WASM_TYPE(Name, Id, SingletonId) \
1465 InitBuiltinType(SingletonId, BuiltinType::Id);
1466#include "clang/Basic/WebAssemblyReferenceTypes.def"
1467 }
1468
1469 if (Target.getTriple().isAMDGPU() ||
1470 (AuxTarget && AuxTarget->getTriple().isAMDGPU())) {
1471#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
1472 InitBuiltinType(SingletonId, BuiltinType::Id);
1473#include "clang/Basic/AMDGPUTypes.def"
1474 }
1475
1476 // Builtin type for __objc_yes and __objc_no
1477 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1479
1480 ObjCConstantStringType = QualType();
1481
1482 ObjCSuperType = QualType();
1483
1484 // void * type
1485 if (LangOpts.OpenCLGenericAddressSpace) {
1486 auto Q = VoidTy.getQualifiers();
1490 } else {
1492 }
1493
1494 // nullptr type (C++0x 2.14.7)
1495 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1496
1497 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1498 InitBuiltinType(HalfTy, BuiltinType::Half);
1499
1500 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1501
1502 // Builtin type used to help define __builtin_va_list.
1503 VaListTagDecl = nullptr;
1504
1505 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1506 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1509 }
1510}
1511
1513 return SourceMgr.getDiagnostics();
1514}
1515
1517 AttrVec *&Result = DeclAttrs[D];
1518 if (!Result) {
1519 void *Mem = Allocate(sizeof(AttrVec));
1520 Result = new (Mem) AttrVec;
1521 }
1522
1523 return *Result;
1524}
1525
1526/// Erase the attributes corresponding to the given declaration.
1528 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1529 if (Pos != DeclAttrs.end()) {
1530 Pos->second->~AttrVec();
1531 DeclAttrs.erase(Pos);
1532 }
1533}
1534
1535// FIXME: Remove ?
1538 assert(Var->isStaticDataMember() && "Not a static data member");
1540 .dyn_cast<MemberSpecializationInfo *>();
1541}
1542
1545 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1546 TemplateOrInstantiation.find(Var);
1547 if (Pos == TemplateOrInstantiation.end())
1548 return {};
1549
1550 return Pos->second;
1551}
1552
1553void
1556 SourceLocation PointOfInstantiation) {
1557 assert(Inst->isStaticDataMember() && "Not a static data member");
1558 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1560 Tmpl, TSK, PointOfInstantiation));
1561}
1562
1563void
1566 assert(!TemplateOrInstantiation[Inst] &&
1567 "Already noted what the variable was instantiated from");
1568 TemplateOrInstantiation[Inst] = TSI;
1569}
1570
1571NamedDecl *
1573 return InstantiatedFromUsingDecl.lookup(UUD);
1574}
1575
1576void
1578 assert((isa<UsingDecl>(Pattern) ||
1579 isa<UnresolvedUsingValueDecl>(Pattern) ||
1580 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1581 "pattern decl is not a using decl");
1582 assert((isa<UsingDecl>(Inst) ||
1583 isa<UnresolvedUsingValueDecl>(Inst) ||
1584 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1585 "instantiation did not produce a using decl");
1586 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1587 InstantiatedFromUsingDecl[Inst] = Pattern;
1588}
1589
1592 return InstantiatedFromUsingEnumDecl.lookup(UUD);
1593}
1594
1596 UsingEnumDecl *Pattern) {
1597 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1598 InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1599}
1600
1603 return InstantiatedFromUsingShadowDecl.lookup(Inst);
1604}
1605
1606void
1608 UsingShadowDecl *Pattern) {
1609 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1610 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1611}
1612
1613FieldDecl *
1615 return InstantiatedFromUnnamedFieldDecl.lookup(Field);
1616}
1617
1619 FieldDecl *Tmpl) {
1620 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1621 "Instantiated field decl is not unnamed");
1622 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1623 "Template field decl is not unnamed");
1624 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1625 "Already noted what unnamed field was instantiated from");
1626
1627 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1628}
1629
1632 return overridden_methods(Method).begin();
1633}
1634
1637 return overridden_methods(Method).end();
1638}
1639
1640unsigned
1642 auto Range = overridden_methods(Method);
1643 return Range.end() - Range.begin();
1644}
1645
1648 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1649 OverriddenMethods.find(Method->getCanonicalDecl());
1650 if (Pos == OverriddenMethods.end())
1651 return overridden_method_range(nullptr, nullptr);
1652 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1653}
1654
1656 const CXXMethodDecl *Overridden) {
1657 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1658 OverriddenMethods[Method].push_back(Overridden);
1659}
1660
1662 const NamedDecl *D,
1663 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1664 assert(D);
1665
1666 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1667 Overridden.append(overridden_methods_begin(CXXMethod),
1668 overridden_methods_end(CXXMethod));
1669 return;
1670 }
1671
1672 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1673 if (!Method)
1674 return;
1675
1677 Method->getOverriddenMethods(OverDecls);
1678 Overridden.append(OverDecls.begin(), OverDecls.end());
1679}
1680
1682 assert(!Import->getNextLocalImport() &&
1683 "Import declaration already in the chain");
1684 assert(!Import->isFromASTFile() && "Non-local import declaration");
1685 if (!FirstLocalImport) {
1686 FirstLocalImport = Import;
1687 LastLocalImport = Import;
1688 return;
1689 }
1690
1691 LastLocalImport->setNextLocalImport(Import);
1692 LastLocalImport = Import;
1693}
1694
1695//===----------------------------------------------------------------------===//
1696// Type Sizing and Analysis
1697//===----------------------------------------------------------------------===//
1698
1699/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1700/// scalar floating point type.
1701const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1702 switch (T->castAs<BuiltinType>()->getKind()) {
1703 default:
1704 llvm_unreachable("Not a floating point type!");
1705 case BuiltinType::BFloat16:
1706 return Target->getBFloat16Format();
1707 case BuiltinType::Float16:
1708 return Target->getHalfFormat();
1709 case BuiltinType::Half:
1710 return Target->getHalfFormat();
1711 case BuiltinType::Float: return Target->getFloatFormat();
1712 case BuiltinType::Double: return Target->getDoubleFormat();
1713 case BuiltinType::Ibm128:
1714 return Target->getIbm128Format();
1715 case BuiltinType::LongDouble:
1716 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1717 return AuxTarget->getLongDoubleFormat();
1718 return Target->getLongDoubleFormat();
1719 case BuiltinType::Float128:
1720 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1721 return AuxTarget->getFloat128Format();
1722 return Target->getFloat128Format();
1723 }
1724}
1725
1726CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1727 unsigned Align = Target->getCharWidth();
1728
1729 const unsigned AlignFromAttr = D->getMaxAlignment();
1730 if (AlignFromAttr)
1731 Align = AlignFromAttr;
1732
1733 // __attribute__((aligned)) can increase or decrease alignment
1734 // *except* on a struct or struct member, where it only increases
1735 // alignment unless 'packed' is also specified.
1736 //
1737 // It is an error for alignas to decrease alignment, so we can
1738 // ignore that possibility; Sema should diagnose it.
1739 bool UseAlignAttrOnly;
1740 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D))
1741 UseAlignAttrOnly =
1742 FD->hasAttr<PackedAttr>() || FD->getParent()->hasAttr<PackedAttr>();
1743 else
1744 UseAlignAttrOnly = AlignFromAttr != 0;
1745 // If we're using the align attribute only, just ignore everything
1746 // else about the declaration and its type.
1747 if (UseAlignAttrOnly) {
1748 // do nothing
1749 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1750 QualType T = VD->getType();
1751 if (const auto *RT = T->getAs<ReferenceType>()) {
1752 if (ForAlignof)
1753 T = RT->getPointeeType();
1754 else
1755 T = getPointerType(RT->getPointeeType());
1756 }
1757 QualType BaseT = getBaseElementType(T);
1758 if (T->isFunctionType())
1759 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1760 else if (!BaseT->isIncompleteType()) {
1761 // Adjust alignments of declarations with array type by the
1762 // large-array alignment on the target.
1763 if (const ArrayType *arrayType = getAsArrayType(T)) {
1764 unsigned MinWidth = Target->getLargeArrayMinWidth();
1765 if (!ForAlignof && MinWidth) {
1766 if (isa<VariableArrayType>(arrayType))
1767 Align = std::max(Align, Target->getLargeArrayAlign());
1768 else if (isa<ConstantArrayType>(arrayType) &&
1769 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1770 Align = std::max(Align, Target->getLargeArrayAlign());
1771 }
1772 }
1773 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1774 if (BaseT.getQualifiers().hasUnaligned())
1775 Align = Target->getCharWidth();
1776 }
1777
1778 // Ensure miminum alignment for global variables.
1779 if (const auto *VD = dyn_cast<VarDecl>(D))
1780 if (VD->hasGlobalStorage() && !ForAlignof) {
1781 uint64_t TypeSize =
1782 !BaseT->isIncompleteType() ? getTypeSize(T.getTypePtr()) : 0;
1783 Align = std::max(Align, getMinGlobalAlignOfVar(TypeSize, VD));
1784 }
1785
1786 // Fields can be subject to extra alignment constraints, like if
1787 // the field is packed, the struct is packed, or the struct has a
1788 // a max-field-alignment constraint (#pragma pack). So calculate
1789 // the actual alignment of the field within the struct, and then
1790 // (as we're expected to) constrain that by the alignment of the type.
1791 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1792 const RecordDecl *Parent = Field->getParent();
1793 // We can only produce a sensible answer if the record is valid.
1794 if (!Parent->isInvalidDecl()) {
1795 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1796
1797 // Start with the record's overall alignment.
1798 unsigned FieldAlign = toBits(Layout.getAlignment());
1799
1800 // Use the GCD of that and the offset within the record.
1801 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1802 if (Offset > 0) {
1803 // Alignment is always a power of 2, so the GCD will be a power of 2,
1804 // which means we get to do this crazy thing instead of Euclid's.
1805 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1806 if (LowBitOfOffset < FieldAlign)
1807 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1808 }
1809
1810 Align = std::min(Align, FieldAlign);
1811 }
1812 }
1813 }
1814
1815 // Some targets have hard limitation on the maximum requestable alignment in
1816 // aligned attribute for static variables.
1817 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1818 const auto *VD = dyn_cast<VarDecl>(D);
1819 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1820 Align = std::min(Align, MaxAlignedAttr);
1821
1822 return toCharUnitsFromBits(Align);
1823}
1824
1826 return toCharUnitsFromBits(Target->getExnObjectAlignment());
1827}
1828
1829// getTypeInfoDataSizeInChars - Return the size of a type, in
1830// chars. If the type is a record, its data size is returned. This is
1831// the size of the memcpy that's performed when assigning this type
1832// using a trivial copy/move assignment operator.
1835
1836 // In C++, objects can sometimes be allocated into the tail padding
1837 // of a base-class subobject. We decide whether that's possible
1838 // during class layout, so here we can just trust the layout results.
1839 if (getLangOpts().CPlusPlus) {
1840 if (const auto *RT = T->getAs<RecordType>();
1841 RT && !RT->getDecl()->isInvalidDecl()) {
1842 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1843 Info.Width = layout.getDataSize();
1844 }
1845 }
1846
1847 return Info;
1848}
1849
1850/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1851/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1854 const ConstantArrayType *CAT) {
1855 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1856 uint64_t Size = CAT->getZExtSize();
1857 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1858 (uint64_t)(-1)/Size) &&
1859 "Overflow in array type char size evaluation");
1860 uint64_t Width = EltInfo.Width.getQuantity() * Size;
1861 unsigned Align = EltInfo.Align.getQuantity();
1862 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1864 Width = llvm::alignTo(Width, Align);
1867 EltInfo.AlignRequirement);
1868}
1869
1871 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1872 return getConstantArrayInfoInChars(*this, CAT);
1873 TypeInfo Info = getTypeInfo(T);
1876}
1877
1879 return getTypeInfoInChars(T.getTypePtr());
1880}
1881
1883 // HLSL doesn't promote all small integer types to int, it
1884 // just uses the rank-based promotion rules for all types.
1885 if (getLangOpts().HLSL)
1886 return false;
1887
1888 if (const auto *BT = T->getAs<BuiltinType>())
1889 switch (BT->getKind()) {
1890 case BuiltinType::Bool:
1891 case BuiltinType::Char_S:
1892 case BuiltinType::Char_U:
1893 case BuiltinType::SChar:
1894 case BuiltinType::UChar:
1895 case BuiltinType::Short:
1896 case BuiltinType::UShort:
1897 case BuiltinType::WChar_S:
1898 case BuiltinType::WChar_U:
1899 case BuiltinType::Char8:
1900 case BuiltinType::Char16:
1901 case BuiltinType::Char32:
1902 return true;
1903 default:
1904 return false;
1905 }
1906
1907 // Enumerated types are promotable to their compatible integer types
1908 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
1909 if (const auto *ET = T->getAs<EnumType>()) {
1910 if (T->isDependentType() || ET->getDecl()->getPromotionType().isNull() ||
1911 ET->getDecl()->isScoped())
1912 return false;
1913
1914 return true;
1915 }
1916
1917 return false;
1918}
1919
1922}
1923
1925 return isAlignmentRequired(T.getTypePtr());
1926}
1927
1929 bool NeedsPreferredAlignment) const {
1930 // An alignment on a typedef overrides anything else.
1931 if (const auto *TT = T->getAs<TypedefType>())
1932 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1933 return Align;
1934
1935 // If we have an (array of) complete type, we're done.
1937 if (!T->isIncompleteType())
1938 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
1939
1940 // If we had an array type, its element type might be a typedef
1941 // type with an alignment attribute.
1942 if (const auto *TT = T->getAs<TypedefType>())
1943 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1944 return Align;
1945
1946 // Otherwise, see if the declaration of the type had an attribute.
1947 if (const auto *TT = T->getAs<TagType>())
1948 return TT->getDecl()->getMaxAlignment();
1949
1950 return 0;
1951}
1952
1954 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1955 if (I != MemoizedTypeInfo.end())
1956 return I->second;
1957
1958 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1959 TypeInfo TI = getTypeInfoImpl(T);
1960 MemoizedTypeInfo[T] = TI;
1961 return TI;
1962}
1963
1964/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1965/// method does not work on incomplete types.
1966///
1967/// FIXME: Pointers into different addr spaces could have different sizes and
1968/// alignment requirements: getPointerInfo should take an AddrSpace, this
1969/// should take a QualType, &c.
1970TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1971 uint64_t Width = 0;
1972 unsigned Align = 8;
1975 switch (T->getTypeClass()) {
1976#define TYPE(Class, Base)
1977#define ABSTRACT_TYPE(Class, Base)
1978#define NON_CANONICAL_TYPE(Class, Base)
1979#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1980#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1981 case Type::Class: \
1982 assert(!T->isDependentType() && "should not see dependent types here"); \
1983 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1984#include "clang/AST/TypeNodes.inc"
1985 llvm_unreachable("Should not see dependent types");
1986
1987 case Type::FunctionNoProto:
1988 case Type::FunctionProto:
1989 // GCC extension: alignof(function) = 32 bits
1990 Width = 0;
1991 Align = 32;
1992 break;
1993
1994 case Type::IncompleteArray:
1995 case Type::VariableArray:
1996 case Type::ConstantArray:
1997 case Type::ArrayParameter: {
1998 // Model non-constant sized arrays as size zero, but track the alignment.
1999 uint64_t Size = 0;
2000 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
2001 Size = CAT->getZExtSize();
2002
2003 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
2004 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
2005 "Overflow in array type bit size evaluation");
2006 Width = EltInfo.Width * Size;
2007 Align = EltInfo.Align;
2008 AlignRequirement = EltInfo.AlignRequirement;
2009 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
2010 getTargetInfo().getPointerWidth(LangAS::Default) == 64)
2011 Width = llvm::alignTo(Width, Align);
2012 break;
2013 }
2014
2015 case Type::ExtVector:
2016 case Type::Vector: {
2017 const auto *VT = cast<VectorType>(T);
2018 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
2019 Width = VT->isExtVectorBoolType() ? VT->getNumElements()
2020 : EltInfo.Width * VT->getNumElements();
2021 // Enforce at least byte size and alignment.
2022 Width = std::max<unsigned>(8, Width);
2023 Align = std::max<unsigned>(8, Width);
2024
2025 // If the alignment is not a power of 2, round up to the next power of 2.
2026 // This happens for non-power-of-2 length vectors.
2027 if (Align & (Align-1)) {
2028 Align = llvm::bit_ceil(Align);
2029 Width = llvm::alignTo(Width, Align);
2030 }
2031 // Adjust the alignment based on the target max.
2032 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
2033 if (TargetVectorAlign && TargetVectorAlign < Align)
2034 Align = TargetVectorAlign;
2035 if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
2036 // Adjust the alignment for fixed-length SVE vectors. This is important
2037 // for non-power-of-2 vector lengths.
2038 Align = 128;
2039 else if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
2040 // Adjust the alignment for fixed-length SVE predicates.
2041 Align = 16;
2042 else if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
2043 VT->getVectorKind() == VectorKind::RVVFixedLengthMask ||
2044 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
2045 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
2046 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4)
2047 // Adjust the alignment for fixed-length RVV vectors.
2048 Align = std::min<unsigned>(64, Width);
2049 break;
2050 }
2051
2052 case Type::ConstantMatrix: {
2053 const auto *MT = cast<ConstantMatrixType>(T);
2054 TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
2055 // The internal layout of a matrix value is implementation defined.
2056 // Initially be ABI compatible with arrays with respect to alignment and
2057 // size.
2058 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
2059 Align = ElementInfo.Align;
2060 break;
2061 }
2062
2063 case Type::Builtin:
2064 switch (cast<BuiltinType>(T)->getKind()) {
2065 default: llvm_unreachable("Unknown builtin type!");
2066 case BuiltinType::Void:
2067 // GCC extension: alignof(void) = 8 bits.
2068 Width = 0;
2069 Align = 8;
2070 break;
2071 case BuiltinType::Bool:
2072 Width = Target->getBoolWidth();
2073 Align = Target->getBoolAlign();
2074 break;
2075 case BuiltinType::Char_S:
2076 case BuiltinType::Char_U:
2077 case BuiltinType::UChar:
2078 case BuiltinType::SChar:
2079 case BuiltinType::Char8:
2080 Width = Target->getCharWidth();
2081 Align = Target->getCharAlign();
2082 break;
2083 case BuiltinType::WChar_S:
2084 case BuiltinType::WChar_U:
2085 Width = Target->getWCharWidth();
2086 Align = Target->getWCharAlign();
2087 break;
2088 case BuiltinType::Char16:
2089 Width = Target->getChar16Width();
2090 Align = Target->getChar16Align();
2091 break;
2092 case BuiltinType::Char32:
2093 Width = Target->getChar32Width();
2094 Align = Target->getChar32Align();
2095 break;
2096 case BuiltinType::UShort:
2097 case BuiltinType::Short:
2098 Width = Target->getShortWidth();
2099 Align = Target->getShortAlign();
2100 break;
2101 case BuiltinType::UInt:
2102 case BuiltinType::Int:
2103 Width = Target->getIntWidth();
2104 Align = Target->getIntAlign();
2105 break;
2106 case BuiltinType::ULong:
2107 case BuiltinType::Long:
2108 Width = Target->getLongWidth();
2109 Align = Target->getLongAlign();
2110 break;
2111 case BuiltinType::ULongLong:
2112 case BuiltinType::LongLong:
2113 Width = Target->getLongLongWidth();
2114 Align = Target->getLongLongAlign();
2115 break;
2116 case BuiltinType::Int128:
2117 case BuiltinType::UInt128:
2118 Width = 128;
2119 Align = Target->getInt128Align();
2120 break;
2121 case BuiltinType::ShortAccum:
2122 case BuiltinType::UShortAccum:
2123 case BuiltinType::SatShortAccum:
2124 case BuiltinType::SatUShortAccum:
2125 Width = Target->getShortAccumWidth();
2126 Align = Target->getShortAccumAlign();
2127 break;
2128 case BuiltinType::Accum:
2129 case BuiltinType::UAccum:
2130 case BuiltinType::SatAccum:
2131 case BuiltinType::SatUAccum:
2132 Width = Target->getAccumWidth();
2133 Align = Target->getAccumAlign();
2134 break;
2135 case BuiltinType::LongAccum:
2136 case BuiltinType::ULongAccum:
2137 case BuiltinType::SatLongAccum:
2138 case BuiltinType::SatULongAccum:
2139 Width = Target->getLongAccumWidth();
2140 Align = Target->getLongAccumAlign();
2141 break;
2142 case BuiltinType::ShortFract:
2143 case BuiltinType::UShortFract:
2144 case BuiltinType::SatShortFract:
2145 case BuiltinType::SatUShortFract:
2146 Width = Target->getShortFractWidth();
2147 Align = Target->getShortFractAlign();
2148 break;
2149 case BuiltinType::Fract:
2150 case BuiltinType::UFract:
2151 case BuiltinType::SatFract:
2152 case BuiltinType::SatUFract:
2153 Width = Target->getFractWidth();
2154 Align = Target->getFractAlign();
2155 break;
2156 case BuiltinType::LongFract:
2157 case BuiltinType::ULongFract:
2158 case BuiltinType::SatLongFract:
2159 case BuiltinType::SatULongFract:
2160 Width = Target->getLongFractWidth();
2161 Align = Target->getLongFractAlign();
2162 break;
2163 case BuiltinType::BFloat16:
2164 if (Target->hasBFloat16Type()) {
2165 Width = Target->getBFloat16Width();
2166 Align = Target->getBFloat16Align();
2167 } else if ((getLangOpts().SYCLIsDevice ||
2168 (getLangOpts().OpenMP &&
2169 getLangOpts().OpenMPIsTargetDevice)) &&
2170 AuxTarget->hasBFloat16Type()) {
2171 Width = AuxTarget->getBFloat16Width();
2172 Align = AuxTarget->getBFloat16Align();
2173 }
2174 break;
2175 case BuiltinType::Float16:
2176 case BuiltinType::Half:
2177 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2178 !getLangOpts().OpenMPIsTargetDevice) {
2179 Width = Target->getHalfWidth();
2180 Align = Target->getHalfAlign();
2181 } else {
2182 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2183 "Expected OpenMP device compilation.");
2184 Width = AuxTarget->getHalfWidth();
2185 Align = AuxTarget->getHalfAlign();
2186 }
2187 break;
2188 case BuiltinType::Float:
2189 Width = Target->getFloatWidth();
2190 Align = Target->getFloatAlign();
2191 break;
2192 case BuiltinType::Double:
2193 Width = Target->getDoubleWidth();
2194 Align = Target->getDoubleAlign();
2195 break;
2196 case BuiltinType::Ibm128:
2197 Width = Target->getIbm128Width();
2198 Align = Target->getIbm128Align();
2199 break;
2200 case BuiltinType::LongDouble:
2201 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2202 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2203 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2204 Width = AuxTarget->getLongDoubleWidth();
2205 Align = AuxTarget->getLongDoubleAlign();
2206 } else {
2207 Width = Target->getLongDoubleWidth();
2208 Align = Target->getLongDoubleAlign();
2209 }
2210 break;
2211 case BuiltinType::Float128:
2212 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2213 !getLangOpts().OpenMPIsTargetDevice) {
2214 Width = Target->getFloat128Width();
2215 Align = Target->getFloat128Align();
2216 } else {
2217 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2218 "Expected OpenMP device compilation.");
2219 Width = AuxTarget->getFloat128Width();
2220 Align = AuxTarget->getFloat128Align();
2221 }
2222 break;
2223 case BuiltinType::NullPtr:
2224 // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
2225 Width = Target->getPointerWidth(LangAS::Default);
2226 Align = Target->getPointerAlign(LangAS::Default);
2227 break;
2228 case BuiltinType::ObjCId:
2229 case BuiltinType::ObjCClass:
2230 case BuiltinType::ObjCSel:
2231 Width = Target->getPointerWidth(LangAS::Default);
2232 Align = Target->getPointerAlign(LangAS::Default);
2233 break;
2234 case BuiltinType::OCLSampler:
2235 case BuiltinType::OCLEvent:
2236 case BuiltinType::OCLClkEvent:
2237 case BuiltinType::OCLQueue:
2238 case BuiltinType::OCLReserveID:
2239#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2240 case BuiltinType::Id:
2241#include "clang/Basic/OpenCLImageTypes.def"
2242#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2243 case BuiltinType::Id:
2244#include "clang/Basic/OpenCLExtensionTypes.def"
2245 AS = Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
2246 Width = Target->getPointerWidth(AS);
2247 Align = Target->getPointerAlign(AS);
2248 break;
2249 // The SVE types are effectively target-specific. The length of an
2250 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2251 // of 128 bits. There is one predicate bit for each vector byte, so the
2252 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2253 //
2254 // Because the length is only known at runtime, we use a dummy value
2255 // of 0 for the static length. The alignment values are those defined
2256 // by the Procedure Call Standard for the Arm Architecture.
2257#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
2258 case BuiltinType::Id: \
2259 Width = 0; \
2260 Align = 128; \
2261 break;
2262#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
2263 case BuiltinType::Id: \
2264 Width = 0; \
2265 Align = 16; \
2266 break;
2267#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
2268 case BuiltinType::Id: \
2269 Width = 0; \
2270 Align = 16; \
2271 break;
2272#define AARCH64_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
2273 ElBits, NF) \
2274 case BuiltinType::Id: \
2275 Width = NumEls * ElBits * NF; \
2276 Align = NumEls * ElBits; \
2277 break;
2278#include "clang/Basic/AArch64SVEACLETypes.def"
2279#define PPC_VECTOR_TYPE(Name, Id, Size) \
2280 case BuiltinType::Id: \
2281 Width = Size; \
2282 Align = Size; \
2283 break;
2284#include "clang/Basic/PPCTypes.def"
2285#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
2286 IsFP, IsBF) \
2287 case BuiltinType::Id: \
2288 Width = 0; \
2289 Align = ElBits; \
2290 break;
2291#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2292 case BuiltinType::Id: \
2293 Width = 0; \
2294 Align = 8; \
2295 break;
2296#include "clang/Basic/RISCVVTypes.def"
2297#define WASM_TYPE(Name, Id, SingletonId) \
2298 case BuiltinType::Id: \
2299 Width = 0; \
2300 Align = 8; \
2301 break;
2302#include "clang/Basic/WebAssemblyReferenceTypes.def"
2303#define AMDGPU_TYPE(NAME, ID, SINGLETONID, WIDTH, ALIGN) \
2304 case BuiltinType::ID: \
2305 Width = WIDTH; \
2306 Align = ALIGN; \
2307 break;
2308#include "clang/Basic/AMDGPUTypes.def"
2309#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2310#include "clang/Basic/HLSLIntangibleTypes.def"
2311 Width = Target->getPointerWidth(LangAS::Default);
2312 Align = Target->getPointerAlign(LangAS::Default);
2313 break;
2314 }
2315 break;
2316 case Type::ObjCObjectPointer:
2317 Width = Target->getPointerWidth(LangAS::Default);
2318 Align = Target->getPointerAlign(LangAS::Default);
2319 break;
2320 case Type::BlockPointer:
2321 AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
2322 Width = Target->getPointerWidth(AS);
2323 Align = Target->getPointerAlign(AS);
2324 break;
2325 case Type::LValueReference:
2326 case Type::RValueReference:
2327 // alignof and sizeof should never enter this code path here, so we go
2328 // the pointer route.
2329 AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
2330 Width = Target->getPointerWidth(AS);
2331 Align = Target->getPointerAlign(AS);
2332 break;
2333 case Type::Pointer:
2334 AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
2335 Width = Target->getPointerWidth(AS);
2336 Align = Target->getPointerAlign(AS);
2337 break;
2338 case Type::MemberPointer: {
2339 const auto *MPT = cast<MemberPointerType>(T);
2340 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2341 Width = MPI.Width;
2342 Align = MPI.Align;
2343 break;
2344 }
2345 case Type::Complex: {
2346 // Complex types have the same alignment as their elements, but twice the
2347 // size.
2348 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2349 Width = EltInfo.Width * 2;
2350 Align = EltInfo.Align;
2351 break;
2352 }
2353 case Type::ObjCObject:
2354 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2355 case Type::Adjusted:
2356 case Type::Decayed:
2357 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2358 case Type::ObjCInterface: {
2359 const auto *ObjCI = cast<ObjCInterfaceType>(T);
2360 if (ObjCI->getDecl()->isInvalidDecl()) {
2361 Width = 8;
2362 Align = 8;
2363 break;
2364 }
2365 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2366 Width = toBits(Layout.getSize());
2367 Align = toBits(Layout.getAlignment());
2368 break;
2369 }
2370 case Type::BitInt: {
2371 const auto *EIT = cast<BitIntType>(T);
2372 Align = Target->getBitIntAlign(EIT->getNumBits());
2373 Width = Target->getBitIntWidth(EIT->getNumBits());
2374 break;
2375 }
2376 case Type::Record:
2377 case Type::Enum: {
2378 const auto *TT = cast<TagType>(T);
2379
2380 if (TT->getDecl()->isInvalidDecl()) {
2381 Width = 8;
2382 Align = 8;
2383 break;
2384 }
2385
2386 if (const auto *ET = dyn_cast<EnumType>(TT)) {
2387 const EnumDecl *ED = ET->getDecl();
2388 TypeInfo Info =
2390 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2391 Info.Align = AttrAlign;
2393 }
2394 return Info;
2395 }
2396
2397 const auto *RT = cast<RecordType>(TT);
2398 const RecordDecl *RD = RT->getDecl();
2399 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2400 Width = toBits(Layout.getSize());
2401 Align = toBits(Layout.getAlignment());
2402 AlignRequirement = RD->hasAttr<AlignedAttr>()
2405 break;
2406 }
2407
2408 case Type::SubstTemplateTypeParm:
2409 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2410 getReplacementType().getTypePtr());
2411
2412 case Type::Auto:
2413 case Type::DeducedTemplateSpecialization: {
2414 const auto *A = cast<DeducedType>(T);
2415 assert(!A->getDeducedType().isNull() &&
2416 "cannot request the size of an undeduced or dependent auto type");
2417 return getTypeInfo(A->getDeducedType().getTypePtr());
2418 }
2419
2420 case Type::Paren:
2421 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2422
2423 case Type::MacroQualified:
2424 return getTypeInfo(
2425 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2426
2427 case Type::ObjCTypeParam:
2428 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2429
2430 case Type::Using:
2431 return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr());
2432
2433 case Type::Typedef: {
2434 const auto *TT = cast<TypedefType>(T);
2435 TypeInfo Info = getTypeInfo(TT->desugar().getTypePtr());
2436 // If the typedef has an aligned attribute on it, it overrides any computed
2437 // alignment we have. This violates the GCC documentation (which says that
2438 // attribute(aligned) can only round up) but matches its implementation.
2439 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2440 Align = AttrAlign;
2441 AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2442 } else {
2443 Align = Info.Align;
2444 AlignRequirement = Info.AlignRequirement;
2445 }
2446 Width = Info.Width;
2447 break;
2448 }
2449
2450 case Type::Elaborated:
2451 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
2452
2453 case Type::Attributed:
2454 return getTypeInfo(
2455 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2456
2457 case Type::CountAttributed:
2458 return getTypeInfo(cast<CountAttributedType>(T)->desugar().getTypePtr());
2459
2460 case Type::BTFTagAttributed:
2461 return getTypeInfo(
2462 cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr());
2463
2464 case Type::HLSLAttributedResource:
2465 return getTypeInfo(
2466 cast<HLSLAttributedResourceType>(T)->getWrappedType().getTypePtr());
2467
2468 case Type::Atomic: {
2469 // Start with the base type information.
2470 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2471 Width = Info.Width;
2472 Align = Info.Align;
2473
2474 if (!Width) {
2475 // An otherwise zero-sized type should still generate an
2476 // atomic operation.
2477 Width = Target->getCharWidth();
2478 assert(Align);
2479 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2480 // If the size of the type doesn't exceed the platform's max
2481 // atomic promotion width, make the size and alignment more
2482 // favorable to atomic operations:
2483
2484 // Round the size up to a power of 2.
2485 Width = llvm::bit_ceil(Width);
2486
2487 // Set the alignment equal to the size.
2488 Align = static_cast<unsigned>(Width);
2489 }
2490 }
2491 break;
2492
2493 case Type::Pipe:
2494 Width = Target->getPointerWidth(LangAS::opencl_global);
2495 Align = Target->getPointerAlign(LangAS::opencl_global);
2496 break;
2497 }
2498
2499 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2500 return TypeInfo(Width, Align, AlignRequirement);
2501}
2502
2504 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2505 if (I != MemoizedUnadjustedAlign.end())
2506 return I->second;
2507
2508 unsigned UnadjustedAlign;
2509 if (const auto *RT = T->getAs<RecordType>()) {
2510 const RecordDecl *RD = RT->getDecl();
2511 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2512 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2513 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2514 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2515 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2516 } else {
2517 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2518 }
2519
2520 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2521 return UnadjustedAlign;
2522}
2523
2525 unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign(
2526 getTargetInfo().getTriple(), Target->getTargetOpts().FeatureMap);
2527 return SimdAlign;
2528}
2529
2530/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2532 return CharUnits::fromQuantity(BitSize / getCharWidth());
2533}
2534
2535/// toBits - Convert a size in characters to a size in characters.
2536int64_t ASTContext::toBits(CharUnits CharSize) const {
2537 return CharSize.getQuantity() * getCharWidth();
2538}
2539
2540/// getTypeSizeInChars - Return the size of the specified type, in characters.
2541/// This method does not work on incomplete types.
2543 return getTypeInfoInChars(T).Width;
2544}
2546 return getTypeInfoInChars(T).Width;
2547}
2548
2549/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2550/// characters. This method does not work on incomplete types.
2553}
2556}
2557
2558/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2559/// type, in characters, before alignment adjustments. This method does
2560/// not work on incomplete types.
2563}
2566}
2567
2568/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2569/// type for the current target in bits. This can be different than the ABI
2570/// alignment in cases where it is beneficial for performance or backwards
2571/// compatibility preserving to overalign a data type. (Note: despite the name,
2572/// the preferred alignment is ABI-impacting, and not an optimization.)
2574 TypeInfo TI = getTypeInfo(T);
2575 unsigned ABIAlign = TI.Align;
2576
2578
2579 // The preferred alignment of member pointers is that of a pointer.
2580 if (T->isMemberPointerType())
2581 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2582
2583 if (!Target->allowsLargerPreferedTypeAlignment())
2584 return ABIAlign;
2585
2586 if (const auto *RT = T->getAs<RecordType>()) {
2587 const RecordDecl *RD = RT->getDecl();
2588
2589 // When used as part of a typedef, or together with a 'packed' attribute,
2590 // the 'aligned' attribute can be used to decrease alignment. Note that the
2591 // 'packed' case is already taken into consideration when computing the
2592 // alignment, we only need to handle the typedef case here.
2594 RD->isInvalidDecl())
2595 return ABIAlign;
2596
2597 unsigned PreferredAlign = static_cast<unsigned>(
2598 toBits(getASTRecordLayout(RD).PreferredAlignment));
2599 assert(PreferredAlign >= ABIAlign &&
2600 "PreferredAlign should be at least as large as ABIAlign.");
2601 return PreferredAlign;
2602 }
2603
2604 // Double (and, for targets supporting AIX `power` alignment, long double) and
2605 // long long should be naturally aligned (despite requiring less alignment) if
2606 // possible.
2607 if (const auto *CT = T->getAs<ComplexType>())
2608 T = CT->getElementType().getTypePtr();
2609 if (const auto *ET = T->getAs<EnumType>())
2610 T = ET->getDecl()->getIntegerType().getTypePtr();
2611 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2612 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2613 T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2614 (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2615 Target->defaultsToAIXPowerAlignment()))
2616 // Don't increase the alignment if an alignment attribute was specified on a
2617 // typedef declaration.
2618 if (!TI.isAlignRequired())
2619 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2620
2621 return ABIAlign;
2622}
2623
2624/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2625/// for __attribute__((aligned)) on this target, to be used if no alignment
2626/// value is specified.
2629}
2630
2631/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2632/// to a global variable of the specified type.
2634 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2635 return std::max(getPreferredTypeAlign(T),
2636 getMinGlobalAlignOfVar(TypeSize, VD));
2637}
2638
2639/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2640/// should be given to a global variable of the specified type.
2642 const VarDecl *VD) const {
2644}
2645
2647 const VarDecl *VD) const {
2648 // Make the default handling as that of a non-weak definition in the
2649 // current translation unit.
2650 bool HasNonWeakDef = !VD || (VD->hasDefinition() && !VD->isWeak());
2651 return getTargetInfo().getMinGlobalAlign(Size, HasNonWeakDef);
2652}
2653
2655 CharUnits Offset = CharUnits::Zero();
2656 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2657 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2658 Offset += Layout->getBaseClassOffset(Base);
2659 Layout = &getASTRecordLayout(Base);
2660 }
2661 return Offset;
2662}
2663
2665 const ValueDecl *MPD = MP.getMemberPointerDecl();
2668 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2669 const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext());
2670 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2671 const CXXRecordDecl *Base = RD;
2672 const CXXRecordDecl *Derived = Path[I];
2673 if (DerivedMember)
2674 std::swap(Base, Derived);
2676 RD = Path[I];
2677 }
2678 if (DerivedMember)
2680 return ThisAdjustment;
2681}
2682
2683/// DeepCollectObjCIvars -
2684/// This routine first collects all declared, but not synthesized, ivars in
2685/// super class and then collects all ivars, including those synthesized for
2686/// current class. This routine is used for implementation of current class
2687/// when all ivars, declared and synthesized are known.
2689 bool leafClass,
2691 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2692 DeepCollectObjCIvars(SuperClass, false, Ivars);
2693 if (!leafClass) {
2694 llvm::append_range(Ivars, OI->ivars());
2695 } else {
2696 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2697 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2698 Iv= Iv->getNextIvar())
2699 Ivars.push_back(Iv);
2700 }
2701}
2702
2703/// CollectInheritedProtocols - Collect all protocols in current class and
2704/// those inherited by it.
2707 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2708 // We can use protocol_iterator here instead of
2709 // all_referenced_protocol_iterator since we are walking all categories.
2710 for (auto *Proto : OI->all_referenced_protocols()) {
2711 CollectInheritedProtocols(Proto, Protocols);
2712 }
2713
2714 // Categories of this Interface.
2715 for (const auto *Cat : OI->visible_categories())
2716 CollectInheritedProtocols(Cat, Protocols);
2717
2718 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2719 while (SD) {
2720 CollectInheritedProtocols(SD, Protocols);
2721 SD = SD->getSuperClass();
2722 }
2723 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2724 for (auto *Proto : OC->protocols()) {
2725 CollectInheritedProtocols(Proto, Protocols);
2726 }
2727 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2728 // Insert the protocol.
2729 if (!Protocols.insert(
2730 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2731 return;
2732
2733 for (auto *Proto : OP->protocols())
2734 CollectInheritedProtocols(Proto, Protocols);
2735 }
2736}
2737
2739 const RecordDecl *RD,
2740 bool CheckIfTriviallyCopyable) {
2741 assert(RD->isUnion() && "Must be union type");
2742 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2743
2744 for (const auto *Field : RD->fields()) {
2745 if (!Context.hasUniqueObjectRepresentations(Field->getType(),
2746 CheckIfTriviallyCopyable))
2747 return false;
2748 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2749 if (FieldSize != UnionSize)
2750 return false;
2751 }
2752 return !RD->field_empty();
2753}
2754
2755static int64_t getSubobjectOffset(const FieldDecl *Field,
2756 const ASTContext &Context,
2757 const clang::ASTRecordLayout & /*Layout*/) {
2758 return Context.getFieldOffset(Field);
2759}
2760
2761static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2762 const ASTContext &Context,
2763 const clang::ASTRecordLayout &Layout) {
2764 return Context.toBits(Layout.getBaseClassOffset(RD));
2765}
2766
2767static std::optional<int64_t>
2769 const RecordDecl *RD,
2770 bool CheckIfTriviallyCopyable);
2771
2772static std::optional<int64_t>
2773getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context,
2774 bool CheckIfTriviallyCopyable) {
2775 if (Field->getType()->isRecordType()) {
2776 const RecordDecl *RD = Field->getType()->getAsRecordDecl();
2777 if (!RD->isUnion())
2778 return structHasUniqueObjectRepresentations(Context, RD,
2779 CheckIfTriviallyCopyable);
2780 }
2781
2782 // A _BitInt type may not be unique if it has padding bits
2783 // but if it is a bitfield the padding bits are not used.
2784 bool IsBitIntType = Field->getType()->isBitIntType();
2785 if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2786 !Context.hasUniqueObjectRepresentations(Field->getType(),
2787 CheckIfTriviallyCopyable))
2788 return std::nullopt;
2789
2790 int64_t FieldSizeInBits =
2791 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2792 if (Field->isBitField()) {
2793 // If we have explicit padding bits, they don't contribute bits
2794 // to the actual object representation, so return 0.
2795 if (Field->isUnnamedBitField())
2796 return 0;
2797
2798 int64_t BitfieldSize = Field->getBitWidthValue(Context);
2799 if (IsBitIntType) {
2800 if ((unsigned)BitfieldSize >
2801 cast<BitIntType>(Field->getType())->getNumBits())
2802 return std::nullopt;
2803 } else if (BitfieldSize > FieldSizeInBits) {
2804 return std::nullopt;
2805 }
2806 FieldSizeInBits = BitfieldSize;
2807 } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations(
2808 Field->getType(), CheckIfTriviallyCopyable)) {
2809 return std::nullopt;
2810 }
2811 return FieldSizeInBits;
2812}
2813
2814static std::optional<int64_t>
2816 bool CheckIfTriviallyCopyable) {
2817 return structHasUniqueObjectRepresentations(Context, RD,
2818 CheckIfTriviallyCopyable);
2819}
2820
2821template <typename RangeT>
2823 const RangeT &Subobjects, int64_t CurOffsetInBits,
2824 const ASTContext &Context, const clang::ASTRecordLayout &Layout,
2825 bool CheckIfTriviallyCopyable) {
2826 for (const auto *Subobject : Subobjects) {
2827 std::optional<int64_t> SizeInBits =
2828 getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable);
2829 if (!SizeInBits)
2830 return std::nullopt;
2831 if (*SizeInBits != 0) {
2832 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2833 if (Offset != CurOffsetInBits)
2834 return std::nullopt;
2835 CurOffsetInBits += *SizeInBits;
2836 }
2837 }
2838 return CurOffsetInBits;
2839}
2840
2841static std::optional<int64_t>
2843 const RecordDecl *RD,
2844 bool CheckIfTriviallyCopyable) {
2845 assert(!RD->isUnion() && "Must be struct/class type");
2846 const auto &Layout = Context.getASTRecordLayout(RD);
2847
2848 int64_t CurOffsetInBits = 0;
2849 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2850 if (ClassDecl->isDynamicClass())
2851 return std::nullopt;
2852
2854 for (const auto &Base : ClassDecl->bases()) {
2855 // Empty types can be inherited from, and non-empty types can potentially
2856 // have tail padding, so just make sure there isn't an error.
2857 Bases.emplace_back(Base.getType()->getAsCXXRecordDecl());
2858 }
2859
2860 llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
2861 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
2862 });
2863
2864 std::optional<int64_t> OffsetAfterBases =
2866 Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable);
2867 if (!OffsetAfterBases)
2868 return std::nullopt;
2869 CurOffsetInBits = *OffsetAfterBases;
2870 }
2871
2872 std::optional<int64_t> OffsetAfterFields =
2874 RD->fields(), CurOffsetInBits, Context, Layout,
2875 CheckIfTriviallyCopyable);
2876 if (!OffsetAfterFields)
2877 return std::nullopt;
2878 CurOffsetInBits = *OffsetAfterFields;
2879
2880 return CurOffsetInBits;
2881}
2882
2884 QualType Ty, bool CheckIfTriviallyCopyable) const {
2885 // C++17 [meta.unary.prop]:
2886 // The predicate condition for a template specialization
2887 // has_unique_object_representations<T> shall be satisfied if and only if:
2888 // (9.1) - T is trivially copyable, and
2889 // (9.2) - any two objects of type T with the same value have the same
2890 // object representation, where:
2891 // - two objects of array or non-union class type are considered to have
2892 // the same value if their respective sequences of direct subobjects
2893 // have the same values, and
2894 // - two objects of union type are considered to have the same value if
2895 // they have the same active member and the corresponding members have
2896 // the same value.
2897 // The set of scalar types for which this condition holds is
2898 // implementation-defined. [ Note: If a type has padding bits, the condition
2899 // does not hold; otherwise, the condition holds true for unsigned integral
2900 // types. -- end note ]
2901 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2902
2903 // Arrays are unique only if their element type is unique.
2904 if (Ty->isArrayType())
2906 CheckIfTriviallyCopyable);
2907
2908 assert((Ty->isVoidType() || !Ty->isIncompleteType()) &&
2909 "hasUniqueObjectRepresentations should not be called with an "
2910 "incomplete type");
2911
2912 // (9.1) - T is trivially copyable...
2913 if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(*this))
2914 return false;
2915
2916 // All integrals and enums are unique.
2917 if (Ty->isIntegralOrEnumerationType()) {
2918 // Except _BitInt types that have padding bits.
2919 if (const auto *BIT = Ty->getAs<BitIntType>())
2920 return getTypeSize(BIT) == BIT->getNumBits();
2921
2922 return true;
2923 }
2924
2925 // All other pointers are unique.
2926 if (Ty->isPointerType())
2927 return true;
2928
2929 if (const auto *MPT = Ty->getAs<MemberPointerType>())
2930 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2931
2932 if (Ty->isRecordType()) {
2933 const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl();
2934
2935 if (Record->isInvalidDecl())
2936 return false;
2937
2938 if (Record->isUnion())
2940 CheckIfTriviallyCopyable);
2941
2942 std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(
2943 *this, Record, CheckIfTriviallyCopyable);
2944
2945 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(Ty));
2946 }
2947
2948 // FIXME: More cases to handle here (list by rsmith):
2949 // vectors (careful about, eg, vector of 3 foo)
2950 // _Complex int and friends
2951 // _Atomic T
2952 // Obj-C block pointers
2953 // Obj-C object pointers
2954 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2955 // clk_event_t, queue_t, reserve_id_t)
2956 // There're also Obj-C class types and the Obj-C selector type, but I think it
2957 // makes sense for those to return false here.
2958
2959 return false;
2960}
2961
2963 unsigned count = 0;
2964 // Count ivars declared in class extension.
2965 for (const auto *Ext : OI->known_extensions())
2966 count += Ext->ivar_size();
2967
2968 // Count ivar defined in this class's implementation. This
2969 // includes synthesized ivars.
2970 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2971 count += ImplDecl->ivar_size();
2972
2973 return count;
2974}
2975
2977 if (!E)
2978 return false;
2979
2980 // nullptr_t is always treated as null.
2981 if (E->getType()->isNullPtrType()) return true;
2982
2983 if (E->getType()->isAnyPointerType() &&
2986 return true;
2987
2988 // Unfortunately, __null has type 'int'.
2989 if (isa<GNUNullExpr>(E)) return true;
2990
2991 return false;
2992}
2993
2994/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
2995/// exists.
2997 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2998 I = ObjCImpls.find(D);
2999 if (I != ObjCImpls.end())
3000 return cast<ObjCImplementationDecl>(I->second);
3001 return nullptr;
3002}
3003
3004/// Get the implementation of ObjCCategoryDecl, or nullptr if none
3005/// exists.
3007 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3008 I = ObjCImpls.find(D);
3009 if (I != ObjCImpls.end())
3010 return cast<ObjCCategoryImplDecl>(I->second);
3011 return nullptr;
3012}
3013
3014/// Set the implementation of ObjCInterfaceDecl.
3016 ObjCImplementationDecl *ImplD) {
3017 assert(IFaceD && ImplD && "Passed null params");
3018 ObjCImpls[IFaceD] = ImplD;
3019}
3020
3021/// Set the implementation of ObjCCategoryDecl.
3023 ObjCCategoryImplDecl *ImplD) {
3024 assert(CatD && ImplD && "Passed null params");
3025 ObjCImpls[CatD] = ImplD;
3026}
3027
3028const ObjCMethodDecl *
3030 return ObjCMethodRedecls.lookup(MD);
3031}
3032
3034 const ObjCMethodDecl *Redecl) {
3035 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
3036 ObjCMethodRedecls[MD] = Redecl;
3037}
3038
3040 const NamedDecl *ND) const {
3041 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
3042 return ID;
3043 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
3044 return CD->getClassInterface();
3045 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
3046 return IMD->getClassInterface();
3047
3048 return nullptr;
3049}
3050
3051/// Get the copy initialization expression of VarDecl, or nullptr if
3052/// none exists.
3054 assert(VD && "Passed null params");
3055 assert(VD->hasAttr<BlocksAttr>() &&
3056 "getBlockVarCopyInits - not __block var");
3057 auto I = BlockVarCopyInits.find(VD);
3058 if (I != BlockVarCopyInits.end())
3059 return I->second;
3060 return {nullptr, false};
3061}
3062
3063/// Set the copy initialization expression of a block var decl.
3065 bool CanThrow) {
3066 assert(VD && CopyExpr && "Passed null params");
3067 assert(VD->hasAttr<BlocksAttr>() &&
3068 "setBlockVarCopyInits - not __block var");
3069 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
3070}
3071
3073 unsigned DataSize) const {
3074 if (!DataSize)
3076 else
3077 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
3078 "incorrect data size provided to CreateTypeSourceInfo!");
3079
3080 auto *TInfo =
3081 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
3082 new (TInfo) TypeSourceInfo(T, DataSize);
3083 return TInfo;
3084}
3085
3087 SourceLocation L) const {
3089 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
3090 return DI;
3091}
3092
3093const ASTRecordLayout &
3095 return getObjCLayout(D, nullptr);
3096}
3097
3098const ASTRecordLayout &
3100 const ObjCImplementationDecl *D) const {
3101 return getObjCLayout(D->getClassInterface(), D);
3102}
3103
3106 bool &AnyNonCanonArgs) {
3107 SmallVector<TemplateArgument, 16> CanonArgs(Args);
3108 for (auto &Arg : CanonArgs) {
3109 TemplateArgument OrigArg = Arg;
3110 Arg = C.getCanonicalTemplateArgument(Arg);
3111 AnyNonCanonArgs |= !Arg.structurallyEquals(OrigArg);
3112 }
3113 return CanonArgs;
3114}
3115
3116//===----------------------------------------------------------------------===//
3117// Type creation/memoization methods
3118//===----------------------------------------------------------------------===//
3119
3121ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3122 unsigned fastQuals = quals.getFastQualifiers();
3123 quals.removeFastQualifiers();
3124
3125 // Check if we've already instantiated this type.
3126 llvm::FoldingSetNodeID ID;
3127 ExtQuals::Profile(ID, baseType, quals);
3128 void *insertPos = nullptr;
3129 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
3130 assert(eq->getQualifiers() == quals);
3131 return QualType(eq, fastQuals);
3132 }
3133
3134 // If the base type is not canonical, make the appropriate canonical type.
3135 QualType canon;
3136 if (!baseType->isCanonicalUnqualified()) {
3137 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3138 canonSplit.Quals.addConsistentQualifiers(quals);
3139 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
3140
3141 // Re-find the insert position.
3142 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
3143 }
3144
3145 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3146 ExtQualNodes.InsertNode(eq, insertPos);
3147 return QualType(eq, fastQuals);
3148}
3149
3151 LangAS AddressSpace) const {
3152 QualType CanT = getCanonicalType(T);
3153 if (CanT.getAddressSpace() == AddressSpace)
3154 return T;
3155
3156 // If we are composing extended qualifiers together, merge together
3157 // into one ExtQuals node.
3158 QualifierCollector Quals;
3159 const Type *TypeNode = Quals.strip(T);
3160
3161 // If this type already has an address space specified, it cannot get
3162 // another one.
3163 assert(!Quals.hasAddressSpace() &&
3164 "Type cannot be in multiple addr spaces!");
3165 Quals.addAddressSpace(AddressSpace);
3166
3167 return getExtQualType(TypeNode, Quals);
3168}
3169
3171 // If the type is not qualified with an address space, just return it
3172 // immediately.
3173 if (!T.hasAddressSpace())
3174 return T;
3175
3176 QualifierCollector Quals;
3177 const Type *TypeNode;
3178 // For arrays, strip the qualifier off the element type, then reconstruct the
3179 // array type
3180 if (T.getTypePtr()->isArrayType()) {
3181 T = getUnqualifiedArrayType(T, Quals);
3182 TypeNode = T.getTypePtr();
3183 } else {
3184 // If we are composing extended qualifiers together, merge together
3185 // into one ExtQuals node.
3186 while (T.hasAddressSpace()) {
3187 TypeNode = Quals.strip(T);
3188
3189 // If the type no longer has an address space after stripping qualifiers,
3190 // jump out.
3191 if (!QualType(TypeNode, 0).hasAddressSpace())
3192 break;
3193
3194 // There might be sugar in the way. Strip it and try again.
3195 T = T.getSingleStepDesugaredType(*this);
3196 }
3197 }
3198
3199 Quals.removeAddressSpace();
3200
3201 // Removal of the address space can mean there are no longer any
3202 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3203 // or required.
3204 if (Quals.hasNonFastQualifiers())
3205 return getExtQualType(TypeNode, Quals);
3206 else
3207 return QualType(TypeNode, Quals.getFastQualifiers());
3208}
3209
3210uint16_t
3212 assert(RD->isPolymorphic() &&
3213 "Attempted to get vtable pointer discriminator on a monomorphic type");
3214 std::unique_ptr<MangleContext> MC(createMangleContext());
3215 SmallString<256> Str;
3216 llvm::raw_svector_ostream Out(Str);
3217 MC->mangleCXXVTable(RD, Out);
3218 return llvm::getPointerAuthStableSipHash(Str);
3219}
3220
3221/// Encode a function type for use in the discriminator of a function pointer
3222/// type. We can't use the itanium scheme for this since C has quite permissive
3223/// rules for type compatibility that we need to be compatible with.
3224///
3225/// Formally, this function associates every function pointer type T with an
3226/// encoded string E(T). Let the equivalence relation T1 ~ T2 be defined as
3227/// E(T1) == E(T2). E(T) is part of the ABI of values of type T. C type
3228/// compatibility requires equivalent treatment under the ABI, so
3229/// CCompatible(T1, T2) must imply E(T1) == E(T2), that is, CCompatible must be
3230/// a subset of ~. Crucially, however, it must be a proper subset because
3231/// CCompatible is not an equivalence relation: for example, int[] is compatible
3232/// with both int[1] and int[2], but the latter are not compatible with each
3233/// other. Therefore this encoding function must be careful to only distinguish
3234/// types if there is no third type with which they are both required to be
3235/// compatible.
3237 raw_ostream &OS, QualType QT) {
3238 // FIXME: Consider address space qualifiers.
3239 const Type *T = QT.getCanonicalType().getTypePtr();
3240
3241 // FIXME: Consider using the C++ type mangling when we encounter a construct
3242 // that is incompatible with C.
3243
3244 switch (T->getTypeClass()) {
3245 case Type::Atomic:
3247 Ctx, OS, cast<AtomicType>(T)->getValueType());
3248
3249 case Type::LValueReference:
3250 OS << "R";
3252 cast<ReferenceType>(T)->getPointeeType());
3253 return;
3254 case Type::RValueReference:
3255 OS << "O";
3257 cast<ReferenceType>(T)->getPointeeType());
3258 return;
3259
3260 case Type::Pointer:
3261 // C11 6.7.6.1p2:
3262 // For two pointer types to be compatible, both shall be identically
3263 // qualified and both shall be pointers to compatible types.
3264 // FIXME: we should also consider pointee types.
3265 OS << "P";
3266 return;
3267
3268 case Type::ObjCObjectPointer:
3269 case Type::BlockPointer:
3270 OS << "P";
3271 return;
3272
3273 case Type::Complex:
3274 OS << "C";
3276 Ctx, OS, cast<ComplexType>(T)->getElementType());
3277
3278 case Type::VariableArray:
3279 case Type::ConstantArray:
3280 case Type::IncompleteArray:
3281 case Type::ArrayParameter:
3282 // C11 6.7.6.2p6:
3283 // For two array types to be compatible, both shall have compatible
3284 // element types, and if both size specifiers are present, and are integer
3285 // constant expressions, then both size specifiers shall have the same
3286 // constant value [...]
3287 //
3288 // So since ElemType[N] has to be compatible ElemType[], we can't encode the
3289 // width of the array.
3290 OS << "A";
3292 Ctx, OS, cast<ArrayType>(T)->getElementType());
3293
3294 case Type::ObjCInterface:
3295 case Type::ObjCObject:
3296 OS << "<objc_object>";
3297 return;
3298
3299 case Type::Enum: {
3300 // C11 6.7.2.2p4:
3301 // Each enumerated type shall be compatible with char, a signed integer
3302 // type, or an unsigned integer type.
3303 //
3304 // So we have to treat enum types as integers.
3305 QualType UnderlyingType = cast<EnumType>(T)->getDecl()->getIntegerType();
3307 Ctx, OS, UnderlyingType.isNull() ? Ctx.IntTy : UnderlyingType);
3308 }
3309
3310 case Type::FunctionNoProto:
3311 case Type::FunctionProto: {
3312 // C11 6.7.6.3p15:
3313 // For two function types to be compatible, both shall specify compatible
3314 // return types. Moreover, the parameter type lists, if both are present,
3315 // shall agree in the number of parameters and in the use of the ellipsis
3316 // terminator; corresponding parameters shall have compatible types.
3317 //
3318 // That paragraph goes on to describe how unprototyped functions are to be
3319 // handled, which we ignore here. Unprototyped function pointers are hashed
3320 // as though they were prototyped nullary functions since thats probably
3321 // what the user meant. This behavior is non-conforming.
3322 // FIXME: If we add a "custom discriminator" function type attribute we
3323 // should encode functions as their discriminators.
3324 OS << "F";
3325 const auto *FuncType = cast<FunctionType>(T);
3326 encodeTypeForFunctionPointerAuth(Ctx, OS, FuncType->getReturnType());
3327 if (const auto *FPT = dyn_cast<FunctionProtoType>(FuncType)) {
3328 for (QualType Param : FPT->param_types()) {
3329 Param = Ctx.getSignatureParameterType(Param);
3330 encodeTypeForFunctionPointerAuth(Ctx, OS, Param);
3331 }
3332 if (FPT->isVariadic())
3333 OS << "z";
3334 }
3335 OS << "E";
3336 return;
3337 }
3338
3339 case Type::MemberPointer: {
3340 OS << "M";
3341 const auto *MPT = T->castAs<MemberPointerType>();
3342 encodeTypeForFunctionPointerAuth(Ctx, OS, QualType(MPT->getClass(), 0));
3343 encodeTypeForFunctionPointerAuth(Ctx, OS, MPT->getPointeeType());
3344 return;
3345 }
3346 case Type::ExtVector:
3347 case Type::Vector:
3348 OS << "Dv" << Ctx.getTypeSizeInChars(T).getQuantity();
3349 break;
3350
3351 // Don't bother discriminating based on these types.
3352 case Type::Pipe:
3353 case Type::BitInt:
3354 case Type::ConstantMatrix:
3355 OS << "?";
3356 return;
3357
3358 case Type::Builtin: {
3359 const auto *BTy = T->castAs<BuiltinType>();
3360 switch (BTy->getKind()) {
3361#define SIGNED_TYPE(Id, SingletonId) \
3362 case BuiltinType::Id: \
3363 OS << "i"; \
3364 return;
3365#define UNSIGNED_TYPE(Id, SingletonId) \
3366 case BuiltinType::Id: \
3367 OS << "i"; \
3368 return;
3369#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
3370#define BUILTIN_TYPE(Id, SingletonId)
3371#include "clang/AST/BuiltinTypes.def"
3372 llvm_unreachable("placeholder types should not appear here.");
3373
3374 case BuiltinType::Half:
3375 OS << "Dh";
3376 return;
3377 case BuiltinType::Float:
3378 OS << "f";
3379 return;
3380 case BuiltinType::Double:
3381 OS << "d";
3382 return;
3383 case BuiltinType::LongDouble:
3384 OS << "e";
3385 return;
3386 case BuiltinType::Float16:
3387 OS << "DF16_";
3388 return;
3389 case BuiltinType::Float128:
3390 OS << "g";
3391 return;
3392
3393 case BuiltinType::Void:
3394 OS << "v";
3395 return;
3396
3397 case BuiltinType::ObjCId:
3398 case BuiltinType::ObjCClass:
3399 case BuiltinType::ObjCSel:
3400 case BuiltinType::NullPtr:
3401 OS << "P";
3402 return;
3403
3404 // Don't bother discriminating based on OpenCL types.
3405 case BuiltinType::OCLSampler:
3406 case BuiltinType::OCLEvent:
3407 case BuiltinType::OCLClkEvent:
3408 case BuiltinType::OCLQueue:
3409 case BuiltinType::OCLReserveID:
3410 case BuiltinType::BFloat16:
3411 case BuiltinType::VectorQuad:
3412 case BuiltinType::VectorPair:
3413 OS << "?";
3414 return;
3415
3416 // Don't bother discriminating based on these seldom-used types.
3417 case BuiltinType::Ibm128:
3418 return;
3419#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3420 case BuiltinType::Id: \
3421 return;
3422#include "clang/Basic/OpenCLImageTypes.def"
3423#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3424 case BuiltinType::Id: \
3425 return;
3426#include "clang/Basic/OpenCLExtensionTypes.def"
3427#define SVE_TYPE(Name, Id, SingletonId) \
3428 case BuiltinType::Id: \
3429 return;
3430#include "clang/Basic/AArch64SVEACLETypes.def"
3431#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3432 case BuiltinType::Id: \
3433 return;
3434#include "clang/Basic/HLSLIntangibleTypes.def"
3435 case BuiltinType::Dependent:
3436 llvm_unreachable("should never get here");
3437#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
3438#include "clang/Basic/AMDGPUTypes.def"
3439 case BuiltinType::WasmExternRef:
3440#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3441#include "clang/Basic/RISCVVTypes.def"
3442 llvm_unreachable("not yet implemented");
3443 }
3444 llvm_unreachable("should never get here");
3445 }
3446 case Type::Record: {
3447 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
3448 const IdentifierInfo *II = RD->getIdentifier();
3449
3450 // In C++, an immediate typedef of an anonymous struct or union
3451 // is considered to name it for ODR purposes, but C's specification
3452 // of type compatibility does not have a similar rule. Using the typedef
3453 // name in function type discriminators anyway, as we do here,
3454 // therefore technically violates the C standard: two function pointer
3455 // types defined in terms of two typedef'd anonymous structs with
3456 // different names are formally still compatible, but we are assigning
3457 // them different discriminators and therefore incompatible ABIs.
3458 //
3459 // This is a relatively minor violation that significantly improves
3460 // discrimination in some cases and has not caused problems in
3461 // practice. Regardless, it is now part of the ABI in places where
3462 // function type discrimination is used, and it can no longer be
3463 // changed except on new platforms.
3464
3465 if (!II)
3466 if (const TypedefNameDecl *Typedef = RD->getTypedefNameForAnonDecl())
3467 II = Typedef->getDeclName().getAsIdentifierInfo();
3468
3469 if (!II) {
3470 OS << "<anonymous_record>";
3471 return;
3472 }
3473 OS << II->getLength() << II->getName();
3474 return;
3475 }
3476 case Type::HLSLAttributedResource:
3477 llvm_unreachable("should never get here");
3478 break;
3479 case Type::DeducedTemplateSpecialization:
3480 case Type::Auto:
3481#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3482#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3483#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3484#define ABSTRACT_TYPE(Class, Base)
3485#define TYPE(Class, Base)
3486#include "clang/AST/TypeNodes.inc"
3487 llvm_unreachable("unexpected non-canonical or dependent type!");
3488 return;
3489 }
3490}
3491
3493 assert(!T->isDependentType() &&
3494 "cannot compute type discriminator of a dependent type");
3495
3496 SmallString<256> Str;
3497 llvm::raw_svector_ostream Out(Str);
3498
3500 T = T->getPointeeType();
3501
3502 if (T->isFunctionType()) {
3504 } else {
3505 T = T.getUnqualifiedType();
3506 std::unique_ptr<MangleContext> MC(createMangleContext());
3507 MC->mangleCanonicalTypeName(T, Out);
3508 }
3509
3510 return llvm::getPointerAuthStableSipHash(Str);
3511}
3512
3514 Qualifiers::GC GCAttr) const {
3515 QualType CanT = getCanonicalType(T);
3516 if (CanT.getObjCGCAttr() == GCAttr)
3517 return T;
3518
3519 if (const auto *ptr = T->getAs<PointerType>()) {
3520 QualType Pointee = ptr->getPointeeType();
3521 if (Pointee->isAnyPointerType()) {
3522 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
3523 return getPointerType(ResultType);
3524 }
3525 }
3526
3527 // If we are composing extended qualifiers together, merge together
3528 // into one ExtQuals node.
3529 QualifierCollector Quals;
3530 const Type *TypeNode = Quals.strip(T);
3531
3532 // If this type already has an ObjCGC specified, it cannot get
3533 // another one.
3534 assert(!Quals.hasObjCGCAttr() &&
3535 "Type cannot have multiple ObjCGCs!");
3536 Quals.addObjCGCAttr(GCAttr);
3537
3538 return getExtQualType(TypeNode, Quals);
3539}
3540
3542 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3543 QualType Pointee = Ptr->getPointeeType();
3544 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3545 return getPointerType(removeAddrSpaceQualType(Pointee));
3546 }
3547 }
3548 return T;
3549}
3550
3552 QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull,
3553 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3554 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3555
3556 llvm::FoldingSetNodeID ID;
3557 CountAttributedType::Profile(ID, WrappedTy, CountExpr, CountInBytes, OrNull);
3558
3559 void *InsertPos = nullptr;
3560 CountAttributedType *CATy =
3561 CountAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
3562 if (CATy)
3563 return QualType(CATy, 0);
3564
3565 QualType CanonTy = getCanonicalType(WrappedTy);
3566 size_t Size = CountAttributedType::totalSizeToAlloc<TypeCoupledDeclRefInfo>(
3567 DependentDecls.size());
3569 new (CATy) CountAttributedType(WrappedTy, CanonTy, CountExpr, CountInBytes,
3570 OrNull, DependentDecls);
3571 Types.push_back(CATy);
3572 CountAttributedTypes.InsertNode(CATy, InsertPos);
3573
3574 return QualType(CATy, 0);
3575}
3576
3579 llvm::function_ref<QualType(QualType)> Adjust) const {
3580 switch (Orig->getTypeClass()) {
3581 case Type::Attributed: {
3582 const auto *AT = cast<AttributedType>(Orig);
3583 return getAttributedType(AT->getAttrKind(),
3584 adjustType(AT->getModifiedType(), Adjust),
3585 adjustType(AT->getEquivalentType(), Adjust),
3586 AT->getAttr());
3587 }
3588
3589 case Type::BTFTagAttributed: {
3590 const auto *BTFT = dyn_cast<BTFTagAttributedType>(Orig);
3591 return getBTFTagAttributedType(BTFT->getAttr(),
3592 adjustType(BTFT->getWrappedType(), Adjust));
3593 }
3594
3595 case Type::Elaborated: {
3596 const auto *ET = cast<ElaboratedType>(Orig);
3597 return getElaboratedType(ET->getKeyword(), ET->getQualifier(),
3598 adjustType(ET->getNamedType(), Adjust));
3599 }
3600
3601 case Type::Paren:
3602 return getParenType(
3603 adjustType(cast<ParenType>(Orig)->getInnerType(), Adjust));
3604
3605 case Type::Adjusted: {
3606 const auto *AT = cast<AdjustedType>(Orig);
3607 return getAdjustedType(AT->getOriginalType(),
3608 adjustType(AT->getAdjustedType(), Adjust));
3609 }
3610
3611 case Type::MacroQualified: {
3612 const auto *MQT = cast<MacroQualifiedType>(Orig);
3613 return getMacroQualifiedType(adjustType(MQT->getUnderlyingType(), Adjust),
3614 MQT->getMacroIdentifier());
3615 }
3616
3617 default:
3618 return Adjust(Orig);
3619 }
3620}
3621
3623 FunctionType::ExtInfo Info) {
3624 if (T->getExtInfo() == Info)
3625 return T;
3626
3628 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3629 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3630 } else {
3631 const auto *FPT = cast<FunctionProtoType>(T);
3632 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3633 EPI.ExtInfo = Info;
3634 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3635 }
3636
3637 return cast<FunctionType>(Result.getTypePtr());
3638}
3639
3641 QualType ResultType) {
3642 return adjustType(FunctionType, [&](QualType Orig) {
3643 if (const auto *FNPT = Orig->getAs<FunctionNoProtoType>())
3644 return getFunctionNoProtoType(ResultType, FNPT->getExtInfo());
3645
3646 const auto *FPT = Orig->castAs<FunctionProtoType>();
3647 return getFunctionType(ResultType, FPT->getParamTypes(),
3648 FPT->getExtProtoInfo());
3649 });
3650}
3651
3653 QualType ResultType) {
3654 FD = FD->getMostRecentDecl();
3655 while (true) {
3656 FD->setType(adjustFunctionResultType(FD->getType(), ResultType));
3657 if (FunctionDecl *Next = FD->getPreviousDecl())
3658 FD = Next;
3659 else
3660 break;
3661 }
3663 L->DeducedReturnType(FD, ResultType);
3664}
3665
3666/// Get a function type and produce the equivalent function type with the
3667/// specified exception specification. Type sugar that can be present on a
3668/// declaration of a function with an exception specification is permitted
3669/// and preserved. Other type sugar (for instance, typedefs) is not.
3671 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3672 return adjustType(Orig, [&](QualType Ty) {
3673 const auto *Proto = Ty->castAs<FunctionProtoType>();
3674 return getFunctionType(Proto->getReturnType(), Proto->getParamTypes(),
3675 Proto->getExtProtoInfo().withExceptionSpec(ESI));
3676 });
3677}
3678
3680 QualType U) const {
3681 return hasSameType(T, U) ||
3682 (getLangOpts().CPlusPlus17 &&
3685}
3686
3688 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3689 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3690 SmallVector<QualType, 16> Args(Proto->param_types().size());
3691 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3692 Args[i] = removePtrSizeAddrSpace(Proto->param_types()[i]);
3693 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3694 }
3695
3696 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3697 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3698 return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3699 }
3700
3701 return T;
3702}
3703
3705 return hasSameType(T, U) ||
3708}
3709
3711 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3712 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3713 EPI.ExtParameterInfos = nullptr;
3714 return getFunctionType(Proto->getReturnType(), Proto->param_types(), EPI);
3715 }
3716 return T;
3717}
3718
3720 QualType U) const {
3723}
3724
3727 bool AsWritten) {
3728 // Update the type.
3729 QualType Updated =
3731 FD->setType(Updated);
3732
3733 if (!AsWritten)
3734 return;
3735
3736 // Update the type in the type source information too.
3737 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3738 // If the type and the type-as-written differ, we may need to update
3739 // the type-as-written too.
3740 if (TSInfo->getType() != FD->getType())
3741 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3742
3743 // FIXME: When we get proper type location information for exceptions,
3744 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3745 // up the TypeSourceInfo;
3746 assert(TypeLoc::getFullDataSizeForType(Updated) ==
3747 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3748 "TypeLoc size mismatch from updating exception specification");
3749 TSInfo->overrideType(Updated);
3750 }
3751}
3752
3753/// getComplexType - Return the uniqued reference to the type for a complex
3754/// number with the specified element type.
3756 // Unique pointers, to guarantee there is only one pointer of a particular
3757 // structure.
3758 llvm::FoldingSetNodeID ID;
3760
3761 void *InsertPos = nullptr;
3762 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3763 return QualType(CT, 0);
3764
3765 // If the pointee type isn't canonical, this won't be a canonical type either,
3766 // so fill in the canonical type field.
3767 QualType Canonical;
3768 if (!T.isCanonical()) {
3769 Canonical = getComplexType(getCanonicalType(T));
3770
3771 // Get the new insert position for the node we care about.
3772 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3773 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3774 }
3775 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
3776 Types.push_back(New);
3777 ComplexTypes.InsertNode(New, InsertPos);
3778 return QualType(New, 0);
3779}
3780
3781/// getPointerType - Return the uniqued reference to the type for a pointer to
3782/// the specified type.
3784 // Unique pointers, to guarantee there is only one pointer of a particular
3785 // structure.
3786 llvm::FoldingSetNodeID ID;
3788
3789 void *InsertPos = nullptr;
3790 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3791 return QualType(PT, 0);
3792
3793 // If the pointee type isn't canonical, this won't be a canonical type either,
3794 // so fill in the canonical type field.
3795 QualType Canonical;
3796 if (!T.isCanonical()) {
3797 Canonical = getPointerType(getCanonicalType(T));
3798
3799 // Get the new insert position for the node we care about.
3800 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3801 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3802 }
3803 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
3804 Types.push_back(New);
3805 PointerTypes.InsertNode(New, InsertPos);
3806 return QualType(New, 0);
3807}
3808
3810 llvm::FoldingSetNodeID ID;
3811 AdjustedType::Profile(ID, Orig, New);
3812 void *InsertPos = nullptr;
3813 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3814 if (AT)
3815 return QualType(AT, 0);
3816
3817 QualType Canonical = getCanonicalType(New);
3818
3819 // Get the new insert position for the node we care about.
3820 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3821 assert(!AT && "Shouldn't be in the map!");
3822
3823 AT = new (*this, alignof(AdjustedType))
3824 AdjustedType(Type::Adjusted, Orig, New, Canonical);
3825 Types.push_back(AT);
3826 AdjustedTypes.InsertNode(AT, InsertPos);
3827 return QualType(AT, 0);
3828}
3829
3831 llvm::FoldingSetNodeID ID;
3832 AdjustedType::Profile(ID, Orig, Decayed);
3833 void *InsertPos = nullptr;
3834 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3835 if (AT)
3836 return QualType(AT, 0);
3837
3838 QualType Canonical = getCanonicalType(Decayed);
3839
3840 // Get the new insert position for the node we care about.
3841 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3842 assert(!AT && "Shouldn't be in the map!");
3843
3844 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
3845 Types.push_back(AT);
3846 AdjustedTypes.InsertNode(AT, InsertPos);
3847 return QualType(AT, 0);
3848}
3849
3851 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
3852
3853 QualType Decayed;
3854
3855 // C99 6.7.5.3p7:
3856 // A declaration of a parameter as "array of type" shall be
3857 // adjusted to "qualified pointer to type", where the type
3858 // qualifiers (if any) are those specified within the [ and ] of
3859 // the array type derivation.
3860 if (T->isArrayType())
3861 Decayed = getArrayDecayedType(T);
3862
3863 // C99 6.7.5.3p8:
3864 // A declaration of a parameter as "function returning type"
3865 // shall be adjusted to "pointer to function returning type", as
3866 // in 6.3.2.1.
3867 if (T->isFunctionType())
3868 Decayed = getPointerType(T);
3869
3870 return getDecayedType(T, Decayed);
3871}
3872
3874 if (Ty->isArrayParameterType())
3875 return Ty;
3876 assert(Ty->isConstantArrayType() && "Ty must be an array type.");
3877 const auto *ATy = cast<ConstantArrayType>(Ty);
3878 llvm::FoldingSetNodeID ID;
3879 ATy->Profile(ID, *this, ATy->getElementType(), ATy->getZExtSize(),
3880 ATy->getSizeExpr(), ATy->getSizeModifier(),
3881 ATy->getIndexTypeQualifiers().getAsOpaqueValue());
3882 void *InsertPos = nullptr;
3883 ArrayParameterType *AT =
3884 ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
3885 if (AT)
3886 return QualType(AT, 0);
3887
3888 QualType Canonical;
3889 if (!Ty.isCanonical()) {
3890 Canonical = getArrayParameterType(getCanonicalType(Ty));
3891
3892 // Get the new insert position for the node we care about.
3893 AT = ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
3894 assert(!AT && "Shouldn't be in the map!");
3895 }
3896
3897 AT = new (*this, alignof(ArrayParameterType))
3898 ArrayParameterType(ATy, Canonical);
3899 Types.push_back(AT);
3900 ArrayParameterTypes.InsertNode(AT, InsertPos);
3901 return QualType(AT, 0);
3902}
3903
3904/// getBlockPointerType - Return the uniqued reference to the type for
3905/// a pointer to the specified block.
3907 assert(T->isFunctionType() && "block of function types only");
3908 // Unique pointers, to guarantee there is only one block of a particular
3909 // structure.
3910 llvm::FoldingSetNodeID ID;
3912
3913 void *InsertPos = nullptr;
3914 if (BlockPointerType *PT =
3915 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3916 return QualType(PT, 0);
3917
3918 // If the block pointee type isn't canonical, this won't be a canonical
3919 // type either so fill in the canonical type field.
3920 QualType Canonical;
3921 if (!T.isCanonical()) {
3923
3924 // Get the new insert position for the node we care about.
3925 BlockPointerType *NewIP =
3926 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3927 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3928 }
3929 auto *New =
3930 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
3931 Types.push_back(New);
3932 BlockPointerTypes.InsertNode(New, InsertPos);
3933 return QualType(New, 0);
3934}
3935
3936/// getLValueReferenceType - Return the uniqued reference to the type for an
3937/// lvalue reference to the specified type.
3939ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
3940 assert((!T->isPlaceholderType() ||
3941 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
3942 "Unresolved placeholder type");
3943
3944 // Unique pointers, to guarantee there is only one pointer of a particular
3945 // structure.
3946 llvm::FoldingSetNodeID ID;
3947 ReferenceType::Profile(ID, T, SpelledAsLValue);
3948
3949 void *InsertPos = nullptr;
3950 if (LValueReferenceType *RT =
3951 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3952 return QualType(RT, 0);
3953
3954 const auto *InnerRef = T->getAs<ReferenceType>();
3955
3956 // If the referencee type isn't canonical, this won't be a canonical type
3957 // either, so fill in the canonical type field.
3958 QualType Canonical;
3959 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
3960 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3961 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
3962
3963 // Get the new insert position for the node we care about.
3964 LValueReferenceType *NewIP =
3965 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3966 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3967 }
3968
3969 auto *New = new (*this, alignof(LValueReferenceType))
3970 LValueReferenceType(T, Canonical, SpelledAsLValue);
3971 Types.push_back(New);
3972 LValueReferenceTypes.InsertNode(New, InsertPos);
3973
3974 return QualType(New, 0);
3975}
3976
3977/// getRValueReferenceType - Return the uniqued reference to the type for an
3978/// rvalue reference to the specified type.
3980 assert((!T->isPlaceholderType() ||
3981 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
3982 "Unresolved placeholder type");
3983
3984 // Unique pointers, to guarantee there is only one pointer of a particular
3985 // structure.
3986 llvm::FoldingSetNodeID ID;
3987 ReferenceType::Profile(ID, T, false);
3988
3989 void *InsertPos = nullptr;
3990 if (RValueReferenceType *RT =
3991 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3992 return QualType(RT, 0);
3993
3994 const auto *InnerRef = T->getAs<ReferenceType>();
3995
3996 // If the referencee type isn't canonical, this won't be a canonical type
3997 // either, so fill in the canonical type field.
3998 QualType Canonical;
3999 if (InnerRef || !T.isCanonical()) {
4000 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4001 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
4002
4003 // Get the new insert position for the node we care about.
4004 RValueReferenceType *NewIP =
4005 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4006 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4007 }
4008
4009 auto *New = new (*this, alignof(RValueReferenceType))
4010 RValueReferenceType(T, Canonical);
4011 Types.push_back(New);
4012 RValueReferenceTypes.InsertNode(New, InsertPos);
4013 return QualType(New, 0);
4014}
4015
4016/// getMemberPointerType - Return the uniqued reference to the type for a
4017/// member pointer to the specified type, in the specified class.
4019 // Unique pointers, to guarantee there is only one pointer of a particular
4020 // structure.
4021 llvm::FoldingSetNodeID ID;
4022 MemberPointerType::Profile(ID, T, Cls);
4023
4024 void *InsertPos = nullptr;
4025 if (MemberPointerType *PT =
4026 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4027 return QualType(PT, 0);
4028
4029 // If the pointee or class type isn't canonical, this won't be a canonical
4030 // type either, so fill in the canonical type field.
4031 QualType Canonical;
4032 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
4034
4035 // Get the new insert position for the node we care about.
4036 MemberPointerType *NewIP =
4037 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4038 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4039 }
4040 auto *New = new (*this, alignof(MemberPointerType))
4041 MemberPointerType(T, Cls, Canonical);
4042 Types.push_back(New);
4043 MemberPointerTypes.InsertNode(New, InsertPos);
4044 return QualType(New, 0);
4045}
4046
4047/// getConstantArrayType - Return the unique reference to the type for an
4048/// array of the specified element type.
4050 const llvm::APInt &ArySizeIn,
4051 const Expr *SizeExpr,
4053 unsigned IndexTypeQuals) const {
4054 assert((EltTy->isDependentType() ||
4055 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
4056 "Constant array of VLAs is illegal!");
4057
4058 // We only need the size as part of the type if it's instantiation-dependent.
4059 if (SizeExpr && !SizeExpr->isInstantiationDependent())
4060 SizeExpr = nullptr;
4061
4062 // Convert the array size into a canonical width matching the pointer size for
4063 // the target.
4064 llvm::APInt ArySize(ArySizeIn);
4065 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
4066
4067 llvm::FoldingSetNodeID ID;
4068 ConstantArrayType::Profile(ID, *this, EltTy, ArySize.getZExtValue(), SizeExpr,
4069 ASM, IndexTypeQuals);
4070
4071 void *InsertPos = nullptr;
4072 if (ConstantArrayType *ATP =
4073 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
4074 return QualType(ATP, 0);
4075
4076 // If the element type isn't canonical or has qualifiers, or the array bound
4077 // is instantiation-dependent, this won't be a canonical type either, so fill
4078 // in the canonical type field.
4079 QualType Canon;
4080 // FIXME: Check below should look for qualifiers behind sugar.
4081 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
4082 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4083 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
4084 ASM, IndexTypeQuals);
4085 Canon = getQualifiedType(Canon, canonSplit.Quals);
4086
4087 // Get the new insert position for the node we care about.
4088 ConstantArrayType *NewIP =
4089 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
4090 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4091 }
4092
4093 auto *New = ConstantArrayType::Create(*this, EltTy, Canon, ArySize, SizeExpr,
4094 ASM, IndexTypeQuals);
4095 ConstantArrayTypes.InsertNode(New, InsertPos);
4096 Types.push_back(New);
4097 return QualType(New, 0);
4098}
4099
4100/// getVariableArrayDecayedType - Turns the given type, which may be
4101/// variably-modified, into the corresponding type with all the known
4102/// sizes replaced with [*].
4104 // Vastly most common case.
4105 if (!type->isVariablyModifiedType()) return type;
4106
4107 QualType result;
4108
4109 SplitQualType split = type.getSplitDesugaredType();
4110 const Type *ty = split.Ty;
4111 switch (ty->getTypeClass()) {
4112#define TYPE(Class, Base)
4113#define ABSTRACT_TYPE(Class, Base)
4114#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4115#include "clang/AST/TypeNodes.inc"
4116 llvm_unreachable("didn't desugar past all non-canonical types?");
4117
4118 // These types should never be variably-modified.
4119 case Type::Builtin:
4120 case Type::Complex:
4121 case Type::Vector:
4122 case Type::DependentVector:
4123 case Type::ExtVector:
4124 case Type::DependentSizedExtVector:
4125 case Type::ConstantMatrix:
4126 case Type::DependentSizedMatrix:
4127 case Type::DependentAddressSpace:
4128 case Type::ObjCObject:
4129 case Type::ObjCInterface:
4130 case Type::ObjCObjectPointer:
4131 case Type::Record:
4132 case Type::Enum:
4133 case Type::UnresolvedUsing:
4134 case Type::TypeOfExpr:
4135 case Type::TypeOf:
4136 case Type::Decltype:
4137 case Type::UnaryTransform:
4138 case Type::DependentName:
4139 case Type::InjectedClassName:
4140 case Type::TemplateSpecialization:
4141 case Type::DependentTemplateSpecialization:
4142 case Type::TemplateTypeParm:
4143 case Type::SubstTemplateTypeParmPack:
4144 case Type::Auto:
4145 case Type::DeducedTemplateSpecialization:
4146 case Type::PackExpansion:
4147 case Type::PackIndexing:
4148 case Type::BitInt:
4149 case Type::DependentBitInt:
4150 case Type::ArrayParameter:
4151 case Type::HLSLAttributedResource:
4152 llvm_unreachable("type should never be variably-modified");
4153
4154 // These types can be variably-modified but should never need to
4155 // further decay.
4156 case Type::FunctionNoProto:
4157 case Type::FunctionProto:
4158 case Type::BlockPointer:
4159 case Type::MemberPointer:
4160 case Type::Pipe:
4161 return type;
4162
4163 // These types can be variably-modified. All these modifications
4164 // preserve structure except as noted by comments.
4165 // TODO: if we ever care about optimizing VLAs, there are no-op
4166 // optimizations available here.
4167 case Type::Pointer:
4169 cast<PointerType>(ty)->getPointeeType()));
4170 break;
4171
4172 case Type::LValueReference: {
4173 const auto *lv = cast<LValueReferenceType>(ty);
4174 result = getLValueReferenceType(
4175 getVariableArrayDecayedType(lv->getPointeeType()),
4176 lv->isSpelledAsLValue());
4177 break;
4178 }
4179
4180 case Type::RValueReference: {
4181 const auto *lv = cast<RValueReferenceType>(ty);
4182 result = getRValueReferenceType(
4183 getVariableArrayDecayedType(lv->getPointeeType()));
4184 break;
4185 }
4186
4187 case Type::Atomic: {
4188 const auto *at = cast<AtomicType>(ty);
4189 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
4190 break;
4191 }
4192
4193 case Type::ConstantArray: {
4194 const auto *cat = cast<ConstantArrayType>(ty);
4195 result = getConstantArrayType(
4196 getVariableArrayDecayedType(cat->getElementType()),
4197 cat->getSize(),
4198 cat->getSizeExpr(),
4199 cat->getSizeModifier(),
4200 cat->getIndexTypeCVRQualifiers());
4201 break;
4202 }
4203
4204 case Type::DependentSizedArray: {
4205 const auto *dat = cast<DependentSizedArrayType>(ty);
4207 getVariableArrayDecayedType(dat->getElementType()),
4208 dat->getSizeExpr(),
4209 dat->getSizeModifier(),
4210 dat->getIndexTypeCVRQualifiers(),
4211 dat->getBracketsRange());
4212 break;
4213 }
4214
4215 // Turn incomplete types into [*] types.
4216 case Type::IncompleteArray: {
4217 const auto *iat = cast<IncompleteArrayType>(ty);
4218 result =
4220 /*size*/ nullptr, ArraySizeModifier::Normal,
4221 iat->getIndexTypeCVRQualifiers(), SourceRange());
4222 break;
4223 }
4224
4225 // Turn VLA types into [*] types.
4226 case Type::VariableArray: {
4227 const auto *vat = cast<VariableArrayType>(ty);
4228 result = getVariableArrayType(
4229 getVariableArrayDecayedType(vat->getElementType()),
4230 /*size*/ nullptr, ArraySizeModifier::Star,
4231 vat->getIndexTypeCVRQualifiers(), vat->getBracketsRange());
4232 break;
4233 }
4234 }
4235
4236 // Apply the top-level qualifiers from the original.
4237 return getQualifiedType(result, split.Quals);
4238}
4239
4240/// getVariableArrayType - Returns a non-unique reference to the type for a
4241/// variable array of the specified element type.
4244 unsigned IndexTypeQuals,
4245 SourceRange Brackets) const {
4246 // Since we don't unique expressions, it isn't possible to unique VLA's
4247 // that have an expression provided for their size.
4248 QualType Canon;
4249
4250 // Be sure to pull qualifiers off the element type.
4251 // FIXME: Check below should look for qualifiers behind sugar.
4252 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
4253 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4254 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
4255 IndexTypeQuals, Brackets);
4256 Canon = getQualifiedType(Canon, canonSplit.Quals);
4257 }
4258
4259 auto *New = new (*this, alignof(VariableArrayType))
4260 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
4261
4262 VariableArrayTypes.push_back(New);
4263 Types.push_back(New);
4264 return QualType(New, 0);
4265}
4266
4267/// getDependentSizedArrayType - Returns a non-unique reference to
4268/// the type for a dependently-sized array of the specified element
4269/// type.
4271 Expr *numElements,
4273 unsigned elementTypeQuals,
4274 SourceRange brackets) const {
4275 assert((!numElements || numElements->isTypeDependent() ||
4276 numElements->isValueDependent()) &&
4277 "Size must be type- or value-dependent!");
4278
4279 SplitQualType canonElementType = getCanonicalType(elementType).split();
4280
4281 void *insertPos = nullptr;
4282 llvm::FoldingSetNodeID ID;
4284 ID, *this, numElements ? QualType(canonElementType.Ty, 0) : elementType,
4285 ASM, elementTypeQuals, numElements);
4286
4287 // Look for an existing type with these properties.
4288 DependentSizedArrayType *canonTy =
4289 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4290
4291 // Dependently-sized array types that do not have a specified number
4292 // of elements will have their sizes deduced from a dependent
4293 // initializer.
4294 if (!numElements) {
4295 if (canonTy)
4296 return QualType(canonTy, 0);
4297
4298 auto *newType = new (*this, alignof(DependentSizedArrayType))
4299 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
4300 elementTypeQuals, brackets);
4301 DependentSizedArrayTypes.InsertNode(newType, insertPos);
4302 Types.push_back(newType);
4303 return QualType(newType, 0);
4304 }
4305
4306 // If we don't have one, build one.
4307 if (!canonTy) {
4308 canonTy = new (*this, alignof(DependentSizedArrayType))
4309 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
4310 numElements, ASM, elementTypeQuals, brackets);
4311 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
4312 Types.push_back(canonTy);
4313 }
4314
4315 // Apply qualifiers from the element type to the array.
4316 QualType canon = getQualifiedType(QualType(canonTy,0),
4317 canonElementType.Quals);
4318
4319 // If we didn't need extra canonicalization for the element type or the size
4320 // expression, then just use that as our result.
4321 if (QualType(canonElementType.Ty, 0) == elementType &&
4322 canonTy->getSizeExpr() == numElements)
4323 return canon;
4324
4325 // Otherwise, we need to build a type which follows the spelling
4326 // of the element type.
4327 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
4328 DependentSizedArrayType(elementType, canon, numElements, ASM,
4329 elementTypeQuals, brackets);
4330 Types.push_back(sugaredType);
4331 return QualType(sugaredType, 0);
4332}
4333
4336 unsigned elementTypeQuals) const {
4337 llvm::FoldingSetNodeID ID;
4338 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
4339
4340 void *insertPos = nullptr;
4341 if (IncompleteArrayType *iat =
4342 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
4343 return QualType(iat, 0);
4344
4345 // If the element type isn't canonical, this won't be a canonical type
4346 // either, so fill in the canonical type field. We also have to pull
4347 // qualifiers off the element type.
4348 QualType canon;
4349
4350 // FIXME: Check below should look for qualifiers behind sugar.
4351 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
4352 SplitQualType canonSplit = getCanonicalType(elementType).split();
4353 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
4354 ASM, elementTypeQuals);
4355 canon = getQualifiedType(canon, canonSplit.Quals);
4356
4357 // Get the new insert position for the node we care about.
4358 IncompleteArrayType *existing =
4359 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4360 assert(!existing && "Shouldn't be in the map!"); (void) existing;
4361 }
4362
4363 auto *newType = new (*this, alignof(IncompleteArrayType))
4364 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
4365
4366 IncompleteArrayTypes.InsertNode(newType, insertPos);
4367 Types.push_back(newType);
4368 return QualType(newType, 0);
4369}
4370
4373#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
4374 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
4375 NUMVECTORS};
4376
4377#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
4378 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
4379
4380 switch (Ty->getKind()) {
4381 default:
4382 llvm_unreachable("Unsupported builtin vector type");
4383
4384#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4385 ElBits, NF, IsSigned) \
4386 case BuiltinType::Id: \
4387 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4388 llvm::ElementCount::getScalable(NumEls), NF};
4389#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4390 ElBits, NF) \
4391 case BuiltinType::Id: \
4392 return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy), \
4393 llvm::ElementCount::getScalable(NumEls), NF};
4394#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4395 ElBits, NF) \
4396 case BuiltinType::Id: \
4397 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4398#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4399 case BuiltinType::Id: \
4400 return {BoolTy, llvm::ElementCount::getScalable(NumEls), NF};
4401#define AARCH64_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4402 ElBits, NF) \
4403 case BuiltinType::Id: \
4404 return {getIntTypeForBitwidth(ElBits, false), \
4405 llvm::ElementCount::getFixed(NumEls), NF};
4406#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId)
4407#include "clang/Basic/AArch64SVEACLETypes.def"
4408
4409#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4410 IsSigned) \
4411 case BuiltinType::Id: \
4412 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4413 llvm::ElementCount::getScalable(NumEls), NF};
4414#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4415 case BuiltinType::Id: \
4416 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4417 llvm::ElementCount::getScalable(NumEls), NF};
4418#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4419 case BuiltinType::Id: \
4420 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4421#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4422 case BuiltinType::Id: \
4423 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4424#include "clang/Basic/RISCVVTypes.def"
4425 }
4426}
4427
4428/// getExternrefType - Return a WebAssembly externref type, which represents an
4429/// opaque reference to a host value.
4431 if (Target->getTriple().isWasm() && Target->hasFeature("reference-types")) {
4432#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4433 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4434 return SingletonId;
4435#include "clang/Basic/WebAssemblyReferenceTypes.def"
4436 }
4437 llvm_unreachable(
4438 "shouldn't try to generate type externref outside WebAssembly target");
4439}
4440
4441/// getScalableVectorType - Return the unique reference to a scalable vector
4442/// type of the specified element type and size. VectorType must be a built-in
4443/// type.
4445 unsigned NumFields) const {
4446 if (Target->hasAArch64SVETypes()) {
4447 uint64_t EltTySize = getTypeSize(EltTy);
4448
4449#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4450 ElBits, NF, IsSigned) \
4451 if (EltTy->hasIntegerRepresentation() && !EltTy->isBooleanType() && \
4452 EltTy->hasSignedIntegerRepresentation() == IsSigned && \
4453 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4454 return SingletonId; \
4455 }
4456#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4457 ElBits, NF) \
4458 if (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4459 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4460 return SingletonId; \
4461 }
4462#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4463 ElBits, NF) \
4464 if (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4465 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4466 return SingletonId; \
4467 }
4468#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4469 if (EltTy->isBooleanType() && NumElts == (NumEls * NF) && NumFields == 1) \
4470 return SingletonId;
4471#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId)
4472#define AARCH64_VECTOR_TYPE(Name, MangledName, Id, SingletonId)
4473#include "clang/Basic/AArch64SVEACLETypes.def"
4474 } else if (Target->hasRISCVVTypes()) {
4475 uint64_t EltTySize = getTypeSize(EltTy);
4476#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4477 IsFP, IsBF) \
4478 if (!EltTy->isBooleanType() && \
4479 ((EltTy->hasIntegerRepresentation() && \
4480 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4481 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4482 IsFP && !IsBF) || \
4483 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4484 IsBF && !IsFP)) && \
4485 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4486 return SingletonId;
4487#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4488 if (EltTy->isBooleanType() && NumElts == NumEls) \
4489 return SingletonId;
4490#include "clang/Basic/RISCVVTypes.def"
4491 }
4492 return QualType();
4493}
4494
4495/// getVectorType - Return the unique reference to a vector type of
4496/// the specified element type and size. VectorType must be a built-in type.
4498 VectorKind VecKind) const {
4499 assert(vecType->isBuiltinType() ||
4500 (vecType->isBitIntType() &&
4501 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4502 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits()) &&
4503 vecType->castAs<BitIntType>()->getNumBits() >= 8));
4504
4505 // Check if we've already instantiated a vector of this type.
4506 llvm::FoldingSetNodeID ID;
4507 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
4508
4509 void *InsertPos = nullptr;
4510 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4511 return QualType(VTP, 0);
4512
4513 // If the element type isn't canonical, this won't be a canonical type either,
4514 // so fill in the canonical type field.
4515 QualType Canonical;
4516 if (!vecType.isCanonical()) {
4517 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4518
4519 // Get the new insert position for the node we care about.
4520 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4521 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4522 }
4523 auto *New = new (*this, alignof(VectorType))
4524 VectorType(vecType, NumElts, Canonical, VecKind);
4525 VectorTypes.InsertNode(New, InsertPos);
4526 Types.push_back(New);
4527 return QualType(New, 0);
4528}
4529
4531 SourceLocation AttrLoc,
4532 VectorKind VecKind) const {
4533 llvm::FoldingSetNodeID ID;
4534 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4535 VecKind);
4536 void *InsertPos = nullptr;
4537 DependentVectorType *Canon =
4538 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4540
4541 if (Canon) {
4542 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4543 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4544 } else {
4545 QualType CanonVecTy = getCanonicalType(VecType);
4546 if (CanonVecTy == VecType) {
4547 New = new (*this, alignof(DependentVectorType))
4548 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4549
4550 DependentVectorType *CanonCheck =
4551 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4552 assert(!CanonCheck &&
4553 "Dependent-sized vector_size canonical type broken");
4554 (void)CanonCheck;
4555 DependentVectorTypes.InsertNode(New, InsertPos);
4556 } else {
4557 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4558 SourceLocation(), VecKind);
4559 New = new (*this, alignof(DependentVectorType))
4560 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4561 }
4562 }
4563
4564 Types.push_back(New);
4565 return QualType(New, 0);
4566}
4567
4568/// getExtVectorType - Return the unique reference to an extended vector type of
4569/// the specified element type and size. VectorType must be a built-in type.
4571 unsigned NumElts) const {
4572 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4573 (vecType->isBitIntType() &&
4574 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4575 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits()) &&
4576 vecType->castAs<BitIntType>()->getNumBits() >= 8));
4577
4578 // Check if we've already instantiated a vector of this type.
4579 llvm::FoldingSetNodeID ID;
4580 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4582 void *InsertPos = nullptr;
4583 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4584 return QualType(VTP, 0);
4585
4586 // If the element type isn't canonical, this won't be a canonical type either,
4587 // so fill in the canonical type field.
4588 QualType Canonical;
4589 if (!vecType.isCanonical()) {
4590 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4591
4592 // Get the new insert position for the node we care about.
4593 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4594 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4595 }
4596 auto *New = new (*this, alignof(ExtVectorType))
4597 ExtVectorType(vecType, NumElts, Canonical);
4598 VectorTypes.InsertNode(New, InsertPos);
4599 Types.push_back(New);
4600 return QualType(New, 0);
4601}
4602
4605 Expr *SizeExpr,
4606 SourceLocation AttrLoc) const {
4607 llvm::FoldingSetNodeID ID;
4609 SizeExpr);
4610
4611 void *InsertPos = nullptr;
4613 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4615 if (Canon) {
4616 // We already have a canonical version of this array type; use it as
4617 // the canonical type for a newly-built type.
4618 New = new (*this, alignof(DependentSizedExtVectorType))
4619 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4620 AttrLoc);
4621 } else {
4622 QualType CanonVecTy = getCanonicalType(vecType);
4623 if (CanonVecTy == vecType) {
4624 New = new (*this, alignof(DependentSizedExtVectorType))
4625 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4626
4627 DependentSizedExtVectorType *CanonCheck
4628 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4629 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4630 (void)CanonCheck;
4631 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4632 } else {
4633 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4634 SourceLocation());
4635 New = new (*this, alignof(DependentSizedExtVectorType))
4636 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4637 }
4638 }
4639
4640 Types.push_back(New);
4641 return QualType(New, 0);
4642}
4643
4645 unsigned NumColumns) const {
4646 llvm::FoldingSetNodeID ID;
4647 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4648 Type::ConstantMatrix);
4649
4650 assert(MatrixType::isValidElementType(ElementTy) &&
4651 "need a valid element type");
4652 assert(ConstantMatrixType::isDimensionValid(NumRows) &&
4654 "need valid matrix dimensions");
4655 void *InsertPos = nullptr;
4656 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4657 return QualType(MTP, 0);
4658
4659 QualType Canonical;
4660 if (!ElementTy.isCanonical()) {
4661 Canonical =
4662 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4663
4664 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4665 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4666 (void)NewIP;
4667 }
4668
4669 auto *New = new (*this, alignof(ConstantMatrixType))
4670 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4671 MatrixTypes.InsertNode(New, InsertPos);
4672 Types.push_back(New);
4673 return QualType(New, 0);
4674}
4675
4677 Expr *RowExpr,
4678 Expr *ColumnExpr,
4679 SourceLocation AttrLoc) const {
4680 QualType CanonElementTy = getCanonicalType(ElementTy);
4681 llvm::FoldingSetNodeID ID;
4682 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4683 ColumnExpr);
4684
4685 void *InsertPos = nullptr;
4687 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4688
4689 if (!Canon) {
4690 Canon = new (*this, alignof(DependentSizedMatrixType))
4691 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4692 ColumnExpr, AttrLoc);
4693#ifndef NDEBUG
4694 DependentSizedMatrixType *CanonCheck =
4695 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4696 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4697#endif
4698 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4699 Types.push_back(Canon);
4700 }
4701
4702 // Already have a canonical version of the matrix type
4703 //
4704 // If it exactly matches the requested type, use it directly.
4705 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4706 Canon->getRowExpr() == ColumnExpr)
4707 return QualType(Canon, 0);
4708
4709 // Use Canon as the canonical type for newly-built type.
4710 DependentSizedMatrixType *New = new (*this, alignof(DependentSizedMatrixType))
4711 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4712 ColumnExpr, AttrLoc);
4713 Types.push_back(New);
4714 return QualType(New, 0);
4715}
4716
4718 Expr *AddrSpaceExpr,
4719 SourceLocation AttrLoc) const {
4720 assert(AddrSpaceExpr->isInstantiationDependent());
4721
4722 QualType canonPointeeType = getCanonicalType(PointeeType);
4723
4724 void *insertPos = nullptr;
4725 llvm::FoldingSetNodeID ID;
4726 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4727 AddrSpaceExpr);
4728
4729 DependentAddressSpaceType *canonTy =
4730 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4731
4732 if (!canonTy) {
4733 canonTy = new (*this, alignof(DependentAddressSpaceType))
4734 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
4735 AttrLoc);
4736 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4737 Types.push_back(canonTy);
4738 }
4739
4740 if (canonPointeeType == PointeeType &&
4741 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4742 return QualType(canonTy, 0);
4743
4744 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
4745 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
4746 AddrSpaceExpr, AttrLoc);
4747 Types.push_back(sugaredType);
4748 return QualType(sugaredType, 0);
4749}
4750
4751/// Determine whether \p T is canonical as the result type of a function.
4753 return T.isCanonical() &&
4754 (T.getObjCLifetime() == Qualifiers::OCL_None ||
4755 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4756}
4757
4758/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4761 const FunctionType::ExtInfo &Info) const {
4762 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
4763 // functionality creates a function without a prototype regardless of
4764 // language mode (so it makes them even in C++). Once the rewriter has been
4765 // fixed, this assertion can be enabled again.
4766 //assert(!LangOpts.requiresStrictPrototypes() &&
4767 // "strict prototypes are disabled");
4768
4769 // Unique functions, to guarantee there is only one function of a particular
4770 // structure.
4771 llvm::FoldingSetNodeID ID;
4772 FunctionNoProtoType::Profile(ID, ResultTy, Info);
4773
4774 void *InsertPos = nullptr;
4775 if (FunctionNoProtoType *FT =
4776 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4777 return QualType(FT, 0);
4778
4779 QualType Canonical;
4780 if (!isCanonicalResultType(ResultTy)) {
4781 Canonical =
4783
4784 // Get the new insert position for the node we care about.
4785 FunctionNoProtoType *NewIP =
4786 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4787 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4788 }
4789
4790 auto *New = new (*this, alignof(FunctionNoProtoType))
4791 FunctionNoProtoType(ResultTy, Canonical, Info);
4792 Types.push_back(New);
4793 FunctionNoProtoTypes.InsertNode(New, InsertPos);
4794 return QualType(New, 0);
4795}
4796
4799 CanQualType CanResultType = getCanonicalType(ResultType);
4800
4801 // Canonical result types do not have ARC lifetime qualifiers.
4802 if (CanResultType.getQualifiers().hasObjCLifetime()) {
4803 Qualifiers Qs = CanResultType.getQualifiers();
4804 Qs.removeObjCLifetime();
4806 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
4807 }
4808
4809 return CanResultType;
4810}
4811
4813 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
4814 if (ESI.Type == EST_None)
4815 return true;
4816 if (!NoexceptInType)
4817 return false;
4818
4819 // C++17 onwards: exception specification is part of the type, as a simple
4820 // boolean "can this function type throw".
4821 if (ESI.Type == EST_BasicNoexcept)
4822 return true;
4823
4824 // A noexcept(expr) specification is (possibly) canonical if expr is
4825 // value-dependent.
4826 if (ESI.Type == EST_DependentNoexcept)
4827 return true;
4828
4829 // A dynamic exception specification is canonical if it only contains pack
4830 // expansions (so we can't tell whether it's non-throwing) and all its
4831 // contained types are canonical.
4832 if (ESI.Type == EST_Dynamic) {
4833 bool AnyPackExpansions = false;
4834 for (QualType ET : ESI.Exceptions) {
4835 if (!ET.isCanonical())
4836 return false;
4837 if (ET->getAs<PackExpansionType>())
4838 AnyPackExpansions = true;
4839 }
4840 return AnyPackExpansions;
4841 }
4842
4843 return false;
4844}
4845
4846QualType ASTContext::getFunctionTypeInternal(
4847 QualType ResultTy, ArrayRef<QualType> ArgArray,
4848 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
4849 size_t NumArgs = ArgArray.size();
4850
4851 // Unique functions, to guarantee there is only one function of a particular
4852 // structure.
4853 llvm::FoldingSetNodeID ID;
4854 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
4855 *this, true);
4856
4857 QualType Canonical;
4858 bool Unique = false;
4859
4860 void *InsertPos = nullptr;
4861 if (FunctionProtoType *FPT =
4862 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4863 QualType Existing = QualType(FPT, 0);
4864
4865 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
4866 // it so long as our exception specification doesn't contain a dependent
4867 // noexcept expression, or we're just looking for a canonical type.
4868 // Otherwise, we're going to need to create a type
4869 // sugar node to hold the concrete expression.
4870 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
4871 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
4872 return Existing;
4873
4874 // We need a new type sugar node for this one, to hold the new noexcept
4875 // expression. We do no canonicalization here, but that's OK since we don't
4876 // expect to see the same noexcept expression much more than once.
4877 Canonical = getCanonicalType(Existing);
4878 Unique = true;
4879 }
4880
4881 bool NoexceptInType = getLangOpts().CPlusPlus17;
4882 bool IsCanonicalExceptionSpec =
4884
4885 // Determine whether the type being created is already canonical or not.
4886 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
4887 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
4888 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
4889 if (!ArgArray[i].isCanonicalAsParam())
4890 isCanonical = false;
4891
4892 if (OnlyWantCanonical)
4893 assert(isCanonical &&
4894 "given non-canonical parameters constructing canonical type");
4895
4896 // If this type isn't canonical, get the canonical version of it if we don't
4897 // already have it. The exception spec is only partially part of the
4898 // canonical type, and only in C++17 onwards.
4899 if (!isCanonical && Canonical.isNull()) {
4900 SmallVector<QualType, 16> CanonicalArgs;
4901 CanonicalArgs.reserve(NumArgs);
4902 for (unsigned i = 0; i != NumArgs; ++i)
4903 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
4904
4905 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
4906 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
4907 CanonicalEPI.HasTrailingReturn = false;
4908
4909 if (IsCanonicalExceptionSpec) {
4910 // Exception spec is already OK.
4911 } else if (NoexceptInType) {
4912 switch (EPI.ExceptionSpec.Type) {
4914 // We don't know yet. It shouldn't matter what we pick here; no-one
4915 // should ever look at this.
4916 [[fallthrough]];
4917 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
4918 CanonicalEPI.ExceptionSpec.Type = EST_None;
4919 break;
4920
4921 // A dynamic exception specification is almost always "not noexcept",
4922 // with the exception that a pack expansion might expand to no types.
4923 case EST_Dynamic: {
4924 bool AnyPacks = false;
4925 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
4926 if (ET->getAs<PackExpansionType>())
4927 AnyPacks = true;
4928 ExceptionTypeStorage.push_back(getCanonicalType(ET));
4929 }
4930 if (!AnyPacks)
4931 CanonicalEPI.ExceptionSpec.Type = EST_None;
4932 else {
4933 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
4934 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
4935 }
4936 break;
4937 }
4938
4939 case EST_DynamicNone:
4940 case EST_BasicNoexcept:
4941 case EST_NoexceptTrue:
4942 case EST_NoThrow:
4943 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
4944 break;
4945
4947 llvm_unreachable("dependent noexcept is already canonical");
4948 }
4949 } else {
4951 }
4952
4953 // Adjust the canonical function result type.
4954 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
4955 Canonical =
4956 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
4957
4958 // Get the new insert position for the node we care about.
4959 FunctionProtoType *NewIP =
4960 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4961 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4962 }
4963
4964 // Compute the needed size to hold this FunctionProtoType and the
4965 // various trailing objects.
4966 auto ESH = FunctionProtoType::getExceptionSpecSize(
4967 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
4968 size_t Size = FunctionProtoType::totalSizeToAlloc<
4974 EPI.requiresFunctionProtoTypeArmAttributes(), ESH.NumExceptionType,
4975 ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
4976 EPI.ExtParameterInfos ? NumArgs : 0,
4978 EPI.FunctionEffects.conditions().size());
4979
4980 auto *FTP = (FunctionProtoType *)Allocate(Size, alignof(FunctionProtoType));
4982 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
4983 Types.push_back(FTP);
4984 if (!Unique)
4985 FunctionProtoTypes.InsertNode(FTP, InsertPos);
4986 if (!EPI.FunctionEffects.empty())
4987 AnyFunctionEffects = true;
4988 return QualType(FTP, 0);
4989}
4990
4991QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
4992 llvm::FoldingSetNodeID ID;
4993 PipeType::Profile(ID, T, ReadOnly);
4994
4995 void *InsertPos = nullptr;
4996 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
4997 return QualType(PT, 0);
4998
4999 // If the pipe element type isn't canonical, this won't be a canonical type
5000 // either, so fill in the canonical type field.
5001 QualType Canonical;
5002 if (!T.isCanonical()) {
5003 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
5004
5005 // Get the new insert position for the node we care about.
5006 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
5007 assert(!NewIP && "Shouldn't be in the map!");
5008 (void)NewIP;
5009 }
5010 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
5011 Types.push_back(New);
5012 PipeTypes.InsertNode(New, InsertPos);
5013 return QualType(New, 0);
5014}
5015
5017 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
5018 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
5019 : Ty;
5020}
5021
5023 return getPipeType(T, true);
5024}
5025
5027 return getPipeType(T, false);
5028}
5029
5030QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
5031 llvm::FoldingSetNodeID ID;
5032 BitIntType::Profile(ID, IsUnsigned, NumBits);
5033
5034 void *InsertPos = nullptr;
5035 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5036 return QualType(EIT, 0);
5037
5038 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
5039 BitIntTypes.InsertNode(New, InsertPos);
5040 Types.push_back(New);
5041 return QualType(New, 0);
5042}
5043
5045 Expr *NumBitsExpr) const {
5046 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
5047 llvm::FoldingSetNodeID ID;
5048 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
5049
5050 void *InsertPos = nullptr;
5051 if (DependentBitIntType *Existing =
5052 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5053 return QualType(Existing, 0);
5054
5055 auto *New = new (*this, alignof(DependentBitIntType))
5056 DependentBitIntType(IsUnsigned, NumBitsExpr);
5057 DependentBitIntTypes.InsertNode(New, InsertPos);
5058
5059 Types.push_back(New);
5060 return QualType(New, 0);
5061}
5062
5063#ifndef NDEBUG
5065 if (!isa<CXXRecordDecl>(D)) return false;
5066 const auto *RD = cast<CXXRecordDecl>(D);
5067 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
5068 return true;
5069 if (RD->getDescribedClassTemplate() &&
5070 !isa<ClassTemplateSpecializationDecl>(RD))
5071 return true;
5072 return false;
5073}
5074#endif
5075
5076/// getInjectedClassNameType - Return the unique reference to the
5077/// injected class name type for the specified templated declaration.
5079 QualType TST) const {
5081 if (Decl->TypeForDecl) {
5082 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
5083 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
5084 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
5085 Decl->TypeForDecl = PrevDecl->TypeForDecl;
5086 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
5087 } else {
5088 Type *newType = new (*this, alignof(InjectedClassNameType))
5090 Decl->TypeForDecl = newType;
5091 Types.push_back(newType);
5092 }
5093 return QualType(Decl->TypeForDecl, 0);
5094}
5095
5096/// getTypeDeclType - Return the unique reference to the type for the
5097/// specified type declaration.
5098QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
5099 assert(Decl && "Passed null for Decl param");
5100 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
5101
5102 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
5103 return getTypedefType(Typedef);
5104
5105 assert(!isa<TemplateTypeParmDecl>(Decl) &&
5106 "Template type parameter types are always available.");
5107
5108 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
5109 assert(Record->isFirstDecl() && "struct/union has previous declaration");
5111 return getRecordType(Record);
5112 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
5113 assert(Enum->isFirstDecl() && "enum has previous declaration");
5114 return getEnumType(Enum);
5115 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
5116 return getUnresolvedUsingType(Using);
5117 } else
5118 llvm_unreachable("TypeDecl without a type?");
5119
5120 return QualType(Decl->TypeForDecl, 0);
5121}
5122
5123/// getTypedefType - Return the unique reference to the type for the
5124/// specified typedef name decl.
5126 QualType Underlying) const {
5127 if (!Decl->TypeForDecl) {
5128 if (Underlying.isNull())
5129 Underlying = Decl->getUnderlyingType();
5130 auto *NewType = new (*this, alignof(TypedefType)) TypedefType(
5131 Type::Typedef, Decl, QualType(), getCanonicalType(Underlying));
5132 Decl->TypeForDecl = NewType;
5133 Types.push_back(NewType);
5134 return QualType(NewType, 0);
5135 }
5136 if (Underlying.isNull() || Decl->getUnderlyingType() == Underlying)
5137 return QualType(Decl->TypeForDecl, 0);
5138 assert(hasSameType(Decl->getUnderlyingType(), Underlying));
5139
5140 llvm::FoldingSetNodeID ID;
5141 TypedefType::Profile(ID, Decl, Underlying);
5142
5143 void *InsertPos = nullptr;
5144 if (TypedefType *T = TypedefTypes.FindNodeOrInsertPos(ID, InsertPos)) {
5145 assert(!T->typeMatchesDecl() &&
5146 "non-divergent case should be handled with TypeDecl");
5147 return QualType(T, 0);
5148 }
5149
5150 void *Mem = Allocate(TypedefType::totalSizeToAlloc<QualType>(true),
5151 alignof(TypedefType));
5152 auto *NewType = new (Mem) TypedefType(Type::Typedef, Decl, Underlying,
5153 getCanonicalType(Underlying));
5154 TypedefTypes.InsertNode(NewType, InsertPos);
5155 Types.push_back(NewType);
5156 return QualType(NewType, 0);
5157}
5158
5160 QualType Underlying) const {
5161 llvm::FoldingSetNodeID ID;
5162 UsingType::Profile(ID, Found, Underlying);
5163
5164 void *InsertPos = nullptr;
5165 if (UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5166 return QualType(T, 0);
5167
5168 const Type *TypeForDecl =
5169 cast<TypeDecl>(Found->getTargetDecl())->getTypeForDecl();
5170
5171 assert(!Underlying.hasLocalQualifiers());
5172 QualType Canon = Underlying->getCanonicalTypeInternal();
5173 assert(TypeForDecl->getCanonicalTypeInternal() == Canon);
5174
5175 if (Underlying.getTypePtr() == TypeForDecl)
5176 Underlying = QualType();
5177 void *Mem =
5178 Allocate(UsingType::totalSizeToAlloc<QualType>(!Underlying.isNull()),
5179 alignof(UsingType));
5180 UsingType *NewType = new (Mem) UsingType(Found, Underlying, Canon);
5181 Types.push_back(NewType);
5182 UsingTypes.InsertNode(NewType, InsertPos);
5183 return QualType(NewType, 0);
5184}
5185
5187 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
5188
5189 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
5190 if (PrevDecl->TypeForDecl)
5191 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
5192
5193 auto *newType = new (*this, alignof(RecordType)) RecordType(Decl);
5194 Decl->TypeForDecl = newType;
5195 Types.push_back(newType);
5196 return QualType(newType, 0);
5197}
5198
5200 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
5201
5202 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
5203 if (PrevDecl->TypeForDecl)
5204 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
5205
5206 auto *newType = new (*this, alignof(EnumType)) EnumType(Decl);
5207 Decl->TypeForDecl = newType;
5208 Types.push_back(newType);
5209 return QualType(newType, 0);
5210}
5211
5213 const UnresolvedUsingTypenameDecl *Decl) const {
5214 if (Decl->TypeForDecl)
5215 return QualType(Decl->TypeForDecl, 0);
5216
5217 if (const UnresolvedUsingTypenameDecl *CanonicalDecl =
5219 if (CanonicalDecl->TypeForDecl)
5220 return QualType(Decl->TypeForDecl = CanonicalDecl->TypeForDecl, 0);
5221
5222 Type *newType =
5223 new (*this, alignof(UnresolvedUsingType)) UnresolvedUsingType(Decl);
5224 Decl->TypeForDecl = newType;
5225 Types.push_back(newType);
5226 return QualType(newType, 0);
5227}
5228
5230 QualType modifiedType,
5231 QualType equivalentType,
5232 const Attr *attr) const {
5233 llvm::FoldingSetNodeID id;
5234 AttributedType::Profile(id, attrKind, modifiedType, equivalentType, attr);
5235
5236 void *insertPos = nullptr;
5237 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
5238 if (type) return QualType(type, 0);
5239
5240 assert(!attr || attr->getKind() == attrKind);
5241
5242 QualType canon = getCanonicalType(equivalentType);
5243 type = new (*this, alignof(AttributedType))
5244 AttributedType(canon, attrKind, attr, modifiedType, equivalentType);
5245
5246 Types.push_back(type);
5247 AttributedTypes.InsertNode(type, insertPos);
5248
5249 return QualType(type, 0);
5250}
5251
5253 QualType equivalentType) const {
5254 return getAttributedType(attr->getKind(), modifiedType, equivalentType, attr);
5255}
5256
5258 QualType modifiedType,
5259 QualType equivalentType) {
5260 switch (nullability) {
5262 return getAttributedType(attr::TypeNonNull, modifiedType, equivalentType);
5263
5265 return getAttributedType(attr::TypeNullable, modifiedType, equivalentType);
5266
5268 return getAttributedType(attr::TypeNullableResult, modifiedType,
5269 equivalentType);
5270
5272 return getAttributedType(attr::TypeNullUnspecified, modifiedType,
5273 equivalentType);
5274 }
5275
5276 llvm_unreachable("Unknown nullability kind");
5277}
5278
5279QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
5280 QualType Wrapped) const {
5281 llvm::FoldingSetNodeID ID;
5282 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
5283
5284 void *InsertPos = nullptr;
5286 BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
5287 if (Ty)
5288 return QualType(Ty, 0);
5289
5290 QualType Canon = getCanonicalType(Wrapped);
5291 Ty = new (*this, alignof(BTFTagAttributedType))
5292 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
5293
5294 Types.push_back(Ty);
5295 BTFTagAttributedTypes.InsertNode(Ty, InsertPos);
5296
5297 return QualType(Ty, 0);
5298}
5299
5301 QualType Wrapped, QualType Contained,
5303
5304 llvm::FoldingSetNodeID ID;
5305 HLSLAttributedResourceType::Profile(ID, Wrapped, Contained, Attrs);
5306
5307 void *InsertPos = nullptr;
5309 HLSLAttributedResourceTypes.FindNodeOrInsertPos(ID, InsertPos);
5310 if (Ty)
5311 return QualType(Ty, 0);
5312
5313 Ty = new (*this, alignof(HLSLAttributedResourceType))
5314 HLSLAttributedResourceType(Wrapped, Contained, Attrs);
5315
5316 Types.push_back(Ty);
5317 HLSLAttributedResourceTypes.InsertNode(Ty, InsertPos);
5318
5319 return QualType(Ty, 0);
5320}
5321/// Retrieve a substitution-result type.
5323 QualType Replacement, Decl *AssociatedDecl, unsigned Index,
5324 std::optional<unsigned> PackIndex,
5325 SubstTemplateTypeParmTypeFlag Flag) const {
5326 llvm::FoldingSetNodeID ID;
5327 SubstTemplateTypeParmType::Profile(ID, Replacement, AssociatedDecl, Index,
5328 PackIndex, Flag);
5329 void *InsertPos = nullptr;
5330 SubstTemplateTypeParmType *SubstParm =
5331 SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5332
5333 if (!SubstParm) {
5334 void *Mem = Allocate(SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
5335 !Replacement.isCanonical()),
5336 alignof(SubstTemplateTypeParmType));
5337 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
5338 Index, PackIndex, Flag);
5339 Types.push_back(SubstParm);
5340 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
5341 }
5342
5343 return QualType(SubstParm, 0);
5344}
5345
5346/// Retrieve a
5349 unsigned Index, bool Final,
5350 const TemplateArgument &ArgPack) {
5351#ifndef NDEBUG
5352 for (const auto &P : ArgPack.pack_elements())
5353 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
5354#endif
5355
5356 llvm::FoldingSetNodeID ID;
5357 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
5358 ArgPack);
5359 void *InsertPos = nullptr;
5360 if (SubstTemplateTypeParmPackType *SubstParm =
5361 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
5362 return QualType(SubstParm, 0);
5363
5364 QualType Canon;
5365 {
5366 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5367 if (!AssociatedDecl->isCanonicalDecl() ||
5368 !CanonArgPack.structurallyEquals(ArgPack)) {
5370 AssociatedDecl->getCanonicalDecl(), Index, Final, CanonArgPack);
5371 [[maybe_unused]] const auto *Nothing =
5372 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
5373 assert(!Nothing);
5374 }
5375 }
5376
5377 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
5378 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
5379 ArgPack);
5380 Types.push_back(SubstParm);
5381 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
5382 return QualType(SubstParm, 0);
5383}
5384
5385/// Retrieve the template type parameter type for a template
5386/// parameter or parameter pack with the given depth, index, and (optionally)
5387/// name.
5388QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
5389 bool ParameterPack,
5390 TemplateTypeParmDecl *TTPDecl) const {
5391 llvm::FoldingSetNodeID ID;
5392 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
5393 void *InsertPos = nullptr;
5394 TemplateTypeParmType *TypeParm
5395 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5396
5397 if (TypeParm)
5398 return QualType(TypeParm, 0);
5399
5400 if (TTPDecl) {
5401 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
5402 TypeParm = new (*this, alignof(TemplateTypeParmType))
5403 TemplateTypeParmType(Depth, Index, ParameterPack, TTPDecl, Canon);
5404
5405 TemplateTypeParmType *TypeCheck
5406 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5407 assert(!TypeCheck && "Template type parameter canonical type broken");
5408 (void)TypeCheck;
5409 } else
5410 TypeParm = new (*this, alignof(TemplateTypeParmType)) TemplateTypeParmType(
5411 Depth, Index, ParameterPack, /*TTPDecl=*/nullptr, /*Canon=*/QualType());
5412
5413 Types.push_back(TypeParm);
5414 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
5415
5416 return QualType(TypeParm, 0);
5417}
5418
5421 SourceLocation NameLoc,
5422 const TemplateArgumentListInfo &Args,
5423 QualType Underlying) const {
5424 assert(!Name.getAsDependentTemplateName() &&
5425 "No dependent template names here!");
5426 QualType TST =
5427 getTemplateSpecializationType(Name, Args.arguments(), Underlying);
5428
5433 TL.setTemplateNameLoc(NameLoc);
5434 TL.setLAngleLoc(Args.getLAngleLoc());
5435 TL.setRAngleLoc(Args.getRAngleLoc());
5436 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5437 TL.setArgLocInfo(i, Args[i].getLocInfo());
5438 return DI;
5439}
5440
5444 QualType Underlying) const {
5445 assert(!Template.getAsDependentTemplateName() &&
5446 "No dependent template names here!");
5447
5449 ArgVec.reserve(Args.size());
5450 for (const TemplateArgumentLoc &Arg : Args)
5451 ArgVec.push_back(Arg.getArgument());
5452
5453 return getTemplateSpecializationType(Template, ArgVec, Underlying);
5454}
5455
5456#ifndef NDEBUG
5458 for (const TemplateArgument &Arg : Args)
5459 if (Arg.isPackExpansion())
5460 return true;
5461
5462 return true;
5463}
5464#endif
5465
5469 QualType Underlying) const {
5470 assert(!Template.getAsDependentTemplateName() &&
5471 "No dependent template names here!");
5472
5473 const auto *TD = Template.getAsTemplateDecl(/*IgnoreDeduced=*/true);
5474 bool IsTypeAlias = TD && TD->isTypeAlias();
5475 QualType CanonType;
5476 if (!Underlying.isNull())
5477 CanonType = getCanonicalType(Underlying);
5478 else {
5479 // We can get here with an alias template when the specialization contains
5480 // a pack expansion that does not match up with a parameter pack.
5481 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
5482 "Caller must compute aliased type");
5483 IsTypeAlias = false;
5484 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
5485 }
5486
5487 // Allocate the (non-canonical) template specialization type, but don't
5488 // try to unique it: these types typically have location information that
5489 // we don't unique and don't want to lose.
5490 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
5491 sizeof(TemplateArgument) * Args.size() +
5492 (IsTypeAlias ? sizeof(QualType) : 0),
5494 auto *Spec
5495 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
5496 IsTypeAlias ? Underlying : QualType());
5497
5498 Types.push_back(Spec);
5499 return QualType(Spec, 0);
5500}
5501
5503 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
5504 assert(!Template.getAsDependentTemplateName() &&
5505 "No dependent template names here!");
5506
5507 // Build the canonical template specialization type.
5508 // Any DeducedTemplateNames are ignored, because the effective name of a TST
5509 // accounts for the TST arguments laid over any default arguments contained in
5510 // its name.
5511 TemplateName CanonTemplate =
5512 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true);
5513
5514 bool AnyNonCanonArgs = false;
5515 auto CanonArgs =
5516 ::getCanonicalTemplateArguments(*this, Args, AnyNonCanonArgs);
5517
5518 // Determine whether this canonical template specialization type already
5519 // exists.
5520 llvm::FoldingSetNodeID ID;
5521 TemplateSpecializationType::Profile(ID, CanonTemplate,
5522 CanonArgs, *this);
5523
5524 void *InsertPos = nullptr;
5526 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5527
5528 if (!Spec) {
5529 // Allocate a new canonical template specialization type.
5530 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
5531 sizeof(TemplateArgument) * CanonArgs.size()),
5533 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
5534 CanonArgs,
5535 QualType(), QualType());
5536 Types.push_back(Spec);
5537 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
5538 }
5539
5540 assert(Spec->isDependentType() &&
5541 "Non-dependent template-id type must have a canonical type");
5542 return QualType(Spec, 0);
5543}
5544
5547 QualType NamedType,
5548 TagDecl *OwnedTagDecl) const {
5549 llvm::FoldingSetNodeID ID;
5550 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
5551
5552 void *InsertPos = nullptr;
5553 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
5554 if (T)
5555 return QualType(T, 0);
5556
5557 QualType Canon = NamedType;
5558 if (!Canon.isCanonical()) {
5559 Canon = getCanonicalType(NamedType);
5560 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
5561 assert(!CheckT && "Elaborated canonical type broken");
5562 (void)CheckT;
5563 }
5564
5565 void *Mem =
5566 Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
5567 alignof(ElaboratedType));
5568 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
5569
5570 Types.push_back(T);
5571 ElaboratedTypes.InsertNode(T, InsertPos);
5572 return QualType(T, 0);
5573}
5574
5577 llvm::FoldingSetNodeID ID;
5578 ParenType::Profile(ID, InnerType);
5579
5580 void *InsertPos = nullptr;
5581 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
5582 if (T)
5583 return QualType(T, 0);
5584
5585 QualType Canon = InnerType;
5586 if (!Canon.isCanonical()) {
5587 Canon = getCanonicalType(InnerType);
5588 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
5589 assert(!CheckT && "Paren canonical type broken");
5590 (void)CheckT;
5591 }
5592
5593 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
5594 Types.push_back(T);
5595 ParenTypes.InsertNode(T, InsertPos);
5596 return QualType(T, 0);
5597}
5598
5601 const IdentifierInfo *MacroII) const {
5602 QualType Canon = UnderlyingTy;
5603 if (!Canon.isCanonical())
5604 Canon = getCanonicalType(UnderlyingTy);
5605
5606 auto *newType = new (*this, alignof(MacroQualifiedType))
5607 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
5608 Types.push_back(newType);
5609 return QualType(newType, 0);
5610}
5611
5614 const IdentifierInfo *Name,
5615 QualType Canon) const {
5616 if (Canon.isNull()) {
5618 if (CanonNNS != NNS)
5619 Canon = getDependentNameType(Keyword, CanonNNS, Name);
5620 }
5621
5622 llvm::FoldingSetNodeID ID;
5623 DependentNameType::Profile(ID, Keyword, NNS, Name);
5624
5625 void *InsertPos = nullptr;
5627 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
5628 if (T)
5629 return QualType(T, 0);
5630
5631 T = new (*this, alignof(DependentNameType))
5632 DependentNameType(Keyword, NNS, Name, Canon);
5633 Types.push_back(T);
5634 DependentNameTypes.InsertNode(T, InsertPos);
5635 return QualType(T, 0);
5636}
5637
5640 const IdentifierInfo *Name, ArrayRef<TemplateArgumentLoc> Args) const {
5641 // TODO: avoid this copy
5643 for (unsigned I = 0, E = Args.size(); I != E; ++I)
5644 ArgCopy.push_back(Args[I].getArgument());
5645 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
5646}
5647
5650 ElaboratedTypeKeyword Keyword,
5652 const IdentifierInfo *Name,
5653 ArrayRef<TemplateArgument> Args) const {
5654 assert((!NNS || NNS->isDependent()) &&
5655 "nested-name-specifier must be dependent");
5656
5657 llvm::FoldingSetNodeID ID;
5658 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
5659 Name, Args);
5660
5661 void *InsertPos = nullptr;
5663 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5664 if (T)
5665 return QualType(T, 0);
5666
5668
5669 ElaboratedTypeKeyword CanonKeyword = Keyword;
5670 if (Keyword == ElaboratedTypeKeyword::None)
5671 CanonKeyword = ElaboratedTypeKeyword::Typename;
5672
5673 bool AnyNonCanonArgs = false;
5674 auto CanonArgs =
5675 ::getCanonicalTemplateArguments(*this, Args, AnyNonCanonArgs);
5676
5677 QualType Canon;
5678 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
5679 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
5680 Name,
5681 CanonArgs);
5682
5683 // Find the insert position again.
5684 [[maybe_unused]] auto *Nothing =
5685 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5686 assert(!Nothing && "canonical type broken");
5687 }
5688
5689 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
5690 sizeof(TemplateArgument) * Args.size()),
5692 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
5693 Name, Args, Canon);
5694 Types.push_back(T);
5695 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
5696 return QualType(T, 0);
5697}
5698
5700 TemplateArgument Arg;
5701 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
5702 QualType ArgType = getTypeDeclType(TTP);
5703 if (TTP->isParameterPack())
5704 ArgType = getPackExpansionType(ArgType, std::nullopt);
5705
5706 Arg = TemplateArgument(ArgType);
5707 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5708 QualType T =
5709 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
5710 // For class NTTPs, ensure we include the 'const' so the type matches that
5711 // of a real template argument.
5712 // FIXME: It would be more faithful to model this as something like an
5713 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
5714 ExprValueKind VK;
5715 if (T->isRecordType()) {
5716 // C++ [temp.param]p8: An id-expression naming a non-type
5717 // template-parameter of class type T denotes a static storage duration
5718 // object of type const T.
5719 T.addConst();
5720 VK = VK_LValue;
5721 } else {
5722 VK = Expr::getValueKindForType(NTTP->getType());
5723 }
5724 Expr *E = new (*this)
5725 DeclRefExpr(*this, NTTP, /*RefersToEnclosingVariableOrCapture=*/false,
5726 T, VK, NTTP->getLocation());
5727
5728 if (NTTP->isParameterPack())
5729 E = new (*this)
5730 PackExpansionExpr(DependentTy, E, NTTP->getLocation(), std::nullopt);
5731 Arg = TemplateArgument(E);
5732 } else {
5733 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
5735 nullptr, /*TemplateKeyword=*/false, TemplateName(TTP));
5736 if (TTP->isParameterPack())
5737 Arg = TemplateArgument(Name, std::optional<unsigned>());
5738 else
5739 Arg = TemplateArgument(Name);
5740 }
5741
5742 if (Param->isTemplateParameterPack())
5743 Arg =
5744 TemplateArgument::CreatePackCopy(const_cast<ASTContext &>(*this), Arg);
5745
5746 return Arg;
5747}
5748
5750 std::optional<unsigned> NumExpansions,
5751 bool ExpectPackInType) const {
5752 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
5753 "Pack expansions must expand one or more parameter packs");
5754
5755 llvm::FoldingSetNodeID ID;
5756 PackExpansionType::Profile(ID, Pattern, NumExpansions);
5757
5758 void *InsertPos = nullptr;
5759 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
5760 if (T)
5761 return QualType(T, 0);
5762
5763 QualType Canon;
5764 if (!Pattern.isCanonical()) {
5765 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
5766 /*ExpectPackInType=*/false);
5767
5768 // Find the insert position again, in case we inserted an element into
5769 // PackExpansionTypes and invalidated our insert position.
5770 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
5771 }
5772
5773 T = new (*this, alignof(PackExpansionType))
5774 PackExpansionType(Pattern, Canon, NumExpansions);
5775 Types.push_back(T);
5776 PackExpansionTypes.InsertNode(T, InsertPos);
5777 return QualType(T, 0);
5778}
5779
5780/// CmpProtocolNames - Comparison predicate for sorting protocols
5781/// alphabetically.
5782static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
5783 ObjCProtocolDecl *const *RHS) {
5784 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
5785}
5786
5788 if (Protocols.empty()) return true;
5789
5790 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
5791 return false;
5792
5793 for (unsigned i = 1; i != Protocols.size(); ++i)
5794 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
5795 Protocols[i]->getCanonicalDecl() != Protocols[i])
5796 return false;
5797 return true;
5798}
5799
5800static void
5802 // Sort protocols, keyed by name.
5803 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
5804
5805 // Canonicalize.
5806 for (ObjCProtocolDecl *&P : Protocols)
5807 P = P->getCanonicalDecl();
5808
5809 // Remove duplicates.
5810 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
5811 Protocols.erase(ProtocolsEnd, Protocols.end());
5812}
5813
5815 ObjCProtocolDecl * const *Protocols,
5816 unsigned NumProtocols) const {
5817 return getObjCObjectType(BaseType, {},
5818 llvm::ArrayRef(Protocols, NumProtocols),
5819 /*isKindOf=*/false);
5820}
5821
5823 QualType baseType,
5824 ArrayRef<QualType> typeArgs,
5826 bool isKindOf) const {
5827 // If the base type is an interface and there aren't any protocols or
5828 // type arguments to add, then the interface type will do just fine.
5829 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
5830 isa<ObjCInterfaceType>(baseType))
5831 return baseType;
5832
5833 // Look in the folding set for an existing type.
5834 llvm::FoldingSetNodeID ID;
5835 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
5836 void *InsertPos = nullptr;
5837 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
5838 return QualType(QT, 0);
5839
5840 // Determine the type arguments to be used for canonicalization,
5841 // which may be explicitly specified here or written on the base
5842 // type.
5843 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
5844 if (effectiveTypeArgs.empty()) {
5845 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
5846 effectiveTypeArgs = baseObject->getTypeArgs();
5847 }
5848
5849 // Build the canonical type, which has the canonical base type and a
5850 // sorted-and-uniqued list of protocols and the type arguments
5851 // canonicalized.
5852 QualType canonical;
5853 bool typeArgsAreCanonical = llvm::all_of(
5854 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
5855 bool protocolsSorted = areSortedAndUniqued(protocols);
5856 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
5857 // Determine the canonical type arguments.
5858 ArrayRef<QualType> canonTypeArgs;
5859 SmallVector<QualType, 4> canonTypeArgsVec;
5860 if (!typeArgsAreCanonical) {
5861 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
5862 for (auto typeArg : effectiveTypeArgs)
5863 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
5864 canonTypeArgs = canonTypeArgsVec;
5865 } else {
5866 canonTypeArgs = effectiveTypeArgs;
5867 }
5868
5869 ArrayRef<ObjCProtocolDecl *> canonProtocols;
5870 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
5871 if (!protocolsSorted) {
5872 canonProtocolsVec.append(protocols.begin(), protocols.end());
5873 SortAndUniqueProtocols(canonProtocolsVec);
5874 canonProtocols = canonProtocolsVec;
5875 } else {
5876 canonProtocols = protocols;
5877 }
5878
5879 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
5880 canonProtocols, isKindOf);
5881
5882 // Regenerate InsertPos.
5883 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
5884 }
5885
5886 unsigned size = sizeof(ObjCObjectTypeImpl);
5887 size += typeArgs.size() * sizeof(QualType);
5888 size += protocols.size() * sizeof(ObjCProtocolDecl *);
5889 void *mem = Allocate(size, alignof(ObjCObjectTypeImpl));
5890 auto *T =
5891 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
5892 isKindOf);
5893
5894 Types.push_back(T);
5895 ObjCObjectTypes.InsertNode(T, InsertPos);
5896 return QualType(T, 0);
5897}
5898
5899/// Apply Objective-C protocol qualifiers to the given type.
5900/// If this is for the canonical type of a type parameter, we can apply
5901/// protocol qualifiers on the ObjCObjectPointerType.
5904 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
5905 bool allowOnPointerType) const {
5906 hasError = false;
5907
5908 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
5909 return getObjCTypeParamType(objT->getDecl(), protocols);
5910 }
5911
5912 // Apply protocol qualifiers to ObjCObjectPointerType.
5913 if (allowOnPointerType) {
5914 if (const auto *objPtr =
5915 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
5916 const ObjCObjectType *objT = objPtr->getObjectType();
5917 // Merge protocol lists and construct ObjCObjectType.
5919 protocolsVec.append(objT->qual_begin(),
5920 objT->qual_end());
5921 protocolsVec.append(protocols.begin(), protocols.end());
5922 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
5924 objT->getBaseType(),
5925 objT->getTypeArgsAsWritten(),
5926 protocols,
5927 objT->isKindOfTypeAsWritten());
5929 }
5930 }
5931
5932 // Apply protocol qualifiers to ObjCObjectType.
5933 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
5934 // FIXME: Check for protocols to which the class type is already
5935 // known to conform.
5936
5937 return getObjCObjectType(objT->getBaseType(),
5938 objT->getTypeArgsAsWritten(),
5939 protocols,
5940 objT->isKindOfTypeAsWritten());
5941 }
5942
5943 // If the canonical type is ObjCObjectType, ...
5944 if (type->isObjCObjectType()) {
5945 // Silently overwrite any existing protocol qualifiers.
5946 // TODO: determine whether that's the right thing to do.
5947
5948 // FIXME: Check for protocols to which the class type is already
5949 // known to conform.
5950 return getObjCObjectType(type, {}, protocols, false);
5951 }
5952
5953 // id<protocol-list>
5954 if (type->isObjCIdType()) {
5955 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
5956 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
5957 objPtr->isKindOfType());
5959 }
5960
5961 // Class<protocol-list>
5962 if (type->isObjCClassType()) {
5963 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
5964 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
5965 objPtr->isKindOfType());
5967 }
5968
5969 hasError = true;
5970 return type;
5971}
5972
5975 ArrayRef<ObjCProtocolDecl *> protocols) const {
5976 // Look in the folding set for an existing type.
5977 llvm::FoldingSetNodeID ID;
5978 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
5979 void *InsertPos = nullptr;
5980 if (ObjCTypeParamType *TypeParam =
5981 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
5982 return QualType(TypeParam, 0);
5983
5984 // We canonicalize to the underlying type.
5985 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
5986 if (!protocols.empty()) {
5987 // Apply the protocol qualifers.
5988 bool hasError;
5990 Canonical, protocols, hasError, true /*allowOnPointerType*/));
5991 assert(!hasError && "Error when apply protocol qualifier to bound type");
5992 }
5993
5994 unsigned size = sizeof(ObjCTypeParamType);
5995 size += protocols.size() * sizeof(ObjCProtocolDecl *);
5996 void *mem = Allocate(size, alignof(ObjCTypeParamType));
5997 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
5998
5999 Types.push_back(newType);
6000 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
6001 return QualType(newType, 0);
6002}
6003
6005 ObjCTypeParamDecl *New) const {
6007 // Update TypeForDecl after updating TypeSourceInfo.
6008 auto NewTypeParamTy = cast<ObjCTypeParamType>(New->getTypeForDecl());
6010 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
6011 QualType UpdatedTy = getObjCTypeParamType(New, protocols);
6012 New->setTypeForDecl(UpdatedTy.getTypePtr());
6013}
6014
6015/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
6016/// protocol list adopt all protocols in QT's qualified-id protocol
6017/// list.
6019 ObjCInterfaceDecl *IC) {
6020 if (!QT->isObjCQualifiedIdType())
6021 return false;
6022
6023 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
6024 // If both the right and left sides have qualifiers.
6025 for (auto *Proto : OPT->quals()) {
6026 if (!IC->ClassImplementsProtocol(Proto, false))
6027 return false;
6028 }
6029 return true;
6030 }
6031 return false;
6032}
6033
6034/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
6035/// QT's qualified-id protocol list adopt all protocols in IDecl's list
6036/// of protocols.
6038 ObjCInterfaceDecl *IDecl) {
6039 if (!QT->isObjCQualifiedIdType())
6040 return false;
6041 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
6042 if (!OPT)
6043 return false;
6044 if (!IDecl->hasDefinition())
6045 return false;
6047 CollectInheritedProtocols(IDecl, InheritedProtocols);
6048 if (InheritedProtocols.empty())
6049 return false;
6050 // Check that if every protocol in list of id<plist> conforms to a protocol
6051 // of IDecl's, then bridge casting is ok.
6052 bool Conforms = false;
6053 for (auto *Proto : OPT->quals()) {
6054 Conforms = false;
6055 for (auto *PI : InheritedProtocols) {
6056 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
6057 Conforms = true;
6058 break;
6059 }
6060 }
6061 if (!Conforms)
6062 break;
6063 }
6064 if (Conforms)
6065 return true;
6066
6067 for (auto *PI : InheritedProtocols) {
6068 // If both the right and left sides have qualifiers.
6069 bool Adopts = false;
6070 for (auto *Proto : OPT->quals()) {
6071 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
6072 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
6073 break;
6074 }
6075 if (!Adopts)
6076 return false;
6077 }
6078 return true;
6079}
6080
6081/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
6082/// the given object type.
6084 llvm::FoldingSetNodeID ID;
6085 ObjCObjectPointerType::Profile(ID, ObjectT);
6086
6087 void *InsertPos = nullptr;
6088 if (ObjCObjectPointerType *QT =
6089 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
6090 return QualType(QT, 0);
6091
6092 // Find the canonical object type.
6093 QualType Canonical;
6094 if (!ObjectT.isCanonical()) {
6095 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
6096
6097 // Regenerate InsertPos.
6098 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
6099 }
6100
6101 // No match.
6102 void *Mem =
6104 auto *QType =
6105 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
6106
6107 Types.push_back(QType);
6108 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
6109 return QualType(QType, 0);
6110}
6111
6112/// getObjCInterfaceType - Return the unique reference to the type for the
6113/// specified ObjC interface decl. The list of protocols is optional.
6115 ObjCInterfaceDecl *PrevDecl) const {
6116 if (Decl->TypeForDecl)
6117 return QualType(Decl->TypeForDecl, 0);
6118
6119 if (PrevDecl) {
6120 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
6121 Decl->TypeForDecl = PrevDecl->TypeForDecl;
6122 return QualType(PrevDecl->TypeForDecl, 0);
6123 }
6124
6125 // Prefer the definition, if there is one.
6126 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
6127 Decl = Def;
6128
6129 void *Mem = Allocate(sizeof(ObjCInterfaceType), alignof(ObjCInterfaceType));
6130 auto *T = new (Mem) ObjCInterfaceType(Decl);
6131 Decl->TypeForDecl = T;
6132 Types.push_back(T);
6133 return QualType(T, 0);
6134}
6135
6136/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
6137/// TypeOfExprType AST's (since expression's are never shared). For example,
6138/// multiple declarations that refer to "typeof(x)" all contain different
6139/// DeclRefExpr's. This doesn't effect the type checker, since it operates
6140/// on canonical type's (which are always unique).
6142 TypeOfExprType *toe;
6143 if (tofExpr->isTypeDependent()) {
6144 llvm::FoldingSetNodeID ID;
6145 DependentTypeOfExprType::Profile(ID, *this, tofExpr,
6146 Kind == TypeOfKind::Unqualified);
6147
6148 void *InsertPos = nullptr;
6150 DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
6151 if (Canon) {
6152 // We already have a "canonical" version of an identical, dependent
6153 // typeof(expr) type. Use that as our canonical type.
6154 toe = new (*this, alignof(TypeOfExprType)) TypeOfExprType(
6155 *this, tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
6156 } else {
6157 // Build a new, canonical typeof(expr) type.
6158 Canon = new (*this, alignof(DependentTypeOfExprType))
6159 DependentTypeOfExprType(*this, tofExpr, Kind);
6160 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
6161 toe = Canon;
6162 }
6163 } else {
6164 QualType Canonical = getCanonicalType(tofExpr->getType());
6165 toe = new (*this, alignof(TypeOfExprType))
6166 TypeOfExprType(*this, tofExpr, Kind, Canonical);
6167 }
6168 Types.push_back(toe);
6169 return QualType(toe, 0);
6170}
6171
6172/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
6173/// TypeOfType nodes. The only motivation to unique these nodes would be
6174/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
6175/// an issue. This doesn't affect the type checker, since it operates
6176/// on canonical types (which are always unique).
6178 QualType Canonical = getCanonicalType(tofType);
6179 auto *tot = new (*this, alignof(TypeOfType))
6180 TypeOfType(*this, tofType, Canonical, Kind);
6181 Types.push_back(tot);
6182 return QualType(tot, 0);
6183}
6184
6185/// getReferenceQualifiedType - Given an expr, will return the type for
6186/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
6187/// and class member access into account.
6189 // C++11 [dcl.type.simple]p4:
6190 // [...]
6191 QualType T = E->getType();
6192 switch (E->getValueKind()) {
6193 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6194 // type of e;
6195 case VK_XValue:
6196 return getRValueReferenceType(T);
6197 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6198 // type of e;
6199 case VK_LValue:
6200 return getLValueReferenceType(T);
6201 // - otherwise, decltype(e) is the type of e.
6202 case VK_PRValue:
6203 return T;
6204 }
6205 llvm_unreachable("Unknown value kind");
6206}
6207
6208/// Unlike many "get<Type>" functions, we don't unique DecltypeType
6209/// nodes. This would never be helpful, since each such type has its own
6210/// expression, and would not give a significant memory saving, since there
6211/// is an Expr tree under each such type.
6213 DecltypeType *dt;
6214
6215 // C++11 [temp.type]p2:
6216 // If an expression e involves a template parameter, decltype(e) denotes a
6217 // unique dependent type. Two such decltype-specifiers refer to the same
6218 // type only if their expressions are equivalent (14.5.6.1).
6219 if (e->isInstantiationDependent()) {
6220 llvm::FoldingSetNodeID ID;
6221 DependentDecltypeType::Profile(ID, *this, e);
6222
6223 void *InsertPos = nullptr;
6225 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
6226 if (!Canon) {
6227 // Build a new, canonical decltype(expr) type.
6228 Canon = new (*this, alignof(DependentDecltypeType))
6230 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
6231 }
6232 dt = new (*this, alignof(DecltypeType))
6233 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
6234 } else {
6235 dt = new (*this, alignof(DecltypeType))
6236 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
6237 }
6238 Types.push_back(dt);
6239 return QualType(dt, 0);
6240}
6241
6243 bool FullySubstituted,
6244 ArrayRef<QualType> Expansions,
6245 int Index) const {
6246 QualType Canonical;
6247 if (FullySubstituted && Index != -1) {
6248 Canonical = getCanonicalType(Expansions[Index]);
6249 } else {
6250 llvm::FoldingSetNodeID ID;
6251 PackIndexingType::Profile(ID, *this, Pattern, IndexExpr, FullySubstituted);
6252 void *InsertPos = nullptr;
6253 PackIndexingType *Canon =
6254 DependentPackIndexingTypes.FindNodeOrInsertPos(ID, InsertPos);
6255 if (!Canon) {
6256 void *Mem = Allocate(
6257 PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6259 Canon = new (Mem) PackIndexingType(*this, QualType(), Pattern, IndexExpr,
6260 FullySubstituted, Expansions);
6261 DependentPackIndexingTypes.InsertNode(Canon, InsertPos);
6262 }
6263 Canonical = QualType(Canon, 0);
6264 }
6265
6266 void *Mem =
6267 Allocate(PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6269 auto *T = new (Mem) PackIndexingType(*this, Canonical, Pattern, IndexExpr,
6270 FullySubstituted, Expansions);
6271 Types.push_back(T);
6272 return QualType(T, 0);
6273}
6274
6275/// getUnaryTransformationType - We don't unique these, since the memory
6276/// savings are minimal and these are rare.
6278 QualType UnderlyingType,
6280 const {
6281 UnaryTransformType *ut = nullptr;
6282
6283 if (BaseType->isDependentType()) {
6284 // Look in the folding set for an existing type.
6285 llvm::FoldingSetNodeID ID;
6287
6288 void *InsertPos = nullptr;
6290 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
6291
6292 if (!Canon) {
6293 // Build a new, canonical __underlying_type(type) type.
6294 Canon = new (*this, alignof(DependentUnaryTransformType))
6295 DependentUnaryTransformType(*this, getCanonicalType(BaseType), Kind);
6296 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
6297 }
6298 ut = new (*this, alignof(UnaryTransformType))
6299 UnaryTransformType(BaseType, QualType(), Kind, QualType(Canon, 0));
6300 } else {
6301 QualType CanonType = getCanonicalType(UnderlyingType);
6302 ut = new (*this, alignof(UnaryTransformType))
6303 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
6304 }
6305 Types.push_back(ut);
6306 return QualType(ut, 0);
6307}
6308
6309QualType ASTContext::getAutoTypeInternal(
6310 QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent,
6311 bool IsPack, ConceptDecl *TypeConstraintConcept,
6312 ArrayRef<TemplateArgument> TypeConstraintArgs, bool IsCanon) const {
6313 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
6314 !TypeConstraintConcept && !IsDependent)
6315 return getAutoDeductType();
6316
6317 // Look in the folding set for an existing type.
6318 llvm::FoldingSetNodeID ID;
6319 bool IsDeducedDependent =
6320 !DeducedType.isNull() && DeducedType->isDependentType();
6321 AutoType::Profile(ID, *this, DeducedType, Keyword,
6322 IsDependent || IsDeducedDependent, TypeConstraintConcept,
6323 TypeConstraintArgs);
6324 if (auto const AT_iter = AutoTypes.find(ID); AT_iter != AutoTypes.end())
6325 return QualType(AT_iter->getSecond(), 0);
6326
6327 QualType Canon;
6328 if (!IsCanon) {
6329 if (!DeducedType.isNull()) {
6330 Canon = DeducedType.getCanonicalType();
6331 } else if (TypeConstraintConcept) {
6332 bool AnyNonCanonArgs = false;
6333 ConceptDecl *CanonicalConcept = TypeConstraintConcept->getCanonicalDecl();
6334 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
6335 *this, TypeConstraintArgs, AnyNonCanonArgs);
6336 if (CanonicalConcept != TypeConstraintConcept || AnyNonCanonArgs) {
6337 Canon =
6338 getAutoTypeInternal(QualType(), Keyword, IsDependent, IsPack,
6339 CanonicalConcept, CanonicalConceptArgs, true);
6340 }
6341 }
6342 }
6343
6344 void *Mem = Allocate(sizeof(AutoType) +
6345 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
6346 alignof(AutoType));
6347 auto *AT = new (Mem) AutoType(
6348 DeducedType, Keyword,
6349 (IsDependent ? TypeDependence::DependentInstantiation
6350 : TypeDependence::None) |
6351 (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None),
6352 Canon, TypeConstraintConcept, TypeConstraintArgs);
6353#ifndef NDEBUG
6354 llvm::FoldingSetNodeID InsertedID;
6355 AT->Profile(InsertedID, *this);
6356 assert(InsertedID == ID && "ID does not match");
6357#endif
6358 Types.push_back(AT);
6359 AutoTypes.try_emplace(ID, AT);
6360 return QualType(AT, 0);
6361}
6362
6363/// getAutoType - Return the uniqued reference to the 'auto' type which has been
6364/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
6365/// canonical deduced-but-dependent 'auto' type.
6368 bool IsDependent, bool IsPack,
6369 ConceptDecl *TypeConstraintConcept,
6370 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
6371 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
6372 assert((!IsDependent || DeducedType.isNull()) &&
6373 "A dependent auto should be undeduced");
6374 return getAutoTypeInternal(DeducedType, Keyword, IsDependent, IsPack,
6375 TypeConstraintConcept, TypeConstraintArgs);
6376}
6377
6379 QualType CanonT = T.getCanonicalType();
6380
6381 // Remove a type-constraint from a top-level auto or decltype(auto).
6382 if (auto *AT = CanonT->getAs<AutoType>()) {
6383 if (!AT->isConstrained())
6384 return T;
6385 return getQualifiedType(getAutoType(QualType(), AT->getKeyword(),
6386 AT->isDependentType(),
6387 AT->containsUnexpandedParameterPack()),
6388 T.getQualifiers());
6389 }
6390
6391 // FIXME: We only support constrained auto at the top level in the type of a
6392 // non-type template parameter at the moment. Once we lift that restriction,
6393 // we'll need to recursively build types containing auto here.
6394 assert(!CanonT->getContainedAutoType() ||
6395 !CanonT->getContainedAutoType()->isConstrained());
6396 return T;
6397}
6398
6399QualType ASTContext::getDeducedTemplateSpecializationTypeInternal(
6400 TemplateName Template, QualType DeducedType, bool IsDependent,
6401 QualType Canon) const {
6402 // Look in the folding set for an existing type.
6403 void *InsertPos = nullptr;
6404 llvm::FoldingSetNodeID ID;
6406 IsDependent);
6408 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6409 return QualType(DTST, 0);
6410
6411 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
6412 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent,
6413 Canon);
6414 llvm::FoldingSetNodeID TempID;
6415 DTST->Profile(TempID);
6416 assert(ID == TempID && "ID does not match");
6417 Types.push_back(DTST);
6418 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
6419 return QualType(DTST, 0);
6420}
6421
6422/// Return the uniqued reference to the deduced template specialization type
6423/// which has been deduced to the given type, or to the canonical undeduced
6424/// such type, or the canonical deduced-but-dependent such type.
6426 TemplateName Template, QualType DeducedType, bool IsDependent) const {
6427 QualType Canon = DeducedType.isNull()
6428 ? getDeducedTemplateSpecializationTypeInternal(
6430 IsDependent, QualType())
6431 : DeducedType.getCanonicalType();
6432 return getDeducedTemplateSpecializationTypeInternal(Template, DeducedType,
6433 IsDependent, Canon);
6434}
6435
6436/// getAtomicType - Return the uniqued reference to the atomic type for
6437/// the given value type.
6439 // Unique pointers, to guarantee there is only one pointer of a particular
6440 // structure.
6441 llvm::FoldingSetNodeID ID;
6443
6444 void *InsertPos = nullptr;
6445 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
6446 return QualType(AT, 0);
6447
6448 // If the atomic value type isn't canonical, this won't be a canonical type
6449 // either, so fill in the canonical type field.
6450 QualType Canonical;
6451 if (!T.isCanonical()) {
6452 Canonical = getAtomicType(getCanonicalType(T));
6453
6454 // Get the new insert position for the node we care about.
6455 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
6456 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
6457 }
6458 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
6459 Types.push_back(New);
6460 AtomicTypes.InsertNode(New, InsertPos);
6461 return QualType(New, 0);
6462}
6463
6464/// getAutoDeductType - Get type pattern for deducing against 'auto'.
6466 if (AutoDeductTy.isNull())
6467 AutoDeductTy = QualType(new (*this, alignof(AutoType))
6469 TypeDependence::None, QualType(),
6470 /*concept*/ nullptr, /*args*/ {}),
6471 0);
6472 return AutoDeductTy;
6473}
6474
6475/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
6479 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
6480 return AutoRRefDeductTy;
6481}
6482
6483/// getTagDeclType - Return the unique reference to the type for the
6484/// specified TagDecl (struct/union/class/enum) decl.
6486 assert(Decl);
6487 // FIXME: What is the design on getTagDeclType when it requires casting
6488 // away const? mutable?
6489 return getTypeDeclType(const_cast<TagDecl*>(Decl));
6490}
6491
6492/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
6493/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
6494/// needs to agree with the definition in <stddef.h>.
6496 return getFromTargetType(Target->getSizeType());
6497}
6498
6499/// Return the unique signed counterpart of the integer type
6500/// corresponding to size_t.
6502 return getFromTargetType(Target->getSignedSizeType());
6503}
6504
6505/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
6507 return getFromTargetType(Target->getIntMaxType());
6508}
6509
6510/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
6512 return getFromTargetType(Target->getUIntMaxType());
6513}
6514
6515/// getSignedWCharType - Return the type of "signed wchar_t".
6516/// Used when in C++, as a GCC extension.
6518 // FIXME: derive from "Target" ?
6519 return WCharTy;
6520}
6521
6522/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
6523/// Used when in C++, as a GCC extension.
6525 // FIXME: derive from "Target" ?
6526 return UnsignedIntTy;
6527}
6528
6530 return getFromTargetType(Target->getIntPtrType());
6531}
6532
6535}
6536
6537/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
6538/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
6540 return getFromTargetType(Target->getPtrDiffType(LangAS::Default));
6541}
6542
6543/// Return the unique unsigned counterpart of "ptrdiff_t"
6544/// integer type. The standard (C11 7.21.6.1p7) refers to this type
6545/// in the definition of %tu format specifier.
6547 return getFromTargetType(Target->getUnsignedPtrDiffType(LangAS::Default));
6548}
6549
6550/// Return the unique type for "pid_t" defined in
6551/// <sys/types.h>. We need this to compute the correct type for vfork().
6553 return getFromTargetType(Target->getProcessIDType());
6554}
6555
6556//===----------------------------------------------------------------------===//
6557// Type Operators
6558//===----------------------------------------------------------------------===//
6559
6561 // Push qualifiers into arrays, and then discard any remaining
6562 // qualifiers.
6563 T = getCanonicalType(T);
6565 const Type *Ty = T.getTypePtr();
6567 if (getLangOpts().HLSL && isa<ConstantArrayType>(Ty)) {
6569 } else if (isa<ArrayType>(Ty)) {
6571 } else if (isa<FunctionType>(Ty)) {
6572 Result = getPointerType(QualType(Ty, 0));
6573 } else {
6574 Result = QualType(Ty, 0);
6575 }
6576
6578}
6579
6581 Qualifiers &quals) const {
6582 SplitQualType splitType = type.getSplitUnqualifiedType();
6583
6584 // FIXME: getSplitUnqualifiedType() actually walks all the way to
6585 // the unqualified desugared type and then drops it on the floor.
6586 // We then have to strip that sugar back off with
6587 // getUnqualifiedDesugaredType(), which is silly.
6588 const auto *AT =
6589 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
6590
6591 // If we don't have an array, just use the results in splitType.
6592 if (!AT) {
6593 quals = splitType.Quals;
6594 return QualType(splitType.Ty, 0);
6595 }
6596
6597 // Otherwise, recurse on the array's element type.
6598 QualType elementType = AT->getElementType();
6599 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
6600
6601 // If that didn't change the element type, AT has no qualifiers, so we
6602 // can just use the results in splitType.
6603 if (elementType == unqualElementType) {
6604 assert(quals.empty()); // from the recursive call
6605 quals = splitType.Quals;
6606 return QualType(splitType.Ty, 0);
6607 }
6608
6609 // Otherwise, add in the qualifiers from the outermost type, then
6610 // build the type back up.
6611 quals.addConsistentQualifiers(splitType.Quals);
6612
6613 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
6614 return getConstantArrayType(unqualElementType, CAT->getSize(),
6615 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
6616 }
6617
6618 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
6619 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
6620 }
6621
6622 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
6623 return getVariableArrayType(unqualElementType,
6624 VAT->getSizeExpr(),
6625 VAT->getSizeModifier(),
6626 VAT->getIndexTypeCVRQualifiers(),
6627 VAT->getBracketsRange());
6628 }
6629
6630 const auto *DSAT = cast<DependentSizedArrayType>(AT);
6631 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
6632 DSAT->getSizeModifier(), 0,
6633 SourceRange());
6634}
6635
6636/// Attempt to unwrap two types that may both be array types with the same bound
6637/// (or both be array types of unknown bound) for the purpose of comparing the
6638/// cv-decomposition of two types per C++ [conv.qual].
6639///
6640/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
6641/// C++20 [conv.qual], if permitted by the current language mode.
6643 bool AllowPiMismatch) const {
6644 while (true) {
6645 auto *AT1 = getAsArrayType(T1);
6646 if (!AT1)
6647 return;
6648
6649 auto *AT2 = getAsArrayType(T2);
6650 if (!AT2)
6651 return;
6652
6653 // If we don't have two array types with the same constant bound nor two
6654 // incomplete array types, we've unwrapped everything we can.
6655 // C++20 also permits one type to be a constant array type and the other
6656 // to be an incomplete array type.
6657 // FIXME: Consider also unwrapping array of unknown bound and VLA.
6658 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
6659 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
6660 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
6661 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
6662 isa<IncompleteArrayType>(AT2))))
6663 return;
6664 } else if (isa<IncompleteArrayType>(AT1)) {
6665 if (!(isa<IncompleteArrayType>(AT2) ||
6666 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
6667 isa<ConstantArrayType>(AT2))))
6668 return;
6669 } else {
6670 return;
6671 }
6672
6673 T1 = AT1->getElementType();
6674 T2 = AT2->getElementType();
6675 }
6676}
6677
6678/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
6679///
6680/// If T1 and T2 are both pointer types of the same kind, or both array types
6681/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
6682/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
6683///
6684/// This function will typically be called in a loop that successively
6685/// "unwraps" pointer and pointer-to-member types to compare them at each
6686/// level.
6687///
6688/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
6689/// C++20 [conv.qual], if permitted by the current language mode.
6690///
6691/// \return \c true if a pointer type was unwrapped, \c false if we reached a
6692/// pair of types that can't be unwrapped further.
6694 bool AllowPiMismatch) const {
6695 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
6696
6697 const auto *T1PtrType = T1->getAs<PointerType>();
6698 const auto *T2PtrType = T2->getAs<PointerType>();
6699 if (T1PtrType && T2PtrType) {
6700 T1 = T1PtrType->getPointeeType();
6701 T2 = T2PtrType->getPointeeType();
6702 return true;
6703 }
6704
6705 const auto *T1MPType = T1->getAs<MemberPointerType>();
6706 const auto *T2MPType = T2->getAs<MemberPointerType>();
6707 if (T1MPType && T2MPType &&
6708 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
6709 QualType(T2MPType->getClass(), 0))) {
6710 T1 = T1MPType->getPointeeType();
6711 T2 = T2MPType->getPointeeType();
6712 return true;
6713 }
6714
6715 if (getLangOpts().ObjC) {
6716 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
6717 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
6718 if (T1OPType && T2OPType) {
6719 T1 = T1OPType->getPointeeType();
6720 T2 = T2OPType->getPointeeType();
6721 return true;
6722 }
6723 }
6724
6725 // FIXME: Block pointers, too?
6726
6727 return false;
6728}
6729
6731 while (true) {
6732 Qualifiers Quals;
6733 T1 = getUnqualifiedArrayType(T1, Quals);
6734 T2 = getUnqualifiedArrayType(T2, Quals);
6735 if (hasSameType(T1, T2))
6736 return true;
6737 if (!UnwrapSimilarTypes(T1, T2))
6738 return false;
6739 }
6740}
6741
6743 while (true) {
6744 Qualifiers Quals1, Quals2;
6745 T1 = getUnqualifiedArrayType(T1, Quals1);
6746 T2 = getUnqualifiedArrayType(T2, Quals2);
6747
6748 Quals1.removeCVRQualifiers();
6749 Quals2.removeCVRQualifiers();
6750 if (Quals1 != Quals2)
6751 return false;
6752
6753 if (hasSameType(T1, T2))
6754 return true;
6755
6756 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
6757 return false;
6758 }
6759}
6760
6763 SourceLocation NameLoc) const {
6764 switch (Name.getKind()) {
6767 // DNInfo work in progress: CHECKME: what about DNLoc?
6768 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
6769 NameLoc);
6770
6772 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
6773 // DNInfo work in progress: CHECKME: what about DNLoc?
6774 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
6775 }
6776
6778 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
6779 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
6780 }
6781
6783 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
6784 DeclarationName DName;
6785 if (DTN->isIdentifier()) {
6787 return DeclarationNameInfo(DName, NameLoc);
6788 } else {
6790 // DNInfo work in progress: FIXME: source locations?
6791 DeclarationNameLoc DNLoc =
6793 return DeclarationNameInfo(DName, NameLoc, DNLoc);
6794 }
6795 }
6796
6799 = Name.getAsSubstTemplateTemplateParm();
6800 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
6801 NameLoc);
6802 }
6803
6806 = Name.getAsSubstTemplateTemplateParmPack();
6808 NameLoc);
6809 }
6811 return DeclarationNameInfo(Name.getAsUsingShadowDecl()->getDeclName(),
6812 NameLoc);
6814 DeducedTemplateStorage *DTS = Name.getAsDeducedTemplateName();
6815 return getNameForTemplate(DTS->getUnderlying(), NameLoc);
6816 }
6817 }
6818
6819 llvm_unreachable("bad template name kind!");
6820}
6821
6822static const TemplateArgument *
6824 auto handleParam = [](auto *TP) -> const TemplateArgument * {
6825 if (!TP->hasDefaultArgument())
6826 return nullptr;
6827 return &TP->getDefaultArgument().getArgument();
6828 };
6829 switch (P->getKind()) {
6830 case NamedDecl::TemplateTypeParm:
6831 return handleParam(cast<TemplateTypeParmDecl>(P));
6832 case NamedDecl::NonTypeTemplateParm:
6833 return handleParam(cast<NonTypeTemplateParmDecl>(P));
6834 case NamedDecl::TemplateTemplateParm:
6835 return handleParam(cast<TemplateTemplateParmDecl>(P));
6836 default:
6837 llvm_unreachable("Unexpected template parameter kind");
6838 }
6839}
6840
6842 bool IgnoreDeduced) const {
6843 while (std::optional<TemplateName> UnderlyingOrNone =
6844 Name.desugar(IgnoreDeduced))
6845 Name = *UnderlyingOrNone;
6846
6847 switch (Name.getKind()) {
6849 TemplateDecl *Template = Name.getAsTemplateDecl();
6850 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
6851 Template = getCanonicalTemplateTemplateParmDecl(TTP);
6852
6853 // The canonical template name is the canonical template declaration.
6854 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
6855 }
6856
6859 llvm_unreachable("cannot canonicalize unresolved template");
6860
6862 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
6863 assert(DTN && "Non-dependent template names must refer to template decls.");
6864 return DTN->CanonicalTemplateName;
6865 }
6866
6869 Name.getAsSubstTemplateTemplateParmPack();
6870 TemplateArgument canonArgPack =
6873 canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
6874 subst->getFinal(), subst->getIndex());
6875 }
6877 assert(IgnoreDeduced == false);
6878 DeducedTemplateStorage *DTS = Name.getAsDeducedTemplateName();
6879 DefaultArguments DefArgs = DTS->getDefaultArguments();
6880 TemplateName Underlying = DTS->getUnderlying();
6881
6882 TemplateName CanonUnderlying =
6883 getCanonicalTemplateName(Underlying, /*IgnoreDeduced=*/true);
6884 bool NonCanonical = CanonUnderlying != Underlying;
6885 auto CanonArgs =
6886 getCanonicalTemplateArguments(*this, DefArgs.Args, NonCanonical);
6887
6888 ArrayRef<NamedDecl *> Params =
6889 CanonUnderlying.getAsTemplateDecl()->getTemplateParameters()->asArray();
6890 assert(CanonArgs.size() <= Params.size());
6891 // A deduced template name which deduces the same default arguments already
6892 // declared in the underlying template is the same template as the
6893 // underlying template. We need need to note any arguments which differ from
6894 // the corresponding declaration. If any argument differs, we must build a
6895 // deduced template name.
6896 for (int I = CanonArgs.size() - 1; I >= 0; --I) {
6898 if (!A)
6899 break;
6900 auto CanonParamDefArg = getCanonicalTemplateArgument(*A);
6901 TemplateArgument &CanonDefArg = CanonArgs[I];
6902 if (CanonDefArg.structurallyEquals(CanonParamDefArg))
6903 continue;
6904 // Keep popping from the back any deault arguments which are the same.
6905 if (I == int(CanonArgs.size() - 1))
6906 CanonArgs.pop_back();
6907 NonCanonical = true;
6908 }
6909 return NonCanonical ? getDeducedTemplateName(
6910 CanonUnderlying,
6911 /*DefaultArgs=*/{DefArgs.StartPos, CanonArgs})
6912 : Name;
6913 }
6917 llvm_unreachable("always sugar node");
6918 }
6919
6920 llvm_unreachable("bad template name!");
6921}
6922
6924 const TemplateName &Y,
6925 bool IgnoreDeduced) const {
6926 return getCanonicalTemplateName(X, IgnoreDeduced) ==
6927 getCanonicalTemplateName(Y, IgnoreDeduced);
6928}
6929
6930bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
6931 if (!XCE != !YCE)
6932 return false;
6933
6934 if (!XCE)
6935 return true;
6936
6937 llvm::FoldingSetNodeID XCEID, YCEID;
6938 XCE->Profile(XCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
6939 YCE->Profile(YCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
6940 return XCEID == YCEID;
6941}
6942
6944 const TypeConstraint *YTC) const {
6945 if (!XTC != !YTC)
6946 return false;
6947
6948 if (!XTC)
6949 return true;
6950
6951 auto *NCX = XTC->getNamedConcept();
6952 auto *NCY = YTC->getNamedConcept();
6953 if (!NCX || !NCY || !isSameEntity(NCX, NCY))
6954 return false;
6957 return false;
6959 if (XTC->getConceptReference()
6961 ->NumTemplateArgs !=
6963 return false;
6964
6965 // Compare slowly by profiling.
6966 //
6967 // We couldn't compare the profiling result for the template
6968 // args here. Consider the following example in different modules:
6969 //
6970 // template <__integer_like _Tp, C<_Tp> Sentinel>
6971 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
6972 // return __t;
6973 // }
6974 //
6975 // When we compare the profiling result for `C<_Tp>` in different
6976 // modules, it will compare the type of `_Tp` in different modules.
6977 // However, the type of `_Tp` in different modules refer to different
6978 // types here naturally. So we couldn't compare the profiling result
6979 // for the template args directly.
6982}
6983
6985 const NamedDecl *Y) const {
6986 if (X->getKind() != Y->getKind())
6987 return false;
6988
6989 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
6990 auto *TY = cast<TemplateTypeParmDecl>(Y);
6991 if (TX->isParameterPack() != TY->isParameterPack())
6992 return false;
6993 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
6994 return false;
6995 return isSameTypeConstraint(TX->getTypeConstraint(),
6996 TY->getTypeConstraint());
6997 }
6998
6999 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7000 auto *TY = cast<NonTypeTemplateParmDecl>(Y);
7001 return TX->isParameterPack() == TY->isParameterPack() &&
7002 TX->getASTContext().hasSameType(TX->getType(), TY->getType()) &&
7003 isSameConstraintExpr(TX->getPlaceholderTypeConstraint(),
7004 TY->getPlaceholderTypeConstraint());
7005 }
7006
7007 auto *TX = cast<TemplateTemplateParmDecl>(X);
7008 auto *TY = cast<TemplateTemplateParmDecl>(Y);
7009 return TX->isParameterPack() == TY->isParameterPack() &&
7010 isSameTemplateParameterList(TX->getTemplateParameters(),
7011 TY->getTemplateParameters());
7012}
7013
7015 const TemplateParameterList *X, const TemplateParameterList *Y) const {
7016 if (X->size() != Y->size())
7017 return false;
7018
7019 for (unsigned I = 0, N = X->size(); I != N; ++I)
7020 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
7021 return false;
7022
7023 return isSameConstraintExpr(X->getRequiresClause(), Y->getRequiresClause());
7024}
7025
7027 const NamedDecl *Y) const {
7028 // If the type parameter isn't the same already, we don't need to check the
7029 // default argument further.
7030 if (!isSameTemplateParameter(X, Y))
7031 return false;
7032
7033 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(X)) {
7034 auto *TTPY = cast<TemplateTypeParmDecl>(Y);
7035 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7036 return false;
7037
7038 return hasSameType(TTPX->getDefaultArgument().getArgument().getAsType(),
7039 TTPY->getDefaultArgument().getArgument().getAsType());
7040 }
7041
7042 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7043 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Y);
7044 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
7045 return false;
7046
7047 Expr *DefaultArgumentX =
7048 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7049 Expr *DefaultArgumentY =
7050 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7051 llvm::FoldingSetNodeID XID, YID;
7052 DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true);
7053 DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true);
7054 return XID == YID;
7055 }
7056
7057 auto *TTPX = cast<TemplateTemplateParmDecl>(X);
7058 auto *TTPY = cast<TemplateTemplateParmDecl>(Y);
7059
7060 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7061 return false;
7062
7063 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
7064 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
7065 return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate());
7066}
7067
7069 if (auto *NS = X->getAsNamespace())
7070 return NS;
7071 if (auto *NAS = X->getAsNamespaceAlias())
7072 return NAS->getNamespace();
7073 return nullptr;
7074}
7075
7077 const NestedNameSpecifier *Y) {
7078 if (auto *NSX = getNamespace(X)) {
7079 auto *NSY = getNamespace(Y);
7080 if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl())
7081 return false;
7082 } else if (X->getKind() != Y->getKind())
7083 return false;
7084
7085 // FIXME: For namespaces and types, we're permitted to check that the entity
7086 // is named via the same tokens. We should probably do so.
7087 switch (X->getKind()) {
7089 if (X->getAsIdentifier() != Y->getAsIdentifier())
7090 return false;
7091 break;
7094 // We've already checked that we named the same namespace.
7095 break;
7098 if (X->getAsType()->getCanonicalTypeInternal() !=
7100 return false;
7101 break;
7104 return true;
7105 }
7106
7107 // Recurse into earlier portion of NNS, if any.
7108 auto *PX = X->getPrefix();
7109 auto *PY = Y->getPrefix();
7110 if (PX && PY)
7111 return isSameQualifier(PX, PY);
7112 return !PX && !PY;
7113}
7114
7115/// Determine whether the attributes we can overload on are identical for A and
7116/// B. Will ignore any overloadable attrs represented in the type of A and B.
7118 const FunctionDecl *B) {
7119 // Note that pass_object_size attributes are represented in the function's
7120 // ExtParameterInfo, so we don't need to check them here.
7121
7122 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
7123 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
7124 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
7125
7126 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
7127 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
7128 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
7129
7130 // Return false if the number of enable_if attributes is different.
7131 if (!Cand1A || !Cand2A)
7132 return false;
7133
7134 Cand1ID.clear();
7135 Cand2ID.clear();
7136
7137 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
7138 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
7139
7140 // Return false if any of the enable_if expressions of A and B are
7141 // different.
7142 if (Cand1ID != Cand2ID)
7143 return false;
7144 }
7145 return true;
7146}
7147
7148bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
7149 // Caution: this function is called by the AST reader during deserialization,
7150 // so it cannot rely on AST invariants being met. Non-trivial accessors
7151 // should be avoided, along with any traversal of redeclaration chains.
7152
7153 if (X == Y)
7154 return true;
7155
7156 if (X->getDeclName() != Y->getDeclName())
7157 return false;
7158
7159 // Must be in the same context.
7160 //
7161 // Note that we can't use DeclContext::Equals here, because the DeclContexts
7162 // could be two different declarations of the same function. (We will fix the
7163 // semantic DC to refer to the primary definition after merging.)
7164 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
7165 cast<Decl>(Y->getDeclContext()->getRedeclContext())))
7166 return false;
7167
7168 // Two typedefs refer to the same entity if they have the same underlying
7169 // type.
7170 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
7171 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
7172 return hasSameType(TypedefX->getUnderlyingType(),
7173 TypedefY->getUnderlyingType());
7174
7175 // Must have the same kind.
7176 if (X->getKind() != Y->getKind())
7177 return false;
7178
7179 // Objective-C classes and protocols with the same name always match.
7180 if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
7181 return true;
7182
7183 if (isa<ClassTemplateSpecializationDecl>(X)) {
7184 // No need to handle these here: we merge them when adding them to the
7185 // template.
7186 return false;
7187 }
7188
7189 // Compatible tags match.
7190 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
7191 const auto *TagY = cast<TagDecl>(Y);
7192 return (TagX->getTagKind() == TagY->getTagKind()) ||
7193 ((TagX->getTagKind() == TagTypeKind::Struct ||
7194 TagX->getTagKind() == TagTypeKind::Class ||
7195 TagX->getTagKind() == TagTypeKind::Interface) &&
7196 (TagY->getTagKind() == TagTypeKind::Struct ||
7197 TagY->getTagKind() == TagTypeKind::Class ||
7198 TagY->getTagKind() == TagTypeKind::Interface));
7199 }
7200
7201 // Functions with the same type and linkage match.
7202 // FIXME: This needs to cope with merging of prototyped/non-prototyped
7203 // functions, etc.
7204 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
7205 const auto *FuncY = cast<FunctionDecl>(Y);
7206 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
7207 const auto *CtorY = cast<CXXConstructorDecl>(Y);
7208 if (CtorX->getInheritedConstructor() &&
7209 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
7210 CtorY->getInheritedConstructor().getConstructor()))
7211 return false;
7212 }
7213
7214 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
7215 return false;
7216
7217 // Multiversioned functions with different feature strings are represented
7218 // as separate declarations.
7219 if (FuncX->isMultiVersion()) {
7220 const auto *TAX = FuncX->getAttr<TargetAttr>();
7221 const auto *TAY = FuncY->getAttr<TargetAttr>();
7222 assert(TAX && TAY && "Multiversion Function without target attribute");
7223
7224 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
7225 return false;
7226 }
7227
7228 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
7229 // not the same entity if they are constrained.
7230 if ((FuncX->isMemberLikeConstrainedFriend() ||
7231 FuncY->isMemberLikeConstrainedFriend()) &&
7232 !FuncX->getLexicalDeclContext()->Equals(
7233 FuncY->getLexicalDeclContext())) {
7234 return false;
7235 }
7236
7237 if (!isSameConstraintExpr(FuncX->getTrailingRequiresClause(),
7238 FuncY->getTrailingRequiresClause()))
7239 return false;
7240
7241 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
7242 // Map to the first declaration that we've already merged into this one.
7243 // The TSI of redeclarations might not match (due to calling conventions
7244 // being inherited onto the type but not the TSI), but the TSI type of
7245 // the first declaration of the function should match across modules.
7246 FD = FD->getCanonicalDecl();
7247 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
7248 : FD->getType();
7249 };
7250 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
7251 if (!hasSameType(XT, YT)) {
7252 // We can get functions with different types on the redecl chain in C++17
7253 // if they have differing exception specifications and at least one of
7254 // the excpetion specs is unresolved.
7255 auto *XFPT = XT->getAs<FunctionProtoType>();
7256 auto *YFPT = YT->getAs<FunctionProtoType>();
7257 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
7258 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
7261 return true;
7262 return false;
7263 }
7264
7265 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
7266 hasSameOverloadableAttrs(FuncX, FuncY);
7267 }
7268
7269 // Variables with the same type and linkage match.
7270 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
7271 const auto *VarY = cast<VarDecl>(Y);
7272 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
7273 // During deserialization, we might compare variables before we load
7274 // their types. Assume the types will end up being the same.
7275 if (VarX->getType().isNull() || VarY->getType().isNull())
7276 return true;
7277
7278 if (hasSameType(VarX->getType(), VarY->getType()))
7279 return true;
7280
7281 // We can get decls with different types on the redecl chain. Eg.
7282 // template <typename T> struct S { static T Var[]; }; // #1
7283 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
7284 // Only? happens when completing an incomplete array type. In this case
7285 // when comparing #1 and #2 we should go through their element type.
7286 const ArrayType *VarXTy = getAsArrayType(VarX->getType());
7287 const ArrayType *VarYTy = getAsArrayType(VarY->getType());
7288 if (!VarXTy || !VarYTy)
7289 return false;
7290 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
7291 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
7292 }
7293 return false;
7294 }
7295
7296 // Namespaces with the same name and inlinedness match.
7297 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
7298 const auto *NamespaceY = cast<NamespaceDecl>(Y);
7299 return NamespaceX->isInline() == NamespaceY->isInline();
7300 }
7301
7302 // Identical template names and kinds match if their template parameter lists
7303 // and patterns match.
7304 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
7305 const auto *TemplateY = cast<TemplateDecl>(Y);
7306
7307 // ConceptDecl wouldn't be the same if their constraint expression differs.
7308 if (const auto *ConceptX = dyn_cast<ConceptDecl>(X)) {
7309 const auto *ConceptY = cast<ConceptDecl>(Y);
7310 if (!isSameConstraintExpr(ConceptX->getConstraintExpr(),
7311 ConceptY->getConstraintExpr()))
7312 return false;
7313 }
7314
7315 return isSameEntity(TemplateX->getTemplatedDecl(),
7316 TemplateY->getTemplatedDecl()) &&
7317 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
7318 TemplateY->getTemplateParameters());
7319 }
7320
7321 // Fields with the same name and the same type match.
7322 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
7323 const auto *FDY = cast<FieldDecl>(Y);
7324 // FIXME: Also check the bitwidth is odr-equivalent, if any.
7325 return hasSameType(FDX->getType(), FDY->getType());
7326 }
7327
7328 // Indirect fields with the same target field match.
7329 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
7330 const auto *IFDY = cast<IndirectFieldDecl>(Y);
7331 return IFDX->getAnonField()->getCanonicalDecl() ==
7332 IFDY->getAnonField()->getCanonicalDecl();
7333 }
7334
7335 // Enumerators with the same name match.
7336 if (isa<EnumConstantDecl>(X))
7337 // FIXME: Also check the value is odr-equivalent.
7338 return true;
7339
7340 // Using shadow declarations with the same target match.
7341 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
7342 const auto *USY = cast<UsingShadowDecl>(Y);
7343 return declaresSameEntity(USX->getTargetDecl(), USY->getTargetDecl());
7344 }
7345
7346 // Using declarations with the same qualifier match. (We already know that
7347 // the name matches.)
7348 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
7349 const auto *UY = cast<UsingDecl>(Y);
7350 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7351 UX->hasTypename() == UY->hasTypename() &&
7352 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7353 }
7354 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
7355 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
7356 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7357 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7358 }
7359 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
7360 return isSameQualifier(
7361 UX->getQualifier(),
7362 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
7363 }
7364
7365 // Using-pack declarations are only created by instantiation, and match if
7366 // they're instantiated from matching UnresolvedUsing...Decls.
7367 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
7368 return declaresSameEntity(
7369 UX->getInstantiatedFromUsingDecl(),
7370 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
7371 }
7372
7373 // Namespace alias definitions with the same target match.
7374 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
7375 const auto *NAY = cast<NamespaceAliasDecl>(Y);
7376 return NAX->getNamespace()->Equals(NAY->getNamespace());
7377 }
7378
7379 return false;
7380}
7381
7384 switch (Arg.getKind()) {
7386 return Arg;
7387
7389 return Arg;
7390
7392 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
7394 Arg.getIsDefaulted());
7395 }
7396
7399 /*isNullPtr*/ true, Arg.getIsDefaulted());
7400
7403 Arg.getIsDefaulted());
7404
7406 return TemplateArgument(
7409
7412
7414 return TemplateArgument(*this,
7417
7420 /*isNullPtr*/ false, Arg.getIsDefaulted());
7421
7423 bool AnyNonCanonArgs = false;
7424 auto CanonArgs = ::getCanonicalTemplateArguments(
7425 *this, Arg.pack_elements(), AnyNonCanonArgs);
7426 if (!AnyNonCanonArgs)
7427 return Arg;
7429 const_cast<ASTContext &>(*this), CanonArgs);
7430 NewArg.setIsDefaulted(Arg.getIsDefaulted());
7431 return NewArg;
7432 }
7433 }
7434
7435 // Silence GCC warning
7436 llvm_unreachable("Unhandled template argument kind");
7437}
7438
7441 if (!NNS)
7442 return nullptr;
7443
7444 switch (NNS->getKind()) {
7446 // Canonicalize the prefix but keep the identifier the same.
7447 return NestedNameSpecifier::Create(*this,
7449 NNS->getAsIdentifier());
7450
7452 // A namespace is canonical; build a nested-name-specifier with
7453 // this namespace and no prefix.
7454 return NestedNameSpecifier::Create(*this, nullptr,
7455 NNS->getAsNamespace()->getFirstDecl());
7456
7458 // A namespace is canonical; build a nested-name-specifier with
7459 // this namespace and no prefix.
7461 *this, nullptr,
7463
7464 // The difference between TypeSpec and TypeSpecWithTemplate is that the
7465 // latter will have the 'template' keyword when printed.
7468 const Type *T = getCanonicalType(NNS->getAsType());
7469
7470 // If we have some kind of dependent-named type (e.g., "typename T::type"),
7471 // break it apart into its prefix and identifier, then reconsititute those
7472 // as the canonical nested-name-specifier. This is required to canonicalize
7473 // a dependent nested-name-specifier involving typedefs of dependent-name
7474 // types, e.g.,
7475 // typedef typename T::type T1;
7476 // typedef typename T1::type T2;
7477 if (const auto *DNT = T->getAs<DependentNameType>())
7478 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
7479 DNT->getIdentifier());
7480 if (const auto *DTST = T->getAs<DependentTemplateSpecializationType>())
7481 return NestedNameSpecifier::Create(*this, DTST->getQualifier(), true, T);
7482
7483 // TODO: Set 'Template' parameter to true for other template types.
7484 return NestedNameSpecifier::Create(*this, nullptr, false, T);
7485 }
7486
7489 // The global specifier and __super specifer are canonical and unique.
7490 return NNS;
7491 }
7492
7493 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
7494}
7495
7497 // Handle the non-qualified case efficiently.
7498 if (!T.hasLocalQualifiers()) {
7499 // Handle the common positive case fast.
7500 if (const auto *AT = dyn_cast<ArrayType>(T))
7501 return AT;
7502 }
7503
7504 // Handle the common negative case fast.
7505 if (!isa<ArrayType>(T.getCanonicalType()))
7506 return nullptr;
7507
7508 // Apply any qualifiers from the array type to the element type. This
7509 // implements C99 6.7.3p8: "If the specification of an array type includes
7510 // any type qualifiers, the element type is so qualified, not the array type."
7511
7512 // If we get here, we either have type qualifiers on the type, or we have
7513 // sugar such as a typedef in the way. If we have type qualifiers on the type
7514 // we must propagate them down into the element type.
7515
7516 SplitQualType split = T.getSplitDesugaredType();
7517 Qualifiers qs = split.Quals;
7518
7519 // If we have a simple case, just return now.
7520 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
7521 if (!ATy || qs.empty())
7522 return ATy;
7523
7524 // Otherwise, we have an array and we have qualifiers on it. Push the
7525 // qualifiers into the array element type and return a new array type.
7526 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
7527
7528 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
7529 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
7530 CAT->getSizeExpr(),
7531 CAT->getSizeModifier(),
7532 CAT->getIndexTypeCVRQualifiers()));
7533 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
7534 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
7535 IAT->getSizeModifier(),
7536 IAT->getIndexTypeCVRQualifiers()));
7537
7538 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
7539 return cast<ArrayType>(
7541 DSAT->getSizeExpr(),
7542 DSAT->getSizeModifier(),
7543 DSAT->getIndexTypeCVRQualifiers(),
7544 DSAT->getBracketsRange()));
7545
7546 const auto *VAT = cast<VariableArrayType>(ATy);
7547 return cast<ArrayType>(getVariableArrayType(NewEltTy,
7548 VAT->getSizeExpr(),
7549 VAT->getSizeModifier(),
7550 VAT->getIndexTypeCVRQualifiers(),
7551 VAT->getBracketsRange()));
7552}
7553
7556 return getArrayParameterType(T);
7557 if (T->isArrayType() || T->isFunctionType())
7558 return getDecayedType(T);
7559 return T;
7560}
7561
7565 return T.getUnqualifiedType();
7566}
7567
7569 // C++ [except.throw]p3:
7570 // A throw-expression initializes a temporary object, called the exception
7571 // object, the type of which is determined by removing any top-level
7572 // cv-qualifiers from the static type of the operand of throw and adjusting
7573 // the type from "array of T" or "function returning T" to "pointer to T"
7574 // or "pointer to function returning T", [...]
7576 if (T->isArrayType() || T->isFunctionType())
7577 T = getDecayedType(T);
7578 return T.getUnqualifiedType();
7579}
7580
7581/// getArrayDecayedType - Return the properly qualified result of decaying the
7582/// specified array type to a pointer. This operation is non-trivial when
7583/// handling typedefs etc. The canonical type of "T" must be an array type,
7584/// this returns a pointer to a properly qualified element of the array.
7585///
7586/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
7588 // Get the element type with 'getAsArrayType' so that we don't lose any
7589 // typedefs in the element type of the array. This also handles propagation
7590 // of type qualifiers from the array type into the element type if present
7591 // (C99 6.7.3p8).
7592 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
7593 assert(PrettyArrayType && "Not an array type!");
7594
7595 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
7596
7597 // int x[restrict 4] -> int *restrict
7599 PrettyArrayType->getIndexTypeQualifiers());
7600
7601 // int x[_Nullable] -> int * _Nullable
7602 if (auto Nullability = Ty->getNullability()) {
7603 Result = const_cast<ASTContext *>(this)->getAttributedType(*Nullability,
7604 Result, Result);
7605 }
7606 return Result;
7607}
7608
7610 return getBaseElementType(array->getElementType());
7611}
7612
7614 Qualifiers qs;
7615 while (true) {
7616 SplitQualType split = type.getSplitDesugaredType();
7617 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
7618 if (!array) break;
7619
7620 type = array->getElementType();
7622 }
7623
7624 return getQualifiedType(type, qs);
7625}
7626
7627/// getConstantArrayElementCount - Returns number of constant array elements.
7628uint64_t
7630 uint64_t ElementCount = 1;
7631 do {
7632 ElementCount *= CA->getZExtSize();
7633 CA = dyn_cast_or_null<ConstantArrayType>(
7635 } while (CA);
7636 return ElementCount;
7637}
7638
7640 const ArrayInitLoopExpr *AILE) const {
7641 if (!AILE)
7642 return 0;
7643
7644 uint64_t ElementCount = 1;
7645
7646 do {
7647 ElementCount *= AILE->getArraySize().getZExtValue();
7648 AILE = dyn_cast<ArrayInitLoopExpr>(AILE->getSubExpr());
7649 } while (AILE);
7650
7651 return ElementCount;
7652}
7653
7654/// getFloatingRank - Return a relative rank for floating point types.
7655/// This routine will assert if passed a built-in type that isn't a float.
7657 if (const auto *CT = T->getAs<ComplexType>())
7658 return getFloatingRank(CT->getElementType());
7659
7660 switch (T->castAs<BuiltinType>()->getKind()) {
7661 default: llvm_unreachable("getFloatingRank(): not a floating type");
7662 case BuiltinType::Float16: return Float16Rank;
7663 case BuiltinType::Half: return HalfRank;
7664 case BuiltinType::Float: return FloatRank;
7665 case BuiltinType::Double: return DoubleRank;
7666 case BuiltinType::LongDouble: return LongDoubleRank;
7667 case BuiltinType::Float128: return Float128Rank;
7668 case BuiltinType::BFloat16: return BFloat16Rank;
7669 case BuiltinType::Ibm128: return Ibm128Rank;
7670 }
7671}
7672
7673/// getFloatingTypeOrder - Compare the rank of the two specified floating
7674/// point types, ignoring the domain of the type (i.e. 'double' ==
7675/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
7676/// LHS < RHS, return -1.
7678 FloatingRank LHSR = getFloatingRank(LHS);
7679 FloatingRank RHSR = getFloatingRank(RHS);
7680
7681 if (LHSR == RHSR)
7682 return 0;
7683 if (LHSR > RHSR)
7684 return 1;
7685 return -1;
7686}
7687
7690 return 0;
7691 return getFloatingTypeOrder(LHS, RHS);
7692}
7693
7694/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
7695/// routine will assert if passed a built-in type that isn't an integer or enum,
7696/// or if it is not canonicalized.
7697unsigned ASTContext::getIntegerRank(const Type *T) const {
7698 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
7699
7700 // Results in this 'losing' to any type of the same size, but winning if
7701 // larger.
7702 if (const auto *EIT = dyn_cast<BitIntType>(T))
7703 return 0 + (EIT->getNumBits() << 3);
7704
7705 switch (cast<BuiltinType>(T)->getKind()) {
7706 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
7707 case BuiltinType::Bool:
7708 return 1 + (getIntWidth(BoolTy) << 3);
7709 case BuiltinType::Char_S:
7710 case BuiltinType::Char_U:
7711 case BuiltinType::SChar:
7712 case BuiltinType::UChar:
7713 return 2 + (getIntWidth(CharTy) << 3);
7714 case BuiltinType::Short:
7715 case BuiltinType::UShort:
7716 return 3 + (getIntWidth(ShortTy) << 3);
7717 case BuiltinType::Int:
7718 case BuiltinType::UInt:
7719 return 4 + (getIntWidth(IntTy) << 3);
7720 case BuiltinType::Long:
7721 case BuiltinType::ULong:
7722 return 5 + (getIntWidth(LongTy) << 3);
7723 case BuiltinType::LongLong:
7724 case BuiltinType::ULongLong:
7725 return 6 + (getIntWidth(LongLongTy) << 3);
7726 case BuiltinType::Int128:
7727 case BuiltinType::UInt128:
7728 return 7 + (getIntWidth(Int128Ty) << 3);
7729
7730 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
7731 // their underlying types" [c++20 conv.rank]
7732 case BuiltinType::Char8:
7733 return getIntegerRank(UnsignedCharTy.getTypePtr());
7734 case BuiltinType::Char16:
7735 return getIntegerRank(
7736 getFromTargetType(Target->getChar16Type()).getTypePtr());
7737 case BuiltinType::Char32:
7738 return getIntegerRank(
7739 getFromTargetType(Target->getChar32Type()).getTypePtr());
7740 case BuiltinType::WChar_S:
7741 case BuiltinType::WChar_U:
7742 return getIntegerRank(
7743 getFromTargetType(Target->getWCharType()).getTypePtr());
7744 }
7745}
7746
7747/// Whether this is a promotable bitfield reference according
7748/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
7749///
7750/// \returns the type this bit-field will promote to, or NULL if no
7751/// promotion occurs.
7753 if (E->isTypeDependent() || E->isValueDependent())
7754 return {};
7755
7756 // C++ [conv.prom]p5:
7757 // If the bit-field has an enumerated type, it is treated as any other
7758 // value of that type for promotion purposes.
7760 return {};
7761
7762 // FIXME: We should not do this unless E->refersToBitField() is true. This
7763 // matters in C where getSourceBitField() will find bit-fields for various
7764 // cases where the source expression is not a bit-field designator.
7765
7766 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
7767 if (!Field)
7768 return {};
7769
7770 QualType FT = Field->getType();
7771
7772 uint64_t BitWidth = Field->getBitWidthValue(*this);
7773 uint64_t IntSize = getTypeSize(IntTy);
7774 // C++ [conv.prom]p5:
7775 // A prvalue for an integral bit-field can be converted to a prvalue of type
7776 // int if int can represent all the values of the bit-field; otherwise, it
7777 // can be converted to unsigned int if unsigned int can represent all the
7778 // values of the bit-field. If the bit-field is larger yet, no integral
7779 // promotion applies to it.
7780 // C11 6.3.1.1/2:
7781 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
7782 // If an int can represent all values of the original type (as restricted by
7783 // the width, for a bit-field), the value is converted to an int; otherwise,
7784 // it is converted to an unsigned int.
7785 //
7786 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
7787 // We perform that promotion here to match GCC and C++.
7788 // FIXME: C does not permit promotion of an enum bit-field whose rank is
7789 // greater than that of 'int'. We perform that promotion to match GCC.
7790 //
7791 // C23 6.3.1.1p2:
7792 // The value from a bit-field of a bit-precise integer type is converted to
7793 // the corresponding bit-precise integer type. (The rest is the same as in
7794 // C11.)
7795 if (QualType QT = Field->getType(); QT->isBitIntType())
7796 return QT;
7797
7798 if (BitWidth < IntSize)
7799 return IntTy;
7800
7801 if (BitWidth == IntSize)
7802 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
7803
7804 // Bit-fields wider than int are not subject to promotions, and therefore act
7805 // like the base type. GCC has some weird bugs in this area that we
7806 // deliberately do not follow (GCC follows a pre-standard resolution to
7807 // C's DR315 which treats bit-width as being part of the type, and this leaks
7808 // into their semantics in some cases).
7809 return {};
7810}
7811
7812/// getPromotedIntegerType - Returns the type that Promotable will
7813/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
7814/// integer type.
7816 assert(!Promotable.isNull());
7817 assert(isPromotableIntegerType(Promotable));
7818 if (const auto *ET = Promotable->getAs<EnumType>())
7819 return ET->getDecl()->getPromotionType();
7820
7821 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
7822 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
7823 // (3.9.1) can be converted to a prvalue of the first of the following
7824 // types that can represent all the values of its underlying type:
7825 // int, unsigned int, long int, unsigned long int, long long int, or
7826 // unsigned long long int [...]
7827 // FIXME: Is there some better way to compute this?
7828 if (BT->getKind() == BuiltinType::WChar_S ||
7829 BT->getKind() == BuiltinType::WChar_U ||
7830 BT->getKind() == BuiltinType::Char8 ||
7831 BT->getKind() == BuiltinType::Char16 ||
7832 BT->getKind() == BuiltinType::Char32) {
7833 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
7834 uint64_t FromSize = getTypeSize(BT);
7835 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
7837 for (const auto &PT : PromoteTypes) {
7838 uint64_t ToSize = getTypeSize(PT);
7839 if (FromSize < ToSize ||
7840 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
7841 return PT;
7842 }
7843 llvm_unreachable("char type should fit into long long");
7844 }
7845 }
7846
7847 // At this point, we should have a signed or unsigned integer type.
7848 if (Promotable->isSignedIntegerType())
7849 return IntTy;
7850 uint64_t PromotableSize = getIntWidth(Promotable);
7851 uint64_t IntSize = getIntWidth(IntTy);
7852 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
7853 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
7854}
7855
7856/// Recurses in pointer/array types until it finds an objc retainable
7857/// type and returns its ownership.
7859 while (!T.isNull()) {
7860 if (T.getObjCLifetime() != Qualifiers::OCL_None)
7861 return T.getObjCLifetime();
7862 if (T->isArrayType())
7864 else if (const auto *PT = T->getAs<PointerType>())
7865 T = PT->getPointeeType();
7866 else if (const auto *RT = T->getAs<ReferenceType>())
7867 T = RT->getPointeeType();
7868 else
7869 break;
7870 }
7871
7872 return Qualifiers::OCL_None;
7873}
7874
7875static const Type *getIntegerTypeForEnum(const EnumType *ET) {
7876 // Incomplete enum types are not treated as integer types.
7877 // FIXME: In C++, enum types are never integer types.
7878 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
7879 return ET->getDecl()->getIntegerType().getTypePtr();
7880 return nullptr;
7881}
7882
7883/// getIntegerTypeOrder - Returns the highest ranked integer type:
7884/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
7885/// LHS < RHS, return -1.
7887 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
7888 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
7889
7890 // Unwrap enums to their underlying type.
7891 if (const auto *ET = dyn_cast<EnumType>(LHSC))
7892 LHSC = getIntegerTypeForEnum(ET);
7893 if (const auto *ET = dyn_cast<EnumType>(RHSC))
7894 RHSC = getIntegerTypeForEnum(ET);
7895
7896 if (LHSC == RHSC) return 0;
7897
7898 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
7899 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
7900
7901 unsigned LHSRank = getIntegerRank(LHSC);
7902 unsigned RHSRank = getIntegerRank(RHSC);
7903
7904 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
7905 if (LHSRank == RHSRank) return 0;
7906 return LHSRank > RHSRank ? 1 : -1;
7907 }
7908
7909 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
7910 if (LHSUnsigned) {
7911 // If the unsigned [LHS] type is larger, return it.
7912 if (LHSRank >= RHSRank)
7913 return 1;
7914
7915 // If the signed type can represent all values of the unsigned type, it
7916 // wins. Because we are dealing with 2's complement and types that are
7917 // powers of two larger than each other, this is always safe.
7918 return -1;
7919 }
7920
7921 // If the unsigned [RHS] type is larger, return it.
7922 if (RHSRank >= LHSRank)
7923 return -1;
7924
7925 // If the signed type can represent all values of the unsigned type, it
7926 // wins. Because we are dealing with 2's complement and types that are
7927 // powers of two larger than each other, this is always safe.
7928 return 1;
7929}
7930
7932 if (CFConstantStringTypeDecl)
7933 return CFConstantStringTypeDecl;
7934
7935 assert(!CFConstantStringTagDecl &&
7936 "tag and typedef should be initialized together");
7937 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
7938 CFConstantStringTagDecl->startDefinition();
7939
7940 struct {
7941 QualType Type;
7942 const char *Name;
7943 } Fields[5];
7944 unsigned Count = 0;
7945
7946 /// Objective-C ABI
7947 ///
7948 /// typedef struct __NSConstantString_tag {
7949 /// const int *isa;
7950 /// int flags;
7951 /// const char *str;
7952 /// long length;
7953 /// } __NSConstantString;
7954 ///
7955 /// Swift ABI (4.1, 4.2)
7956 ///
7957 /// typedef struct __NSConstantString_tag {
7958 /// uintptr_t _cfisa;
7959 /// uintptr_t _swift_rc;
7960 /// _Atomic(uint64_t) _cfinfoa;
7961 /// const char *_ptr;
7962 /// uint32_t _length;
7963 /// } __NSConstantString;
7964 ///
7965 /// Swift ABI (5.0)
7966 ///
7967 /// typedef struct __NSConstantString_tag {
7968 /// uintptr_t _cfisa;
7969 /// uintptr_t _swift_rc;
7970 /// _Atomic(uint64_t) _cfinfoa;
7971 /// const char *_ptr;
7972 /// uintptr_t _length;
7973 /// } __NSConstantString;
7974
7975 const auto CFRuntime = getLangOpts().CFRuntime;
7976 if (static_cast<unsigned>(CFRuntime) <
7977 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
7978 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
7979 Fields[Count++] = { IntTy, "flags" };
7980 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
7981 Fields[Count++] = { LongTy, "length" };
7982 } else {
7983 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
7984 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
7985 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
7986 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
7989 Fields[Count++] = { IntTy, "_ptr" };
7990 else
7991 Fields[Count++] = { getUIntPtrType(), "_ptr" };
7992 }
7993
7994 // Create fields
7995 for (unsigned i = 0; i < Count; ++i) {
7996 FieldDecl *Field =
7997 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
7998 SourceLocation(), &Idents.get(Fields[i].Name),
7999 Fields[i].Type, /*TInfo=*/nullptr,
8000 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8001 Field->setAccess(AS_public);
8002 CFConstantStringTagDecl->addDecl(Field);
8003 }
8004
8005 CFConstantStringTagDecl->completeDefinition();
8006 // This type is designed to be compatible with NSConstantString, but cannot
8007 // use the same name, since NSConstantString is an interface.
8008 auto tagType = getTagDeclType(CFConstantStringTagDecl);
8009 CFConstantStringTypeDecl =
8010 buildImplicitTypedef(tagType, "__NSConstantString");
8011
8012 return CFConstantStringTypeDecl;
8013}
8014
8016 if (!CFConstantStringTagDecl)
8017 getCFConstantStringDecl(); // Build the tag and the typedef.
8018 return CFConstantStringTagDecl;
8019}
8020
8021// getCFConstantStringType - Return the type used for constant CFStrings.
8024}
8025
8027 if (ObjCSuperType.isNull()) {
8028 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
8029 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
8030 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
8031 }
8032 return ObjCSuperType;
8033}
8034
8036 const auto *TD = T->castAs<TypedefType>();
8037 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
8038 const auto *TagType =
8039 CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>();
8040 CFConstantStringTagDecl = TagType->getDecl();
8041}
8042
8044 if (BlockDescriptorType)
8045 return getTagDeclType(BlockDescriptorType);
8046
8047 RecordDecl *RD;
8048 // FIXME: Needs the FlagAppleBlock bit.
8049 RD = buildImplicitRecord("__block_descriptor");
8050 RD->startDefinition();
8051
8052 QualType FieldTypes[] = {
8055 };
8056
8057 static const char *const FieldNames[] = {
8058 "reserved",
8059 "Size"
8060 };
8061
8062 for (size_t i = 0; i < 2; ++i) {
8064 *this, RD, SourceLocation(), SourceLocation(),
8065 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8066 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8067 Field->setAccess(AS_public);
8068 RD->addDecl(Field);
8069 }
8070
8071 RD->completeDefinition();
8072
8073 BlockDescriptorType = RD;
8074
8075 return getTagDeclType(BlockDescriptorType);
8076}
8077
8079 if (BlockDescriptorExtendedType)
8080 return getTagDeclType(BlockDescriptorExtendedType);
8081
8082 RecordDecl *RD;
8083 // FIXME: Needs the FlagAppleBlock bit.
8084 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
8085 RD->startDefinition();
8086
8087 QualType FieldTypes[] = {
8092 };
8093
8094 static const char *const FieldNames[] = {
8095 "reserved",
8096 "Size",
8097 "CopyFuncPtr",
8098 "DestroyFuncPtr"
8099 };
8100
8101 for (size_t i = 0; i < 4; ++i) {
8103 *this, RD, SourceLocation(), SourceLocation(),
8104 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8105 /*BitWidth=*/nullptr,
8106 /*Mutable=*/false, ICIS_NoInit);
8107 Field->setAccess(AS_public);
8108 RD->addDecl(Field);
8109 }
8110
8111 RD->completeDefinition();
8112
8113 BlockDescriptorExtendedType = RD;
8114 return getTagDeclType(BlockDescriptorExtendedType);
8115}
8116
8118 const auto *BT = dyn_cast<BuiltinType>(T);
8119
8120 if (!BT) {
8121 if (isa<PipeType>(T))
8122 return OCLTK_Pipe;
8123
8124 return OCLTK_Default;
8125 }
8126
8127 switch (BT->getKind()) {
8128#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8129 case BuiltinType::Id: \
8130 return OCLTK_Image;
8131#include "clang/Basic/OpenCLImageTypes.def"
8132
8133 case BuiltinType::OCLClkEvent:
8134 return OCLTK_ClkEvent;
8135
8136 case BuiltinType::OCLEvent:
8137 return OCLTK_Event;
8138
8139 case BuiltinType::OCLQueue:
8140 return OCLTK_Queue;
8141
8142 case BuiltinType::OCLReserveID:
8143 return OCLTK_ReserveID;
8144
8145 case BuiltinType::OCLSampler:
8146 return OCLTK_Sampler;
8147
8148 default:
8149 return OCLTK_Default;
8150 }
8151}
8152
8154 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
8155}
8156
8157/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
8158/// requires copy/dispose. Note that this must match the logic
8159/// in buildByrefHelpers.
8161 const VarDecl *D) {
8162 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
8163 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
8164 if (!copyExpr && record->hasTrivialDestructor()) return false;
8165
8166 return true;
8167 }
8168
8169 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
8170 // move or destroy.
8172 return true;
8173
8174 if (!Ty->isObjCRetainableType()) return false;
8175
8176 Qualifiers qs = Ty.getQualifiers();
8177
8178 // If we have lifetime, that dominates.
8179 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
8180 switch (lifetime) {
8181 case Qualifiers::OCL_None: llvm_unreachable("impossible");
8182
8183 // These are just bits as far as the runtime is concerned.
8186 return false;
8187
8188 // These cases should have been taken care of when checking the type's
8189 // non-triviality.
8192 llvm_unreachable("impossible");
8193 }
8194 llvm_unreachable("fell out of lifetime switch!");
8195 }
8196 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
8198}
8199
8201 Qualifiers::ObjCLifetime &LifeTime,
8202 bool &HasByrefExtendedLayout) const {
8203 if (!getLangOpts().ObjC ||
8204 getLangOpts().getGC() != LangOptions::NonGC)
8205 return false;
8206
8207 HasByrefExtendedLayout = false;
8208 if (Ty->isRecordType()) {
8209 HasByrefExtendedLayout = true;
8210 LifeTime = Qualifiers::OCL_None;
8211 } else if ((LifeTime = Ty.getObjCLifetime())) {
8212 // Honor the ARC qualifiers.
8213 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
8214 // The MRR rule.
8216 } else {
8217 LifeTime = Qualifiers::OCL_None;
8218 }
8219 return true;
8220}
8221
8223 assert(Target && "Expected target to be initialized");
8224 const llvm::Triple &T = Target->getTriple();
8225 // Windows is LLP64 rather than LP64
8226 if (T.isOSWindows() && T.isArch64Bit())
8227 return UnsignedLongLongTy;
8228 return UnsignedLongTy;
8229}
8230
8232 assert(Target && "Expected target to be initialized");
8233 const llvm::Triple &T = Target->getTriple();
8234 // Windows is LLP64 rather than LP64
8235 if (T.isOSWindows() && T.isArch64Bit())
8236 return LongLongTy;
8237 return LongTy;
8238}
8239
8241 if (!ObjCInstanceTypeDecl)
8242 ObjCInstanceTypeDecl =
8243 buildImplicitTypedef(getObjCIdType(), "instancetype");
8244 return ObjCInstanceTypeDecl;
8245}
8246
8247// This returns true if a type has been typedefed to BOOL:
8248// typedef <type> BOOL;
8250 if (const auto *TT = dyn_cast<TypedefType>(T))
8251 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
8252 return II->isStr("BOOL");
8253
8254 return false;
8255}
8256
8257/// getObjCEncodingTypeSize returns size of type for objective-c encoding
8258/// purpose.
8260 if (!type->isIncompleteArrayType() && type->isIncompleteType())
8261 return CharUnits::Zero();
8262
8264
8265 // Make all integer and enum types at least as large as an int
8266 if (sz.isPositive() && type->isIntegralOrEnumerationType())
8267 sz = std::max(sz, getTypeSizeInChars(IntTy));
8268 // Treat arrays as pointers, since that's how they're passed in.
8269 else if (type->isArrayType())
8271 return sz;
8272}
8273
8275 return getTargetInfo().getCXXABI().isMicrosoft() &&
8276 VD->isStaticDataMember() &&
8278 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
8279}
8280
8283 if (!VD->isInline())
8285
8286 // In almost all cases, it's a weak definition.
8287 auto *First = VD->getFirstDecl();
8288 if (First->isInlineSpecified() || !First->isStaticDataMember())
8290
8291 // If there's a file-context declaration in this translation unit, it's a
8292 // non-discardable definition.
8293 for (auto *D : VD->redecls())
8295 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
8297
8298 // If we've not seen one yet, we don't know.
8300}
8301
8302static std::string charUnitsToString(const CharUnits &CU) {
8303 return llvm::itostr(CU.getQuantity());
8304}
8305
8306/// getObjCEncodingForBlock - Return the encoded type for this block
8307/// declaration.
8309 std::string S;
8310
8311 const BlockDecl *Decl = Expr->getBlockDecl();
8312 QualType BlockTy =
8314 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
8315 // Encode result type.
8316 if (getLangOpts().EncodeExtendedBlockSig)
8318 true /*Extended*/);
8319 else
8320 getObjCEncodingForType(BlockReturnTy, S);
8321 // Compute size of all parameters.
8322 // Start with computing size of a pointer in number of bytes.
8323 // FIXME: There might(should) be a better way of doing this computation!
8325 CharUnits ParmOffset = PtrSize;
8326 for (auto *PI : Decl->parameters()) {
8327 QualType PType = PI->getType();
8329 if (sz.isZero())
8330 continue;
8331 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
8332 ParmOffset += sz;
8333 }
8334 // Size of the argument frame
8335 S += charUnitsToString(ParmOffset);
8336 // Block pointer and offset.
8337 S += "@?0";
8338
8339 // Argument types.
8340 ParmOffset = PtrSize;
8341 for (auto *PVDecl : Decl->parameters()) {
8342 QualType PType = PVDecl->getOriginalType();
8343 if (const auto *AT =
8344 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8345 // Use array's original type only if it has known number of
8346 // elements.
8347 if (!isa<ConstantArrayType>(AT))
8348 PType = PVDecl->getType();
8349 } else if (PType->isFunctionType())
8350 PType = PVDecl->getType();
8351 if (getLangOpts().EncodeExtendedBlockSig)
8353 S, true /*Extended*/);
8354 else
8355 getObjCEncodingForType(PType, S);
8356 S += charUnitsToString(ParmOffset);
8357 ParmOffset += getObjCEncodingTypeSize(PType);
8358 }
8359
8360 return S;
8361}
8362
8363std::string
8365 std::string S;
8366 // Encode result type.
8367 getObjCEncodingForType(Decl->getReturnType(), S);
8368 CharUnits ParmOffset;
8369 // Compute size of all parameters.
8370 for (auto *PI : Decl->parameters()) {
8371 QualType PType = PI->getType();
8373 if (sz.isZero())
8374 continue;
8375
8376 assert(sz.isPositive() &&
8377 "getObjCEncodingForFunctionDecl - Incomplete param type");
8378 ParmOffset += sz;
8379 }
8380 S += charUnitsToString(ParmOffset);
8381 ParmOffset = CharUnits::Zero();
8382
8383 // Argument types.
8384 for (auto *PVDecl : Decl->parameters()) {
8385 QualType PType = PVDecl->getOriginalType();
8386 if (const auto *AT =
8387 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8388 // Use array's original type only if it has known number of
8389 // elements.
8390 if (!isa<ConstantArrayType>(AT))
8391 PType = PVDecl->getType();
8392 } else if (PType->isFunctionType())
8393 PType = PVDecl->getType();
8394 getObjCEncodingForType(PType, S);
8395 S += charUnitsToString(ParmOffset);
8396 ParmOffset += getObjCEncodingTypeSize(PType);
8397 }
8398
8399 return S;
8400}
8401
8402/// getObjCEncodingForMethodParameter - Return the encoded type for a single
8403/// method parameter or return type. If Extended, include class names and
8404/// block object types.
8406 QualType T, std::string& S,
8407 bool Extended) const {
8408 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
8410 // Encode parameter type.
8411 ObjCEncOptions Options = ObjCEncOptions()
8412 .setExpandPointedToStructures()
8413 .setExpandStructures()
8414 .setIsOutermostType();
8415 if (Extended)
8416 Options.setEncodeBlockParameters().setEncodeClassNames();
8417 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
8418}
8419
8420/// getObjCEncodingForMethodDecl - Return the encoded type for this method
8421/// declaration.
8423 bool Extended) const {
8424 // FIXME: This is not very efficient.
8425 // Encode return type.
8426 std::string S;
8427 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
8428 Decl->getReturnType(), S, Extended);
8429 // Compute size of all parameters.
8430 // Start with computing size of a pointer in number of bytes.
8431 // FIXME: There might(should) be a better way of doing this computation!
8433 // The first two arguments (self and _cmd) are pointers; account for
8434 // their size.
8435 CharUnits ParmOffset = 2 * PtrSize;
8436 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8437 E = Decl->sel_param_end(); PI != E; ++PI) {
8438 QualType PType = (*PI)->getType();
8440 if (sz.isZero())
8441 continue;
8442
8443 assert(sz.isPositive() &&
8444 "getObjCEncodingForMethodDecl - Incomplete param type");
8445 ParmOffset += sz;
8446 }
8447 S += charUnitsToString(ParmOffset);
8448 S += "@0:";
8449 S += charUnitsToString(PtrSize);
8450
8451 // Argument types.
8452 ParmOffset = 2 * PtrSize;
8453 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8454 E = Decl->sel_param_end(); PI != E; ++PI) {
8455 const ParmVarDecl *PVDecl = *PI;
8456 QualType PType = PVDecl->getOriginalType();
8457 if (const auto *AT =
8458 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8459 // Use array's original type only if it has known number of
8460 // elements.
8461 if (!isa<ConstantArrayType>(AT))
8462 PType = PVDecl->getType();
8463 } else if (PType->isFunctionType())
8464 PType = PVDecl->getType();
8466 PType, S, Extended);
8467 S += charUnitsToString(ParmOffset);
8468 ParmOffset += getObjCEncodingTypeSize(PType);
8469 }
8470
8471 return S;
8472}
8473
8476 const ObjCPropertyDecl *PD,
8477 const Decl *Container) const {
8478 if (!Container)
8479 return nullptr;
8480 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
8481 for (auto *PID : CID->property_impls())
8482 if (PID->getPropertyDecl() == PD)
8483 return PID;
8484 } else {
8485 const auto *OID = cast<ObjCImplementationDecl>(Container);
8486 for (auto *PID : OID->property_impls())
8487 if (PID->getPropertyDecl() == PD)
8488 return PID;
8489 }
8490 return nullptr;
8491}
8492
8493/// getObjCEncodingForPropertyDecl - Return the encoded type for this
8494/// property declaration. If non-NULL, Container must be either an
8495/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
8496/// NULL when getting encodings for protocol properties.
8497/// Property attributes are stored as a comma-delimited C string. The simple
8498/// attributes readonly and bycopy are encoded as single characters. The
8499/// parametrized attributes, getter=name, setter=name, and ivar=name, are
8500/// encoded as single characters, followed by an identifier. Property types
8501/// are also encoded as a parametrized attribute. The characters used to encode
8502/// these attributes are defined by the following enumeration:
8503/// @code
8504/// enum PropertyAttributes {
8505/// kPropertyReadOnly = 'R', // property is read-only.
8506/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
8507/// kPropertyByref = '&', // property is a reference to the value last assigned
8508/// kPropertyDynamic = 'D', // property is dynamic
8509/// kPropertyGetter = 'G', // followed by getter selector name
8510/// kPropertySetter = 'S', // followed by setter selector name
8511/// kPropertyInstanceVariable = 'V' // followed by instance variable name
8512/// kPropertyType = 'T' // followed by old-style type encoding.
8513/// kPropertyWeak = 'W' // 'weak' property
8514/// kPropertyStrong = 'P' // property GC'able
8515/// kPropertyNonAtomic = 'N' // property non-atomic
8516/// kPropertyOptional = '?' // property optional
8517/// };
8518/// @endcode
8519std::string
8521 const Decl *Container) const {
8522 // Collect information from the property implementation decl(s).
8523 bool Dynamic = false;
8524 ObjCPropertyImplDecl *SynthesizePID = nullptr;
8525
8526 if (ObjCPropertyImplDecl *PropertyImpDecl =
8528 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
8529 Dynamic = true;
8530 else
8531 SynthesizePID = PropertyImpDecl;
8532 }
8533
8534 // FIXME: This is not very efficient.
8535 std::string S = "T";
8536
8537 // Encode result type.
8538 // GCC has some special rules regarding encoding of properties which
8539 // closely resembles encoding of ivars.
8541
8542 if (PD->isOptional())
8543 S += ",?";
8544
8545 if (PD->isReadOnly()) {
8546 S += ",R";
8548 S += ",C";
8550 S += ",&";
8552 S += ",W";
8553 } else {
8554 switch (PD->getSetterKind()) {
8555 case ObjCPropertyDecl::Assign: break;
8556 case ObjCPropertyDecl::Copy: S += ",C"; break;
8557 case ObjCPropertyDecl::Retain: S += ",&"; break;
8558 case ObjCPropertyDecl::Weak: S += ",W"; break;
8559 }
8560 }
8561
8562 // It really isn't clear at all what this means, since properties
8563 // are "dynamic by default".
8564 if (Dynamic)
8565 S += ",D";
8566
8568 S += ",N";
8569
8571 S += ",G";
8572 S += PD->getGetterName().getAsString();
8573 }
8574
8576 S += ",S";
8577 S += PD->getSetterName().getAsString();
8578 }
8579
8580 if (SynthesizePID) {
8581 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
8582 S += ",V";
8583 S += OID->getNameAsString();
8584 }
8585
8586 // FIXME: OBJCGC: weak & strong
8587 return S;
8588}
8589
8590/// getLegacyIntegralTypeEncoding -
8591/// Another legacy compatibility encoding: 32-bit longs are encoded as
8592/// 'l' or 'L' , but not always. For typedefs, we need to use
8593/// 'i' or 'I' instead if encoding a struct field, or a pointer!
8595 if (PointeeTy->getAs<TypedefType>()) {
8596 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
8597 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
8598 PointeeTy = UnsignedIntTy;
8599 else
8600 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
8601 PointeeTy = IntTy;
8602 }
8603 }
8604}
8605
8607 const FieldDecl *Field,
8608 QualType *NotEncodedT) const {
8609 // We follow the behavior of gcc, expanding structures which are
8610 // directly pointed to, and expanding embedded structures. Note that
8611 // these rules are sufficient to prevent recursive encoding of the
8612 // same type.
8613 getObjCEncodingForTypeImpl(T, S,
8614 ObjCEncOptions()
8615 .setExpandPointedToStructures()
8616 .setExpandStructures()
8617 .setIsOutermostType(),
8618 Field, NotEncodedT);
8619}
8620
8622 std::string& S) const {
8623 // Encode result type.
8624 // GCC has some special rules regarding encoding of properties which
8625 // closely resembles encoding of ivars.
8626 getObjCEncodingForTypeImpl(T, S,
8627 ObjCEncOptions()
8628 .setExpandPointedToStructures()
8629 .setExpandStructures()
8630 .setIsOutermostType()
8631 .setEncodingProperty(),
8632 /*Field=*/nullptr);
8633}
8634
8636 const BuiltinType *BT) {
8637 BuiltinType::Kind kind = BT->getKind();
8638 switch (kind) {
8639 case BuiltinType::Void: return 'v';
8640 case BuiltinType::Bool: return 'B';
8641 case BuiltinType::Char8:
8642 case BuiltinType::Char_U:
8643 case BuiltinType::UChar: return 'C';
8644 case BuiltinType::Char16:
8645 case BuiltinType::UShort: return 'S';
8646 case BuiltinType::Char32:
8647 case BuiltinType::UInt: return 'I';
8648 case BuiltinType::ULong:
8649 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
8650 case BuiltinType::UInt128: return 'T';
8651 case BuiltinType::ULongLong: return 'Q';
8652 case BuiltinType::Char_S:
8653 case BuiltinType::SChar: return 'c';
8654 case BuiltinType::Short: return 's';
8655 case BuiltinType::WChar_S:
8656 case BuiltinType::WChar_U:
8657 case BuiltinType::Int: return 'i';
8658 case BuiltinType::Long:
8659 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
8660 case BuiltinType::LongLong: return 'q';
8661 case BuiltinType::Int128: return 't';
8662 case BuiltinType::Float: return 'f';
8663 case BuiltinType::Double: return 'd';
8664 case BuiltinType::LongDouble: return 'D';
8665 case BuiltinType::NullPtr: return '*'; // like char*
8666
8667 case BuiltinType::BFloat16:
8668 case BuiltinType::Float16:
8669 case BuiltinType::Float128:
8670 case BuiltinType::Ibm128:
8671 case BuiltinType::Half:
8672 case BuiltinType::ShortAccum:
8673 case BuiltinType::Accum:
8674 case BuiltinType::LongAccum:
8675 case BuiltinType::UShortAccum:
8676 case BuiltinType::UAccum:
8677 case BuiltinType::ULongAccum:
8678 case BuiltinType::ShortFract:
8679 case BuiltinType::Fract:
8680 case BuiltinType::LongFract:
8681 case BuiltinType::UShortFract:
8682 case BuiltinType::UFract:
8683 case BuiltinType::ULongFract:
8684 case BuiltinType::SatShortAccum:
8685 case BuiltinType::SatAccum:
8686 case BuiltinType::SatLongAccum:
8687 case BuiltinType::SatUShortAccum:
8688 case BuiltinType::SatUAccum:
8689 case BuiltinType::SatULongAccum:
8690 case BuiltinType::SatShortFract:
8691 case BuiltinType::SatFract:
8692 case BuiltinType::SatLongFract:
8693 case BuiltinType::SatUShortFract:
8694 case BuiltinType::SatUFract:
8695 case BuiltinType::SatULongFract:
8696 // FIXME: potentially need @encodes for these!
8697 return ' ';
8698
8699#define SVE_TYPE(Name, Id, SingletonId) \
8700 case BuiltinType::Id:
8701#include "clang/Basic/AArch64SVEACLETypes.def"
8702#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
8703#include "clang/Basic/RISCVVTypes.def"
8704#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
8705#include "clang/Basic/WebAssemblyReferenceTypes.def"
8706#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
8707#include "clang/Basic/AMDGPUTypes.def"
8708 {
8709 DiagnosticsEngine &Diags = C->getDiagnostics();
8710 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
8711 "cannot yet @encode type %0");
8712 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
8713 return ' ';
8714 }
8715
8716 case BuiltinType::ObjCId:
8717 case BuiltinType::ObjCClass:
8718 case BuiltinType::ObjCSel:
8719 llvm_unreachable("@encoding ObjC primitive type");
8720
8721 // OpenCL and placeholder types don't need @encodings.
8722#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8723 case BuiltinType::Id:
8724#include "clang/Basic/OpenCLImageTypes.def"
8725#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
8726 case BuiltinType::Id:
8727#include "clang/Basic/OpenCLExtensionTypes.def"
8728 case BuiltinType::OCLEvent:
8729 case BuiltinType::OCLClkEvent:
8730 case BuiltinType::OCLQueue:
8731 case BuiltinType::OCLReserveID:
8732 case BuiltinType::OCLSampler:
8733 case BuiltinType::Dependent:
8734#define PPC_VECTOR_TYPE(Name, Id, Size) \
8735 case BuiltinType::Id:
8736#include "clang/Basic/PPCTypes.def"
8737#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
8738#include "clang/Basic/HLSLIntangibleTypes.def"
8739#define BUILTIN_TYPE(KIND, ID)
8740#define PLACEHOLDER_TYPE(KIND, ID) \
8741 case BuiltinType::KIND:
8742#include "clang/AST/BuiltinTypes.def"
8743 llvm_unreachable("invalid builtin type for @encode");
8744 }
8745 llvm_unreachable("invalid BuiltinType::Kind value");
8746}
8747
8748static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
8749 EnumDecl *Enum = ET->getDecl();
8750
8751 // The encoding of an non-fixed enum type is always 'i', regardless of size.
8752 if (!Enum->isFixed())
8753 return 'i';
8754
8755 // The encoding of a fixed enum type matches its fixed underlying type.
8756 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
8758}
8759
8760static void EncodeBitField(const ASTContext *Ctx, std::string& S,
8761 QualType T, const FieldDecl *FD) {
8762 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
8763 S += 'b';
8764 // The NeXT runtime encodes bit fields as b followed by the number of bits.
8765 // The GNU runtime requires more information; bitfields are encoded as b,
8766 // then the offset (in bits) of the first element, then the type of the
8767 // bitfield, then the size in bits. For example, in this structure:
8768 //
8769 // struct
8770 // {
8771 // int integer;
8772 // int flags:2;
8773 // };
8774 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
8775 // runtime, but b32i2 for the GNU runtime. The reason for this extra
8776 // information is not especially sensible, but we're stuck with it for
8777 // compatibility with GCC, although providing it breaks anything that
8778 // actually uses runtime introspection and wants to work on both runtimes...
8779 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
8780 uint64_t Offset;
8781
8782 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
8783 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
8784 IVD);
8785 } else {
8786 const RecordDecl *RD = FD->getParent();
8787 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
8788 Offset = RL.getFieldOffset(FD->getFieldIndex());
8789 }
8790
8791 S += llvm::utostr(Offset);
8792
8793 if (const auto *ET = T->getAs<EnumType>())
8794 S += ObjCEncodingForEnumType(Ctx, ET);
8795 else {
8796 const auto *BT = T->castAs<BuiltinType>();
8797 S += getObjCEncodingForPrimitiveType(Ctx, BT);
8798 }
8799 }
8800 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
8801}
8802
8803// Helper function for determining whether the encoded type string would include
8804// a template specialization type.
8806 bool VisitBasesAndFields) {
8808
8809 if (auto *PT = T->getAs<PointerType>())
8811 PT->getPointeeType().getTypePtr(), false);
8812
8813 auto *CXXRD = T->getAsCXXRecordDecl();
8814
8815 if (!CXXRD)
8816 return false;
8817
8818 if (isa<ClassTemplateSpecializationDecl>(CXXRD))
8819 return true;
8820
8821 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
8822 return false;
8823
8824 for (const auto &B : CXXRD->bases())
8825 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
8826 true))
8827 return true;
8828
8829 for (auto *FD : CXXRD->fields())
8830 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
8831 true))
8832 return true;
8833
8834 return false;
8835}
8836
8837// FIXME: Use SmallString for accumulating string.
8838void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
8839 const ObjCEncOptions Options,
8840 const FieldDecl *FD,
8841 QualType *NotEncodedT) const {
8843 switch (CT->getTypeClass()) {
8844 case Type::Builtin:
8845 case Type::Enum:
8846 if (FD && FD->isBitField())
8847 return EncodeBitField(this, S, T, FD);
8848 if (const auto *BT = dyn_cast<BuiltinType>(CT))
8849 S += getObjCEncodingForPrimitiveType(this, BT);
8850 else
8851 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
8852 return;
8853
8854 case Type::Complex:
8855 S += 'j';
8856 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
8857 ObjCEncOptions(),
8858 /*Field=*/nullptr);
8859 return;
8860
8861 case Type::Atomic:
8862 S += 'A';
8863 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
8864 ObjCEncOptions(),
8865 /*Field=*/nullptr);
8866 return;
8867
8868 // encoding for pointer or reference types.
8869 case Type::Pointer:
8870 case Type::LValueReference:
8871 case Type::RValueReference: {
8872 QualType PointeeTy;
8873 if (isa<PointerType>(CT)) {
8874 const auto *PT = T->castAs<PointerType>();
8875 if (PT->isObjCSelType()) {
8876 S += ':';
8877 return;
8878 }
8879 PointeeTy = PT->getPointeeType();
8880 } else {
8881 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
8882 }
8883
8884 bool isReadOnly = false;
8885 // For historical/compatibility reasons, the read-only qualifier of the
8886 // pointee gets emitted _before_ the '^'. The read-only qualifier of
8887 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
8888 // Also, do not emit the 'r' for anything but the outermost type!
8889 if (T->getAs<TypedefType>()) {
8890 if (Options.IsOutermostType() && T.isConstQualified()) {
8891 isReadOnly = true;
8892 S += 'r';
8893 }
8894 } else if (Options.IsOutermostType()) {
8895 QualType P = PointeeTy;
8896 while (auto PT = P->getAs<PointerType>())
8897 P = PT->getPointeeType();
8898 if (P.isConstQualified()) {
8899 isReadOnly = true;
8900 S += 'r';
8901 }
8902 }
8903 if (isReadOnly) {
8904 // Another legacy compatibility encoding. Some ObjC qualifier and type
8905 // combinations need to be rearranged.
8906 // Rewrite "in const" from "nr" to "rn"
8907 if (StringRef(S).ends_with("nr"))
8908 S.replace(S.end()-2, S.end(), "rn");
8909 }
8910
8911 if (PointeeTy->isCharType()) {
8912 // char pointer types should be encoded as '*' unless it is a
8913 // type that has been typedef'd to 'BOOL'.
8914 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
8915 S += '*';
8916 return;
8917 }
8918 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
8919 // GCC binary compat: Need to convert "struct objc_class *" to "#".
8920 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
8921 S += '#';
8922 return;
8923 }
8924 // GCC binary compat: Need to convert "struct objc_object *" to "@".
8925 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
8926 S += '@';
8927 return;
8928 }
8929 // If the encoded string for the class includes template names, just emit
8930 // "^v" for pointers to the class.
8931 if (getLangOpts().CPlusPlus &&
8932 (!getLangOpts().EncodeCXXClassTemplateSpec &&
8934 RTy, Options.ExpandPointedToStructures()))) {
8935 S += "^v";
8936 return;
8937 }
8938 // fall through...
8939 }
8940 S += '^';
8942
8943 ObjCEncOptions NewOptions;
8944 if (Options.ExpandPointedToStructures())
8945 NewOptions.setExpandStructures();
8946 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
8947 /*Field=*/nullptr, NotEncodedT);
8948 return;
8949 }
8950
8951 case Type::ConstantArray:
8952 case Type::IncompleteArray:
8953 case Type::VariableArray: {
8954 const auto *AT = cast<ArrayType>(CT);
8955
8956 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
8957 // Incomplete arrays are encoded as a pointer to the array element.
8958 S += '^';
8959
8960 getObjCEncodingForTypeImpl(
8961 AT->getElementType(), S,
8962 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
8963 } else {
8964 S += '[';
8965
8966 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
8967 S += llvm::utostr(CAT->getZExtSize());
8968 else {
8969 //Variable length arrays are encoded as a regular array with 0 elements.
8970 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
8971 "Unknown array type!");
8972 S += '0';
8973 }
8974
8975 getObjCEncodingForTypeImpl(
8976 AT->getElementType(), S,
8977 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
8978 NotEncodedT);
8979 S += ']';
8980 }
8981 return;
8982 }
8983
8984 case Type::FunctionNoProto:
8985 case Type::FunctionProto:
8986 S += '?';
8987 return;
8988
8989 case Type::Record: {
8990 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
8991 S += RDecl->isUnion() ? '(' : '{';
8992 // Anonymous structures print as '?'
8993 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
8994 S += II->getName();
8995 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
8996 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
8997 llvm::raw_string_ostream OS(S);
8998 printTemplateArgumentList(OS, TemplateArgs.asArray(),
9000 }
9001 } else {
9002 S += '?';
9003 }
9004 if (Options.ExpandStructures()) {
9005 S += '=';
9006 if (!RDecl->isUnion()) {
9007 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
9008 } else {
9009 for (const auto *Field : RDecl->fields()) {
9010 if (FD) {
9011 S += '"';
9012 S += Field->getNameAsString();
9013 S += '"';
9014 }
9015
9016 // Special case bit-fields.
9017 if (Field->isBitField()) {
9018 getObjCEncodingForTypeImpl(Field->getType(), S,
9019 ObjCEncOptions().setExpandStructures(),
9020 Field);
9021 } else {
9022 QualType qt = Field->getType();
9024 getObjCEncodingForTypeImpl(
9025 qt, S,
9026 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
9027 NotEncodedT);
9028 }
9029 }
9030 }
9031 }
9032 S += RDecl->isUnion() ? ')' : '}';
9033 return;
9034 }
9035
9036 case Type::BlockPointer: {
9037 const auto *BT = T->castAs<BlockPointerType>();
9038 S += "@?"; // Unlike a pointer-to-function, which is "^?".
9039 if (Options.EncodeBlockParameters()) {
9040 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
9041
9042 S += '<';
9043 // Block return type
9044 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
9045 Options.forComponentType(), FD, NotEncodedT);
9046 // Block self
9047 S += "@?";
9048 // Block parameters
9049 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
9050 for (const auto &I : FPT->param_types())
9051 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
9052 NotEncodedT);
9053 }
9054 S += '>';
9055 }
9056 return;
9057 }
9058
9059 case Type::ObjCObject: {
9060 // hack to match legacy encoding of *id and *Class
9062 if (Ty->isObjCIdType()) {
9063 S += "{objc_object=}";
9064 return;
9065 }
9066 else if (Ty->isObjCClassType()) {
9067 S += "{objc_class=}";
9068 return;
9069 }
9070 // TODO: Double check to make sure this intentionally falls through.
9071 [[fallthrough]];
9072 }
9073
9074 case Type::ObjCInterface: {
9075 // Ignore protocol qualifiers when mangling at this level.
9076 // @encode(class_name)
9077 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
9078 S += '{';
9079 S += OI->getObjCRuntimeNameAsString();
9080 if (Options.ExpandStructures()) {
9081 S += '=';
9083 DeepCollectObjCIvars(OI, true, Ivars);
9084 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
9085 const FieldDecl *Field = Ivars[i];
9086 if (Field->isBitField())
9087 getObjCEncodingForTypeImpl(Field->getType(), S,
9088 ObjCEncOptions().setExpandStructures(),
9089 Field);
9090 else
9091 getObjCEncodingForTypeImpl(Field->getType(), S,
9092 ObjCEncOptions().setExpandStructures(), FD,
9093 NotEncodedT);
9094 }
9095 }
9096 S += '}';
9097 return;
9098 }
9099
9100 case Type::ObjCObjectPointer: {
9101 const auto *OPT = T->castAs<ObjCObjectPointerType>();
9102 if (OPT->isObjCIdType()) {
9103 S += '@';
9104 return;
9105 }
9106
9107 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
9108 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
9109 // Since this is a binary compatibility issue, need to consult with
9110 // runtime folks. Fortunately, this is a *very* obscure construct.
9111 S += '#';
9112 return;
9113 }
9114
9115 if (OPT->isObjCQualifiedIdType()) {
9116 getObjCEncodingForTypeImpl(
9117 getObjCIdType(), S,
9118 Options.keepingOnly(ObjCEncOptions()
9119 .setExpandPointedToStructures()
9120 .setExpandStructures()),
9121 FD);
9122 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
9123 // Note that we do extended encoding of protocol qualifier list
9124 // Only when doing ivar or property encoding.
9125 S += '"';
9126 for (const auto *I : OPT->quals()) {
9127 S += '<';
9128 S += I->getObjCRuntimeNameAsString();
9129 S += '>';
9130 }
9131 S += '"';
9132 }
9133 return;
9134 }
9135
9136 S += '@';
9137 if (OPT->getInterfaceDecl() &&
9138 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
9139 S += '"';
9140 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
9141 for (const auto *I : OPT->quals()) {
9142 S += '<';
9143 S += I->getObjCRuntimeNameAsString();
9144 S += '>';
9145 }
9146 S += '"';
9147 }
9148 return;
9149 }
9150
9151 // gcc just blithely ignores member pointers.
9152 // FIXME: we should do better than that. 'M' is available.
9153 case Type::MemberPointer:
9154 // This matches gcc's encoding, even though technically it is insufficient.
9155 //FIXME. We should do a better job than gcc.
9156 case Type::Vector:
9157 case Type::ExtVector:
9158 // Until we have a coherent encoding of these three types, issue warning.
9159 if (NotEncodedT)
9160 *NotEncodedT = T;
9161 return;
9162
9163 case Type::ConstantMatrix:
9164 if (NotEncodedT)
9165 *NotEncodedT = T;
9166 return;
9167
9168 case Type::BitInt:
9169 if (NotEncodedT)
9170 *NotEncodedT = T;
9171 return;
9172
9173 // We could see an undeduced auto type here during error recovery.
9174 // Just ignore it.
9175 case Type::Auto:
9176 case Type::DeducedTemplateSpecialization:
9177 return;
9178
9179 case Type::HLSLAttributedResource:
9180 llvm_unreachable("unexpected type");
9181
9182 case Type::ArrayParameter:
9183 case Type::Pipe:
9184#define ABSTRACT_TYPE(KIND, BASE)
9185#define TYPE(KIND, BASE)
9186#define DEPENDENT_TYPE(KIND, BASE) \
9187 case Type::KIND:
9188#define NON_CANONICAL_TYPE(KIND, BASE) \
9189 case Type::KIND:
9190#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
9191 case Type::KIND:
9192#include "clang/AST/TypeNodes.inc"
9193 llvm_unreachable("@encode for dependent type!");
9194 }
9195 llvm_unreachable("bad type kind!");
9196}
9197
9198void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
9199 std::string &S,
9200 const FieldDecl *FD,
9201 bool includeVBases,
9202 QualType *NotEncodedT) const {
9203 assert(RDecl && "Expected non-null RecordDecl");
9204 assert(!RDecl->isUnion() && "Should not be called for unions");
9205 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
9206 return;
9207
9208 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
9209 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
9210 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
9211
9212 if (CXXRec) {
9213 for (const auto &BI : CXXRec->bases()) {
9214 if (!BI.isVirtual()) {
9215 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9216 if (base->isEmpty())
9217 continue;
9218 uint64_t offs = toBits(layout.getBaseClassOffset(base));
9219 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9220 std::make_pair(offs, base));
9221 }
9222 }
9223 }
9224
9225 for (FieldDecl *Field : RDecl->fields()) {
9226 if (!Field->isZeroLengthBitField(*this) && Field->isZeroSize(*this))
9227 continue;
9228 uint64_t offs = layout.getFieldOffset(Field->getFieldIndex());
9229 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9230 std::make_pair(offs, Field));
9231 }
9232
9233 if (CXXRec && includeVBases) {
9234 for (const auto &BI : CXXRec->vbases()) {
9235 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9236 if (base->isEmpty())
9237 continue;
9238 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
9239 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
9240 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
9241 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
9242 std::make_pair(offs, base));
9243 }
9244 }
9245
9246 CharUnits size;
9247 if (CXXRec) {
9248 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
9249 } else {
9250 size = layout.getSize();
9251 }
9252
9253#ifndef NDEBUG
9254 uint64_t CurOffs = 0;
9255#endif
9256 std::multimap<uint64_t, NamedDecl *>::iterator
9257 CurLayObj = FieldOrBaseOffsets.begin();
9258
9259 if (CXXRec && CXXRec->isDynamicClass() &&
9260 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
9261 if (FD) {
9262 S += "\"_vptr$";
9263 std::string recname = CXXRec->getNameAsString();
9264 if (recname.empty()) recname = "?";
9265 S += recname;
9266 S += '"';
9267 }
9268 S += "^^?";
9269#ifndef NDEBUG
9270 CurOffs += getTypeSize(VoidPtrTy);
9271#endif
9272 }
9273
9274 if (!RDecl->hasFlexibleArrayMember()) {
9275 // Mark the end of the structure.
9276 uint64_t offs = toBits(size);
9277 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9278 std::make_pair(offs, nullptr));
9279 }
9280
9281 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
9282#ifndef NDEBUG
9283 assert(CurOffs <= CurLayObj->first);
9284 if (CurOffs < CurLayObj->first) {
9285 uint64_t padding = CurLayObj->first - CurOffs;
9286 // FIXME: There doesn't seem to be a way to indicate in the encoding that
9287 // packing/alignment of members is different that normal, in which case
9288 // the encoding will be out-of-sync with the real layout.
9289 // If the runtime switches to just consider the size of types without
9290 // taking into account alignment, we could make padding explicit in the
9291 // encoding (e.g. using arrays of chars). The encoding strings would be
9292 // longer then though.
9293 CurOffs += padding;
9294 }
9295#endif
9296
9297 NamedDecl *dcl = CurLayObj->second;
9298 if (!dcl)
9299 break; // reached end of structure.
9300
9301 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
9302 // We expand the bases without their virtual bases since those are going
9303 // in the initial structure. Note that this differs from gcc which
9304 // expands virtual bases each time one is encountered in the hierarchy,
9305 // making the encoding type bigger than it really is.
9306 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
9307 NotEncodedT);
9308 assert(!base->isEmpty());
9309#ifndef NDEBUG
9310 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
9311#endif
9312 } else {
9313 const auto *field = cast<FieldDecl>(dcl);
9314 if (FD) {
9315 S += '"';
9316 S += field->getNameAsString();
9317 S += '"';
9318 }
9319
9320 if (field->isBitField()) {
9321 EncodeBitField(this, S, field->getType(), field);
9322#ifndef NDEBUG
9323 CurOffs += field->getBitWidthValue(*this);
9324#endif
9325 } else {
9326 QualType qt = field->getType();
9328 getObjCEncodingForTypeImpl(
9329 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
9330 FD, NotEncodedT);
9331#ifndef NDEBUG
9332 CurOffs += getTypeSize(field->getType());
9333#endif
9334 }
9335 }
9336 }
9337}
9338
9340 std::string& S) const {
9341 if (QT & Decl::OBJC_TQ_In)
9342 S += 'n';
9343 if (QT & Decl::OBJC_TQ_Inout)
9344 S += 'N';
9345 if (QT & Decl::OBJC_TQ_Out)
9346 S += 'o';
9347 if (QT & Decl::OBJC_TQ_Bycopy)
9348 S += 'O';
9349 if (QT & Decl::OBJC_TQ_Byref)
9350 S += 'R';
9351 if (QT & Decl::OBJC_TQ_Oneway)
9352 S += 'V';
9353}
9354
9356 if (!ObjCIdDecl) {
9359 ObjCIdDecl = buildImplicitTypedef(T, "id");
9360 }
9361 return ObjCIdDecl;
9362}
9363
9365 if (!ObjCSelDecl) {
9367 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
9368 }
9369 return ObjCSelDecl;
9370}
9371
9373 if (!ObjCClassDecl) {
9376 ObjCClassDecl = buildImplicitTypedef(T, "Class");
9377 }
9378 return ObjCClassDecl;
9379}
9380
9382 if (!ObjCProtocolClassDecl) {
9383 ObjCProtocolClassDecl
9386 &Idents.get("Protocol"),
9387 /*typeParamList=*/nullptr,
9388 /*PrevDecl=*/nullptr,
9389 SourceLocation(), true);
9390 }
9391
9392 return ObjCProtocolClassDecl;
9393}
9394
9395//===----------------------------------------------------------------------===//
9396// __builtin_va_list Construction Functions
9397//===----------------------------------------------------------------------===//
9398
9400 StringRef Name) {
9401 // typedef char* __builtin[_ms]_va_list;
9402 QualType T = Context->getPointerType(Context->CharTy);
9403 return Context->buildImplicitTypedef(T, Name);
9404}
9405
9407 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
9408}
9409
9411 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
9412}
9413
9415 // typedef void* __builtin_va_list;
9416 QualType T = Context->getPointerType(Context->VoidTy);
9417 return Context->buildImplicitTypedef(T, "__builtin_va_list");
9418}
9419
9420static TypedefDecl *
9422 // struct __va_list
9423 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
9424 if (Context->getLangOpts().CPlusPlus) {
9425 // namespace std { struct __va_list {
9426 auto *NS = NamespaceDecl::Create(
9427 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
9428 /*Inline=*/false, SourceLocation(), SourceLocation(),
9429 &Context->Idents.get("std"),
9430 /*PrevDecl=*/nullptr, /*Nested=*/false);
9431 NS->setImplicit();
9432 VaListTagDecl->setDeclContext(NS);
9433 }
9434
9435 VaListTagDecl->startDefinition();
9436
9437 const size_t NumFields = 5;
9438 QualType FieldTypes[NumFields];
9439 const char *FieldNames[NumFields];
9440
9441 // void *__stack;
9442 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
9443 FieldNames[0] = "__stack";
9444
9445 // void *__gr_top;
9446 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
9447 FieldNames[1] = "__gr_top";
9448
9449 // void *__vr_top;
9450 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9451 FieldNames[2] = "__vr_top";
9452
9453 // int __gr_offs;
9454 FieldTypes[3] = Context->IntTy;
9455 FieldNames[3] = "__gr_offs";
9456
9457 // int __vr_offs;
9458 FieldTypes[4] = Context->IntTy;
9459 FieldNames[4] = "__vr_offs";
9460
9461 // Create fields
9462 for (unsigned i = 0; i < NumFields; ++i) {
9463 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9464 VaListTagDecl,
9467 &Context->Idents.get(FieldNames[i]),
9468 FieldTypes[i], /*TInfo=*/nullptr,
9469 /*BitWidth=*/nullptr,
9470 /*Mutable=*/false,
9471 ICIS_NoInit);
9472 Field->setAccess(AS_public);
9473 VaListTagDecl->addDecl(Field);
9474 }
9475 VaListTagDecl->completeDefinition();
9476 Context->VaListTagDecl = VaListTagDecl;
9477 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9478
9479 // } __builtin_va_list;
9480 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
9481}
9482
9484 // typedef struct __va_list_tag {
9485 RecordDecl *VaListTagDecl;
9486
9487 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9488 VaListTagDecl->startDefinition();
9489
9490 const size_t NumFields = 5;
9491 QualType FieldTypes[NumFields];
9492 const char *FieldNames[NumFields];
9493
9494 // unsigned char gpr;
9495 FieldTypes[0] = Context->UnsignedCharTy;
9496 FieldNames[0] = "gpr";
9497
9498 // unsigned char fpr;
9499 FieldTypes[1] = Context->UnsignedCharTy;
9500 FieldNames[1] = "fpr";
9501
9502 // unsigned short reserved;
9503 FieldTypes[2] = Context->UnsignedShortTy;
9504 FieldNames[2] = "reserved";
9505
9506 // void* overflow_arg_area;
9507 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
9508 FieldNames[3] = "overflow_arg_area";
9509
9510 // void* reg_save_area;
9511 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
9512 FieldNames[4] = "reg_save_area";
9513
9514 // Create fields
9515 for (unsigned i = 0; i < NumFields; ++i) {
9516 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
9519 &Context->Idents.get(FieldNames[i]),
9520 FieldTypes[i], /*TInfo=*/nullptr,
9521 /*BitWidth=*/nullptr,
9522 /*Mutable=*/false,
9523 ICIS_NoInit);
9524 Field->setAccess(AS_public);
9525 VaListTagDecl->addDecl(Field);
9526 }
9527 VaListTagDecl->completeDefinition();
9528 Context->VaListTagDecl = VaListTagDecl;
9529 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9530
9531 // } __va_list_tag;
9532 TypedefDecl *VaListTagTypedefDecl =
9533 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
9534
9535 QualType VaListTagTypedefType =
9536 Context->getTypedefType(VaListTagTypedefDecl);
9537
9538 // typedef __va_list_tag __builtin_va_list[1];
9539 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9540 QualType VaListTagArrayType = Context->getConstantArrayType(
9541 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
9542 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9543}
9544
9545static TypedefDecl *
9547 // struct __va_list_tag {
9548 RecordDecl *VaListTagDecl;
9549 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9550 VaListTagDecl->startDefinition();
9551
9552 const size_t NumFields = 4;
9553 QualType FieldTypes[NumFields];
9554 const char *FieldNames[NumFields];
9555
9556 // unsigned gp_offset;
9557 FieldTypes[0] = Context->UnsignedIntTy;
9558 FieldNames[0] = "gp_offset";
9559
9560 // unsigned fp_offset;
9561 FieldTypes[1] = Context->UnsignedIntTy;
9562 FieldNames[1] = "fp_offset";
9563
9564 // void* overflow_arg_area;
9565 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9566 FieldNames[2] = "overflow_arg_area";
9567
9568 // void* reg_save_area;
9569 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
9570 FieldNames[3] = "reg_save_area";
9571
9572 // Create fields
9573 for (unsigned i = 0; i < NumFields; ++i) {
9574 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9575 VaListTagDecl,
9578 &Context->Idents.get(FieldNames[i]),
9579 FieldTypes[i], /*TInfo=*/nullptr,
9580 /*BitWidth=*/nullptr,
9581 /*Mutable=*/false,
9582 ICIS_NoInit);
9583 Field->setAccess(AS_public);
9584 VaListTagDecl->addDecl(Field);
9585 }
9586 VaListTagDecl->completeDefinition();
9587 Context->VaListTagDecl = VaListTagDecl;
9588 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9589
9590 // };
9591
9592 // typedef struct __va_list_tag __builtin_va_list[1];
9593 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9594 QualType VaListTagArrayType = Context->getConstantArrayType(
9595 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
9596 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9597}
9598
9600 // typedef int __builtin_va_list[4];
9601 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
9602 QualType IntArrayType = Context->getConstantArrayType(
9603 Context->IntTy, Size, nullptr, ArraySizeModifier::Normal, 0);
9604 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
9605}
9606
9607static TypedefDecl *
9609 // struct __va_list
9610 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
9611 if (Context->getLangOpts().CPlusPlus) {
9612 // namespace std { struct __va_list {
9613 NamespaceDecl *NS;
9614 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
9615 Context->getTranslationUnitDecl(),
9616 /*Inline=*/false, SourceLocation(),
9617 SourceLocation(), &Context->Idents.get("std"),
9618 /*PrevDecl=*/nullptr, /*Nested=*/false);
9619 NS->setImplicit();
9620 VaListDecl->setDeclContext(NS);
9621 }
9622
9623 VaListDecl->startDefinition();
9624
9625 // void * __ap;
9626 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9627 VaListDecl,
9630 &Context->Idents.get("__ap"),
9631 Context->getPointerType(Context->VoidTy),
9632 /*TInfo=*/nullptr,
9633 /*BitWidth=*/nullptr,
9634 /*Mutable=*/false,
9635 ICIS_NoInit);
9636 Field->setAccess(AS_public);
9637 VaListDecl->addDecl(Field);
9638
9639 // };
9640 VaListDecl->completeDefinition();
9641 Context->VaListTagDecl = VaListDecl;
9642
9643 // typedef struct __va_list __builtin_va_list;
9644 QualType T = Context->getRecordType(VaListDecl);
9645 return Context->buildImplicitTypedef(T, "__builtin_va_list");
9646}
9647
9648static TypedefDecl *
9650 // struct __va_list_tag {
9651 RecordDecl *VaListTagDecl;
9652 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9653 VaListTagDecl->startDefinition();
9654
9655 const size_t NumFields = 4;
9656 QualType FieldTypes[NumFields];
9657 const char *FieldNames[NumFields];
9658
9659 // long __gpr;
9660 FieldTypes[0] = Context->LongTy;
9661 FieldNames[0] = "__gpr";
9662
9663 // long __fpr;
9664 FieldTypes[1] = Context->LongTy;
9665 FieldNames[1] = "__fpr";
9666
9667 // void *__overflow_arg_area;
9668 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9669 FieldNames[2] = "__overflow_arg_area";
9670
9671 // void *__reg_save_area;
9672 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
9673 FieldNames[3] = "__reg_save_area";
9674
9675 // Create fields
9676 for (unsigned i = 0; i < NumFields; ++i) {
9677 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9678 VaListTagDecl,
9681 &Context->Idents.get(FieldNames[i]),
9682 FieldTypes[i], /*TInfo=*/nullptr,
9683 /*BitWidth=*/nullptr,
9684 /*Mutable=*/false,
9685 ICIS_NoInit);
9686 Field->setAccess(AS_public);
9687 VaListTagDecl->addDecl(Field);
9688 }
9689 VaListTagDecl->completeDefinition();
9690 Context->VaListTagDecl = VaListTagDecl;
9691 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9692
9693 // };
9694
9695 // typedef __va_list_tag __builtin_va_list[1];
9696 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9697 QualType VaListTagArrayType = Context->getConstantArrayType(
9698 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
9699
9700 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9701}
9702
9704 // typedef struct __va_list_tag {
9705 RecordDecl *VaListTagDecl;
9706 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9707 VaListTagDecl->startDefinition();
9708
9709 const size_t NumFields = 3;
9710 QualType FieldTypes[NumFields];
9711 const char *FieldNames[NumFields];
9712
9713 // void *CurrentSavedRegisterArea;
9714 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
9715 FieldNames[0] = "__current_saved_reg_area_pointer";
9716
9717 // void *SavedRegAreaEnd;
9718 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
9719 FieldNames[1] = "__saved_reg_area_end_pointer";
9720
9721 // void *OverflowArea;
9722 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9723 FieldNames[2] = "__overflow_area_pointer";
9724
9725 // Create fields
9726 for (unsigned i = 0; i < NumFields; ++i) {
9728 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
9729 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
9730 /*TInfo=*/nullptr,
9731 /*BitWidth=*/nullptr,
9732 /*Mutable=*/false, ICIS_NoInit);
9733 Field->setAccess(AS_public);
9734 VaListTagDecl->addDecl(Field);
9735 }
9736 VaListTagDecl->completeDefinition();
9737 Context->VaListTagDecl = VaListTagDecl;
9738 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9739
9740 // } __va_list_tag;
9741 TypedefDecl *VaListTagTypedefDecl =
9742 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
9743
9744 QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl);
9745
9746 // typedef __va_list_tag __builtin_va_list[1];
9747 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9748 QualType VaListTagArrayType = Context->getConstantArrayType(
9749 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
9750
9751 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9752}
9753
9754static TypedefDecl *
9756 // typedef struct __va_list_tag {
9757 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9758
9759 VaListTagDecl->startDefinition();
9760
9761 // int* __va_stk;
9762 // int* __va_reg;
9763 // int __va_ndx;
9764 constexpr size_t NumFields = 3;
9765 QualType FieldTypes[NumFields] = {Context->getPointerType(Context->IntTy),
9766 Context->getPointerType(Context->IntTy),
9767 Context->IntTy};
9768 const char *FieldNames[NumFields] = {"__va_stk", "__va_reg", "__va_ndx"};
9769
9770 // Create fields
9771 for (unsigned i = 0; i < NumFields; ++i) {
9773 *Context, VaListTagDecl, SourceLocation(), SourceLocation(),
9774 &Context->Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
9775 /*BitWidth=*/nullptr,
9776 /*Mutable=*/false, ICIS_NoInit);
9777 Field->setAccess(AS_public);
9778 VaListTagDecl->addDecl(Field);
9779 }
9780 VaListTagDecl->completeDefinition();
9781 Context->VaListTagDecl = VaListTagDecl;
9782 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9783
9784 // } __va_list_tag;
9785 TypedefDecl *VaListTagTypedefDecl =
9786 Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
9787
9788 return VaListTagTypedefDecl;
9789}
9790
9793 switch (Kind) {
9795 return CreateCharPtrBuiltinVaListDecl(Context);
9797 return CreateVoidPtrBuiltinVaListDecl(Context);
9799 return CreateAArch64ABIBuiltinVaListDecl(Context);
9801 return CreatePowerABIBuiltinVaListDecl(Context);
9803 return CreateX86_64ABIBuiltinVaListDecl(Context);
9805 return CreatePNaClABIBuiltinVaListDecl(Context);
9807 return CreateAAPCSABIBuiltinVaListDecl(Context);
9809 return CreateSystemZBuiltinVaListDecl(Context);
9811 return CreateHexagonBuiltinVaListDecl(Context);
9813 return CreateXtensaABIBuiltinVaListDecl(Context);
9814 }
9815
9816 llvm_unreachable("Unhandled __builtin_va_list type kind");
9817}
9818
9820 if (!BuiltinVaListDecl) {
9821 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
9822 assert(BuiltinVaListDecl->isImplicit());
9823 }
9824
9825 return BuiltinVaListDecl;
9826}
9827
9829 // Force the creation of VaListTagDecl by building the __builtin_va_list
9830 // declaration.
9831 if (!VaListTagDecl)
9832 (void)getBuiltinVaListDecl();
9833
9834 return VaListTagDecl;
9835}
9836
9838 if (!BuiltinMSVaListDecl)
9839 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
9840
9841 return BuiltinMSVaListDecl;
9842}
9843
9845 // Allow redecl custom type checking builtin for HLSL.
9846 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
9848 return true;
9850}
9851
9853 assert(ObjCConstantStringType.isNull() &&
9854 "'NSConstantString' type already set!");
9855
9856 ObjCConstantStringType = getObjCInterfaceType(Decl);
9857}
9858
9859/// Retrieve the template name that corresponds to a non-empty
9860/// lookup.
9863 UnresolvedSetIterator End) const {
9864 unsigned size = End - Begin;
9865 assert(size > 1 && "set is not overloaded!");
9866
9867 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
9868 size * sizeof(FunctionTemplateDecl*));
9869 auto *OT = new (memory) OverloadedTemplateStorage(size);
9870
9871 NamedDecl **Storage = OT->getStorage();
9872 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
9873 NamedDecl *D = *I;
9874 assert(isa<FunctionTemplateDecl>(D) ||
9875 isa<UnresolvedUsingValueDecl>(D) ||
9876 (isa<UsingShadowDecl>(D) &&
9877 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
9878 *Storage++ = D;
9879 }
9880
9881 return TemplateName(OT);
9882}
9883
9884/// Retrieve a template name representing an unqualified-id that has been
9885/// assumed to name a template for ADL purposes.
9887 auto *OT = new (*this) AssumedTemplateStorage(Name);
9888 return TemplateName(OT);
9889}
9890
9891/// Retrieve the template name that represents a qualified
9892/// template name such as \c std::vector.
9894 bool TemplateKeyword,
9895 TemplateName Template) const {
9896 assert(Template.getKind() == TemplateName::Template ||
9897 Template.getKind() == TemplateName::UsingTemplate);
9898
9899 // FIXME: Canonicalization?
9900 llvm::FoldingSetNodeID ID;
9901 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
9902
9903 void *InsertPos = nullptr;
9905 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9906 if (!QTN) {
9907 QTN = new (*this, alignof(QualifiedTemplateName))
9908 QualifiedTemplateName(NNS, TemplateKeyword, Template);
9909 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
9910 }
9911
9912 return TemplateName(QTN);
9913}
9914
9915/// Retrieve the template name that represents a dependent
9916/// template name such as \c MetaFun::template apply.
9919 const IdentifierInfo *Name) const {
9920 assert((!NNS || NNS->isDependent()) &&
9921 "Nested name specifier must be dependent");
9922
9923 llvm::FoldingSetNodeID ID;
9924 DependentTemplateName::Profile(ID, NNS, Name);
9925
9926 void *InsertPos = nullptr;
9928 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9929
9930 if (QTN)
9931 return TemplateName(QTN);
9932
9934 if (CanonNNS == NNS) {
9935 QTN = new (*this, alignof(DependentTemplateName))
9936 DependentTemplateName(NNS, Name);
9937 } else {
9938 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
9939 QTN = new (*this, alignof(DependentTemplateName))
9940 DependentTemplateName(NNS, Name, Canon);
9941 DependentTemplateName *CheckQTN =
9942 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9943 assert(!CheckQTN && "Dependent type name canonicalization broken");
9944 (void)CheckQTN;
9945 }
9946
9947 DependentTemplateNames.InsertNode(QTN, InsertPos);
9948 return TemplateName(QTN);
9949}
9950
9951/// Retrieve the template name that represents a dependent
9952/// template name such as \c MetaFun::template operator+.
9955 OverloadedOperatorKind Operator) const {
9956 assert((!NNS || NNS->isDependent()) &&
9957 "Nested name specifier must be dependent");
9958
9959 llvm::FoldingSetNodeID ID;
9960 DependentTemplateName::Profile(ID, NNS, Operator);
9961
9962 void *InsertPos = nullptr;
9964 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9965
9966 if (QTN)
9967 return TemplateName(QTN);
9968
9970 if (CanonNNS == NNS) {
9971 QTN = new (*this, alignof(DependentTemplateName))
9972 DependentTemplateName(NNS, Operator);
9973 } else {
9974 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
9975 QTN = new (*this, alignof(DependentTemplateName))
9976 DependentTemplateName(NNS, Operator, Canon);
9977
9978 DependentTemplateName *CheckQTN
9979 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9980 assert(!CheckQTN && "Dependent template name canonicalization broken");
9981 (void)CheckQTN;
9982 }
9983
9984 DependentTemplateNames.InsertNode(QTN, InsertPos);
9985 return TemplateName(QTN);
9986}
9987
9989 TemplateName Replacement, Decl *AssociatedDecl, unsigned Index,
9990 std::optional<unsigned> PackIndex) const {
9991 llvm::FoldingSetNodeID ID;
9992 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
9993 Index, PackIndex);
9994
9995 void *insertPos = nullptr;
9997 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
9998
9999 if (!subst) {
10000 subst = new (*this) SubstTemplateTemplateParmStorage(
10001 Replacement, AssociatedDecl, Index, PackIndex);
10002 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
10003 }
10004
10005 return TemplateName(subst);
10006}
10007
10010 Decl *AssociatedDecl,
10011 unsigned Index, bool Final) const {
10012 auto &Self = const_cast<ASTContext &>(*this);
10013 llvm::FoldingSetNodeID ID;
10015 AssociatedDecl, Index, Final);
10016
10017 void *InsertPos = nullptr;
10019 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
10020
10021 if (!Subst) {
10022 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
10023 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
10024 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
10025 }
10026
10027 return TemplateName(Subst);
10028}
10029
10030/// Retrieve the template name that represents a template name
10031/// deduced from a specialization.
10034 DefaultArguments DefaultArgs) const {
10035 if (!DefaultArgs)
10036 return Underlying;
10037
10038 llvm::FoldingSetNodeID ID;
10039 DeducedTemplateStorage::Profile(ID, *this, Underlying, DefaultArgs);
10040
10041 void *InsertPos = nullptr;
10043 DeducedTemplates.FindNodeOrInsertPos(ID, InsertPos);
10044 if (!DTS) {
10045 void *Mem = Allocate(sizeof(DeducedTemplateStorage) +
10046 sizeof(TemplateArgument) * DefaultArgs.Args.size(),
10047 alignof(DeducedTemplateStorage));
10048 DTS = new (Mem) DeducedTemplateStorage(Underlying, DefaultArgs);
10049 DeducedTemplates.InsertNode(DTS, InsertPos);
10050 }
10051 return TemplateName(DTS);
10052}
10053
10054/// getFromTargetType - Given one of the integer types provided by
10055/// TargetInfo, produce the corresponding type. The unsigned @p Type
10056/// is actually a value of type @c TargetInfo::IntType.
10057CanQualType ASTContext::getFromTargetType(unsigned Type) const {
10058 switch (Type) {
10059 case TargetInfo::NoInt: return {};
10062 case TargetInfo::SignedShort: return ShortTy;
10064 case TargetInfo::SignedInt: return IntTy;
10066 case TargetInfo::SignedLong: return LongTy;
10070 }
10071
10072 llvm_unreachable("Unhandled TargetInfo::IntType value");
10073}
10074
10075//===----------------------------------------------------------------------===//
10076// Type Predicates.
10077//===----------------------------------------------------------------------===//
10078
10079/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
10080/// garbage collection attribute.
10081///
10083 if (getLangOpts().getGC() == LangOptions::NonGC)
10084 return Qualifiers::GCNone;
10085
10086 assert(getLangOpts().ObjC);
10087 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
10088
10089 // Default behaviour under objective-C's gc is for ObjC pointers
10090 // (or pointers to them) be treated as though they were declared
10091 // as __strong.
10092 if (GCAttrs == Qualifiers::GCNone) {
10094 return Qualifiers::Strong;
10095 else if (Ty->isPointerType())
10097 } else {
10098 // It's not valid to set GC attributes on anything that isn't a
10099 // pointer.
10100#ifndef NDEBUG
10102 while (const auto *AT = dyn_cast<ArrayType>(CT))
10103 CT = AT->getElementType();
10104 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
10105#endif
10106 }
10107 return GCAttrs;
10108}
10109
10110//===----------------------------------------------------------------------===//
10111// Type Compatibility Testing
10112//===----------------------------------------------------------------------===//
10113
10114/// areCompatVectorTypes - Return true if the two specified vector types are
10115/// compatible.
10116static bool areCompatVectorTypes(const VectorType *LHS,
10117 const VectorType *RHS) {
10118 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10119 return LHS->getElementType() == RHS->getElementType() &&
10120 LHS->getNumElements() == RHS->getNumElements();
10121}
10122
10123/// areCompatMatrixTypes - Return true if the two specified matrix types are
10124/// compatible.
10126 const ConstantMatrixType *RHS) {
10127 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10128 return LHS->getElementType() == RHS->getElementType() &&
10129 LHS->getNumRows() == RHS->getNumRows() &&
10130 LHS->getNumColumns() == RHS->getNumColumns();
10131}
10132
10134 QualType SecondVec) {
10135 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
10136 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
10137
10138 if (hasSameUnqualifiedType(FirstVec, SecondVec))
10139 return true;
10140
10141 // Treat Neon vector types and most AltiVec vector types as if they are the
10142 // equivalent GCC vector types.
10143 const auto *First = FirstVec->castAs<VectorType>();
10144 const auto *Second = SecondVec->castAs<VectorType>();
10145 if (First->getNumElements() == Second->getNumElements() &&
10146 hasSameType(First->getElementType(), Second->getElementType()) &&
10147 First->getVectorKind() != VectorKind::AltiVecPixel &&
10148 First->getVectorKind() != VectorKind::AltiVecBool &&
10151 First->getVectorKind() != VectorKind::SveFixedLengthData &&
10152 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10155 First->getVectorKind() != VectorKind::RVVFixedLengthData &&
10157 First->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10159 First->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10161 First->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10163 First->getVectorKind() != VectorKind::RVVFixedLengthMask_4 &&
10165 return true;
10166
10167 return false;
10168}
10169
10170/// getSVETypeSize - Return SVE vector or predicate register size.
10171static uint64_t getSVETypeSize(ASTContext &Context, const BuiltinType *Ty) {
10172 assert(Ty->isSveVLSBuiltinType() && "Invalid SVE Type");
10173 if (Ty->getKind() == BuiltinType::SveBool ||
10174 Ty->getKind() == BuiltinType::SveCount)
10175 return (Context.getLangOpts().VScaleMin * 128) / Context.getCharWidth();
10176 return Context.getLangOpts().VScaleMin * 128;
10177}
10178
10180 QualType SecondType) {
10181 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10182 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10183 if (const auto *VT = SecondType->getAs<VectorType>()) {
10184 // Predicates have the same representation as uint8 so we also have to
10185 // check the kind to make these types incompatible.
10186 if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
10187 return BT->getKind() == BuiltinType::SveBool;
10188 else if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
10189 return VT->getElementType().getCanonicalType() ==
10190 FirstType->getSveEltType(*this);
10191 else if (VT->getVectorKind() == VectorKind::Generic)
10192 return getTypeSize(SecondType) == getSVETypeSize(*this, BT) &&
10193 hasSameType(VT->getElementType(),
10194 getBuiltinVectorTypeInfo(BT).ElementType);
10195 }
10196 }
10197 return false;
10198 };
10199
10200 return IsValidCast(FirstType, SecondType) ||
10201 IsValidCast(SecondType, FirstType);
10202}
10203
10205 QualType SecondType) {
10206 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10207 const auto *BT = FirstType->getAs<BuiltinType>();
10208 if (!BT)
10209 return false;
10210
10211 const auto *VecTy = SecondType->getAs<VectorType>();
10212 if (VecTy && (VecTy->getVectorKind() == VectorKind::SveFixedLengthData ||
10213 VecTy->getVectorKind() == VectorKind::Generic)) {
10215 getLangOpts().getLaxVectorConversions();
10216
10217 // Can not convert between sve predicates and sve vectors because of
10218 // different size.
10219 if (BT->getKind() == BuiltinType::SveBool &&
10220 VecTy->getVectorKind() == VectorKind::SveFixedLengthData)
10221 return false;
10222
10223 // If __ARM_FEATURE_SVE_BITS != N do not allow GNU vector lax conversion.
10224 // "Whenever __ARM_FEATURE_SVE_BITS==N, GNUT implicitly
10225 // converts to VLAT and VLAT implicitly converts to GNUT."
10226 // ACLE Spec Version 00bet6, 3.7.3.2. Behavior common to vectors and
10227 // predicates.
10228 if (VecTy->getVectorKind() == VectorKind::Generic &&
10229 getTypeSize(SecondType) != getSVETypeSize(*this, BT))
10230 return false;
10231
10232 // If -flax-vector-conversions=all is specified, the types are
10233 // certainly compatible.
10235 return true;
10236
10237 // If -flax-vector-conversions=integer is specified, the types are
10238 // compatible if the elements are integer types.
10240 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10241 FirstType->getSveEltType(*this)->isIntegerType();
10242 }
10243
10244 return false;
10245 };
10246
10247 return IsLaxCompatible(FirstType, SecondType) ||
10248 IsLaxCompatible(SecondType, FirstType);
10249}
10250
10251/// getRVVTypeSize - Return RVV vector register size.
10252static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
10253 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
10254 auto VScale = Context.getTargetInfo().getVScaleRange(Context.getLangOpts());
10255 if (!VScale)
10256 return 0;
10257
10259
10260 uint64_t EltSize = Context.getTypeSize(Info.ElementType);
10261 if (Info.ElementType == Context.BoolTy)
10262 EltSize = 1;
10263
10264 uint64_t MinElts = Info.EC.getKnownMinValue();
10265 return VScale->first * MinElts * EltSize;
10266}
10267
10269 QualType SecondType) {
10270 assert(
10271 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10272 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10273 "Expected RVV builtin type and vector type!");
10274
10275 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10276 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10277 if (const auto *VT = SecondType->getAs<VectorType>()) {
10278 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10280 return FirstType->isRVVVLSBuiltinType() &&
10281 Info.ElementType == BoolTy &&
10282 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)));
10283 }
10284 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1) {
10286 return FirstType->isRVVVLSBuiltinType() &&
10287 Info.ElementType == BoolTy &&
10288 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT) * 8));
10289 }
10290 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2) {
10292 return FirstType->isRVVVLSBuiltinType() &&
10293 Info.ElementType == BoolTy &&
10294 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 4);
10295 }
10296 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10298 return FirstType->isRVVVLSBuiltinType() &&
10299 Info.ElementType == BoolTy &&
10300 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 2);
10301 }
10302 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
10303 VT->getVectorKind() == VectorKind::Generic)
10304 return FirstType->isRVVVLSBuiltinType() &&
10305 getTypeSize(SecondType) == getRVVTypeSize(*this, BT) &&
10306 hasSameType(VT->getElementType(),
10307 getBuiltinVectorTypeInfo(BT).ElementType);
10308 }
10309 }
10310 return false;
10311 };
10312
10313 return IsValidCast(FirstType, SecondType) ||
10314 IsValidCast(SecondType, FirstType);
10315}
10316
10318 QualType SecondType) {
10319 assert(
10320 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10321 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10322 "Expected RVV builtin type and vector type!");
10323
10324 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10325 const auto *BT = FirstType->getAs<BuiltinType>();
10326 if (!BT)
10327 return false;
10328
10329 if (!BT->isRVVVLSBuiltinType())
10330 return false;
10331
10332 const auto *VecTy = SecondType->getAs<VectorType>();
10333 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
10335 getLangOpts().getLaxVectorConversions();
10336
10337 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
10338 if (getTypeSize(SecondType) != getRVVTypeSize(*this, BT))
10339 return false;
10340
10341 // If -flax-vector-conversions=all is specified, the types are
10342 // certainly compatible.
10344 return true;
10345
10346 // If -flax-vector-conversions=integer is specified, the types are
10347 // compatible if the elements are integer types.
10349 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10350 FirstType->getRVVEltType(*this)->isIntegerType();
10351 }
10352
10353 return false;
10354 };
10355
10356 return IsLaxCompatible(FirstType, SecondType) ||
10357 IsLaxCompatible(SecondType, FirstType);
10358}
10359
10361 while (true) {
10362 // __strong id
10363 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
10364 if (Attr->getAttrKind() == attr::ObjCOwnership)
10365 return true;
10366
10367 Ty = Attr->getModifiedType();
10368
10369 // X *__strong (...)
10370 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
10371 Ty = Paren->getInnerType();
10372
10373 // We do not want to look through typedefs, typeof(expr),
10374 // typeof(type), or any other way that the type is somehow
10375 // abstracted.
10376 } else {
10377 return false;
10378 }
10379 }
10380}
10381
10382//===----------------------------------------------------------------------===//
10383// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
10384//===----------------------------------------------------------------------===//
10385
10386/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
10387/// inheritance hierarchy of 'rProto'.
10388bool
10390 ObjCProtocolDecl *rProto) const {
10391 if (declaresSameEntity(lProto, rProto))
10392 return true;
10393 for (auto *PI : rProto->protocols())
10394 if (ProtocolCompatibleWithProtocol(lProto, PI))
10395 return true;
10396 return false;
10397}
10398
10399/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
10400/// Class<pr1, ...>.
10402 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
10403 for (auto *lhsProto : lhs->quals()) {
10404 bool match = false;
10405 for (auto *rhsProto : rhs->quals()) {
10406 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
10407 match = true;
10408 break;
10409 }
10410 }
10411 if (!match)
10412 return false;
10413 }
10414 return true;
10415}
10416
10417/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
10418/// ObjCQualifiedIDType.
10420 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
10421 bool compare) {
10422 // Allow id<P..> and an 'id' in all cases.
10423 if (lhs->isObjCIdType() || rhs->isObjCIdType())
10424 return true;
10425
10426 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
10427 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
10429 return false;
10430
10431 if (lhs->isObjCQualifiedIdType()) {
10432 if (rhs->qual_empty()) {
10433 // If the RHS is a unqualified interface pointer "NSString*",
10434 // make sure we check the class hierarchy.
10435 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10436 for (auto *I : lhs->quals()) {
10437 // when comparing an id<P> on lhs with a static type on rhs,
10438 // see if static class implements all of id's protocols, directly or
10439 // through its super class and categories.
10440 if (!rhsID->ClassImplementsProtocol(I, true))
10441 return false;
10442 }
10443 }
10444 // If there are no qualifiers and no interface, we have an 'id'.
10445 return true;
10446 }
10447 // Both the right and left sides have qualifiers.
10448 for (auto *lhsProto : lhs->quals()) {
10449 bool match = false;
10450
10451 // when comparing an id<P> on lhs with a static type on rhs,
10452 // see if static class implements all of id's protocols, directly or
10453 // through its super class and categories.
10454 for (auto *rhsProto : rhs->quals()) {
10455 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10456 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10457 match = true;
10458 break;
10459 }
10460 }
10461 // If the RHS is a qualified interface pointer "NSString<P>*",
10462 // make sure we check the class hierarchy.
10463 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10464 for (auto *I : lhs->quals()) {
10465 // when comparing an id<P> on lhs with a static type on rhs,
10466 // see if static class implements all of id's protocols, directly or
10467 // through its super class and categories.
10468 if (rhsID->ClassImplementsProtocol(I, true)) {
10469 match = true;
10470 break;
10471 }
10472 }
10473 }
10474 if (!match)
10475 return false;
10476 }
10477
10478 return true;
10479 }
10480
10481 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
10482
10483 if (lhs->getInterfaceType()) {
10484 // If both the right and left sides have qualifiers.
10485 for (auto *lhsProto : lhs->quals()) {
10486 bool match = false;
10487
10488 // when comparing an id<P> on rhs with a static type on lhs,
10489 // see if static class implements all of id's protocols, directly or
10490 // through its super class and categories.
10491 // First, lhs protocols in the qualifier list must be found, direct
10492 // or indirect in rhs's qualifier list or it is a mismatch.
10493 for (auto *rhsProto : rhs->quals()) {
10494 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10495 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10496 match = true;
10497 break;
10498 }
10499 }
10500 if (!match)
10501 return false;
10502 }
10503
10504 // Static class's protocols, or its super class or category protocols
10505 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
10506 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
10507 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
10508 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
10509 // This is rather dubious but matches gcc's behavior. If lhs has
10510 // no type qualifier and its class has no static protocol(s)
10511 // assume that it is mismatch.
10512 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
10513 return false;
10514 for (auto *lhsProto : LHSInheritedProtocols) {
10515 bool match = false;
10516 for (auto *rhsProto : rhs->quals()) {
10517 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10518 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10519 match = true;
10520 break;
10521 }
10522 }
10523 if (!match)
10524 return false;
10525 }
10526 }
10527 return true;
10528 }
10529 return false;
10530}
10531
10532/// canAssignObjCInterfaces - Return true if the two interface types are
10533/// compatible for assignment from RHS to LHS. This handles validation of any
10534/// protocol qualifiers on the LHS or RHS.
10536 const ObjCObjectPointerType *RHSOPT) {
10537 const ObjCObjectType* LHS = LHSOPT->getObjectType();
10538 const ObjCObjectType* RHS = RHSOPT->getObjectType();
10539
10540 // If either type represents the built-in 'id' type, return true.
10541 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
10542 return true;
10543
10544 // Function object that propagates a successful result or handles
10545 // __kindof types.
10546 auto finish = [&](bool succeeded) -> bool {
10547 if (succeeded)
10548 return true;
10549
10550 if (!RHS->isKindOfType())
10551 return false;
10552
10553 // Strip off __kindof and protocol qualifiers, then check whether
10554 // we can assign the other way.
10556 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
10557 };
10558
10559 // Casts from or to id<P> are allowed when the other side has compatible
10560 // protocols.
10561 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
10562 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
10563 }
10564
10565 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
10566 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
10567 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
10568 }
10569
10570 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
10571 if (LHS->isObjCClass() && RHS->isObjCClass()) {
10572 return true;
10573 }
10574
10575 // If we have 2 user-defined types, fall into that path.
10576 if (LHS->getInterface() && RHS->getInterface()) {
10577 return finish(canAssignObjCInterfaces(LHS, RHS));
10578 }
10579
10580 return false;
10581}
10582
10583/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
10584/// for providing type-safety for objective-c pointers used to pass/return
10585/// arguments in block literals. When passed as arguments, passing 'A*' where
10586/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
10587/// not OK. For the return type, the opposite is not OK.
10589 const ObjCObjectPointerType *LHSOPT,
10590 const ObjCObjectPointerType *RHSOPT,
10591 bool BlockReturnType) {
10592
10593 // Function object that propagates a successful result or handles
10594 // __kindof types.
10595 auto finish = [&](bool succeeded) -> bool {
10596 if (succeeded)
10597 return true;
10598
10599 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
10600 if (!Expected->isKindOfType())
10601 return false;
10602
10603 // Strip off __kindof and protocol qualifiers, then check whether
10604 // we can assign the other way.
10606 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
10607 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
10608 BlockReturnType);
10609 };
10610
10611 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
10612 return true;
10613
10614 if (LHSOPT->isObjCBuiltinType()) {
10615 return finish(RHSOPT->isObjCBuiltinType() ||
10616 RHSOPT->isObjCQualifiedIdType());
10617 }
10618
10619 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
10620 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
10621 // Use for block parameters previous type checking for compatibility.
10622 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
10623 // Or corrected type checking as in non-compat mode.
10624 (!BlockReturnType &&
10625 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
10626 else
10628 (BlockReturnType ? LHSOPT : RHSOPT),
10629 (BlockReturnType ? RHSOPT : LHSOPT), false));
10630 }
10631
10632 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
10633 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
10634 if (LHS && RHS) { // We have 2 user-defined types.
10635 if (LHS != RHS) {
10636 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
10637 return finish(BlockReturnType);
10638 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
10639 return finish(!BlockReturnType);
10640 }
10641 else
10642 return true;
10643 }
10644 return false;
10645}
10646
10647/// Comparison routine for Objective-C protocols to be used with
10648/// llvm::array_pod_sort.
10650 ObjCProtocolDecl * const *rhs) {
10651 return (*lhs)->getName().compare((*rhs)->getName());
10652}
10653
10654/// getIntersectionOfProtocols - This routine finds the intersection of set
10655/// of protocols inherited from two distinct objective-c pointer objects with
10656/// the given common base.
10657/// It is used to build composite qualifier list of the composite type of
10658/// the conditional expression involving two objective-c pointer objects.
10659static
10661 const ObjCInterfaceDecl *CommonBase,
10662 const ObjCObjectPointerType *LHSOPT,
10663 const ObjCObjectPointerType *RHSOPT,
10664 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
10665
10666 const ObjCObjectType* LHS = LHSOPT->getObjectType();
10667 const ObjCObjectType* RHS = RHSOPT->getObjectType();
10668 assert(LHS->getInterface() && "LHS must have an interface base");
10669 assert(RHS->getInterface() && "RHS must have an interface base");
10670
10671 // Add all of the protocols for the LHS.
10673
10674 // Start with the protocol qualifiers.
10675 for (auto *proto : LHS->quals()) {
10676 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
10677 }
10678
10679 // Also add the protocols associated with the LHS interface.
10680 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
10681
10682 // Add all of the protocols for the RHS.
10684
10685 // Start with the protocol qualifiers.
10686 for (auto *proto : RHS->quals()) {
10687 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
10688 }
10689
10690 // Also add the protocols associated with the RHS interface.
10691 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
10692
10693 // Compute the intersection of the collected protocol sets.
10694 for (auto *proto : LHSProtocolSet) {
10695 if (RHSProtocolSet.count(proto))
10696 IntersectionSet.push_back(proto);
10697 }
10698
10699 // Compute the set of protocols that is implied by either the common type or
10700 // the protocols within the intersection.
10702 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
10703
10704 // Remove any implied protocols from the list of inherited protocols.
10705 if (!ImpliedProtocols.empty()) {
10706 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
10707 return ImpliedProtocols.contains(proto);
10708 });
10709 }
10710
10711 // Sort the remaining protocols by name.
10712 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
10714}
10715
10716/// Determine whether the first type is a subtype of the second.
10718 QualType rhs) {
10719 // Common case: two object pointers.
10720 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
10721 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
10722 if (lhsOPT && rhsOPT)
10723 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
10724
10725 // Two block pointers.
10726 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
10727 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
10728 if (lhsBlock && rhsBlock)
10729 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
10730
10731 // If either is an unqualified 'id' and the other is a block, it's
10732 // acceptable.
10733 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
10734 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
10735 return true;
10736
10737 return false;
10738}
10739
10740// Check that the given Objective-C type argument lists are equivalent.
10742 const ObjCInterfaceDecl *iface,
10743 ArrayRef<QualType> lhsArgs,
10744 ArrayRef<QualType> rhsArgs,
10745 bool stripKindOf) {
10746 if (lhsArgs.size() != rhsArgs.size())
10747 return false;
10748
10749 ObjCTypeParamList *typeParams = iface->getTypeParamList();
10750 if (!typeParams)
10751 return false;
10752
10753 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
10754 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
10755 continue;
10756
10757 switch (typeParams->begin()[i]->getVariance()) {
10759 if (!stripKindOf ||
10760 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
10761 rhsArgs[i].stripObjCKindOfType(ctx))) {
10762 return false;
10763 }
10764 break;
10765
10767 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
10768 return false;
10769 break;
10770
10772 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
10773 return false;
10774 break;
10775 }
10776 }
10777
10778 return true;
10779}
10780
10782 const ObjCObjectPointerType *Lptr,
10783 const ObjCObjectPointerType *Rptr) {
10784 const ObjCObjectType *LHS = Lptr->getObjectType();
10785 const ObjCObjectType *RHS = Rptr->getObjectType();
10786 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
10787 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
10788
10789 if (!LDecl || !RDecl)
10790 return {};
10791
10792 // When either LHS or RHS is a kindof type, we should return a kindof type.
10793 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
10794 // kindof(A).
10795 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
10796
10797 // Follow the left-hand side up the class hierarchy until we either hit a
10798 // root or find the RHS. Record the ancestors in case we don't find it.
10799 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
10800 LHSAncestors;
10801 while (true) {
10802 // Record this ancestor. We'll need this if the common type isn't in the
10803 // path from the LHS to the root.
10804 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
10805
10806 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
10807 // Get the type arguments.
10808 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
10809 bool anyChanges = false;
10810 if (LHS->isSpecialized() && RHS->isSpecialized()) {
10811 // Both have type arguments, compare them.
10812 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
10813 LHS->getTypeArgs(), RHS->getTypeArgs(),
10814 /*stripKindOf=*/true))
10815 return {};
10816 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
10817 // If only one has type arguments, the result will not have type
10818 // arguments.
10819 LHSTypeArgs = {};
10820 anyChanges = true;
10821 }
10822
10823 // Compute the intersection of protocols.
10825 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
10826 Protocols);
10827 if (!Protocols.empty())
10828 anyChanges = true;
10829
10830 // If anything in the LHS will have changed, build a new result type.
10831 // If we need to return a kindof type but LHS is not a kindof type, we
10832 // build a new result type.
10833 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
10835 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
10836 anyKindOf || LHS->isKindOfType());
10838 }
10839
10840 return getObjCObjectPointerType(QualType(LHS, 0));
10841 }
10842
10843 // Find the superclass.
10844 QualType LHSSuperType = LHS->getSuperClassType();
10845 if (LHSSuperType.isNull())
10846 break;
10847
10848 LHS = LHSSuperType->castAs<ObjCObjectType>();
10849 }
10850
10851 // We didn't find anything by following the LHS to its root; now check
10852 // the RHS against the cached set of ancestors.
10853 while (true) {
10854 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
10855 if (KnownLHS != LHSAncestors.end()) {
10856 LHS = KnownLHS->second;
10857
10858 // Get the type arguments.
10859 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
10860 bool anyChanges = false;
10861 if (LHS->isSpecialized() && RHS->isSpecialized()) {
10862 // Both have type arguments, compare them.
10863 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
10864 LHS->getTypeArgs(), RHS->getTypeArgs(),
10865 /*stripKindOf=*/true))
10866 return {};
10867 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
10868 // If only one has type arguments, the result will not have type
10869 // arguments.
10870 RHSTypeArgs = {};
10871 anyChanges = true;
10872 }
10873
10874 // Compute the intersection of protocols.
10876 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
10877 Protocols);
10878 if (!Protocols.empty())
10879 anyChanges = true;
10880
10881 // If we need to return a kindof type but RHS is not a kindof type, we
10882 // build a new result type.
10883 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
10885 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
10886 anyKindOf || RHS->isKindOfType());
10888 }
10889
10890 return getObjCObjectPointerType(QualType(RHS, 0));
10891 }
10892
10893 // Find the superclass of the RHS.
10894 QualType RHSSuperType = RHS->getSuperClassType();
10895 if (RHSSuperType.isNull())
10896 break;
10897
10898 RHS = RHSSuperType->castAs<ObjCObjectType>();
10899 }
10900
10901 return {};
10902}
10903
10905 const ObjCObjectType *RHS) {
10906 assert(LHS->getInterface() && "LHS is not an interface type");
10907 assert(RHS->getInterface() && "RHS is not an interface type");
10908
10909 // Verify that the base decls are compatible: the RHS must be a subclass of
10910 // the LHS.
10911 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
10912 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
10913 if (!IsSuperClass)
10914 return false;
10915
10916 // If the LHS has protocol qualifiers, determine whether all of them are
10917 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
10918 // LHS).
10919 if (LHS->getNumProtocols() > 0) {
10920 // OK if conversion of LHS to SuperClass results in narrowing of types
10921 // ; i.e., SuperClass may implement at least one of the protocols
10922 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
10923 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
10924 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
10925 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
10926 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
10927 // qualifiers.
10928 for (auto *RHSPI : RHS->quals())
10929 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
10930 // If there is no protocols associated with RHS, it is not a match.
10931 if (SuperClassInheritedProtocols.empty())
10932 return false;
10933
10934 for (const auto *LHSProto : LHS->quals()) {
10935 bool SuperImplementsProtocol = false;
10936 for (auto *SuperClassProto : SuperClassInheritedProtocols)
10937 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
10938 SuperImplementsProtocol = true;
10939 break;
10940 }
10941 if (!SuperImplementsProtocol)
10942 return false;
10943 }
10944 }
10945
10946 // If the LHS is specialized, we may need to check type arguments.
10947 if (LHS->isSpecialized()) {
10948 // Follow the superclass chain until we've matched the LHS class in the
10949 // hierarchy. This substitutes type arguments through.
10950 const ObjCObjectType *RHSSuper = RHS;
10951 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
10952 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
10953
10954 // If the RHS is specializd, compare type arguments.
10955 if (RHSSuper->isSpecialized() &&
10956 !sameObjCTypeArgs(*this, LHS->getInterface(),
10957 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
10958 /*stripKindOf=*/true)) {
10959 return false;
10960 }
10961 }
10962
10963 return true;
10964}
10965
10967 // get the "pointed to" types
10968 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
10969 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
10970
10971 if (!LHSOPT || !RHSOPT)
10972 return false;
10973
10974 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
10975 canAssignObjCInterfaces(RHSOPT, LHSOPT);
10976}
10977
10980 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
10981 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
10982}
10983
10984/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
10985/// both shall have the identically qualified version of a compatible type.
10986/// C99 6.2.7p1: Two types have compatible types if their types are the
10987/// same. See 6.7.[2,3,5] for additional rules.
10989 bool CompareUnqualified) {
10990 if (getLangOpts().CPlusPlus)
10991 return hasSameType(LHS, RHS);
10992
10993 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
10994}
10995
10997 return typesAreCompatible(LHS, RHS);
10998}
10999
11001 return !mergeTypes(LHS, RHS, true).isNull();
11002}
11003
11004/// mergeTransparentUnionType - if T is a transparent union type and a member
11005/// of T is compatible with SubType, return the merged type, else return
11006/// QualType()
11008 bool OfBlockPointer,
11009 bool Unqualified) {
11010 if (const RecordType *UT = T->getAsUnionType()) {
11011 RecordDecl *UD = UT->getDecl();
11012 if (UD->hasAttr<TransparentUnionAttr>()) {
11013 for (const auto *I : UD->fields()) {
11014 QualType ET = I->getType().getUnqualifiedType();
11015 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
11016 if (!MT.isNull())
11017 return MT;
11018 }
11019 }
11020 }
11021
11022 return {};
11023}
11024
11025/// mergeFunctionParameterTypes - merge two types which appear as function
11026/// parameter types
11028 bool OfBlockPointer,
11029 bool Unqualified) {
11030 // GNU extension: two types are compatible if they appear as a function
11031 // argument, one of the types is a transparent union type and the other
11032 // type is compatible with a union member
11033 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
11034 Unqualified);
11035 if (!lmerge.isNull())
11036 return lmerge;
11037
11038 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
11039 Unqualified);
11040 if (!rmerge.isNull())
11041 return rmerge;
11042
11043 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
11044}
11045
11047 bool OfBlockPointer, bool Unqualified,
11048 bool AllowCXX,
11049 bool IsConditionalOperator) {
11050 const auto *lbase = lhs->castAs<FunctionType>();
11051 const auto *rbase = rhs->castAs<FunctionType>();
11052 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
11053 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
11054 bool allLTypes = true;
11055 bool allRTypes = true;
11056
11057 // Check return type
11058 QualType retType;
11059 if (OfBlockPointer) {
11060 QualType RHS = rbase->getReturnType();
11061 QualType LHS = lbase->getReturnType();
11062 bool UnqualifiedResult = Unqualified;
11063 if (!UnqualifiedResult)
11064 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
11065 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
11066 }
11067 else
11068 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
11069 Unqualified);
11070 if (retType.isNull())
11071 return {};
11072
11073 if (Unqualified)
11074 retType = retType.getUnqualifiedType();
11075
11076 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
11077 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
11078 if (Unqualified) {
11079 LRetType = LRetType.getUnqualifiedType();
11080 RRetType = RRetType.getUnqualifiedType();
11081 }
11082
11083 if (getCanonicalType(retType) != LRetType)
11084 allLTypes = false;
11085 if (getCanonicalType(retType) != RRetType)
11086 allRTypes = false;
11087
11088 // FIXME: double check this
11089 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
11090 // rbase->getRegParmAttr() != 0 &&
11091 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
11092 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
11093 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
11094
11095 // Compatible functions must have compatible calling conventions
11096 if (lbaseInfo.getCC() != rbaseInfo.getCC())
11097 return {};
11098
11099 // Regparm is part of the calling convention.
11100 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
11101 return {};
11102 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
11103 return {};
11104
11105 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
11106 return {};
11107 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
11108 return {};
11109 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
11110 return {};
11111
11112 // When merging declarations, it's common for supplemental information like
11113 // attributes to only be present in one of the declarations, and we generally
11114 // want type merging to preserve the union of information. So a merged
11115 // function type should be noreturn if it was noreturn in *either* operand
11116 // type.
11117 //
11118 // But for the conditional operator, this is backwards. The result of the
11119 // operator could be either operand, and its type should conservatively
11120 // reflect that. So a function type in a composite type is noreturn only
11121 // if it's noreturn in *both* operand types.
11122 //
11123 // Arguably, noreturn is a kind of subtype, and the conditional operator
11124 // ought to produce the most specific common supertype of its operand types.
11125 // That would differ from this rule in contravariant positions. However,
11126 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
11127 // as a practical matter, it would only affect C code that does abstraction of
11128 // higher-order functions (taking noreturn callbacks!), which is uncommon to
11129 // say the least. So we use the simpler rule.
11130 bool NoReturn = IsConditionalOperator
11131 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
11132 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
11133 if (lbaseInfo.getNoReturn() != NoReturn)
11134 allLTypes = false;
11135 if (rbaseInfo.getNoReturn() != NoReturn)
11136 allRTypes = false;
11137
11138 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
11139
11140 std::optional<FunctionEffectSet> MergedFX;
11141
11142 if (lproto && rproto) { // two C99 style function prototypes
11143 assert((AllowCXX ||
11144 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
11145 "C++ shouldn't be here");
11146 // Compatible functions must have the same number of parameters
11147 if (lproto->getNumParams() != rproto->getNumParams())
11148 return {};
11149
11150 // Variadic and non-variadic functions aren't compatible
11151 if (lproto->isVariadic() != rproto->isVariadic())
11152 return {};
11153
11154 if (lproto->getMethodQuals() != rproto->getMethodQuals())
11155 return {};
11156
11157 // Function effects are handled similarly to noreturn, see above.
11158 FunctionEffectsRef LHSFX = lproto->getFunctionEffects();
11159 FunctionEffectsRef RHSFX = rproto->getFunctionEffects();
11160 if (LHSFX != RHSFX) {
11161 if (IsConditionalOperator)
11162 MergedFX = FunctionEffectSet::getIntersection(LHSFX, RHSFX);
11163 else {
11165 MergedFX = FunctionEffectSet::getUnion(LHSFX, RHSFX, Errs);
11166 // Here we're discarding a possible error due to conflicts in the effect
11167 // sets. But we're not in a context where we can report it. The
11168 // operation does however guarantee maintenance of invariants.
11169 }
11170 if (*MergedFX != LHSFX)
11171 allLTypes = false;
11172 if (*MergedFX != RHSFX)
11173 allRTypes = false;
11174 }
11175
11177 bool canUseLeft, canUseRight;
11178 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
11179 newParamInfos))
11180 return {};
11181
11182 if (!canUseLeft)
11183 allLTypes = false;
11184 if (!canUseRight)
11185 allRTypes = false;
11186
11187 // Check parameter type compatibility
11189 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
11190 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
11191 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
11193 lParamType, rParamType, OfBlockPointer, Unqualified);
11194 if (paramType.isNull())
11195 return {};
11196
11197 if (Unqualified)
11198 paramType = paramType.getUnqualifiedType();
11199
11200 types.push_back(paramType);
11201 if (Unqualified) {
11202 lParamType = lParamType.getUnqualifiedType();
11203 rParamType = rParamType.getUnqualifiedType();
11204 }
11205
11206 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
11207 allLTypes = false;
11208 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
11209 allRTypes = false;
11210 }
11211
11212 if (allLTypes) return lhs;
11213 if (allRTypes) return rhs;
11214
11215 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
11216 EPI.ExtInfo = einfo;
11217 EPI.ExtParameterInfos =
11218 newParamInfos.empty() ? nullptr : newParamInfos.data();
11219 if (MergedFX)
11220 EPI.FunctionEffects = *MergedFX;
11221 return getFunctionType(retType, types, EPI);
11222 }
11223
11224 if (lproto) allRTypes = false;
11225 if (rproto) allLTypes = false;
11226
11227 const FunctionProtoType *proto = lproto ? lproto : rproto;
11228 if (proto) {
11229 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
11230 if (proto->isVariadic())
11231 return {};
11232 // Check that the types are compatible with the types that
11233 // would result from default argument promotions (C99 6.7.5.3p15).
11234 // The only types actually affected are promotable integer
11235 // types and floats, which would be passed as a different
11236 // type depending on whether the prototype is visible.
11237 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
11238 QualType paramTy = proto->getParamType(i);
11239
11240 // Look at the converted type of enum types, since that is the type used
11241 // to pass enum values.
11242 if (const auto *Enum = paramTy->getAs<EnumType>()) {
11243 paramTy = Enum->getDecl()->getIntegerType();
11244 if (paramTy.isNull())
11245 return {};
11246 }
11247
11248 if (isPromotableIntegerType(paramTy) ||
11249 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
11250 return {};
11251 }
11252
11253 if (allLTypes) return lhs;
11254 if (allRTypes) return rhs;
11255
11257 EPI.ExtInfo = einfo;
11258 if (MergedFX)
11259 EPI.FunctionEffects = *MergedFX;
11260 return getFunctionType(retType, proto->getParamTypes(), EPI);
11261 }
11262
11263 if (allLTypes) return lhs;
11264 if (allRTypes) return rhs;
11265 return getFunctionNoProtoType(retType, einfo);
11266}
11267
11268/// Given that we have an enum type and a non-enum type, try to merge them.
11270 QualType other, bool isBlockReturnType) {
11271 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
11272 // a signed integer type, or an unsigned integer type.
11273 // Compatibility is based on the underlying type, not the promotion
11274 // type.
11275 QualType underlyingType = ET->getDecl()->getIntegerType();
11276 if (underlyingType.isNull())
11277 return {};
11278 if (Context.hasSameType(underlyingType, other))
11279 return other;
11280
11281 // In block return types, we're more permissive and accept any
11282 // integral type of the same size.
11283 if (isBlockReturnType && other->isIntegerType() &&
11284 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
11285 return other;
11286
11287 return {};
11288}
11289
11290QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
11291 bool Unqualified, bool BlockReturnType,
11292 bool IsConditionalOperator) {
11293 // For C++ we will not reach this code with reference types (see below),
11294 // for OpenMP variant call overloading we might.
11295 //
11296 // C++ [expr]: If an expression initially has the type "reference to T", the
11297 // type is adjusted to "T" prior to any further analysis, the expression
11298 // designates the object or function denoted by the reference, and the
11299 // expression is an lvalue unless the reference is an rvalue reference and
11300 // the expression is a function call (possibly inside parentheses).
11301 auto *LHSRefTy = LHS->getAs<ReferenceType>();
11302 auto *RHSRefTy = RHS->getAs<ReferenceType>();
11303 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
11304 LHS->getTypeClass() == RHS->getTypeClass())
11305 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
11306 OfBlockPointer, Unqualified, BlockReturnType);
11307 if (LHSRefTy || RHSRefTy)
11308 return {};
11309
11310 if (Unqualified) {
11311 LHS = LHS.getUnqualifiedType();
11312 RHS = RHS.getUnqualifiedType();
11313 }
11314
11315 QualType LHSCan = getCanonicalType(LHS),
11316 RHSCan = getCanonicalType(RHS);
11317
11318 // If two types are identical, they are compatible.
11319 if (LHSCan == RHSCan)
11320 return LHS;
11321
11322 // If the qualifiers are different, the types aren't compatible... mostly.
11323 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11324 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11325 if (LQuals != RQuals) {
11326 // If any of these qualifiers are different, we have a type
11327 // mismatch.
11328 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11329 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
11330 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
11331 LQuals.hasUnaligned() != RQuals.hasUnaligned())
11332 return {};
11333
11334 // Exactly one GC qualifier difference is allowed: __strong is
11335 // okay if the other type has no GC qualifier but is an Objective
11336 // C object pointer (i.e. implicitly strong by default). We fix
11337 // this by pretending that the unqualified type was actually
11338 // qualified __strong.
11339 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11340 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11341 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11342
11343 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11344 return {};
11345
11346 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
11348 }
11349 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
11351 }
11352 return {};
11353 }
11354
11355 // Okay, qualifiers are equal.
11356
11357 Type::TypeClass LHSClass = LHSCan->getTypeClass();
11358 Type::TypeClass RHSClass = RHSCan->getTypeClass();
11359
11360 // We want to consider the two function types to be the same for these
11361 // comparisons, just force one to the other.
11362 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
11363 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
11364
11365 // Same as above for arrays
11366 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
11367 LHSClass = Type::ConstantArray;
11368 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
11369 RHSClass = Type::ConstantArray;
11370
11371 // ObjCInterfaces are just specialized ObjCObjects.
11372 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
11373 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
11374
11375 // Canonicalize ExtVector -> Vector.
11376 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
11377 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
11378
11379 // If the canonical type classes don't match.
11380 if (LHSClass != RHSClass) {
11381 // Note that we only have special rules for turning block enum
11382 // returns into block int returns, not vice-versa.
11383 if (const auto *ETy = LHS->getAs<EnumType>()) {
11384 return mergeEnumWithInteger(*this, ETy, RHS, false);
11385 }
11386 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
11387 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
11388 }
11389 // allow block pointer type to match an 'id' type.
11390 if (OfBlockPointer && !BlockReturnType) {
11391 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
11392 return LHS;
11393 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
11394 return RHS;
11395 }
11396 // Allow __auto_type to match anything; it merges to the type with more
11397 // information.
11398 if (const auto *AT = LHS->getAs<AutoType>()) {
11399 if (!AT->isDeduced() && AT->isGNUAutoType())
11400 return RHS;
11401 }
11402 if (const auto *AT = RHS->getAs<AutoType>()) {
11403 if (!AT->isDeduced() && AT->isGNUAutoType())
11404 return LHS;
11405 }
11406 return {};
11407 }
11408
11409 // The canonical type classes match.
11410 switch (LHSClass) {
11411#define TYPE(Class, Base)
11412#define ABSTRACT_TYPE(Class, Base)
11413#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
11414#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
11415#define DEPENDENT_TYPE(Class, Base) case Type::Class:
11416#include "clang/AST/TypeNodes.inc"
11417 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
11418
11419 case Type::Auto:
11420 case Type::DeducedTemplateSpecialization:
11421 case Type::LValueReference:
11422 case Type::RValueReference:
11423 case Type::MemberPointer:
11424 llvm_unreachable("C++ should never be in mergeTypes");
11425
11426 case Type::ObjCInterface:
11427 case Type::IncompleteArray:
11428 case Type::VariableArray:
11429 case Type::FunctionProto:
11430 case Type::ExtVector:
11431 llvm_unreachable("Types are eliminated above");
11432
11433 case Type::Pointer:
11434 {
11435 // Merge two pointer types, while trying to preserve typedef info
11436 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
11437 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
11438 if (Unqualified) {
11439 LHSPointee = LHSPointee.getUnqualifiedType();
11440 RHSPointee = RHSPointee.getUnqualifiedType();
11441 }
11442 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
11443 Unqualified);
11444 if (ResultType.isNull())
11445 return {};
11446 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11447 return LHS;
11448 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
11449 return RHS;
11450 return getPointerType(ResultType);
11451 }
11452 case Type::BlockPointer:
11453 {
11454 // Merge two block pointer types, while trying to preserve typedef info
11455 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
11456 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
11457 if (Unqualified) {
11458 LHSPointee = LHSPointee.getUnqualifiedType();
11459 RHSPointee = RHSPointee.getUnqualifiedType();
11460 }
11461 if (getLangOpts().OpenCL) {
11462 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
11463 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
11464 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
11465 // 6.12.5) thus the following check is asymmetric.
11466 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual, *this))
11467 return {};
11468 LHSPteeQual.removeAddressSpace();
11469 RHSPteeQual.removeAddressSpace();
11470 LHSPointee =
11471 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
11472 RHSPointee =
11473 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
11474 }
11475 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
11476 Unqualified);
11477 if (ResultType.isNull())
11478 return {};
11479 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11480 return LHS;
11481 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
11482 return RHS;
11483 return getBlockPointerType(ResultType);
11484 }
11485 case Type::Atomic:
11486 {
11487 // Merge two pointer types, while trying to preserve typedef info
11488 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
11489 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
11490 if (Unqualified) {
11491 LHSValue = LHSValue.getUnqualifiedType();
11492 RHSValue = RHSValue.getUnqualifiedType();
11493 }
11494 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
11495 Unqualified);
11496 if (ResultType.isNull())
11497 return {};
11498 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
11499 return LHS;
11500 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
11501 return RHS;
11502 return getAtomicType(ResultType);
11503 }
11504 case Type::ConstantArray:
11505 {
11506 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
11507 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
11508 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
11509 return {};
11510
11511 QualType LHSElem = getAsArrayType(LHS)->getElementType();
11512 QualType RHSElem = getAsArrayType(RHS)->getElementType();
11513 if (Unqualified) {
11514 LHSElem = LHSElem.getUnqualifiedType();
11515 RHSElem = RHSElem.getUnqualifiedType();
11516 }
11517
11518 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
11519 if (ResultType.isNull())
11520 return {};
11521
11522 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
11523 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
11524
11525 // If either side is a variable array, and both are complete, check whether
11526 // the current dimension is definite.
11527 if (LVAT || RVAT) {
11528 auto SizeFetch = [this](const VariableArrayType* VAT,
11529 const ConstantArrayType* CAT)
11530 -> std::pair<bool,llvm::APInt> {
11531 if (VAT) {
11532 std::optional<llvm::APSInt> TheInt;
11533 Expr *E = VAT->getSizeExpr();
11534 if (E && (TheInt = E->getIntegerConstantExpr(*this)))
11535 return std::make_pair(true, *TheInt);
11536 return std::make_pair(false, llvm::APSInt());
11537 }
11538 if (CAT)
11539 return std::make_pair(true, CAT->getSize());
11540 return std::make_pair(false, llvm::APInt());
11541 };
11542
11543 bool HaveLSize, HaveRSize;
11544 llvm::APInt LSize, RSize;
11545 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
11546 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
11547 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
11548 return {}; // Definite, but unequal, array dimension
11549 }
11550
11551 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
11552 return LHS;
11553 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
11554 return RHS;
11555 if (LCAT)
11556 return getConstantArrayType(ResultType, LCAT->getSize(),
11557 LCAT->getSizeExpr(), ArraySizeModifier(), 0);
11558 if (RCAT)
11559 return getConstantArrayType(ResultType, RCAT->getSize(),
11560 RCAT->getSizeExpr(), ArraySizeModifier(), 0);
11561 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
11562 return LHS;
11563 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
11564 return RHS;
11565 if (LVAT) {
11566 // FIXME: This isn't correct! But tricky to implement because
11567 // the array's size has to be the size of LHS, but the type
11568 // has to be different.
11569 return LHS;
11570 }
11571 if (RVAT) {
11572 // FIXME: This isn't correct! But tricky to implement because
11573 // the array's size has to be the size of RHS, but the type
11574 // has to be different.
11575 return RHS;
11576 }
11577 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
11578 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
11579 return getIncompleteArrayType(ResultType, ArraySizeModifier(), 0);
11580 }
11581 case Type::FunctionNoProto:
11582 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified,
11583 /*AllowCXX=*/false, IsConditionalOperator);
11584 case Type::Record:
11585 case Type::Enum:
11586 return {};
11587 case Type::Builtin:
11588 // Only exactly equal builtin types are compatible, which is tested above.
11589 return {};
11590 case Type::Complex:
11591 // Distinct complex types are incompatible.
11592 return {};
11593 case Type::Vector:
11594 // FIXME: The merged type should be an ExtVector!
11595 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
11596 RHSCan->castAs<VectorType>()))
11597 return LHS;
11598 return {};
11599 case Type::ConstantMatrix:
11601 RHSCan->castAs<ConstantMatrixType>()))
11602 return LHS;
11603 return {};
11604 case Type::ObjCObject: {
11605 // Check if the types are assignment compatible.
11606 // FIXME: This should be type compatibility, e.g. whether
11607 // "LHS x; RHS x;" at global scope is legal.
11609 RHS->castAs<ObjCObjectType>()))
11610 return LHS;
11611 return {};
11612 }
11613 case Type::ObjCObjectPointer:
11614 if (OfBlockPointer) {
11617 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
11618 return LHS;
11619 return {};
11620 }
11623 return LHS;
11624 return {};
11625 case Type::Pipe:
11626 assert(LHS != RHS &&
11627 "Equivalent pipe types should have already been handled!");
11628 return {};
11629 case Type::ArrayParameter:
11630 assert(LHS != RHS &&
11631 "Equivalent ArrayParameter types should have already been handled!");
11632 return {};
11633 case Type::BitInt: {
11634 // Merge two bit-precise int types, while trying to preserve typedef info.
11635 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
11636 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
11637 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
11638 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
11639
11640 // Like unsigned/int, shouldn't have a type if they don't match.
11641 if (LHSUnsigned != RHSUnsigned)
11642 return {};
11643
11644 if (LHSBits != RHSBits)
11645 return {};
11646 return LHS;
11647 }
11648 case Type::HLSLAttributedResource: {
11649 const HLSLAttributedResourceType *LHSTy =
11651 const HLSLAttributedResourceType *RHSTy =
11653 assert(LHSTy->getWrappedType() == RHSTy->getWrappedType() &&
11654 LHSTy->getWrappedType()->isHLSLResourceType() &&
11655 "HLSLAttributedResourceType should always wrap __hlsl_resource_t");
11656
11657 if (LHSTy->getAttrs() == RHSTy->getAttrs() &&
11658 LHSTy->getContainedType() == RHSTy->getContainedType())
11659 return LHS;
11660 return {};
11661 }
11662 }
11663
11664 llvm_unreachable("Invalid Type::Class!");
11665}
11666
11668 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
11669 bool &CanUseFirst, bool &CanUseSecond,
11671 assert(NewParamInfos.empty() && "param info list not empty");
11672 CanUseFirst = CanUseSecond = true;
11673 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
11674 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
11675
11676 // Fast path: if the first type doesn't have ext parameter infos,
11677 // we match if and only if the second type also doesn't have them.
11678 if (!FirstHasInfo && !SecondHasInfo)
11679 return true;
11680
11681 bool NeedParamInfo = false;
11682 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
11683 : SecondFnType->getExtParameterInfos().size();
11684
11685 for (size_t I = 0; I < E; ++I) {
11686 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
11687 if (FirstHasInfo)
11688 FirstParam = FirstFnType->getExtParameterInfo(I);
11689 if (SecondHasInfo)
11690 SecondParam = SecondFnType->getExtParameterInfo(I);
11691
11692 // Cannot merge unless everything except the noescape flag matches.
11693 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
11694 return false;
11695
11696 bool FirstNoEscape = FirstParam.isNoEscape();
11697 bool SecondNoEscape = SecondParam.isNoEscape();
11698 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
11699 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
11700 if (NewParamInfos.back().getOpaqueValue())
11701 NeedParamInfo = true;
11702 if (FirstNoEscape != IsNoEscape)
11703 CanUseFirst = false;
11704 if (SecondNoEscape != IsNoEscape)
11705 CanUseSecond = false;
11706 }
11707
11708 if (!NeedParamInfo)
11709 NewParamInfos.clear();
11710
11711 return true;
11712}
11713
11715 ObjCLayouts[CD] = nullptr;
11716}
11717
11718/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
11719/// 'RHS' attributes and returns the merged version; including for function
11720/// return types.
11722 QualType LHSCan = getCanonicalType(LHS),
11723 RHSCan = getCanonicalType(RHS);
11724 // If two types are identical, they are compatible.
11725 if (LHSCan == RHSCan)
11726 return LHS;
11727 if (RHSCan->isFunctionType()) {
11728 if (!LHSCan->isFunctionType())
11729 return {};
11730 QualType OldReturnType =
11731 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
11732 QualType NewReturnType =
11733 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
11734 QualType ResReturnType =
11735 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
11736 if (ResReturnType.isNull())
11737 return {};
11738 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
11739 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
11740 // In either case, use OldReturnType to build the new function type.
11741 const auto *F = LHS->castAs<FunctionType>();
11742 if (const auto *FPT = cast<FunctionProtoType>(F)) {
11743 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11744 EPI.ExtInfo = getFunctionExtInfo(LHS);
11745 QualType ResultType =
11746 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
11747 return ResultType;
11748 }
11749 }
11750 return {};
11751 }
11752
11753 // If the qualifiers are different, the types can still be merged.
11754 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11755 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11756 if (LQuals != RQuals) {
11757 // If any of these qualifiers are different, we have a type mismatch.
11758 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11759 LQuals.getAddressSpace() != RQuals.getAddressSpace())
11760 return {};
11761
11762 // Exactly one GC qualifier difference is allowed: __strong is
11763 // okay if the other type has no GC qualifier but is an Objective
11764 // C object pointer (i.e. implicitly strong by default). We fix
11765 // this by pretending that the unqualified type was actually
11766 // qualified __strong.
11767 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11768 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11769 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11770
11771 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11772 return {};
11773
11774 if (GC_L == Qualifiers::Strong)
11775 return LHS;
11776 if (GC_R == Qualifiers::Strong)
11777 return RHS;
11778 return {};
11779 }
11780
11781 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
11782 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
11783 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
11784 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
11785 if (ResQT == LHSBaseQT)
11786 return LHS;
11787 if (ResQT == RHSBaseQT)
11788 return RHS;
11789 }
11790 return {};
11791}
11792
11793//===----------------------------------------------------------------------===//
11794// Integer Predicates
11795//===----------------------------------------------------------------------===//
11796
11798 if (const auto *ET = T->getAs<EnumType>())
11799 T = ET->getDecl()->getIntegerType();
11800 if (T->isBooleanType())
11801 return 1;
11802 if (const auto *EIT = T->getAs<BitIntType>())
11803 return EIT->getNumBits();
11804 // For builtin types, just use the standard type sizing method
11805 return (unsigned)getTypeSize(T);
11806}
11807
11809 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
11810 T->isFixedPointType()) &&
11811 "Unexpected type");
11812
11813 // Turn <4 x signed int> -> <4 x unsigned int>
11814 if (const auto *VTy = T->getAs<VectorType>())
11815 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
11816 VTy->getNumElements(), VTy->getVectorKind());
11817
11818 // For _BitInt, return an unsigned _BitInt with same width.
11819 if (const auto *EITy = T->getAs<BitIntType>())
11820 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
11821
11822 // For enums, get the underlying integer type of the enum, and let the general
11823 // integer type signchanging code handle it.
11824 if (const auto *ETy = T->getAs<EnumType>())
11825 T = ETy->getDecl()->getIntegerType();
11826
11827 switch (T->castAs<BuiltinType>()->getKind()) {
11828 case BuiltinType::Char_U:
11829 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
11830 case BuiltinType::Char_S:
11831 case BuiltinType::SChar:
11832 case BuiltinType::Char8:
11833 return UnsignedCharTy;
11834 case BuiltinType::Short:
11835 return UnsignedShortTy;
11836 case BuiltinType::Int:
11837 return UnsignedIntTy;
11838 case BuiltinType::Long:
11839 return UnsignedLongTy;
11840 case BuiltinType::LongLong:
11841 return UnsignedLongLongTy;
11842 case BuiltinType::Int128:
11843 return UnsignedInt128Ty;
11844 // wchar_t is special. It is either signed or not, but when it's signed,
11845 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
11846 // version of its underlying type instead.
11847 case BuiltinType::WChar_S:
11848 return getUnsignedWCharType();
11849
11850 case BuiltinType::ShortAccum:
11851 return UnsignedShortAccumTy;
11852 case BuiltinType::Accum:
11853 return UnsignedAccumTy;
11854 case BuiltinType::LongAccum:
11855 return UnsignedLongAccumTy;
11856 case BuiltinType::SatShortAccum:
11858 case BuiltinType::SatAccum:
11859 return SatUnsignedAccumTy;
11860 case BuiltinType::SatLongAccum:
11862 case BuiltinType::ShortFract:
11863 return UnsignedShortFractTy;
11864 case BuiltinType::Fract:
11865 return UnsignedFractTy;
11866 case BuiltinType::LongFract:
11867 return UnsignedLongFractTy;
11868 case BuiltinType::SatShortFract:
11870 case BuiltinType::SatFract:
11871 return SatUnsignedFractTy;
11872 case BuiltinType::SatLongFract:
11874 default:
11877 "Unexpected signed integer or fixed point type");
11878 return T;
11879 }
11880}
11881
11883 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
11884 T->isFixedPointType()) &&
11885 "Unexpected type");
11886
11887 // Turn <4 x unsigned int> -> <4 x signed int>
11888 if (const auto *VTy = T->getAs<VectorType>())
11889 return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
11890 VTy->getNumElements(), VTy->getVectorKind());
11891
11892 // For _BitInt, return a signed _BitInt with same width.
11893 if (const auto *EITy = T->getAs<BitIntType>())
11894 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
11895
11896 // For enums, get the underlying integer type of the enum, and let the general
11897 // integer type signchanging code handle it.
11898 if (const auto *ETy = T->getAs<EnumType>())
11899 T = ETy->getDecl()->getIntegerType();
11900
11901 switch (T->castAs<BuiltinType>()->getKind()) {
11902 case BuiltinType::Char_S:
11903 // Plain `char` is mapped to `signed char` even if it's already signed
11904 case BuiltinType::Char_U:
11905 case BuiltinType::UChar:
11906 case BuiltinType::Char8:
11907 return SignedCharTy;
11908 case BuiltinType::UShort:
11909 return ShortTy;
11910 case BuiltinType::UInt:
11911 return IntTy;
11912 case BuiltinType::ULong:
11913 return LongTy;
11914 case BuiltinType::ULongLong:
11915 return LongLongTy;
11916 case BuiltinType::UInt128:
11917 return Int128Ty;
11918 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
11919 // there's no matching "signed wchar_t". Therefore we return the signed
11920 // version of its underlying type instead.
11921 case BuiltinType::WChar_U:
11922 return getSignedWCharType();
11923
11924 case BuiltinType::UShortAccum:
11925 return ShortAccumTy;
11926 case BuiltinType::UAccum:
11927 return AccumTy;
11928 case BuiltinType::ULongAccum:
11929 return LongAccumTy;
11930 case BuiltinType::SatUShortAccum:
11931 return SatShortAccumTy;
11932 case BuiltinType::SatUAccum:
11933 return SatAccumTy;
11934 case BuiltinType::SatULongAccum:
11935 return SatLongAccumTy;
11936 case BuiltinType::UShortFract:
11937 return ShortFractTy;
11938 case BuiltinType::UFract:
11939 return FractTy;
11940 case BuiltinType::ULongFract:
11941 return LongFractTy;
11942 case BuiltinType::SatUShortFract:
11943 return SatShortFractTy;
11944 case BuiltinType::SatUFract:
11945 return SatFractTy;
11946 case BuiltinType::SatULongFract:
11947 return SatLongFractTy;
11948 default:
11949 assert(
11951 "Unexpected signed integer or fixed point type");
11952 return T;
11953 }
11954}
11955
11957
11959 QualType ReturnType) {}
11960
11961//===----------------------------------------------------------------------===//
11962// Builtin Type Computation
11963//===----------------------------------------------------------------------===//
11964
11965/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
11966/// pointer over the consumed characters. This returns the resultant type. If
11967/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
11968/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
11969/// a vector of "i*".
11970///
11971/// RequiresICE is filled in on return to indicate whether the value is required
11972/// to be an Integer Constant Expression.
11973static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
11975 bool &RequiresICE,
11976 bool AllowTypeModifiers) {
11977 // Modifiers.
11978 int HowLong = 0;
11979 bool Signed = false, Unsigned = false;
11980 RequiresICE = false;
11981
11982 // Read the prefixed modifiers first.
11983 bool Done = false;
11984 #ifndef NDEBUG
11985 bool IsSpecial = false;
11986 #endif
11987 while (!Done) {
11988 switch (*Str++) {
11989 default: Done = true; --Str; break;
11990 case 'I':
11991 RequiresICE = true;
11992 break;
11993 case 'S':
11994 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
11995 assert(!Signed && "Can't use 'S' modifier multiple times!");
11996 Signed = true;
11997 break;
11998 case 'U':
11999 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
12000 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
12001 Unsigned = true;
12002 break;
12003 case 'L':
12004 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
12005 assert(HowLong <= 2 && "Can't have LLLL modifier");
12006 ++HowLong;
12007 break;
12008 case 'N':
12009 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
12010 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12011 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
12012 #ifndef NDEBUG
12013 IsSpecial = true;
12014 #endif
12015 if (Context.getTargetInfo().getLongWidth() == 32)
12016 ++HowLong;
12017 break;
12018 case 'W':
12019 // This modifier represents int64 type.
12020 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12021 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
12022 #ifndef NDEBUG
12023 IsSpecial = true;
12024 #endif
12025 switch (Context.getTargetInfo().getInt64Type()) {
12026 default:
12027 llvm_unreachable("Unexpected integer type");
12029 HowLong = 1;
12030 break;
12032 HowLong = 2;
12033 break;
12034 }
12035 break;
12036 case 'Z':
12037 // This modifier represents int32 type.
12038 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12039 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
12040 #ifndef NDEBUG
12041 IsSpecial = true;
12042 #endif
12043 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
12044 default:
12045 llvm_unreachable("Unexpected integer type");
12047 HowLong = 0;
12048 break;
12050 HowLong = 1;
12051 break;
12053 HowLong = 2;
12054 break;
12055 }
12056 break;
12057 case 'O':
12058 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12059 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
12060 #ifndef NDEBUG
12061 IsSpecial = true;
12062 #endif
12063 if (Context.getLangOpts().OpenCL)
12064 HowLong = 1;
12065 else
12066 HowLong = 2;
12067 break;
12068 }
12069 }
12070
12071 QualType Type;
12072
12073 // Read the base type.
12074 switch (*Str++) {
12075 default: llvm_unreachable("Unknown builtin type letter!");
12076 case 'x':
12077 assert(HowLong == 0 && !Signed && !Unsigned &&
12078 "Bad modifiers used with 'x'!");
12079 Type = Context.Float16Ty;
12080 break;
12081 case 'y':
12082 assert(HowLong == 0 && !Signed && !Unsigned &&
12083 "Bad modifiers used with 'y'!");
12084 Type = Context.BFloat16Ty;
12085 break;
12086 case 'v':
12087 assert(HowLong == 0 && !Signed && !Unsigned &&
12088 "Bad modifiers used with 'v'!");
12089 Type = Context.VoidTy;
12090 break;
12091 case 'h':
12092 assert(HowLong == 0 && !Signed && !Unsigned &&
12093 "Bad modifiers used with 'h'!");
12094 Type = Context.HalfTy;
12095 break;
12096 case 'f':
12097 assert(HowLong == 0 && !Signed && !Unsigned &&
12098 "Bad modifiers used with 'f'!");
12099 Type = Context.FloatTy;
12100 break;
12101 case 'd':
12102 assert(HowLong < 3 && !Signed && !Unsigned &&
12103 "Bad modifiers used with 'd'!");
12104 if (HowLong == 1)
12105 Type = Context.LongDoubleTy;
12106 else if (HowLong == 2)
12107 Type = Context.Float128Ty;
12108 else
12109 Type = Context.DoubleTy;
12110 break;
12111 case 's':
12112 assert(HowLong == 0 && "Bad modifiers used with 's'!");
12113 if (Unsigned)
12114 Type = Context.UnsignedShortTy;
12115 else
12116 Type = Context.ShortTy;
12117 break;
12118 case 'i':
12119 if (HowLong == 3)
12120 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
12121 else if (HowLong == 2)
12122 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
12123 else if (HowLong == 1)
12124 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
12125 else
12126 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
12127 break;
12128 case 'c':
12129 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
12130 if (Signed)
12131 Type = Context.SignedCharTy;
12132 else if (Unsigned)
12133 Type = Context.UnsignedCharTy;
12134 else
12135 Type = Context.CharTy;
12136 break;
12137 case 'b': // boolean
12138 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
12139 Type = Context.BoolTy;
12140 break;
12141 case 'z': // size_t.
12142 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
12143 Type = Context.getSizeType();
12144 break;
12145 case 'w': // wchar_t.
12146 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
12147 Type = Context.getWideCharType();
12148 break;
12149 case 'F':
12150 Type = Context.getCFConstantStringType();
12151 break;
12152 case 'G':
12153 Type = Context.getObjCIdType();
12154 break;
12155 case 'H':
12156 Type = Context.getObjCSelType();
12157 break;
12158 case 'M':
12159 Type = Context.getObjCSuperType();
12160 break;
12161 case 'a':
12162 Type = Context.getBuiltinVaListType();
12163 assert(!Type.isNull() && "builtin va list type not initialized!");
12164 break;
12165 case 'A':
12166 // This is a "reference" to a va_list; however, what exactly
12167 // this means depends on how va_list is defined. There are two
12168 // different kinds of va_list: ones passed by value, and ones
12169 // passed by reference. An example of a by-value va_list is
12170 // x86, where va_list is a char*. An example of by-ref va_list
12171 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
12172 // we want this argument to be a char*&; for x86-64, we want
12173 // it to be a __va_list_tag*.
12174 Type = Context.getBuiltinVaListType();
12175 assert(!Type.isNull() && "builtin va list type not initialized!");
12176 if (Type->isArrayType())
12177 Type = Context.getArrayDecayedType(Type);
12178 else
12179 Type = Context.getLValueReferenceType(Type);
12180 break;
12181 case 'q': {
12182 char *End;
12183 unsigned NumElements = strtoul(Str, &End, 10);
12184 assert(End != Str && "Missing vector size");
12185 Str = End;
12186
12187 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12188 RequiresICE, false);
12189 assert(!RequiresICE && "Can't require vector ICE");
12190
12191 Type = Context.getScalableVectorType(ElementType, NumElements);
12192 break;
12193 }
12194 case 'Q': {
12195 switch (*Str++) {
12196 case 'a': {
12197 Type = Context.SveCountTy;
12198 break;
12199 }
12200 case 'b': {
12201 Type = Context.AMDGPUBufferRsrcTy;
12202 break;
12203 }
12204 default:
12205 llvm_unreachable("Unexpected target builtin type");
12206 }
12207 break;
12208 }
12209 case 'V': {
12210 char *End;
12211 unsigned NumElements = strtoul(Str, &End, 10);
12212 assert(End != Str && "Missing vector size");
12213 Str = End;
12214
12215 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12216 RequiresICE, false);
12217 assert(!RequiresICE && "Can't require vector ICE");
12218
12219 // TODO: No way to make AltiVec vectors in builtins yet.
12220 Type = Context.getVectorType(ElementType, NumElements, VectorKind::Generic);
12221 break;
12222 }
12223 case 'E': {
12224 char *End;
12225
12226 unsigned NumElements = strtoul(Str, &End, 10);
12227 assert(End != Str && "Missing vector size");
12228
12229 Str = End;
12230
12231 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12232 false);
12233 Type = Context.getExtVectorType(ElementType, NumElements);
12234 break;
12235 }
12236 case 'X': {
12237 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12238 false);
12239 assert(!RequiresICE && "Can't require complex ICE");
12240 Type = Context.getComplexType(ElementType);
12241 break;
12242 }
12243 case 'Y':
12244 Type = Context.getPointerDiffType();
12245 break;
12246 case 'P':
12247 Type = Context.getFILEType();
12248 if (Type.isNull()) {
12250 return {};
12251 }
12252 break;
12253 case 'J':
12254 if (Signed)
12255 Type = Context.getsigjmp_bufType();
12256 else
12257 Type = Context.getjmp_bufType();
12258
12259 if (Type.isNull()) {
12261 return {};
12262 }
12263 break;
12264 case 'K':
12265 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
12266 Type = Context.getucontext_tType();
12267
12268 if (Type.isNull()) {
12270 return {};
12271 }
12272 break;
12273 case 'p':
12274 Type = Context.getProcessIDType();
12275 break;
12276 }
12277
12278 // If there are modifiers and if we're allowed to parse them, go for it.
12279 Done = !AllowTypeModifiers;
12280 while (!Done) {
12281 switch (char c = *Str++) {
12282 default: Done = true; --Str; break;
12283 case '*':
12284 case '&': {
12285 // Both pointers and references can have their pointee types
12286 // qualified with an address space.
12287 char *End;
12288 unsigned AddrSpace = strtoul(Str, &End, 10);
12289 if (End != Str) {
12290 // Note AddrSpace == 0 is not the same as an unspecified address space.
12291 Type = Context.getAddrSpaceQualType(
12292 Type,
12293 Context.getLangASForBuiltinAddressSpace(AddrSpace));
12294 Str = End;
12295 }
12296 if (c == '*')
12297 Type = Context.getPointerType(Type);
12298 else
12299 Type = Context.getLValueReferenceType(Type);
12300 break;
12301 }
12302 // FIXME: There's no way to have a built-in with an rvalue ref arg.
12303 case 'C':
12304 Type = Type.withConst();
12305 break;
12306 case 'D':
12307 Type = Context.getVolatileType(Type);
12308 break;
12309 case 'R':
12310 Type = Type.withRestrict();
12311 break;
12312 }
12313 }
12314
12315 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
12316 "Integer constant 'I' type must be an integer");
12317
12318 return Type;
12319}
12320
12321// On some targets such as PowerPC, some of the builtins are defined with custom
12322// type descriptors for target-dependent types. These descriptors are decoded in
12323// other functions, but it may be useful to be able to fall back to default
12324// descriptor decoding to define builtins mixing target-dependent and target-
12325// independent types. This function allows decoding one type descriptor with
12326// default decoding.
12327QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
12328 GetBuiltinTypeError &Error, bool &RequireICE,
12329 bool AllowTypeModifiers) const {
12330 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
12331}
12332
12333/// GetBuiltinType - Return the type for the specified builtin.
12335 GetBuiltinTypeError &Error,
12336 unsigned *IntegerConstantArgs) const {
12337 const char *TypeStr = BuiltinInfo.getTypeString(Id);
12338 if (TypeStr[0] == '\0') {
12339 Error = GE_Missing_type;
12340 return {};
12341 }
12342
12343 SmallVector<QualType, 8> ArgTypes;
12344
12345 bool RequiresICE = false;
12346 Error = GE_None;
12347 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
12348 RequiresICE, true);
12349 if (Error != GE_None)
12350 return {};
12351
12352 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
12353
12354 while (TypeStr[0] && TypeStr[0] != '.') {
12355 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
12356 if (Error != GE_None)
12357 return {};
12358
12359 // If this argument is required to be an IntegerConstantExpression and the
12360 // caller cares, fill in the bitmask we return.
12361 if (RequiresICE && IntegerConstantArgs)
12362 *IntegerConstantArgs |= 1 << ArgTypes.size();
12363
12364 // Do array -> pointer decay. The builtin should use the decayed type.
12365 if (Ty->isArrayType())
12366 Ty = getArrayDecayedType(Ty);
12367
12368 ArgTypes.push_back(Ty);
12369 }
12370
12371 if (Id == Builtin::BI__GetExceptionInfo)
12372 return {};
12373
12374 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
12375 "'.' should only occur at end of builtin type list!");
12376
12377 bool Variadic = (TypeStr[0] == '.');
12378
12380 Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
12381 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
12382
12383
12384 // We really shouldn't be making a no-proto type here.
12385 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
12386 return getFunctionNoProtoType(ResType, EI);
12387
12389 EPI.ExtInfo = EI;
12390 EPI.Variadic = Variadic;
12392 EPI.ExceptionSpec.Type =
12394
12395 return getFunctionType(ResType, ArgTypes, EPI);
12396}
12397
12399 const FunctionDecl *FD) {
12400 if (!FD->isExternallyVisible())
12401 return GVA_Internal;
12402
12403 // Non-user-provided functions get emitted as weak definitions with every
12404 // use, no matter whether they've been explicitly instantiated etc.
12405 if (!FD->isUserProvided())
12406 return GVA_DiscardableODR;
12407
12409 switch (FD->getTemplateSpecializationKind()) {
12410 case TSK_Undeclared:
12413 break;
12414
12416 return GVA_StrongODR;
12417
12418 // C++11 [temp.explicit]p10:
12419 // [ Note: The intent is that an inline function that is the subject of
12420 // an explicit instantiation declaration will still be implicitly
12421 // instantiated when used so that the body can be considered for
12422 // inlining, but that no out-of-line copy of the inline function would be
12423 // generated in the translation unit. -- end note ]
12426
12429 break;
12430 }
12431
12432 if (!FD->isInlined())
12433 return External;
12434
12435 if ((!Context.getLangOpts().CPlusPlus &&
12436 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12437 !FD->hasAttr<DLLExportAttr>()) ||
12438 FD->hasAttr<GNUInlineAttr>()) {
12439 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
12440
12441 // GNU or C99 inline semantics. Determine whether this symbol should be
12442 // externally visible.
12444 return External;
12445
12446 // C99 inline semantics, where the symbol is not externally visible.
12448 }
12449
12450 // Functions specified with extern and inline in -fms-compatibility mode
12451 // forcibly get emitted. While the body of the function cannot be later
12452 // replaced, the function definition cannot be discarded.
12453 if (FD->isMSExternInline())
12454 return GVA_StrongODR;
12455
12456 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12457 isa<CXXConstructorDecl>(FD) &&
12458 cast<CXXConstructorDecl>(FD)->isInheritingConstructor())
12459 // Our approach to inheriting constructors is fundamentally different from
12460 // that used by the MS ABI, so keep our inheriting constructor thunks
12461 // internal rather than trying to pick an unambiguous mangling for them.
12462 return GVA_Internal;
12463
12464 return GVA_DiscardableODR;
12465}
12466
12468 const Decl *D, GVALinkage L) {
12469 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
12470 // dllexport/dllimport on inline functions.
12471 if (D->hasAttr<DLLImportAttr>()) {
12472 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
12474 } else if (D->hasAttr<DLLExportAttr>()) {
12475 if (L == GVA_DiscardableODR)
12476 return GVA_StrongODR;
12477 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
12478 // Device-side functions with __global__ attribute must always be
12479 // visible externally so they can be launched from host.
12480 if (D->hasAttr<CUDAGlobalAttr>() &&
12481 (L == GVA_DiscardableODR || L == GVA_Internal))
12482 return GVA_StrongODR;
12483 // Single source offloading languages like CUDA/HIP need to be able to
12484 // access static device variables from host code of the same compilation
12485 // unit. This is done by externalizing the static variable with a shared
12486 // name between the host and device compilation which is the same for the
12487 // same compilation unit whereas different among different compilation
12488 // units.
12489 if (Context.shouldExternalize(D))
12490 return GVA_StrongExternal;
12491 }
12492 return L;
12493}
12494
12495/// Adjust the GVALinkage for a declaration based on what an external AST source
12496/// knows about whether there can be other definitions of this declaration.
12497static GVALinkage
12499 GVALinkage L) {
12500 ExternalASTSource *Source = Ctx.getExternalSource();
12501 if (!Source)
12502 return L;
12503
12504 switch (Source->hasExternalDefinitions(D)) {
12506 // Other translation units rely on us to provide the definition.
12507 if (L == GVA_DiscardableODR)
12508 return GVA_StrongODR;
12509 break;
12510
12513
12515 break;
12516 }
12517 return L;
12518}
12519
12523 basicGVALinkageForFunction(*this, FD)));
12524}
12525
12527 const VarDecl *VD) {
12528 // As an extension for interactive REPLs, make sure constant variables are
12529 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
12530 // marking them as internal.
12531 if (Context.getLangOpts().CPlusPlus &&
12532 Context.getLangOpts().IncrementalExtensions &&
12533 VD->getType().isConstQualified() &&
12534 !VD->getType().isVolatileQualified() && !VD->isInline() &&
12535 !isa<VarTemplateSpecializationDecl>(VD) && !VD->getDescribedVarTemplate())
12536 return GVA_DiscardableODR;
12537
12538 if (!VD->isExternallyVisible())
12539 return GVA_Internal;
12540
12541 if (VD->isStaticLocal()) {
12542 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
12543 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
12544 LexicalContext = LexicalContext->getLexicalParent();
12545
12546 // ObjC Blocks can create local variables that don't have a FunctionDecl
12547 // LexicalContext.
12548 if (!LexicalContext)
12549 return GVA_DiscardableODR;
12550
12551 // Otherwise, let the static local variable inherit its linkage from the
12552 // nearest enclosing function.
12553 auto StaticLocalLinkage =
12554 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
12555
12556 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
12557 // be emitted in any object with references to the symbol for the object it
12558 // contains, whether inline or out-of-line."
12559 // Similar behavior is observed with MSVC. An alternative ABI could use
12560 // StrongODR/AvailableExternally to match the function, but none are
12561 // known/supported currently.
12562 if (StaticLocalLinkage == GVA_StrongODR ||
12563 StaticLocalLinkage == GVA_AvailableExternally)
12564 return GVA_DiscardableODR;
12565 return StaticLocalLinkage;
12566 }
12567
12568 // MSVC treats in-class initialized static data members as definitions.
12569 // By giving them non-strong linkage, out-of-line definitions won't
12570 // cause link errors.
12572 return GVA_DiscardableODR;
12573
12574 // Most non-template variables have strong linkage; inline variables are
12575 // linkonce_odr or (occasionally, for compatibility) weak_odr.
12576 GVALinkage StrongLinkage;
12577 switch (Context.getInlineVariableDefinitionKind(VD)) {
12579 StrongLinkage = GVA_StrongExternal;
12580 break;
12583 StrongLinkage = GVA_DiscardableODR;
12584 break;
12586 StrongLinkage = GVA_StrongODR;
12587 break;
12588 }
12589
12590 switch (VD->getTemplateSpecializationKind()) {
12591 case TSK_Undeclared:
12592 return StrongLinkage;
12593
12595 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12596 VD->isStaticDataMember()
12598 : StrongLinkage;
12599
12601 return GVA_StrongODR;
12602
12605
12607 return GVA_DiscardableODR;
12608 }
12609
12610 llvm_unreachable("Invalid Linkage!");
12611}
12612
12616 basicGVALinkageForVariable(*this, VD)));
12617}
12618
12620 if (const auto *VD = dyn_cast<VarDecl>(D)) {
12621 if (!VD->isFileVarDecl())
12622 return false;
12623 // Global named register variables (GNU extension) are never emitted.
12624 if (VD->getStorageClass() == SC_Register)
12625 return false;
12626 if (VD->getDescribedVarTemplate() ||
12627 isa<VarTemplatePartialSpecializationDecl>(VD))
12628 return false;
12629 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
12630 // We never need to emit an uninstantiated function template.
12631 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12632 return false;
12633 } else if (isa<PragmaCommentDecl>(D))
12634 return true;
12635 else if (isa<PragmaDetectMismatchDecl>(D))
12636 return true;
12637 else if (isa<OMPRequiresDecl>(D))
12638 return true;
12639 else if (isa<OMPThreadPrivateDecl>(D))
12640 return !D->getDeclContext()->isDependentContext();
12641 else if (isa<OMPAllocateDecl>(D))
12642 return !D->getDeclContext()->isDependentContext();
12643 else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D))
12644 return !D->getDeclContext()->isDependentContext();
12645 else if (isa<ImportDecl>(D))
12646 return true;
12647 else
12648 return false;
12649
12650 // If this is a member of a class template, we do not need to emit it.
12652 return false;
12653
12654 // Weak references don't produce any output by themselves.
12655 if (D->hasAttr<WeakRefAttr>())
12656 return false;
12657
12658 // Aliases and used decls are required.
12659 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
12660 return true;
12661
12662 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
12663 // Forward declarations aren't required.
12664 if (!FD->doesThisDeclarationHaveABody())
12665 return FD->doesDeclarationForceExternallyVisibleDefinition();
12666
12667 // Constructors and destructors are required.
12668 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
12669 return true;
12670
12671 // The key function for a class is required. This rule only comes
12672 // into play when inline functions can be key functions, though.
12673 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
12674 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
12675 const CXXRecordDecl *RD = MD->getParent();
12676 if (MD->isOutOfLine() && RD->isDynamicClass()) {
12677 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
12678 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
12679 return true;
12680 }
12681 }
12682 }
12683
12685
12686 // static, static inline, always_inline, and extern inline functions can
12687 // always be deferred. Normal inline functions can be deferred in C99/C++.
12688 // Implicit template instantiations can also be deferred in C++.
12690 }
12691
12692 const auto *VD = cast<VarDecl>(D);
12693 assert(VD->isFileVarDecl() && "Expected file scoped var");
12694
12695 // If the decl is marked as `declare target to`, it should be emitted for the
12696 // host and for the device.
12697 if (LangOpts.OpenMP &&
12698 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
12699 return true;
12700
12701 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
12703 return false;
12704
12705 if (VD->shouldEmitInExternalSource())
12706 return false;
12707
12708 // Variables that can be needed in other TUs are required.
12711 return true;
12712
12713 // We never need to emit a variable that is available in another TU.
12715 return false;
12716
12717 // Variables that have destruction with side-effects are required.
12718 if (VD->needsDestruction(*this))
12719 return true;
12720
12721 // Variables that have initialization with side-effects are required.
12722 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
12723 // We can get a value-dependent initializer during error recovery.
12724 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
12725 return true;
12726
12727 // Likewise, variables with tuple-like bindings are required if their
12728 // bindings have side-effects.
12729 if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
12730 for (const auto *BD : DD->bindings())
12731 if (const auto *BindingVD = BD->getHoldingVar())
12732 if (DeclMustBeEmitted(BindingVD))
12733 return true;
12734
12735 return false;
12736}
12737
12739 const FunctionDecl *FD,
12740 llvm::function_ref<void(FunctionDecl *)> Pred) const {
12741 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
12742 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
12743 FD = FD->getMostRecentDecl();
12744 // FIXME: The order of traversal here matters and depends on the order of
12745 // lookup results, which happens to be (mostly) oldest-to-newest, but we
12746 // shouldn't rely on that.
12747 for (auto *CurDecl :
12749 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
12750 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
12751 SeenDecls.insert(CurFD).second) {
12752 Pred(CurFD);
12753 }
12754 }
12755}
12756
12758 bool IsCXXMethod,
12759 bool IsBuiltin) const {
12760 // Pass through to the C++ ABI object
12761 if (IsCXXMethod)
12762 return ABI->getDefaultMethodCallConv(IsVariadic);
12763
12764 // Builtins ignore user-specified default calling convention and remain the
12765 // Target's default calling convention.
12766 if (!IsBuiltin) {
12767 switch (LangOpts.getDefaultCallingConv()) {
12769 break;
12771 return CC_C;
12773 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
12774 return CC_X86FastCall;
12775 break;
12777 if (!IsVariadic)
12778 return CC_X86StdCall;
12779 break;
12781 // __vectorcall cannot be applied to variadic functions.
12782 if (!IsVariadic)
12783 return CC_X86VectorCall;
12784 break;
12786 // __regcall cannot be applied to variadic functions.
12787 if (!IsVariadic)
12788 return CC_X86RegCall;
12789 break;
12791 if (!IsVariadic)
12792 return CC_M68kRTD;
12793 break;
12794 }
12795 }
12796 return Target->getDefaultCallingConv();
12797}
12798
12800 // Pass through to the C++ ABI object
12801 return ABI->isNearlyEmpty(RD);
12802}
12803
12805 if (!VTContext.get()) {
12806 auto ABI = Target->getCXXABI();
12807 if (ABI.isMicrosoft())
12808 VTContext.reset(new MicrosoftVTableContext(*this));
12809 else {
12810 auto ComponentLayout = getLangOpts().RelativeCXXABIVTables
12813 VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout));
12814 }
12815 }
12816 return VTContext.get();
12817}
12818
12820 if (!T)
12821 T = Target;
12822 switch (T->getCXXABI().getKind()) {
12823 case TargetCXXABI::AppleARM64:
12824 case TargetCXXABI::Fuchsia:
12825 case TargetCXXABI::GenericAArch64:
12826 case TargetCXXABI::GenericItanium:
12827 case TargetCXXABI::GenericARM:
12828 case TargetCXXABI::GenericMIPS:
12829 case TargetCXXABI::iOS:
12830 case TargetCXXABI::WebAssembly:
12831 case TargetCXXABI::WatchOS:
12832 case TargetCXXABI::XL:
12834 case TargetCXXABI::Microsoft:
12836 }
12837 llvm_unreachable("Unsupported ABI");
12838}
12839
12841 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
12842 "Device mangle context does not support Microsoft mangling.");
12843 switch (T.getCXXABI().getKind()) {
12844 case TargetCXXABI::AppleARM64:
12845 case TargetCXXABI::Fuchsia:
12846 case TargetCXXABI::GenericAArch64:
12847 case TargetCXXABI::GenericItanium:
12848 case TargetCXXABI::GenericARM:
12849 case TargetCXXABI::GenericMIPS:
12850 case TargetCXXABI::iOS:
12851 case TargetCXXABI::WebAssembly:
12852 case TargetCXXABI::WatchOS:
12853 case TargetCXXABI::XL:
12855 *this, getDiagnostics(),
12856 [](ASTContext &, const NamedDecl *ND) -> std::optional<unsigned> {
12857 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
12858 return RD->getDeviceLambdaManglingNumber();
12859 return std::nullopt;
12860 },
12861 /*IsAux=*/true);
12862 case TargetCXXABI::Microsoft:
12864 /*IsAux=*/true);
12865 }
12866 llvm_unreachable("Unsupported ABI");
12867}
12868
12869CXXABI::~CXXABI() = default;
12870
12872 return ASTRecordLayouts.getMemorySize() +
12873 llvm::capacity_in_bytes(ObjCLayouts) +
12874 llvm::capacity_in_bytes(KeyFunctions) +
12875 llvm::capacity_in_bytes(ObjCImpls) +
12876 llvm::capacity_in_bytes(BlockVarCopyInits) +
12877 llvm::capacity_in_bytes(DeclAttrs) +
12878 llvm::capacity_in_bytes(TemplateOrInstantiation) +
12879 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
12880 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
12881 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
12882 llvm::capacity_in_bytes(OverriddenMethods) +
12883 llvm::capacity_in_bytes(Types) +
12884 llvm::capacity_in_bytes(VariableArrayTypes);
12885}
12886
12887/// getIntTypeForBitwidth -
12888/// sets integer QualTy according to specified details:
12889/// bitwidth, signed/unsigned.
12890/// Returns empty type if there is no appropriate target types.
12892 unsigned Signed) const {
12894 CanQualType QualTy = getFromTargetType(Ty);
12895 if (!QualTy && DestWidth == 128)
12896 return Signed ? Int128Ty : UnsignedInt128Ty;
12897 return QualTy;
12898}
12899
12900/// getRealTypeForBitwidth -
12901/// sets floating point QualTy according to specified bitwidth.
12902/// Returns empty type if there is no appropriate target types.
12904 FloatModeKind ExplicitType) const {
12905 FloatModeKind Ty =
12906 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
12907 switch (Ty) {
12909 return HalfTy;
12911 return FloatTy;
12913 return DoubleTy;
12915 return LongDoubleTy;
12917 return Float128Ty;
12919 return Ibm128Ty;
12921 return {};
12922 }
12923
12924 llvm_unreachable("Unhandled TargetInfo::RealType value");
12925}
12926
12927void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
12928 if (Number <= 1)
12929 return;
12930
12931 MangleNumbers[ND] = Number;
12932
12933 if (Listener)
12934 Listener->AddedManglingNumber(ND, Number);
12935}
12936
12938 bool ForAuxTarget) const {
12939 auto I = MangleNumbers.find(ND);
12940 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
12941 // CUDA/HIP host compilation encodes host and device mangling numbers
12942 // as lower and upper half of 32 bit integer.
12943 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
12944 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
12945 } else {
12946 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
12947 "number for aux target");
12948 }
12949 return Res > 1 ? Res : 1;
12950}
12951
12952void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
12953 if (Number <= 1)
12954 return;
12955
12956 StaticLocalNumbers[VD] = Number;
12957
12958 if (Listener)
12959 Listener->AddedStaticLocalNumbers(VD, Number);
12960}
12961
12963 auto I = StaticLocalNumbers.find(VD);
12964 return I != StaticLocalNumbers.end() ? I->second : 1;
12965}
12966
12969 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
12970 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
12971 if (!MCtx)
12973 return *MCtx;
12974}
12975
12978 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
12979 std::unique_ptr<MangleNumberingContext> &MCtx =
12980 ExtraMangleNumberingContexts[D];
12981 if (!MCtx)
12983 return *MCtx;
12984}
12985
12986std::unique_ptr<MangleNumberingContext>
12988 return ABI->createMangleNumberingContext();
12989}
12990
12991const CXXConstructorDecl *
12993 return ABI->getCopyConstructorForExceptionObject(
12994 cast<CXXRecordDecl>(RD->getFirstDecl()));
12995}
12996
12998 CXXConstructorDecl *CD) {
12999 return ABI->addCopyConstructorForExceptionObject(
13000 cast<CXXRecordDecl>(RD->getFirstDecl()),
13001 cast<CXXConstructorDecl>(CD->getFirstDecl()));
13002}
13003
13005 TypedefNameDecl *DD) {
13006 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
13007}
13008
13011 return ABI->getTypedefNameForUnnamedTagDecl(TD);
13012}
13013
13015 DeclaratorDecl *DD) {
13016 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
13017}
13018
13020 return ABI->getDeclaratorForUnnamedTagDecl(TD);
13021}
13022
13023void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
13024 ParamIndices[D] = index;
13025}
13026
13028 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
13029 assert(I != ParamIndices.end() &&
13030 "ParmIndices lacks entry set by ParmVarDecl");
13031 return I->second;
13032}
13033
13035 unsigned Length) const {
13036 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
13037 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
13038 EltTy = EltTy.withConst();
13039
13040 EltTy = adjustStringLiteralBaseType(EltTy);
13041
13042 // Get an array type for the string, according to C99 6.4.5. This includes
13043 // the null terminator character.
13044 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
13045 ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
13046}
13047
13050 StringLiteral *&Result = StringLiteralCache[Key];
13051 if (!Result)
13053 *this, Key, StringLiteralKind::Ordinary,
13054 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
13055 SourceLocation());
13056 return Result;
13057}
13058
13059MSGuidDecl *
13061 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
13062
13063 llvm::FoldingSetNodeID ID;
13064 MSGuidDecl::Profile(ID, Parts);
13065
13066 void *InsertPos;
13067 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
13068 return Existing;
13069
13070 QualType GUIDType = getMSGuidType().withConst();
13071 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
13072 MSGuidDecls.InsertNode(New, InsertPos);
13073 return New;
13074}
13075
13078 const APValue &APVal) const {
13079 llvm::FoldingSetNodeID ID;
13081
13082 void *InsertPos;
13083 if (UnnamedGlobalConstantDecl *Existing =
13084 UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos))
13085 return Existing;
13086
13088 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
13089 UnnamedGlobalConstantDecls.InsertNode(New, InsertPos);
13090 return New;
13091}
13092
13095 assert(T->isRecordType() && "template param object of unexpected type");
13096
13097 // C++ [temp.param]p8:
13098 // [...] a static storage duration object of type 'const T' [...]
13099 T.addConst();
13100
13101 llvm::FoldingSetNodeID ID;
13103
13104 void *InsertPos;
13105 if (TemplateParamObjectDecl *Existing =
13106 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
13107 return Existing;
13108
13109 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
13110 TemplateParamObjectDecls.InsertNode(New, InsertPos);
13111 return New;
13112}
13113
13115 const llvm::Triple &T = getTargetInfo().getTriple();
13116 if (!T.isOSDarwin())
13117 return false;
13118
13119 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
13120 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
13121 return false;
13122
13123 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
13124 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
13125 uint64_t Size = sizeChars.getQuantity();
13126 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
13127 unsigned Align = alignChars.getQuantity();
13128 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
13129 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
13130}
13131
13132bool
13134 const ObjCMethodDecl *MethodImpl) {
13135 // No point trying to match an unavailable/deprecated mothod.
13136 if (MethodDecl->hasAttr<UnavailableAttr>()
13137 || MethodDecl->hasAttr<DeprecatedAttr>())
13138 return false;
13139 if (MethodDecl->getObjCDeclQualifier() !=
13140 MethodImpl->getObjCDeclQualifier())
13141 return false;
13142 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
13143 return false;
13144
13145 if (MethodDecl->param_size() != MethodImpl->param_size())
13146 return false;
13147
13148 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
13149 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
13150 EF = MethodDecl->param_end();
13151 IM != EM && IF != EF; ++IM, ++IF) {
13152 const ParmVarDecl *DeclVar = (*IF);
13153 const ParmVarDecl *ImplVar = (*IM);
13154 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
13155 return false;
13156 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
13157 return false;
13158 }
13159
13160 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
13161}
13162
13164 LangAS AS;
13166 AS = LangAS::Default;
13167 else
13168 AS = QT->getPointeeType().getAddressSpace();
13169
13171}
13172
13175}
13176
13177bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
13178 if (X == Y)
13179 return true;
13180 if (!X || !Y)
13181 return false;
13182 llvm::FoldingSetNodeID IDX, IDY;
13183 X->Profile(IDX, *this, /*Canonical=*/true);
13184 Y->Profile(IDY, *this, /*Canonical=*/true);
13185 return IDX == IDY;
13186}
13187
13188// The getCommon* helpers return, for given 'same' X and Y entities given as
13189// inputs, another entity which is also the 'same' as the inputs, but which
13190// is closer to the canonical form of the inputs, each according to a given
13191// criteria.
13192// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
13193// the regular ones.
13194
13196 if (!declaresSameEntity(X, Y))
13197 return nullptr;
13198 for (const Decl *DX : X->redecls()) {
13199 // If we reach Y before reaching the first decl, that means X is older.
13200 if (DX == Y)
13201 return X;
13202 // If we reach the first decl, then Y is older.
13203 if (DX->isFirstDecl())
13204 return Y;
13205 }
13206 llvm_unreachable("Corrupt redecls chain");
13207}
13208
13209template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13210static T *getCommonDecl(T *X, T *Y) {
13211 return cast_or_null<T>(
13212 getCommonDecl(const_cast<Decl *>(cast_or_null<Decl>(X)),
13213 const_cast<Decl *>(cast_or_null<Decl>(Y))));
13214}
13215
13216template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13217static T *getCommonDeclChecked(T *X, T *Y) {
13218 return cast<T>(getCommonDecl(const_cast<Decl *>(cast<Decl>(X)),
13219 const_cast<Decl *>(cast<Decl>(Y))));
13220}
13221
13223 TemplateName Y,
13224 bool IgnoreDeduced = false) {
13225 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
13226 return X;
13227 // FIXME: There are cases here where we could find a common template name
13228 // with more sugar. For example one could be a SubstTemplateTemplate*
13229 // replacing the other.
13230 TemplateName CX = Ctx.getCanonicalTemplateName(X, IgnoreDeduced);
13231 if (CX.getAsVoidPointer() !=
13233 return TemplateName();
13234 return CX;
13235}
13236
13239 bool IgnoreDeduced) {
13240 TemplateName R = getCommonTemplateName(Ctx, X, Y, IgnoreDeduced);
13241 assert(R.getAsVoidPointer() != nullptr);
13242 return R;
13243}
13244
13246 ArrayRef<QualType> Ys, bool Unqualified = false) {
13247 assert(Xs.size() == Ys.size());
13248 SmallVector<QualType, 8> Rs(Xs.size());
13249 for (size_t I = 0; I < Rs.size(); ++I)
13250 Rs[I] = Ctx.getCommonSugaredType(Xs[I], Ys[I], Unqualified);
13251 return Rs;
13252}
13253
13254template <class T>
13255static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
13256 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
13257 : SourceLocation();
13258}
13259
13261 const TemplateArgument &X,
13262 const TemplateArgument &Y) {
13263 if (X.getKind() != Y.getKind())
13264 return TemplateArgument();
13265
13266 switch (X.getKind()) {
13268 if (!Ctx.hasSameType(X.getAsType(), Y.getAsType()))
13269 return TemplateArgument();
13270 return TemplateArgument(
13271 Ctx.getCommonSugaredType(X.getAsType(), Y.getAsType()));
13273 if (!Ctx.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
13274 return TemplateArgument();
13275 return TemplateArgument(
13276 Ctx.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
13277 /*Unqualified=*/true);
13279 if (!Ctx.hasSameType(X.getAsExpr()->getType(), Y.getAsExpr()->getType()))
13280 return TemplateArgument();
13281 // FIXME: Try to keep the common sugar.
13282 return X;
13284 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
13285 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13286 if (!CTN.getAsVoidPointer())
13287 return TemplateArgument();
13288 return TemplateArgument(CTN);
13289 }
13291 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
13293 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13294 if (!CTN.getAsVoidPointer())
13295 return TemplateName();
13296 auto NExpX = X.getNumTemplateExpansions();
13297 assert(NExpX == Y.getNumTemplateExpansions());
13298 return TemplateArgument(CTN, NExpX);
13299 }
13300 default:
13301 // FIXME: Handle the other argument kinds.
13302 return X;
13303 }
13304}
13305
13310 if (Xs.size() != Ys.size())
13311 return true;
13312 R.resize(Xs.size());
13313 for (size_t I = 0; I < R.size(); ++I) {
13314 R[I] = getCommonTemplateArgument(Ctx, Xs[I], Ys[I]);
13315 if (R[I].isNull())
13316 return true;
13317 }
13318 return false;
13319}
13320
13325 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
13326 assert(!Different);
13327 (void)Different;
13328 return R;
13329}
13330
13331template <class T>
13333 return X->getKeyword() == Y->getKeyword() ? X->getKeyword()
13335}
13336
13337template <class T>
13339 const T *Y) {
13340 // FIXME: Try to keep the common NNS sugar.
13341 return X->getQualifier() == Y->getQualifier()
13342 ? X->getQualifier()
13343 : Ctx.getCanonicalNestedNameSpecifier(X->getQualifier());
13344}
13345
13346template <class T>
13347static QualType getCommonElementType(ASTContext &Ctx, const T *X, const T *Y) {
13348 return Ctx.getCommonSugaredType(X->getElementType(), Y->getElementType());
13349}
13350
13351template <class T>
13353 Qualifiers &QX, const T *Y,
13354 Qualifiers &QY) {
13355 QualType EX = X->getElementType(), EY = Y->getElementType();
13356 QualType R = Ctx.getCommonSugaredType(EX, EY,
13357 /*Unqualified=*/true);
13358 Qualifiers RQ = R.getQualifiers();
13359 QX += EX.getQualifiers() - RQ;
13360 QY += EY.getQualifiers() - RQ;
13361 return R;
13362}
13363
13364template <class T>
13365static QualType getCommonPointeeType(ASTContext &Ctx, const T *X, const T *Y) {
13366 return Ctx.getCommonSugaredType(X->getPointeeType(), Y->getPointeeType());
13367}
13368
13369template <class T> static auto *getCommonSizeExpr(ASTContext &Ctx, T *X, T *Y) {
13370 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
13371 return X->getSizeExpr();
13372}
13373
13374static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
13375 assert(X->getSizeModifier() == Y->getSizeModifier());
13376 return X->getSizeModifier();
13377}
13378
13380 const ArrayType *Y) {
13381 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
13382 return X->getIndexTypeCVRQualifiers();
13383}
13384
13385// Merges two type lists such that the resulting vector will contain
13386// each type (in a canonical sense) only once, in the order they appear
13387// from X to Y. If they occur in both X and Y, the result will contain
13388// the common sugared type between them.
13391 llvm::DenseMap<QualType, unsigned> Found;
13392 for (auto Ts : {X, Y}) {
13393 for (QualType T : Ts) {
13394 auto Res = Found.try_emplace(Ctx.getCanonicalType(T), Out.size());
13395 if (!Res.second) {
13396 QualType &U = Out[Res.first->second];
13397 U = Ctx.getCommonSugaredType(U, T);
13398 } else {
13399 Out.emplace_back(T);
13400 }
13401 }
13402 }
13403}
13404
13408 SmallVectorImpl<QualType> &ExceptionTypeStorage,
13409 bool AcceptDependent) {
13410 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
13411
13412 // If either of them can throw anything, that is the result.
13413 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
13414 if (EST1 == I)
13415 return ESI1;
13416 if (EST2 == I)
13417 return ESI2;
13418 }
13419
13420 // If either of them is non-throwing, the result is the other.
13421 for (auto I :
13423 if (EST1 == I)
13424 return ESI2;
13425 if (EST2 == I)
13426 return ESI1;
13427 }
13428
13429 // If we're left with value-dependent computed noexcept expressions, we're
13430 // stuck. Before C++17, we can just drop the exception specification entirely,
13431 // since it's not actually part of the canonical type. And this should never
13432 // happen in C++17, because it would mean we were computing the composite
13433 // pointer type of dependent types, which should never happen.
13434 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
13435 assert(AcceptDependent &&
13436 "computing composite pointer type of dependent types");
13438 }
13439
13440 // Switch over the possibilities so that people adding new values know to
13441 // update this function.
13442 switch (EST1) {
13443 case EST_None:
13444 case EST_DynamicNone:
13445 case EST_MSAny:
13446 case EST_BasicNoexcept:
13448 case EST_NoexceptFalse:
13449 case EST_NoexceptTrue:
13450 case EST_NoThrow:
13451 llvm_unreachable("These ESTs should be handled above");
13452
13453 case EST_Dynamic: {
13454 // This is the fun case: both exception specifications are dynamic. Form
13455 // the union of the two lists.
13456 assert(EST2 == EST_Dynamic && "other cases should already be handled");
13457 mergeTypeLists(*this, ExceptionTypeStorage, ESI1.Exceptions,
13458 ESI2.Exceptions);
13460 Result.Exceptions = ExceptionTypeStorage;
13461 return Result;
13462 }
13463
13464 case EST_Unevaluated:
13465 case EST_Uninstantiated:
13466 case EST_Unparsed:
13467 llvm_unreachable("shouldn't see unresolved exception specifications here");
13468 }
13469
13470 llvm_unreachable("invalid ExceptionSpecificationType");
13471}
13472
13474 Qualifiers &QX, const Type *Y,
13475 Qualifiers &QY) {
13476 Type::TypeClass TC = X->getTypeClass();
13477 assert(TC == Y->getTypeClass());
13478 switch (TC) {
13479#define UNEXPECTED_TYPE(Class, Kind) \
13480 case Type::Class: \
13481 llvm_unreachable("Unexpected " Kind ": " #Class);
13482
13483#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
13484#define TYPE(Class, Base)
13485#include "clang/AST/TypeNodes.inc"
13486
13487#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
13488 SUGAR_FREE_TYPE(Builtin)
13489 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
13490 SUGAR_FREE_TYPE(DependentBitInt)
13493 SUGAR_FREE_TYPE(ObjCInterface)
13495 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
13496 SUGAR_FREE_TYPE(UnresolvedUsing)
13497 SUGAR_FREE_TYPE(HLSLAttributedResource)
13498#undef SUGAR_FREE_TYPE
13499#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
13500 NON_UNIQUE_TYPE(TypeOfExpr)
13501 NON_UNIQUE_TYPE(VariableArray)
13502#undef NON_UNIQUE_TYPE
13503
13504 UNEXPECTED_TYPE(TypeOf, "sugar")
13505
13506#undef UNEXPECTED_TYPE
13507
13508 case Type::Auto: {
13509 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
13510 assert(AX->getDeducedType().isNull());
13511 assert(AY->getDeducedType().isNull());
13512 assert(AX->getKeyword() == AY->getKeyword());
13513 assert(AX->isInstantiationDependentType() ==
13514 AY->isInstantiationDependentType());
13515 auto As = getCommonTemplateArguments(Ctx, AX->getTypeConstraintArguments(),
13516 AY->getTypeConstraintArguments());
13517 return Ctx.getAutoType(QualType(), AX->getKeyword(),
13519 AX->containsUnexpandedParameterPack(),
13520 getCommonDeclChecked(AX->getTypeConstraintConcept(),
13521 AY->getTypeConstraintConcept()),
13522 As);
13523 }
13524 case Type::IncompleteArray: {
13525 const auto *AX = cast<IncompleteArrayType>(X),
13526 *AY = cast<IncompleteArrayType>(Y);
13527 return Ctx.getIncompleteArrayType(
13528 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
13530 }
13531 case Type::DependentSizedArray: {
13532 const auto *AX = cast<DependentSizedArrayType>(X),
13533 *AY = cast<DependentSizedArrayType>(Y);
13534 return Ctx.getDependentSizedArrayType(
13535 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
13536 getCommonSizeExpr(Ctx, AX, AY), getCommonSizeModifier(AX, AY),
13538 AX->getBracketsRange() == AY->getBracketsRange()
13539 ? AX->getBracketsRange()
13540 : SourceRange());
13541 }
13542 case Type::ConstantArray: {
13543 const auto *AX = cast<ConstantArrayType>(X),
13544 *AY = cast<ConstantArrayType>(Y);
13545 assert(AX->getSize() == AY->getSize());
13546 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
13547 ? AX->getSizeExpr()
13548 : nullptr;
13549 return Ctx.getConstantArrayType(
13550 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
13552 }
13553 case Type::ArrayParameter: {
13554 const auto *AX = cast<ArrayParameterType>(X),
13555 *AY = cast<ArrayParameterType>(Y);
13556 assert(AX->getSize() == AY->getSize());
13557 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
13558 ? AX->getSizeExpr()
13559 : nullptr;
13560 auto ArrayTy = Ctx.getConstantArrayType(
13561 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
13563 return Ctx.getArrayParameterType(ArrayTy);
13564 }
13565 case Type::Atomic: {
13566 const auto *AX = cast<AtomicType>(X), *AY = cast<AtomicType>(Y);
13567 return Ctx.getAtomicType(
13568 Ctx.getCommonSugaredType(AX->getValueType(), AY->getValueType()));
13569 }
13570 case Type::Complex: {
13571 const auto *CX = cast<ComplexType>(X), *CY = cast<ComplexType>(Y);
13572 return Ctx.getComplexType(getCommonArrayElementType(Ctx, CX, QX, CY, QY));
13573 }
13574 case Type::Pointer: {
13575 const auto *PX = cast<PointerType>(X), *PY = cast<PointerType>(Y);
13576 return Ctx.getPointerType(getCommonPointeeType(Ctx, PX, PY));
13577 }
13578 case Type::BlockPointer: {
13579 const auto *PX = cast<BlockPointerType>(X), *PY = cast<BlockPointerType>(Y);
13580 return Ctx.getBlockPointerType(getCommonPointeeType(Ctx, PX, PY));
13581 }
13582 case Type::ObjCObjectPointer: {
13583 const auto *PX = cast<ObjCObjectPointerType>(X),
13584 *PY = cast<ObjCObjectPointerType>(Y);
13585 return Ctx.getObjCObjectPointerType(getCommonPointeeType(Ctx, PX, PY));
13586 }
13587 case Type::MemberPointer: {
13588 const auto *PX = cast<MemberPointerType>(X),
13589 *PY = cast<MemberPointerType>(Y);
13590 return Ctx.getMemberPointerType(
13591 getCommonPointeeType(Ctx, PX, PY),
13592 Ctx.getCommonSugaredType(QualType(PX->getClass(), 0),
13593 QualType(PY->getClass(), 0))
13594 .getTypePtr());
13595 }
13596 case Type::LValueReference: {
13597 const auto *PX = cast<LValueReferenceType>(X),
13598 *PY = cast<LValueReferenceType>(Y);
13599 // FIXME: Preserve PointeeTypeAsWritten.
13600 return Ctx.getLValueReferenceType(getCommonPointeeType(Ctx, PX, PY),
13601 PX->isSpelledAsLValue() ||
13602 PY->isSpelledAsLValue());
13603 }
13604 case Type::RValueReference: {
13605 const auto *PX = cast<RValueReferenceType>(X),
13606 *PY = cast<RValueReferenceType>(Y);
13607 // FIXME: Preserve PointeeTypeAsWritten.
13608 return Ctx.getRValueReferenceType(getCommonPointeeType(Ctx, PX, PY));
13609 }
13610 case Type::DependentAddressSpace: {
13611 const auto *PX = cast<DependentAddressSpaceType>(X),
13612 *PY = cast<DependentAddressSpaceType>(Y);
13613 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
13614 return Ctx.getDependentAddressSpaceType(getCommonPointeeType(Ctx, PX, PY),
13615 PX->getAddrSpaceExpr(),
13616 getCommonAttrLoc(PX, PY));
13617 }
13618 case Type::FunctionNoProto: {
13619 const auto *FX = cast<FunctionNoProtoType>(X),
13620 *FY = cast<FunctionNoProtoType>(Y);
13621 assert(FX->getExtInfo() == FY->getExtInfo());
13622 return Ctx.getFunctionNoProtoType(
13623 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType()),
13624 FX->getExtInfo());
13625 }
13626 case Type::FunctionProto: {
13627 const auto *FX = cast<FunctionProtoType>(X),
13628 *FY = cast<FunctionProtoType>(Y);
13629 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
13630 EPIY = FY->getExtProtoInfo();
13631 assert(EPIX.ExtInfo == EPIY.ExtInfo);
13632 assert(EPIX.ExtParameterInfos == EPIY.ExtParameterInfos);
13633 assert(EPIX.RefQualifier == EPIY.RefQualifier);
13634 assert(EPIX.TypeQuals == EPIY.TypeQuals);
13635 assert(EPIX.Variadic == EPIY.Variadic);
13636
13637 // FIXME: Can we handle an empty EllipsisLoc?
13638 // Use emtpy EllipsisLoc if X and Y differ.
13639
13640 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
13641
13642 QualType R =
13643 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType());
13644 auto P = getCommonTypes(Ctx, FX->param_types(), FY->param_types(),
13645 /*Unqualified=*/true);
13646
13647 SmallVector<QualType, 8> Exceptions;
13649 EPIX.ExceptionSpec, EPIY.ExceptionSpec, Exceptions, true);
13650 return Ctx.getFunctionType(R, P, EPIX);
13651 }
13652 case Type::ObjCObject: {
13653 const auto *OX = cast<ObjCObjectType>(X), *OY = cast<ObjCObjectType>(Y);
13654 assert(
13655 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
13656 OY->getProtocols().begin(), OY->getProtocols().end(),
13657 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
13658 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
13659 }) &&
13660 "protocol lists must be the same");
13661 auto TAs = getCommonTypes(Ctx, OX->getTypeArgsAsWritten(),
13662 OY->getTypeArgsAsWritten());
13663 return Ctx.getObjCObjectType(
13664 Ctx.getCommonSugaredType(OX->getBaseType(), OY->getBaseType()), TAs,
13665 OX->getProtocols(),
13666 OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
13667 }
13668 case Type::ConstantMatrix: {
13669 const auto *MX = cast<ConstantMatrixType>(X),
13670 *MY = cast<ConstantMatrixType>(Y);
13671 assert(MX->getNumRows() == MY->getNumRows());
13672 assert(MX->getNumColumns() == MY->getNumColumns());
13673 return Ctx.getConstantMatrixType(getCommonElementType(Ctx, MX, MY),
13674 MX->getNumRows(), MX->getNumColumns());
13675 }
13676 case Type::DependentSizedMatrix: {
13677 const auto *MX = cast<DependentSizedMatrixType>(X),
13678 *MY = cast<DependentSizedMatrixType>(Y);
13679 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
13680 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
13681 return Ctx.getDependentSizedMatrixType(
13682 getCommonElementType(Ctx, MX, MY), MX->getRowExpr(),
13683 MX->getColumnExpr(), getCommonAttrLoc(MX, MY));
13684 }
13685 case Type::Vector: {
13686 const auto *VX = cast<VectorType>(X), *VY = cast<VectorType>(Y);
13687 assert(VX->getNumElements() == VY->getNumElements());
13688 assert(VX->getVectorKind() == VY->getVectorKind());
13689 return Ctx.getVectorType(getCommonElementType(Ctx, VX, VY),
13690 VX->getNumElements(), VX->getVectorKind());
13691 }
13692 case Type::ExtVector: {
13693 const auto *VX = cast<ExtVectorType>(X), *VY = cast<ExtVectorType>(Y);
13694 assert(VX->getNumElements() == VY->getNumElements());
13695 return Ctx.getExtVectorType(getCommonElementType(Ctx, VX, VY),
13696 VX->getNumElements());
13697 }
13698 case Type::DependentSizedExtVector: {
13699 const auto *VX = cast<DependentSizedExtVectorType>(X),
13700 *VY = cast<DependentSizedExtVectorType>(Y);
13702 getCommonSizeExpr(Ctx, VX, VY),
13703 getCommonAttrLoc(VX, VY));
13704 }
13705 case Type::DependentVector: {
13706 const auto *VX = cast<DependentVectorType>(X),
13707 *VY = cast<DependentVectorType>(Y);
13708 assert(VX->getVectorKind() == VY->getVectorKind());
13709 return Ctx.getDependentVectorType(
13710 getCommonElementType(Ctx, VX, VY), getCommonSizeExpr(Ctx, VX, VY),
13711 getCommonAttrLoc(VX, VY), VX->getVectorKind());
13712 }
13713 case Type::InjectedClassName: {
13714 const auto *IX = cast<InjectedClassNameType>(X),
13715 *IY = cast<InjectedClassNameType>(Y);
13716 return Ctx.getInjectedClassNameType(
13717 getCommonDeclChecked(IX->getDecl(), IY->getDecl()),
13718 Ctx.getCommonSugaredType(IX->getInjectedSpecializationType(),
13719 IY->getInjectedSpecializationType()));
13720 }
13721 case Type::TemplateSpecialization: {
13722 const auto *TX = cast<TemplateSpecializationType>(X),
13723 *TY = cast<TemplateSpecializationType>(Y);
13724 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
13725 TY->template_arguments());
13727 ::getCommonTemplateNameChecked(Ctx, TX->getTemplateName(),
13728 TY->getTemplateName(),
13729 /*IgnoreDeduced=*/true),
13730 As, X->getCanonicalTypeInternal());
13731 }
13732 case Type::Decltype: {
13733 const auto *DX = cast<DecltypeType>(X);
13734 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Y);
13735 assert(DX->isDependentType());
13736 assert(DY->isDependentType());
13737 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
13738 // As Decltype is not uniqued, building a common type would be wasteful.
13739 return QualType(DX, 0);
13740 }
13741 case Type::PackIndexing: {
13742 const auto *DX = cast<PackIndexingType>(X);
13743 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Y);
13744 assert(DX->isDependentType());
13745 assert(DY->isDependentType());
13746 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
13747 return QualType(DX, 0);
13748 }
13749 case Type::DependentName: {
13750 const auto *NX = cast<DependentNameType>(X),
13751 *NY = cast<DependentNameType>(Y);
13752 assert(NX->getIdentifier() == NY->getIdentifier());
13753 return Ctx.getDependentNameType(
13754 getCommonTypeKeyword(NX, NY), getCommonNNS(Ctx, NX, NY),
13755 NX->getIdentifier(), NX->getCanonicalTypeInternal());
13756 }
13757 case Type::DependentTemplateSpecialization: {
13758 const auto *TX = cast<DependentTemplateSpecializationType>(X),
13759 *TY = cast<DependentTemplateSpecializationType>(Y);
13760 assert(TX->getIdentifier() == TY->getIdentifier());
13761 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
13762 TY->template_arguments());
13764 getCommonTypeKeyword(TX, TY), getCommonNNS(Ctx, TX, TY),
13765 TX->getIdentifier(), As);
13766 }
13767 case Type::UnaryTransform: {
13768 const auto *TX = cast<UnaryTransformType>(X),
13769 *TY = cast<UnaryTransformType>(Y);
13770 assert(TX->getUTTKind() == TY->getUTTKind());
13771 return Ctx.getUnaryTransformType(
13772 Ctx.getCommonSugaredType(TX->getBaseType(), TY->getBaseType()),
13773 Ctx.getCommonSugaredType(TX->getUnderlyingType(),
13774 TY->getUnderlyingType()),
13775 TX->getUTTKind());
13776 }
13777 case Type::PackExpansion: {
13778 const auto *PX = cast<PackExpansionType>(X),
13779 *PY = cast<PackExpansionType>(Y);
13780 assert(PX->getNumExpansions() == PY->getNumExpansions());
13781 return Ctx.getPackExpansionType(
13782 Ctx.getCommonSugaredType(PX->getPattern(), PY->getPattern()),
13783 PX->getNumExpansions(), false);
13784 }
13785 case Type::Pipe: {
13786 const auto *PX = cast<PipeType>(X), *PY = cast<PipeType>(Y);
13787 assert(PX->isReadOnly() == PY->isReadOnly());
13788 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
13790 return (Ctx.*MP)(getCommonElementType(Ctx, PX, PY));
13791 }
13792 case Type::TemplateTypeParm: {
13793 const auto *TX = cast<TemplateTypeParmType>(X),
13794 *TY = cast<TemplateTypeParmType>(Y);
13795 assert(TX->getDepth() == TY->getDepth());
13796 assert(TX->getIndex() == TY->getIndex());
13797 assert(TX->isParameterPack() == TY->isParameterPack());
13798 return Ctx.getTemplateTypeParmType(
13799 TX->getDepth(), TX->getIndex(), TX->isParameterPack(),
13800 getCommonDecl(TX->getDecl(), TY->getDecl()));
13801 }
13802 }
13803 llvm_unreachable("Unknown Type Class");
13804}
13805
13807 const Type *Y,
13808 SplitQualType Underlying) {
13809 Type::TypeClass TC = X->getTypeClass();
13810 if (TC != Y->getTypeClass())
13811 return QualType();
13812 switch (TC) {
13813#define UNEXPECTED_TYPE(Class, Kind) \
13814 case Type::Class: \
13815 llvm_unreachable("Unexpected " Kind ": " #Class);
13816#define TYPE(Class, Base)
13817#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
13818#include "clang/AST/TypeNodes.inc"
13819
13820#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
13823 CANONICAL_TYPE(BlockPointer)
13824 CANONICAL_TYPE(Builtin)
13826 CANONICAL_TYPE(ConstantArray)
13827 CANONICAL_TYPE(ArrayParameter)
13828 CANONICAL_TYPE(ConstantMatrix)
13830 CANONICAL_TYPE(ExtVector)
13831 CANONICAL_TYPE(FunctionNoProto)
13832 CANONICAL_TYPE(FunctionProto)
13833 CANONICAL_TYPE(IncompleteArray)
13834 CANONICAL_TYPE(HLSLAttributedResource)
13835 CANONICAL_TYPE(LValueReference)
13836 CANONICAL_TYPE(MemberPointer)
13837 CANONICAL_TYPE(ObjCInterface)
13838 CANONICAL_TYPE(ObjCObject)
13839 CANONICAL_TYPE(ObjCObjectPointer)
13843 CANONICAL_TYPE(RValueReference)
13844 CANONICAL_TYPE(VariableArray)
13846#undef CANONICAL_TYPE
13847
13848#undef UNEXPECTED_TYPE
13849
13850 case Type::Adjusted: {
13851 const auto *AX = cast<AdjustedType>(X), *AY = cast<AdjustedType>(Y);
13852 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
13853 if (!Ctx.hasSameType(OX, OY))
13854 return QualType();
13855 // FIXME: It's inefficient to have to unify the original types.
13856 return Ctx.getAdjustedType(Ctx.getCommonSugaredType(OX, OY),
13857 Ctx.getQualifiedType(Underlying));
13858 }
13859 case Type::Decayed: {
13860 const auto *DX = cast<DecayedType>(X), *DY = cast<DecayedType>(Y);
13861 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
13862 if (!Ctx.hasSameType(OX, OY))
13863 return QualType();
13864 // FIXME: It's inefficient to have to unify the original types.
13865 return Ctx.getDecayedType(Ctx.getCommonSugaredType(OX, OY),
13866 Ctx.getQualifiedType(Underlying));
13867 }
13868 case Type::Attributed: {
13869 const auto *AX = cast<AttributedType>(X), *AY = cast<AttributedType>(Y);
13870 AttributedType::Kind Kind = AX->getAttrKind();
13871 if (Kind != AY->getAttrKind())
13872 return QualType();
13873 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
13874 if (!Ctx.hasSameType(MX, MY))
13875 return QualType();
13876 // FIXME: It's inefficient to have to unify the modified types.
13877 return Ctx.getAttributedType(Kind, Ctx.getCommonSugaredType(MX, MY),
13878 Ctx.getQualifiedType(Underlying),
13879 AX->getAttr());
13880 }
13881 case Type::BTFTagAttributed: {
13882 const auto *BX = cast<BTFTagAttributedType>(X);
13883 const BTFTypeTagAttr *AX = BX->getAttr();
13884 // The attribute is not uniqued, so just compare the tag.
13885 if (AX->getBTFTypeTag() !=
13886 cast<BTFTagAttributedType>(Y)->getAttr()->getBTFTypeTag())
13887 return QualType();
13888 return Ctx.getBTFTagAttributedType(AX, Ctx.getQualifiedType(Underlying));
13889 }
13890 case Type::Auto: {
13891 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
13892
13893 AutoTypeKeyword KW = AX->getKeyword();
13894 if (KW != AY->getKeyword())
13895 return QualType();
13896
13897 ConceptDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(),
13898 AY->getTypeConstraintConcept());
13900 if (CD &&
13901 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
13902 AY->getTypeConstraintArguments())) {
13903 CD = nullptr; // The arguments differ, so make it unconstrained.
13904 As.clear();
13905 }
13906
13907 // Both auto types can't be dependent, otherwise they wouldn't have been
13908 // sugar. This implies they can't contain unexpanded packs either.
13909 return Ctx.getAutoType(Ctx.getQualifiedType(Underlying), AX->getKeyword(),
13910 /*IsDependent=*/false, /*IsPack=*/false, CD, As);
13911 }
13912 case Type::PackIndexing:
13913 case Type::Decltype:
13914 return QualType();
13915 case Type::DeducedTemplateSpecialization:
13916 // FIXME: Try to merge these.
13917 return QualType();
13918
13919 case Type::Elaborated: {
13920 const auto *EX = cast<ElaboratedType>(X), *EY = cast<ElaboratedType>(Y);
13921 return Ctx.getElaboratedType(
13922 ::getCommonTypeKeyword(EX, EY), ::getCommonNNS(Ctx, EX, EY),
13923 Ctx.getQualifiedType(Underlying),
13924 ::getCommonDecl(EX->getOwnedTagDecl(), EY->getOwnedTagDecl()));
13925 }
13926 case Type::MacroQualified: {
13927 const auto *MX = cast<MacroQualifiedType>(X),
13928 *MY = cast<MacroQualifiedType>(Y);
13929 const IdentifierInfo *IX = MX->getMacroIdentifier();
13930 if (IX != MY->getMacroIdentifier())
13931 return QualType();
13932 return Ctx.getMacroQualifiedType(Ctx.getQualifiedType(Underlying), IX);
13933 }
13934 case Type::SubstTemplateTypeParm: {
13935 const auto *SX = cast<SubstTemplateTypeParmType>(X),
13936 *SY = cast<SubstTemplateTypeParmType>(Y);
13937 Decl *CD =
13938 ::getCommonDecl(SX->getAssociatedDecl(), SY->getAssociatedDecl());
13939 if (!CD)
13940 return QualType();
13941 unsigned Index = SX->getIndex();
13942 if (Index != SY->getIndex())
13943 return QualType();
13944 auto PackIndex = SX->getPackIndex();
13945 if (PackIndex != SY->getPackIndex())
13946 return QualType();
13947 return Ctx.getSubstTemplateTypeParmType(Ctx.getQualifiedType(Underlying),
13948 CD, Index, PackIndex);
13949 }
13950 case Type::ObjCTypeParam:
13951 // FIXME: Try to merge these.
13952 return QualType();
13953 case Type::Paren:
13954 return Ctx.getParenType(Ctx.getQualifiedType(Underlying));
13955
13956 case Type::TemplateSpecialization: {
13957 const auto *TX = cast<TemplateSpecializationType>(X),
13958 *TY = cast<TemplateSpecializationType>(Y);
13959 TemplateName CTN =
13960 ::getCommonTemplateName(Ctx, TX->getTemplateName(),
13961 TY->getTemplateName(), /*IgnoreDeduced=*/true);
13962 if (!CTN.getAsVoidPointer())
13963 return QualType();
13965 if (getCommonTemplateArguments(Ctx, Args, TX->template_arguments(),
13966 TY->template_arguments()))
13967 return QualType();
13968 return Ctx.getTemplateSpecializationType(CTN, Args,
13969 Ctx.getQualifiedType(Underlying));
13970 }
13971 case Type::Typedef: {
13972 const auto *TX = cast<TypedefType>(X), *TY = cast<TypedefType>(Y);
13973 const TypedefNameDecl *CD = ::getCommonDecl(TX->getDecl(), TY->getDecl());
13974 if (!CD)
13975 return QualType();
13976 return Ctx.getTypedefType(CD, Ctx.getQualifiedType(Underlying));
13977 }
13978 case Type::TypeOf: {
13979 // The common sugar between two typeof expressions, where one is
13980 // potentially a typeof_unqual and the other is not, we unify to the
13981 // qualified type as that retains the most information along with the type.
13982 // We only return a typeof_unqual type when both types are unqual types.
13984 if (cast<TypeOfType>(X)->getKind() == cast<TypeOfType>(Y)->getKind() &&
13985 cast<TypeOfType>(X)->getKind() == TypeOfKind::Unqualified)
13987 return Ctx.getTypeOfType(Ctx.getQualifiedType(Underlying), Kind);
13988 }
13989 case Type::TypeOfExpr:
13990 return QualType();
13991
13992 case Type::UnaryTransform: {
13993 const auto *UX = cast<UnaryTransformType>(X),
13994 *UY = cast<UnaryTransformType>(Y);
13995 UnaryTransformType::UTTKind KX = UX->getUTTKind();
13996 if (KX != UY->getUTTKind())
13997 return QualType();
13998 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
13999 if (!Ctx.hasSameType(BX, BY))
14000 return QualType();
14001 // FIXME: It's inefficient to have to unify the base types.
14002 return Ctx.getUnaryTransformType(Ctx.getCommonSugaredType(BX, BY),
14003 Ctx.getQualifiedType(Underlying), KX);
14004 }
14005 case Type::Using: {
14006 const auto *UX = cast<UsingType>(X), *UY = cast<UsingType>(Y);
14007 const UsingShadowDecl *CD =
14008 ::getCommonDecl(UX->getFoundDecl(), UY->getFoundDecl());
14009 if (!CD)
14010 return QualType();
14011 return Ctx.getUsingType(CD, Ctx.getQualifiedType(Underlying));
14012 }
14013 case Type::CountAttributed: {
14014 const auto *DX = cast<CountAttributedType>(X),
14015 *DY = cast<CountAttributedType>(Y);
14016 if (DX->isCountInBytes() != DY->isCountInBytes())
14017 return QualType();
14018 if (DX->isOrNull() != DY->isOrNull())
14019 return QualType();
14020 Expr *CEX = DX->getCountExpr();
14021 Expr *CEY = DY->getCountExpr();
14022 llvm::ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
14023 if (Ctx.hasSameExpr(CEX, CEY))
14024 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14025 DX->isCountInBytes(), DX->isOrNull(),
14026 CDX);
14027 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
14028 return QualType();
14029 // Two declarations with the same integer constant may still differ in their
14030 // expression pointers, so we need to evaluate them.
14031 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
14032 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
14033 if (VX != VY)
14034 return QualType();
14035 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14036 DX->isCountInBytes(), DX->isOrNull(),
14037 CDX);
14038 }
14039 }
14040 llvm_unreachable("Unhandled Type Class");
14041}
14042
14043static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
14045 while (true) {
14046 QTotal.addConsistentQualifiers(T.Quals);
14048 if (NT == QualType(T.Ty, 0))
14049 break;
14050 R.push_back(T);
14051 T = NT.split();
14052 }
14053 return R;
14054}
14055
14057 bool Unqualified) {
14058 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
14059 if (X == Y)
14060 return X;
14061 if (!Unqualified) {
14062 if (X.isCanonical())
14063 return X;
14064 if (Y.isCanonical())
14065 return Y;
14066 }
14067
14068 SplitQualType SX = X.split(), SY = Y.split();
14069 Qualifiers QX, QY;
14070 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
14071 // until we reach their underlying "canonical nodes". Note these are not
14072 // necessarily canonical types, as they may still have sugared properties.
14073 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
14074 auto Xs = ::unwrapSugar(SX, QX), Ys = ::unwrapSugar(SY, QY);
14075 if (SX.Ty != SY.Ty) {
14076 // The canonical nodes differ. Build a common canonical node out of the two,
14077 // unifying their sugar. This may recurse back here.
14078 SX.Ty =
14079 ::getCommonNonSugarTypeNode(*this, SX.Ty, QX, SY.Ty, QY).getTypePtr();
14080 } else {
14081 // The canonical nodes were identical: We may have desugared too much.
14082 // Add any common sugar back in.
14083 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
14084 QX -= SX.Quals;
14085 QY -= SY.Quals;
14086 SX = Xs.pop_back_val();
14087 SY = Ys.pop_back_val();
14088 }
14089 }
14090 if (Unqualified)
14092 else
14093 assert(QX == QY);
14094
14095 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
14096 // related. Walk up these nodes, unifying them and adding the result.
14097 while (!Xs.empty() && !Ys.empty()) {
14098 auto Underlying = SplitQualType(
14099 SX.Ty, Qualifiers::removeCommonQualifiers(SX.Quals, SY.Quals));
14100 SX = Xs.pop_back_val();
14101 SY = Ys.pop_back_val();
14102 SX.Ty = ::getCommonSugarTypeNode(*this, SX.Ty, SY.Ty, Underlying)
14104 // Stop at the first pair which is unrelated.
14105 if (!SX.Ty) {
14106 SX.Ty = Underlying.Ty;
14107 break;
14108 }
14109 QX -= Underlying.Quals;
14110 };
14111
14112 // Add back the missing accumulated qualifiers, which were stripped off
14113 // with the sugar nodes we could not unify.
14114 QualType R = getQualifiedType(SX.Ty, QX);
14115 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
14116 return R;
14117}
14118
14120 assert(Ty->isFixedPointType());
14121
14123 return Ty;
14124
14125 switch (Ty->castAs<BuiltinType>()->getKind()) {
14126 default:
14127 llvm_unreachable("Not a saturated fixed point type!");
14128 case BuiltinType::SatShortAccum:
14129 return ShortAccumTy;
14130 case BuiltinType::SatAccum:
14131 return AccumTy;
14132 case BuiltinType::SatLongAccum:
14133 return LongAccumTy;
14134 case BuiltinType::SatUShortAccum:
14135 return UnsignedShortAccumTy;
14136 case BuiltinType::SatUAccum:
14137 return UnsignedAccumTy;
14138 case BuiltinType::SatULongAccum:
14139 return UnsignedLongAccumTy;
14140 case BuiltinType::SatShortFract:
14141 return ShortFractTy;
14142 case BuiltinType::SatFract:
14143 return FractTy;
14144 case BuiltinType::SatLongFract:
14145 return LongFractTy;
14146 case BuiltinType::SatUShortFract:
14147 return UnsignedShortFractTy;
14148 case BuiltinType::SatUFract:
14149 return UnsignedFractTy;
14150 case BuiltinType::SatULongFract:
14151 return UnsignedLongFractTy;
14152 }
14153}
14154
14156 assert(Ty->isFixedPointType());
14157
14158 if (Ty->isSaturatedFixedPointType()) return Ty;
14159
14160 switch (Ty->castAs<BuiltinType>()->getKind()) {
14161 default:
14162 llvm_unreachable("Not a fixed point type!");
14163 case BuiltinType::ShortAccum:
14164 return SatShortAccumTy;
14165 case BuiltinType::Accum:
14166 return SatAccumTy;
14167 case BuiltinType::LongAccum:
14168 return SatLongAccumTy;
14169 case BuiltinType::UShortAccum:
14171 case BuiltinType::UAccum:
14172 return SatUnsignedAccumTy;
14173 case BuiltinType::ULongAccum:
14175 case BuiltinType::ShortFract:
14176 return SatShortFractTy;
14177 case BuiltinType::Fract:
14178 return SatFractTy;
14179 case BuiltinType::LongFract:
14180 return SatLongFractTy;
14181 case BuiltinType::UShortFract:
14183 case BuiltinType::UFract:
14184 return SatUnsignedFractTy;
14185 case BuiltinType::ULongFract:
14187 }
14188}
14189
14191 if (LangOpts.OpenCL)
14193
14194 if (LangOpts.CUDA)
14196
14197 return getLangASFromTargetAS(AS);
14198}
14199
14200// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
14201// doesn't include ASTContext.h
14202template
14204 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
14206 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
14207 const clang::ASTContext &Ctx, Decl *Value);
14208
14210 assert(Ty->isFixedPointType());
14211
14212 const TargetInfo &Target = getTargetInfo();
14213 switch (Ty->castAs<BuiltinType>()->getKind()) {
14214 default:
14215 llvm_unreachable("Not a fixed point type!");
14216 case BuiltinType::ShortAccum:
14217 case BuiltinType::SatShortAccum:
14218 return Target.getShortAccumScale();
14219 case BuiltinType::Accum:
14220 case BuiltinType::SatAccum:
14221 return Target.getAccumScale();
14222 case BuiltinType::LongAccum:
14223 case BuiltinType::SatLongAccum:
14224 return Target.getLongAccumScale();
14225 case BuiltinType::UShortAccum:
14226 case BuiltinType::SatUShortAccum:
14227 return Target.getUnsignedShortAccumScale();
14228 case BuiltinType::UAccum:
14229 case BuiltinType::SatUAccum:
14230 return Target.getUnsignedAccumScale();
14231 case BuiltinType::ULongAccum:
14232 case BuiltinType::SatULongAccum:
14233 return Target.getUnsignedLongAccumScale();
14234 case BuiltinType::ShortFract:
14235 case BuiltinType::SatShortFract:
14236 return Target.getShortFractScale();
14237 case BuiltinType::Fract:
14238 case BuiltinType::SatFract:
14239 return Target.getFractScale();
14240 case BuiltinType::LongFract:
14241 case BuiltinType::SatLongFract:
14242 return Target.getLongFractScale();
14243 case BuiltinType::UShortFract:
14244 case BuiltinType::SatUShortFract:
14245 return Target.getUnsignedShortFractScale();
14246 case BuiltinType::UFract:
14247 case BuiltinType::SatUFract:
14248 return Target.getUnsignedFractScale();
14249 case BuiltinType::ULongFract:
14250 case BuiltinType::SatULongFract:
14251 return Target.getUnsignedLongFractScale();
14252 }
14253}
14254
14256 assert(Ty->isFixedPointType());
14257
14258 const TargetInfo &Target = getTargetInfo();
14259 switch (Ty->castAs<BuiltinType>()->getKind()) {
14260 default:
14261 llvm_unreachable("Not a fixed point type!");
14262 case BuiltinType::ShortAccum:
14263 case BuiltinType::SatShortAccum:
14264 return Target.getShortAccumIBits();
14265 case BuiltinType::Accum:
14266 case BuiltinType::SatAccum:
14267 return Target.getAccumIBits();
14268 case BuiltinType::LongAccum:
14269 case BuiltinType::SatLongAccum:
14270 return Target.getLongAccumIBits();
14271 case BuiltinType::UShortAccum:
14272 case BuiltinType::SatUShortAccum:
14273 return Target.getUnsignedShortAccumIBits();
14274 case BuiltinType::UAccum:
14275 case BuiltinType::SatUAccum:
14276 return Target.getUnsignedAccumIBits();
14277 case BuiltinType::ULongAccum:
14278 case BuiltinType::SatULongAccum:
14279 return Target.getUnsignedLongAccumIBits();
14280 case BuiltinType::ShortFract:
14281 case BuiltinType::SatShortFract:
14282 case BuiltinType::Fract:
14283 case BuiltinType::SatFract:
14284 case BuiltinType::LongFract:
14285 case BuiltinType::SatLongFract:
14286 case BuiltinType::UShortFract:
14287 case BuiltinType::SatUShortFract:
14288 case BuiltinType::UFract:
14289 case BuiltinType::SatUFract:
14290 case BuiltinType::ULongFract:
14291 case BuiltinType::SatULongFract:
14292 return 0;
14293 }
14294}
14295
14296llvm::FixedPointSemantics
14298 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
14299 "Can only get the fixed point semantics for a "
14300 "fixed point or integer type.");
14301 if (Ty->isIntegerType())
14302 return llvm::FixedPointSemantics::GetIntegerSemantics(
14303 getIntWidth(Ty), Ty->isSignedIntegerType());
14304
14305 bool isSigned = Ty->isSignedFixedPointType();
14306 return llvm::FixedPointSemantics(
14307 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
14309 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
14310}
14311
14312llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
14313 assert(Ty->isFixedPointType());
14314 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
14315}
14316
14317llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
14318 assert(Ty->isFixedPointType());
14319 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
14320}
14321
14323 assert(Ty->isUnsignedFixedPointType() &&
14324 "Expected unsigned fixed point type");
14325
14326 switch (Ty->castAs<BuiltinType>()->getKind()) {
14327 case BuiltinType::UShortAccum:
14328 return ShortAccumTy;
14329 case BuiltinType::UAccum:
14330 return AccumTy;
14331 case BuiltinType::ULongAccum:
14332 return LongAccumTy;
14333 case BuiltinType::SatUShortAccum:
14334 return SatShortAccumTy;
14335 case BuiltinType::SatUAccum:
14336 return SatAccumTy;
14337 case BuiltinType::SatULongAccum:
14338 return SatLongAccumTy;
14339 case BuiltinType::UShortFract:
14340 return ShortFractTy;
14341 case BuiltinType::UFract:
14342 return FractTy;
14343 case BuiltinType::ULongFract:
14344 return LongFractTy;
14345 case BuiltinType::SatUShortFract:
14346 return SatShortFractTy;
14347 case BuiltinType::SatUFract:
14348 return SatFractTy;
14349 case BuiltinType::SatULongFract:
14350 return SatLongFractTy;
14351 default:
14352 llvm_unreachable("Unexpected unsigned fixed point type");
14353 }
14354}
14355
14356// Given a list of FMV features, return a concatenated list of the
14357// corresponding backend features (which may contain duplicates).
14358static std::vector<std::string> getFMVBackendFeaturesFor(
14359 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) {
14360 std::vector<std::string> BackendFeats{{"+fmv"}};
14361 llvm::AArch64::ExtensionSet FeatureBits;
14362 for (StringRef F : FMVFeatStrings)
14363 if (auto FMVExt = llvm::AArch64::parseFMVExtension(F))
14364 if (FMVExt->ID)
14365 FeatureBits.enable(*FMVExt->ID);
14366 FeatureBits.toLLVMFeatureList(BackendFeats);
14367 return BackendFeats;
14368}
14369
14371ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
14372 assert(TD != nullptr);
14373 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TD->getFeaturesStr());
14374
14375 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
14376 return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
14377 });
14378 return ParsedAttr;
14379}
14380
14381void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
14382 const FunctionDecl *FD) const {
14383 if (FD)
14384 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
14385 else
14386 Target->initFeatureMap(FeatureMap, getDiagnostics(),
14387 Target->getTargetOpts().CPU,
14388 Target->getTargetOpts().Features);
14389}
14390
14391// Fills in the supplied string map with the set of target features for the
14392// passed in function.
14393void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
14394 GlobalDecl GD) const {
14395 StringRef TargetCPU = Target->getTargetOpts().CPU;
14396 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
14397 if (const auto *TD = FD->getAttr<TargetAttr>()) {
14399
14400 // Make a copy of the features as passed on the command line into the
14401 // beginning of the additional features from the function to override.
14402 // AArch64 handles command line option features in parseTargetAttr().
14403 if (!Target->getTriple().isAArch64())
14404 ParsedAttr.Features.insert(
14405 ParsedAttr.Features.begin(),
14406 Target->getTargetOpts().FeaturesAsWritten.begin(),
14407 Target->getTargetOpts().FeaturesAsWritten.end());
14408
14409 if (ParsedAttr.CPU != "" && Target->isValidCPUName(ParsedAttr.CPU))
14410 TargetCPU = ParsedAttr.CPU;
14411
14412 // Now populate the feature map, first with the TargetCPU which is either
14413 // the default or a new one from the target attribute string. Then we'll use
14414 // the passed in features (FeaturesAsWritten) along with the new ones from
14415 // the attribute.
14416 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
14417 ParsedAttr.Features);
14418 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
14420 Target->getCPUSpecificCPUDispatchFeatures(
14421 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
14422 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
14423 Features.insert(Features.begin(),
14424 Target->getTargetOpts().FeaturesAsWritten.begin(),
14425 Target->getTargetOpts().FeaturesAsWritten.end());
14426 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14427 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
14428 if (Target->getTriple().isAArch64()) {
14430 TC->getFeatures(Feats, GD.getMultiVersionIndex());
14431 std::vector<std::string> Features = getFMVBackendFeaturesFor(Feats);
14432 Features.insert(Features.begin(),
14433 Target->getTargetOpts().FeaturesAsWritten.begin(),
14434 Target->getTargetOpts().FeaturesAsWritten.end());
14435 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14436 } else if (Target->getTriple().isRISCV()) {
14437 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
14438 std::vector<std::string> Features;
14439 if (VersionStr != "default") {
14440 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(VersionStr);
14441 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
14442 ParsedAttr.Features.end());
14443 }
14444 Features.insert(Features.begin(),
14445 Target->getTargetOpts().FeaturesAsWritten.begin(),
14446 Target->getTargetOpts().FeaturesAsWritten.end());
14447 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14448 } else {
14449 std::vector<std::string> Features;
14450 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
14451 if (VersionStr.starts_with("arch="))
14452 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
14453 else if (VersionStr != "default")
14454 Features.push_back((StringRef{"+"} + VersionStr).str());
14455 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14456 }
14457 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
14458 std::vector<std::string> Features;
14459 if (Target->getTriple().isRISCV()) {
14460 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TV->getName());
14461 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
14462 ParsedAttr.Features.end());
14463 } else {
14464 assert(Target->getTriple().isAArch64());
14466 TV->getFeatures(Feats);
14467 Features = getFMVBackendFeaturesFor(Feats);
14468 }
14469 Features.insert(Features.begin(),
14470 Target->getTargetOpts().FeaturesAsWritten.begin(),
14471 Target->getTargetOpts().FeaturesAsWritten.end());
14472 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14473 } else {
14474 FeatureMap = Target->getTargetOpts().FeatureMap;
14475 }
14476}
14477
14479 const FunctionDecl *FD) {
14480 return {KernelNameType, FD};
14481}
14482
14484 // If the function declaration to register is invalid or dependent, the
14485 // registration attempt is ignored.
14486 if (FD->isInvalidDecl() || FD->isTemplated())
14487 return;
14488
14489 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
14490 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
14491
14492 // Be tolerant of multiple registration attempts so long as each attempt
14493 // is for the same entity. Callers are obligated to detect and diagnose
14494 // conflicting kernel names prior to calling this function.
14495 CanQualType KernelNameType = getCanonicalType(SKEPAttr->getKernelName());
14496 auto IT = SYCLKernels.find(KernelNameType);
14497 assert((IT == SYCLKernels.end() ||
14498 declaresSameEntity(FD, IT->second.getKernelEntryPointDecl())) &&
14499 "SYCL kernel name conflict");
14500 (void)IT;
14501 SYCLKernels.insert(
14502 std::make_pair(KernelNameType, BuildSYCLKernelInfo(KernelNameType, FD)));
14503}
14504
14506 OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
14507 return *OMPTraitInfoVector.back();
14508}
14509
14512 const ASTContext::SectionInfo &Section) {
14513 if (Section.Decl)
14514 return DB << Section.Decl;
14515 return DB << "a prior #pragma section";
14516}
14517
14519 bool IsInternalVar =
14520 isa<VarDecl>(D) &&
14521 basicGVALinkageForVariable(*this, cast<VarDecl>(D)) == GVA_Internal;
14522 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
14523 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
14524 (D->hasAttr<CUDAConstantAttr>() &&
14525 !D->getAttr<CUDAConstantAttr>()->isImplicit());
14526 // CUDA/HIP: managed variables need to be externalized since it is
14527 // a declaration in IR, therefore cannot have internal linkage. Kernels in
14528 // anonymous name space needs to be externalized to avoid duplicate symbols.
14529 return (IsInternalVar &&
14530 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
14531 (D->hasAttr<CUDAGlobalAttr>() &&
14532 basicGVALinkageForFunction(*this, cast<FunctionDecl>(D)) ==
14533 GVA_Internal);
14534}
14535
14537 return mayExternalize(D) &&
14538 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
14539 CUDADeviceVarODRUsedByHost.count(cast<VarDecl>(D)));
14540}
14541
14542StringRef ASTContext::getCUIDHash() const {
14543 if (!CUIDHash.empty())
14544 return CUIDHash;
14545 if (LangOpts.CUID.empty())
14546 return StringRef();
14547 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
14548 return CUIDHash;
14549}
14550
14551const CXXRecordDecl *
14553 assert(ThisClass);
14554 assert(ThisClass->isPolymorphic());
14555 const CXXRecordDecl *PrimaryBase = ThisClass;
14556 while (1) {
14557 assert(PrimaryBase);
14558 assert(PrimaryBase->isPolymorphic());
14559 auto &Layout = getASTRecordLayout(PrimaryBase);
14560 auto Base = Layout.getPrimaryBase();
14561 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
14562 break;
14563 PrimaryBase = Base;
14564 }
14565 return PrimaryBase;
14566}
14567
14569 StringRef MangledName) {
14570 auto *Method = cast<CXXMethodDecl>(VirtualMethodDecl.getDecl());
14571 assert(Method->isVirtual());
14572 bool DefaultIncludesPointerAuth =
14573 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics;
14574
14575 if (!DefaultIncludesPointerAuth)
14576 return true;
14577
14578 auto Existing = ThunksToBeAbbreviated.find(VirtualMethodDecl);
14579 if (Existing != ThunksToBeAbbreviated.end())
14580 return Existing->second.contains(MangledName.str());
14581
14582 std::unique_ptr<MangleContext> Mangler(createMangleContext());
14583 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks;
14584 auto VtableContext = getVTableContext();
14585 if (const auto *ThunkInfos = VtableContext->getThunkInfo(VirtualMethodDecl)) {
14586 auto *Destructor = dyn_cast<CXXDestructorDecl>(Method);
14587 for (const auto &Thunk : *ThunkInfos) {
14588 SmallString<256> ElidedName;
14589 llvm::raw_svector_ostream ElidedNameStream(ElidedName);
14590 if (Destructor)
14591 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
14592 Thunk, /* elideOverrideInfo */ true,
14593 ElidedNameStream);
14594 else
14595 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ true,
14596 ElidedNameStream);
14597 SmallString<256> MangledName;
14598 llvm::raw_svector_ostream mangledNameStream(MangledName);
14599 if (Destructor)
14600 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
14601 Thunk, /* elideOverrideInfo */ false,
14602 mangledNameStream);
14603 else
14604 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ false,
14605 mangledNameStream);
14606
14607 Thunks[ElidedName].push_back(std::string(MangledName));
14608 }
14609 }
14610 llvm::StringSet<> SimplifiedThunkNames;
14611 for (auto &ThunkList : Thunks) {
14612 llvm::sort(ThunkList.second);
14613 SimplifiedThunkNames.insert(ThunkList.second[0]);
14614 }
14615 bool Result = SimplifiedThunkNames.contains(MangledName);
14616 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames);
14617 return Result;
14618}
This file provides AST data structures related to concepts.
static void SortAndUniqueProtocols(SmallVectorImpl< ObjCProtocolDecl * > &Protocols)
static bool isCanonicalExceptionSpecification(const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType)
static SourceLocation getCommonAttrLoc(const T *X, const T *Y)
static auto getCommonTypes(ASTContext &Ctx, ArrayRef< QualType > Xs, ArrayRef< QualType > Ys, bool Unqualified=false)
static auto getCanonicalTemplateArguments(const ASTContext &C, ArrayRef< TemplateArgument > Args, bool &AnyNonCanonArgs)
static char getObjCEncodingForPrimitiveType(const ASTContext *C, const BuiltinType *BT)
static bool NeedsInjectedClassNameType(const RecordDecl *D)
static bool unionHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD, bool CheckIfTriviallyCopyable)
static NamespaceDecl * getNamespace(const NestedNameSpecifier *X)
static TypedefDecl * CreateHexagonBuiltinVaListDecl(const ASTContext *Context)
#define CANONICAL_TYPE(Class)
static NestedNameSpecifier * getCommonNNS(ASTContext &Ctx, const T *X, const T *Y)
static Decl * getCommonDecl(Decl *X, Decl *Y)
static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, const Decl *D, GVALinkage L)
static bool isTypeTypedefedAsBOOL(QualType T)
static void EncodeBitField(const ASTContext *Ctx, std::string &S, QualType T, const FieldDecl *FD)
static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, const VarDecl *VD)
static const TemplateArgument * getDefaultTemplateArgumentOrNone(const NamedDecl *P)
static uint64_t getSVETypeSize(ASTContext &Context, const BuiltinType *Ty)
getSVETypeSize - Return SVE vector or predicate register size.
#define SUGAR_FREE_TYPE(Class)
static bool getCommonTemplateArguments(ASTContext &Ctx, SmallVectorImpl< TemplateArgument > &R, ArrayRef< TemplateArgument > Xs, ArrayRef< TemplateArgument > Ys)
static bool hasTemplateSpecializationInEncodedString(const Type *T, bool VisitBasesAndFields)
static void getIntersectionOfProtocols(ASTContext &Context, const ObjCInterfaceDecl *CommonBase, const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT, SmallVectorImpl< ObjCProtocolDecl * > &IntersectionSet)
getIntersectionOfProtocols - This routine finds the intersection of set of protocols inherited from t...
static bool areCompatMatrixTypes(const ConstantMatrixType *LHS, const ConstantMatrixType *RHS)
areCompatMatrixTypes - Return true if the two specified matrix types are compatible.
static TypedefDecl * CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context)
static bool sameObjCTypeArgs(ASTContext &ctx, const ObjCInterfaceDecl *iface, ArrayRef< QualType > lhsArgs, ArrayRef< QualType > rhsArgs, bool stripKindOf)
static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs, QualType rhs)
Determine whether the first type is a subtype of the second.
static const Type * getIntegerTypeForEnum(const EnumType *ET)
static const Decl & adjustDeclToTemplate(const Decl &D)
If we have a 'templated' declaration for a template, adjust 'D' to refer to the actual template.
Definition: ASTContext.cpp:355
static int CmpProtocolNames(ObjCProtocolDecl *const *LHS, ObjCProtocolDecl *const *RHS)
CmpProtocolNames - Comparison predicate for sorting protocols alphabetically.
static QualType getCommonElementType(ASTContext &Ctx, const T *X, const T *Y)
static TypedefDecl * CreatePowerABIBuiltinVaListDecl(const ASTContext *Context)
static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y)
static std::optional< int64_t > structHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD, bool CheckIfTriviallyCopyable)
static bool hasSameOverloadableAttrs(const FunctionDecl *A, const FunctionDecl *B)
Determine whether the attributes we can overload on are identical for A and B.
static T * getCommonDeclChecked(T *X, T *Y)
static TypedefDecl * CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context)
static int64_t getSubobjectOffset(const FieldDecl *Field, const ASTContext &Context, const clang::ASTRecordLayout &)
static TypedefDecl * CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context)
static TypedefDecl * CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context)
static TemplateName getCommonTemplateNameChecked(ASTContext &Ctx, TemplateName X, TemplateName Y, bool IgnoreDeduced)
static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, QualType other, bool isBlockReturnType)
Given that we have an enum type and a non-enum type, try to merge them.
static GVALinkage adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D, GVALinkage L)
Adjust the GVALinkage for a declaration based on what an external AST source knows about whether ther...
static TypedefDecl * CreateSystemZBuiltinVaListDecl(const ASTContext *Context)
static std::optional< int64_t > getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context, bool CheckIfTriviallyCopyable)
static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, const FunctionDecl *FD)
#define NON_UNIQUE_TYPE(Class)
static TypedefDecl * CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context)
static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI, const LangOptions &LangOpts)
Definition: ASTContext.cpp:900
static auto getCommonIndexTypeCVRQualifiers(const ArrayType *X, const ArrayType *Y)
static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, ASTContext::GetBuiltinTypeError &Error, bool &RequiresICE, bool AllowTypeModifiers)
DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the pointer over the consume...
FloatingRank
Definition: ASTContext.cpp:104
@ FloatRank
Definition: ASTContext.cpp:108
@ LongDoubleRank
Definition: ASTContext.cpp:110
@ Float16Rank
Definition: ASTContext.cpp:106
@ Ibm128Rank
Definition: ASTContext.cpp:112
@ Float128Rank
Definition: ASTContext.cpp:111
@ BFloat16Rank
Definition: ASTContext.cpp:105
@ HalfRank
Definition: ASTContext.cpp:107
@ DoubleRank
Definition: ASTContext.cpp:109
static TypedefDecl * CreateCharPtrBuiltinVaListDecl(const ASTContext *Context)
static void mergeTypeLists(ASTContext &Ctx, SmallVectorImpl< QualType > &Out, ArrayRef< QualType > X, ArrayRef< QualType > Y)
static bool areSortedAndUniqued(ArrayRef< ObjCProtocolDecl * > Protocols)
static TypeInfoChars getConstantArrayInfoInChars(const ASTContext &Context, const ConstantArrayType *CAT)
getConstantArrayInfoInChars - Performing the computation in CharUnits instead of in bits prevents ove...
static FloatingRank getFloatingRank(QualType T)
getFloatingRank - Return a relative rank for floating point types.
static TypedefDecl * CreateXtensaABIBuiltinVaListDecl(const ASTContext *Context)
static TemplateArgument getCommonTemplateArgument(ASTContext &Ctx, const TemplateArgument &X, const TemplateArgument &Y)
static auto * getCommonSizeExpr(ASTContext &Ctx, T *X, T *Y)
static void encodeTypeForFunctionPointerAuth(const ASTContext &Ctx, raw_ostream &OS, QualType QT)
Encode a function type for use in the discriminator of a function pointer type.
static std::optional< int64_t > structSubobjectsHaveUniqueObjectRepresentations(const RangeT &Subobjects, int64_t CurOffsetInBits, const ASTContext &Context, const clang::ASTRecordLayout &Layout, bool CheckIfTriviallyCopyable)
static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET)
static QualType getCommonArrayElementType(ASTContext &Ctx, const T *X, Qualifiers &QX, const T *Y, Qualifiers &QY)
static QualType getCommonPointeeType(ASTContext &Ctx, const T *X, const T *Y)
static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty)
getRVVTypeSize - Return RVV vector register size.
static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal)
static SYCLKernelInfo BuildSYCLKernelInfo(CanQualType KernelNameType, const FunctionDecl *FD)
static int compareObjCProtocolsByName(ObjCProtocolDecl *const *lhs, ObjCProtocolDecl *const *rhs)
Comparison routine for Objective-C protocols to be used with llvm::array_pod_sort.
static QualType getCommonNonSugarTypeNode(ASTContext &Ctx, const Type *X, Qualifiers &QX, const Type *Y, Qualifiers &QY)
static QualType getCommonSugarTypeNode(ASTContext &Ctx, const Type *X, const Type *Y, SplitQualType Underlying)
static bool isSameQualifier(const NestedNameSpecifier *X, const NestedNameSpecifier *Y)
static std::string charUnitsToString(const CharUnits &CU)
static bool hasAnyPackExpansions(ArrayRef< TemplateArgument > Args)
static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod, SmallVectorImpl< const NamedDecl * > &Redeclared)
Definition: ASTContext.cpp:513
static SmallVector< SourceLocation, 2 > getDeclLocsForCommentSearch(const Decl *D, SourceManager &SourceMgr)
Definition: ASTContext.cpp:139
static TemplateName getCommonTemplateName(ASTContext &Ctx, TemplateName X, TemplateName Y, bool IgnoreDeduced=false)
static bool isCanonicalResultType(QualType T)
Determine whether T is canonical as the result type of a function.
static TypedefDecl * CreateMSVaListDecl(const ASTContext *Context)
static bool areCompatVectorTypes(const VectorType *LHS, const VectorType *RHS)
areCompatVectorTypes - Return true if the two specified vector types are compatible.
static TypedefDecl * CreateCharPtrNamedVaListDecl(const ASTContext *Context, StringRef Name)
#define UNEXPECTED_TYPE(Class, Kind)
static TypedefDecl * CreateVaListDecl(const ASTContext *Context, TargetInfo::BuiltinVaListKind Kind)
static std::vector< std::string > getFMVBackendFeaturesFor(const llvm::SmallVectorImpl< StringRef > &FMVFeatStrings)
static ElaboratedTypeKeyword getCommonTypeKeyword(const T *X, const T *Y)
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3443
NodeId Parent
Definition: ASTDiff.cpp:191
StringRef P
Provides definitions for the various language-specific address spaces.
static bool isUnsigned(SValBuilder &SVB, NonLoc Value)
#define SM(sm)
Definition: Cuda.cpp:84
static constexpr Builtin::Info BuiltinInfo[]
Definition: Builtins.cpp:32
Defines enum values for all the target-independent builtin functions.
static bool CanThrow(Expr *E, ASTContext &Ctx)
Definition: CFG.cpp:2686
const Decl * D
IndirectLocalPath & Path
Expr * E
Defines the clang::CommentOptions interface.
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1172
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines OpenMP nodes for declarative directives.
Defines the C++ template declaration subclasses.
Defines the ExceptionSpecificationType enumeration and various utility functions.
Defines the clang::Expr interface and subclasses for C++ expressions.
StringRef Text
Definition: Format.cpp:3033
unsigned Iter
Definition: HTMLLogger.cpp:153
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
static const Decl * getCanonicalDecl(const Decl *D)
#define X(type, name)
Definition: Value.h:144
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
llvm::MachO::Target Target
Definition: MachO.h:51
llvm::MachO::Record Record
Definition: MachO.h:31
static bool hasFeature(StringRef Feature, const LangOptions &LangOpts, const TargetInfo &Target)
Determine whether a translation unit built using the current language options has the given feature.
Definition: Module.cpp:96
Defines the clang::Module class, which describes a module in the source code.
Defines types useful for describing an Objective-C runtime.
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
static QualType getUnderlyingType(const SubRegion *R)
uint32_t Id
Definition: SemaARM.cpp:1134
SourceRange Range
Definition: SemaObjC.cpp:758
SourceLocation Loc
Definition: SemaObjC.cpp:759
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
static QualType getPointeeType(const MemRegion *R)
Defines the TargetCXXABI class, which abstracts details of the C++ ABI that we're targeting.
Defines the clang::TypeLoc interface and its subclasses.
static const TemplateArgument & getArgument(const TemplateArgument &A)
C Language Family Type Representation.
SourceLocation Begin
__device__ __2f16 float c
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
bool isMemberPointerToDerivedMember() const
Definition: APValue.cpp:1063
const ValueDecl * getMemberPointerDecl() const
Definition: APValue.cpp:1056
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition: APValue.cpp:1070
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
bool getByrefLifetime(QualType Ty, Qualifiers::ObjCLifetime &Lifetime, bool &HasByrefExtendedLayout) const
Returns true, if given type has a known lifetime.
MSGuidDecl * getMSGuidDecl(MSGuidDeclParts Parts) const
Return a declaration for the global GUID object representing the given GUID value.
QualType getUsingType(const UsingShadowDecl *Found, QualType Underlying) const
CanQualType AccumTy
Definition: ASTContext.h:1173
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, const ObjCMethodDecl *MethodImp)
CanQualType ObjCBuiltinSelTy
Definition: ASTContext.h:1192
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1141
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2915
CanQualType getCanonicalFunctionResultType(QualType ResultType) const
Adjust the given function result type.
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
llvm::PointerUnion< VarTemplateDecl *, MemberSpecializationInfo * > TemplateOrSpecializationInfo
A type synonym for the TemplateOrInstantiation mapping.
Definition: ASTContext.h:508
LangAS getOpenCLTypeAddrSpace(const Type *T) const
Get address space for OpenCL type.
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
void InitBuiltinTypes(const TargetInfo &Target, const TargetInfo *AuxTarget=nullptr)
Initialize built-in types.
ParentMapContext & getParentMapContext()
Returns the dynamic AST node parent map context.
Definition: ASTContext.cpp:894
QualType getParenType(QualType NamedType) const
size_t getSideTableAllocatedMemory() const
Return the total memory used for various side tables.
MemberSpecializationInfo * getInstantiatedFromStaticDataMember(const VarDecl *Var)
If this variable is an instantiated static data member of a class template specialization,...
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
CanQualType ARCUnbridgedCastTy
Definition: ASTContext.h:1191
QualType getDependentSizedMatrixType(QualType ElementType, Expr *RowExpr, Expr *ColumnExpr, SourceLocation AttrLoc) const
Return the unique reference to the matrix type of the specified element type and size.
QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr, QualType Wrapped) const
llvm::DenseMap< const Decl *, comments::FullComment * > ParsedComments
Mapping from declarations to parsed comments attached to any redeclaration.
Definition: ASTContext.h:896
BuiltinTemplateDecl * getBuiltinCommonTypeDecl() const
unsigned getManglingNumber(const NamedDecl *ND, bool ForAuxTarget=false) const
CanQualType LongTy
Definition: ASTContext.h:1169
unsigned getIntWidth(QualType T) const
CanQualType getCanonicalParamType(QualType T) const
Return the canonical parameter type corresponding to the specific potentially non-canonical one.
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
TemplateOrSpecializationInfo getTemplateOrSpecializationInfo(const VarDecl *Var)
CanQualType WIntTy
Definition: ASTContext.h:1165
@ Weak
Weak definition of inline variable.
@ WeakUnknown
Weak for now, might become strong later in this TU.
void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl)
TypedefDecl * getObjCClassDecl() const
Retrieve the typedef declaration corresponding to the predefined Objective-C 'Class' type.
TypedefNameDecl * getTypedefNameForUnnamedTagDecl(const TagDecl *TD)
TypedefDecl * getCFConstantStringDecl() const
CanQualType Int128Ty
Definition: ASTContext.h:1169
CanQualType SatUnsignedFractTy
Definition: ASTContext.h:1182
BuiltinTemplateDecl * getMakeIntegerSeqDecl() const
void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern)
Remember that the using decl Inst is an instantiation of the using decl Pattern of a class template.
bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an RISC-V vector builtin type and a VectorType that is a fixed-len...
ExternCContextDecl * getExternCContextDecl() const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD) const
Parses the target attributes passed in, and returns only the ones that are valid feature names.
QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent, bool IsPack=false, ConceptDecl *TypeConstraintConcept=nullptr, ArrayRef< TemplateArgument > TypeConstraintArgs={}) const
C++11 deduced auto type.
QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
TypedefDecl * getObjCSelDecl() const
Retrieve the typedef corresponding to the predefined 'SEL' type in Objective-C.
CanQualType UnsignedShortAccumTy
Definition: ASTContext.h:1175
TypedefDecl * getObjCInstanceTypeDecl()
Retrieve the typedef declaration corresponding to the Objective-C "instancetype" type.
uint64_t getFieldOffset(const ValueDecl *FD) const
Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, ArrayRef< TemplateArgumentLoc > Args) const
QualType adjustFunctionResultType(QualType FunctionType, QualType NewResultType)
Change the result type of a function type, preserving sugar such as attributed types.
void setTemplateOrSpecializationInfo(VarDecl *Inst, TemplateOrSpecializationInfo TSI)
bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, ObjCProtocolDecl *rProto) const
ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the inheritance hierarchy of 'rProto...
TypedefDecl * buildImplicitTypedef(QualType T, StringRef Name) const
Create a new implicit TU-level typedef declaration.
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl.
void adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig, ObjCTypeParamDecl *New) const
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
QualType getAutoRRefDeductType() const
C++11 deduction pattern for 'auto &&' type.
TypedefDecl * getBuiltinMSVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_ms_va_list type.
bool ObjCQualifiedIdTypesAreCompatible(const ObjCObjectPointerType *LHS, const ObjCObjectPointerType *RHS, bool ForCompare)
ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an ObjCQualifiedIDType.
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
QualType getBuiltinVaListType() const
Retrieve the type of the __builtin_va_list type.
Definition: ASTContext.h:2251
QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool AllowCXX=false, bool IsConditionalOperator=false)
NamedDecl * getInstantiatedFromUsingDecl(NamedDecl *Inst)
If the given using decl Inst is an instantiation of another (possibly unresolved) using decl,...
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:684
comments::FullComment * cloneFullComment(comments::FullComment *FC, const Decl *D) const
Definition: ASTContext.cpp:592
QualType getUnresolvedUsingType(const UnresolvedUsingTypenameDecl *Decl) const
CharUnits getObjCEncodingTypeSize(QualType T) const
Return the size of type T for Objective-C encoding purpose, in characters.
int getIntegerTypeOrder(QualType LHS, QualType RHS) const
Return the highest ranked integer type, see C99 6.3.1.8p1.
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType, const Attr *attr=nullptr) const
TypedefDecl * getObjCIdDecl() const
Retrieve the typedef corresponding to the predefined id type in Objective-C.
void setCurrentNamedModule(Module *M)
Set the (C++20) module we are building.
QualType getProcessIDType() const
Return the unique type for "pid_t" defined in <sys/types.h>.
CharUnits getMemberPointerPathAdjustment(const APValue &MP) const
Find the 'this' offset for the member path in a pointer-to-member APValue.
bool mayExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel may be externalized.
QualType getTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args, QualType Canon=QualType()) const
std::unique_ptr< MangleNumberingContext > createMangleNumberingContext() const
CanQualType SatAccumTy
Definition: ASTContext.h:1178
QualType getUnsignedPointerDiffType() const
Return the unique unsigned counterpart of "ptrdiff_t" integer type.
QualType getucontext_tType() const
Retrieve the C ucontext_t type.
Definition: ASTContext.h:2125
QualType getRecordType(const RecordDecl *Decl) const
QualType getScalableVectorType(QualType EltTy, unsigned NumElts, unsigned NumFields=1) const
Return the unique reference to a scalable vector type of the specified element type and scalable numb...
bool hasSameExpr(const Expr *X, const Expr *Y) const
Determine whether the given expressions X and Y are equivalent.
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
MangleContext * createMangleContext(const TargetInfo *T=nullptr)
If T is null pointer, assume the target in ASTContext.
QualType getRealTypeForBitwidth(unsigned DestWidth, FloatModeKind ExplicitType) const
getRealTypeForBitwidth - sets floating point QualTy according to specified bitwidth.
QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const
getInjectedClassNameType - Return the unique reference to the injected class name type for the specif...
QualType getVariableArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals, SourceRange Brackets) const
Return a non-unique reference to the type for a variable array of the specified element type.
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
CanQualType ShortAccumTy
Definition: ASTContext.h:1173
ASTMutationListener * getASTMutationListener() const
Retrieve a pointer to the AST mutation listener associated with this AST context, if any.
Definition: ASTContext.h:1289
IdentifierInfo * getBuiltinCommonTypeName() const
Definition: ASTContext.h:2069
unsigned NumImplicitCopyAssignmentOperatorsDeclared
The number of implicitly-declared copy assignment operators for which declarations were built.
Definition: ASTContext.h:3393
uint64_t getTargetNullPointerValue(QualType QT) const
Get target-dependent integer value for null pointer which is used for constant folding.
unsigned getTypeUnadjustedAlign(QualType T) const
Return the ABI-specified natural alignment of a (complete) type T, before alignment adjustments,...
Definition: ASTContext.h:2521
unsigned char getFixedPointIBits(QualType Ty) const
QualType getCorrespondingSignedFixedPointType(QualType Ty) const
CanQualType FloatTy
Definition: ASTContext.h:1172
QualType getArrayParameterType(QualType Ty) const
Return the uniqued reference to a specified array parameter type from the original array type.
QualType getCountAttributedType(QualType T, Expr *CountExpr, bool CountInBytes, bool OrNull, ArrayRef< TypeCoupledDeclRefInfo > DependentDecls) const
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2716
unsigned NumImplicitDestructorsDeclared
The number of implicitly-declared destructors for which declarations were built.
Definition: ASTContext.h:3407
bool mergeExtParameterInfo(const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, bool &CanUseFirst, bool &CanUseSecond, SmallVectorImpl< FunctionProtoType::ExtParameterInfo > &NewParamInfos)
This function merges the ExtParameterInfo lists of two functions.
bool ObjCQualifiedClassTypesAreCompatible(const ObjCObjectPointerType *LHS, const ObjCObjectPointerType *RHS)
ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and Class<pr1, ...>.
bool shouldExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel should be externalized.
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2732
bool propertyTypesAreCompatible(QualType, QualType)
void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, UsingShadowDecl *Pattern)
CanQualType DoubleTy
Definition: ASTContext.h:1172
TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
QualType getDependentVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc, VectorKind VecKind) const
Return the unique reference to the type for a dependently sized vector of the specified element type.
CanQualType SatLongAccumTy
Definition: ASTContext.h:1178
CanQualType getIntMaxType() const
Return the unique type for "intmax_t" (C99 7.18.1.5), defined in <stdint.h>.
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
OpenCLTypeKind getOpenCLTypeKind(const Type *T) const
Map an AST Type to an OpenCLTypeKind enum value.
QualType getFILEType() const
Retrieve the C FILE type.
Definition: ASTContext.h:2089
ArrayRef< Decl * > getModuleInitializers(Module *M)
Get the initializations to perform when importing a module, if any.
void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, std::string &S) const
Put the string version of the type qualifiers QT into S.
unsigned getPreferredTypeAlign(QualType T) const
Return the "preferred" alignment of the specified type T for the current target, in bits.
Definition: ASTContext.h:2573
std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, bool Extended=false) const
Emit the encoded type for the method declaration Decl into S.
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
CanQualType LongDoubleTy
Definition: ASTContext.h:1172
CanQualType OMPArrayShapingTy
Definition: ASTContext.h:1201
ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents, SelectorTable &sels, Builtin::Context &builtins, TranslationUnitKind TUKind)
Definition: ASTContext.cpp:913
QualType getReadPipeType(QualType T) const
Return a read_only pipe type for the specified type.
std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
getObjCEncodingForPropertyDecl - Return the encoded type for this method declaration.
CanQualType Char16Ty
Definition: ASTContext.h:1167
TemplateName getCanonicalTemplateName(TemplateName Name, bool IgnoreDeduced=false) const
Retrieves the "canonical" template name that refers to a given template.
unsigned getStaticLocalNumber(const VarDecl *VD) const
void addComment(const RawComment &RC)
Definition: ASTContext.cpp:346
void getLegacyIntegralTypeEncoding(QualType &t) const
getLegacyIntegralTypeEncoding - Another legacy compatibility encoding: 32-bit longs are encoded as 'l...
bool isSameTypeConstraint(const TypeConstraint *XTC, const TypeConstraint *YTC) const
Determine whether two type contraint are similar enough that they could used in declarations of the s...
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
RecordDecl * buildImplicitRecord(StringRef Name, RecordDecl::TagKind TK=RecordDecl::TagKind::Struct) const
Create a new implicit TU-level CXXRecordDecl or RecordDecl declaration.
QualType getSubstTemplateTypeParmType(QualType Replacement, Decl *AssociatedDecl, unsigned Index, std::optional< unsigned > PackIndex, SubstTemplateTypeParmTypeFlag Flag=SubstTemplateTypeParmTypeFlag::None) const
Retrieve a substitution-result type.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
QualType getMSGuidType() const
Retrieve the implicitly-predeclared 'struct _GUID' type.
Definition: ASTContext.h:2273
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or nullptr if there isn't on...
const ASTRecordLayout & getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const
Get or compute information about the layout of the specified Objective-C implementation.
CanQualType UnsignedLongFractTy
Definition: ASTContext.h:1177
QualType getEnumType(const EnumDecl *Decl) const
overridden_method_range overridden_methods(const CXXMethodDecl *Method) const
QualType getDependentBitIntType(bool Unsigned, Expr *BitsExpr) const
Return a dependent bit-precise integer type with the specified signedness and bit count.
void setObjCImplementation(ObjCInterfaceDecl *IFaceD, ObjCImplementationDecl *ImplD)
Set the implementation of ObjCInterfaceDecl.
StringRef getCUIDHash() const
bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const
Returns true if this is an inline-initialized static data member which is treated as a definition for...
bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
canAssignObjCInterfaces - Return true if the two interface types are compatible for assignment from R...
CanQualType VoidPtrTy
Definition: ASTContext.h:1187
QualType getReferenceQualifiedType(const Expr *e) const
getReferenceQualifiedType - Given an expr, will return the type for that expression,...
bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const
Determine whether two function types are the same, ignoring exception specifications in cases where t...
QualType getBlockDescriptorExtendedType() const
Gets the struct used to keep track of the extended descriptor for pointer to blocks.
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
Definition: ASTContext.h:1188
IdentifierInfo * getMakeIntegerSeqName() const
Definition: ASTContext.h:2057
bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT, ObjCInterfaceDecl *IDecl)
QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in QT's qualified-id protocol list adopt...
void addLazyModuleInitializers(Module *M, ArrayRef< GlobalDeclID > IDs)
bool isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const
Determine whether two 'requires' expressions are similar enough that they may be used in re-declarati...
IdentifierInfo * getTypePackElementName() const
Definition: ASTContext.h:2063
bool BlockRequiresCopying(QualType Ty, const VarDecl *D)
Returns true iff we need copy/dispose helpers for the given type.
CanQualType NullPtrTy
Definition: ASTContext.h:1187
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1703
CanQualType WideCharTy
Definition: ASTContext.h:1164
CanQualType OMPIteratorTy
Definition: ASTContext.h:1201
IdentifierTable & Idents
Definition: ASTContext.h:680
TemplateName getSubstTemplateTemplateParm(TemplateName replacement, Decl *AssociatedDecl, unsigned Index, std::optional< unsigned > PackIndex) const
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:682
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
void addModuleInitializer(Module *M, Decl *Init)
Add a declaration to the list of declarations that are initialized for a module.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:834
QualType getFunctionTypeWithoutPtrSizes(QualType T)
Get a function type and produce the equivalent function type where pointer size address spaces in the...
llvm::iterator_range< overridden_cxx_method_iterator > overridden_method_range
Definition: ASTContext.h:1063
bool isTypeIgnoredBySanitizer(const SanitizerMask &Mask, const QualType &Ty) const
Check if a type can have its sanitizer instrumentation elided based on its presence within an ignorel...
Definition: ASTContext.cpp:854
unsigned getMinGlobalAlignOfVar(uint64_t Size, const VarDecl *VD) const
Return the minimum alignement as specified by the target.
RawCommentList Comments
All comments in this translation unit.
Definition: ASTContext.h:867
bool isSameDefaultTemplateArgument(const NamedDecl *X, const NamedDecl *Y) const
Determine whether two default template arguments are similar enough that they may be used in declarat...
QualType applyObjCProtocolQualifiers(QualType type, ArrayRef< ObjCProtocolDecl * > protocols, bool &hasError, bool allowOnPointerType=false) const
Apply Objective-C protocol qualifiers to the given type.
QualType getMacroQualifiedType(QualType UnderlyingTy, const IdentifierInfo *MacroII) const
QualType removePtrSizeAddrSpace(QualType T) const
Remove the existing address space on the type if it is a pointer size address space and return the ty...
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
CanQualType SatShortFractTy
Definition: ASTContext.h:1181
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
bool canBindObjCObjectType(QualType To, QualType From)
int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const
Compare the rank of two floating point types as above, but compare equal if both types have the same ...
QualType getUIntPtrType() const
Return a type compatible with "uintptr_t" (C99 7.18.1.4), as defined by the target.
void setParameterIndex(const ParmVarDecl *D, unsigned index)
Used by ParmVarDecl to store on the side the index of the parameter when it exceeds the size of the n...
QualType getFunctionTypeWithExceptionSpec(QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const
Get a function type and produce the equivalent function type with the specified exception specificati...
Qualifiers::GC getObjCGCAttrKind(QualType Ty) const
Return one of the GCNone, Weak or Strong Objective-C garbage collection attributes.
CanQualType Ibm128Ty
Definition: ASTContext.h:1172
bool hasUniqueObjectRepresentations(QualType Ty, bool CheckIfTriviallyCopyable=true) const
Return true if the specified type has unique object representations according to (C++17 [meta....
bool typesAreBlockPointerCompatible(QualType, QualType)
CanQualType SatUnsignedAccumTy
Definition: ASTContext.h:1179
bool useAbbreviatedThunkName(GlobalDecl VirtualMethodDecl, StringRef MangledName)
const ASTRecordLayout & getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const
Get or compute information about the layout of the specified Objective-C interface.
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
void setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst, UsingEnumDecl *Pattern)
Remember that the using enum decl Inst is an instantiation of the using enum decl Pattern of a class ...
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
QualType getSignatureParameterType(QualType T) const
Retrieve the parameter type as adjusted for use in the signature of a function, decaying array and fu...
CanQualType ArraySectionTy
Definition: ASTContext.h:1200
QualType getCanonicalTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args) const
CanQualType ObjCBuiltinIdTy
Definition: ASTContext.h:1192
overridden_cxx_method_iterator overridden_methods_end(const CXXMethodDecl *Method) const
VTableContextBase * getVTableContext()
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const
ObjCPropertyImplDecl * getObjCPropertyImplDeclForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
bool isNearlyEmpty(const CXXRecordDecl *RD) const
QualType AutoDeductTy
Definition: ASTContext.h:1223
CanQualType BoolTy
Definition: ASTContext.h:1161
void cacheRawCommentForDecl(const Decl &OriginalD, const RawComment &Comment) const
Attaches Comment to OriginalD and to its redeclaration chain and removes the redeclaration chain from...
Definition: ASTContext.cpp:504
void attachCommentsToJustParsedDecls(ArrayRef< Decl * > Decls, const Preprocessor *PP)
Searches existing comments for doc comments that should be attached to Decls.
Definition: ASTContext.cpp:530
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth,...
void setStaticLocalNumber(const VarDecl *VD, unsigned Number)
QualType getCFConstantStringType() const
Return the C structure type used to represent constant CFStrings.
void eraseDeclAttrs(const Decl *D)
Erase the attributes corresponding to the given declaration.
UsingEnumDecl * getInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst)
If the given using-enum decl Inst is an instantiation of another using-enum decl, return it.
RecordDecl * getCFConstantStringTagDecl() const
QualType getObjCSelType() const
Retrieve the type that corresponds to the predefined Objective-C 'SEL' type.
Definition: ASTContext.h:2206
QualType getDeducedTemplateSpecializationType(TemplateName Template, QualType DeducedType, bool IsDependent) const
C++17 deduced class template specialization type.
std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const
Emit the encoded type for the function Decl into S.
QualType getTemplateTypeParmType(unsigned Depth, unsigned Index, bool ParameterPack, TemplateTypeParmDecl *ParmDecl=nullptr) const
Retrieve the template type parameter type for a template parameter or parameter pack with the given d...
CanQualType UnsignedFractTy
Definition: ASTContext.h:1177
QualType getjmp_bufType() const
Retrieve the C jmp_buf type.
Definition: ASTContext.h:2101
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
QualType mergeFunctionParameterTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false)
mergeFunctionParameterTypes - merge two types which appear as function parameter types
QualType getsigjmp_bufType() const
Retrieve the C sigjmp_buf type.
Definition: ASTContext.h:2113
void addOverriddenMethod(const CXXMethodDecl *Method, const CXXMethodDecl *Overridden)
Note that the given C++ Method overrides the given Overridden method.
CanQualType Float128Ty
Definition: ASTContext.h:1172
CanQualType ObjCBuiltinClassTy
Definition: ASTContext.h:1192
unsigned NumImplicitDefaultConstructorsDeclared
The number of implicitly-declared default constructors for which declarations were built.
Definition: ASTContext.h:3372
CanQualType UnresolvedTemplateTy
Definition: ASTContext.h:1188
OMPTraitInfo & getNewOMPTraitInfo()
Return a new OMPTraitInfo object owned by this context.
CanQualType UnsignedLongTy
Definition: ASTContext.h:1170
void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass, SmallVectorImpl< const ObjCIvarDecl * > &Ivars) const
DeepCollectObjCIvars - This routine first collects all declared, but not synthesized,...
llvm::APFixedPoint getFixedPointMin(QualType Ty) const
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
QualType adjustType(QualType OldType, llvm::function_ref< QualType(QualType)> Adjust) const
Rebuild a type, preserving any existing type sugar.
void addedLocalImportDecl(ImportDecl *Import)
Notify the AST context that a new import declaration has been parsed or implicitly created within thi...
CanQualType UnsignedLongAccumTy
Definition: ASTContext.h:1175
QualType AutoRRefDeductTy
Definition: ASTContext.h:1224
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
CanQualType ShortFractTy
Definition: ASTContext.h:1176
QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const
Return a type for a constant array for a string literal of the specified element type and length.
QualType getCorrespondingSaturatedType(QualType Ty) const
bool isSameEntity(const NamedDecl *X, const NamedDecl *Y) const
Determine whether the two declarations refer to the same entity.
TypeSourceInfo * getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc, const TemplateArgumentListInfo &Args, QualType Canon=QualType()) const
QualType getSubstTemplateTypeParmPackType(Decl *AssociatedDecl, unsigned Index, bool Final, const TemplateArgument &ArgPack)
Retrieve a.
CanQualType BoundMemberTy
Definition: ASTContext.h:1188
CanQualType SatUnsignedShortFractTy
Definition: ASTContext.h:1182
CanQualType CharTy
Definition: ASTContext.h:1162
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
bool hasSameFunctionTypeIgnoringParamABI(QualType T, QualType U) const
Determine if two function types are the same, ignoring parameter ABI annotations.
TypedefDecl * getInt128Decl() const
Retrieve the declaration for the 128-bit signed integer type.
unsigned getOpenMPDefaultSimdAlign(QualType T) const
Get default simd alignment of the specified complete type in bits.
QualType getObjCSuperType() const
Returns the C struct type for objc_super.
QualType getBlockDescriptorType() const
Gets the struct used to keep track of the descriptor for pointer to blocks.
bool CommentsLoaded
True if comments are already loaded from ExternalASTSource.
Definition: ASTContext.h:870
BlockVarCopyInit getBlockVarCopyInit(const VarDecl *VD) const
Get the copy initialization expression of the VarDecl VD, or nullptr if none exists.
unsigned NumImplicitMoveConstructorsDeclared
The number of implicitly-declared move constructors for which declarations were built.
Definition: ASTContext.h:3386
unsigned NumImplicitCopyConstructorsDeclared
The number of implicitly-declared copy constructors for which declarations were built.
Definition: ASTContext.h:3379
CanQualType IntTy
Definition: ASTContext.h:1169
llvm::DenseSet< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
Definition: ASTContext.h:1237
CanQualType PseudoObjectTy
Definition: ASTContext.h:1191
QualType getWebAssemblyExternrefType() const
Return a WebAssembly externref type.
void setTraversalScope(const std::vector< Decl * > &)
Definition: ASTContext.cpp:980
CharUnits getTypeUnadjustedAlignInChars(QualType T) const
getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a type, in characters,...
QualType getAdjustedType(QualType Orig, QualType New) const
Return the uniqued reference to a type adjusted from the original type to a new type.
void PrintStats() const
Definition: ASTContext.cpp:994
unsigned getAlignOfGlobalVar(QualType T, const VarDecl *VD) const
Return the alignment in bits that should be given to a global variable with type T.
TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
comments::FullComment * getLocalCommentForDeclUncached(const Decl *D) const
Return parsed documentation comment attached to a given declaration.
Definition: ASTContext.cpp:607
unsigned NumImplicitDestructors
The number of implicitly-declared destructors.
Definition: ASTContext.h:3403
CanQualType Float16Ty
Definition: ASTContext.h:1186
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2289
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
bool isAlignmentRequired(const Type *T) const
Determine if the alignment the type has was required using an alignment attribute.
TagDecl * MSGuidTagDecl
Definition: ASTContext.h:1231
bool areComparableObjCPointerTypes(QualType LHS, QualType RHS)
MangleContext * createDeviceMangleContext(const TargetInfo &T)
Creates a device mangle context to correctly mangle lambdas in a mixed architecture compile by settin...
CharUnits getExnObjectAlignment() const
Return the alignment (in bytes) of the thrown exception object.
CanQualType SignedCharTy
Definition: ASTContext.h:1169
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
ASTMutationListener * Listener
Definition: ASTContext.h:686
QualType getPackExpansionType(QualType Pattern, std::optional< unsigned > NumExpansions, bool ExpectPackInType=true) const
Form a pack expansion type with the given pattern.
CanQualType ObjCBuiltinBoolTy
Definition: ASTContext.h:1193
TypeInfoChars getTypeInfoInChars(const Type *T) const
QualType getObjCObjectType(QualType Base, ObjCProtocolDecl *const *Protocols, unsigned NumProtocols) const
Legacy interface: cannot provide type arguments or __kindof.
TemplateParamObjectDecl * getTemplateParamObjectDecl(QualType T, const APValue &V) const
Return the template parameter object of the given type with the given value.
CanQualType OverloadTy
Definition: ASTContext.h:1188
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
CanQualType OCLClkEventTy
Definition: ASTContext.h:1197
void adjustExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, bool AsWritten=false)
Change the exception specification on a function once it is delay-parsed, instantiated,...
TypedefDecl * getUInt128Decl() const
Retrieve the declaration for the 128-bit unsigned integer type.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:733
ArrayRef< Module * > getModulesWithMergedDefinition(const NamedDecl *Def)
Get the additional modules in which the definition Def has been merged.
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals, SourceRange Brackets) const
Return a non-unique reference to the type for a dependently-sized array of the specified element type...
uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID, const ObjCImplementationDecl *ID, const ObjCIvarDecl *Ivar) const
Get the offset of an ObjCIvarDecl in bits.
CanQualType SatUnsignedShortAccumTy
Definition: ASTContext.h:1179
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false, bool IsConditionalOperator=false)
const RawComment * getRawCommentForAnyRedecl(const Decl *D, const Decl **OriginalDecl=nullptr) const
Return the documentation comment attached to a given declaration.
Definition: ASTContext.cpp:422
CharUnits getAlignOfGlobalVarInChars(QualType T, const VarDecl *VD) const
Return the alignment in characters that should be given to a global variable with type T.
const ObjCMethodDecl * getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const
Get the duplicate declaration of a ObjCMethod in the same interface, or null if none exists.
static bool isObjCNSObjectType(QualType Ty)
Return true if this is an NSObject object with its NSObject attribute set.
Definition: ASTContext.h:2462
GVALinkage GetGVALinkageForVariable(const VarDecl *VD) const
UsingShadowDecl * getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst)
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2196
Decl * getVaListTagDecl() const
Retrieve the C type declaration corresponding to the predefined __va_list_tag type used to help defin...
QualType getUnsignedWCharType() const
Return the type of "unsigned wchar_t".
QualType getFunctionTypeWithoutParamABIs(QualType T) const
Get or construct a function type that is equivalent to the input type except that the parameter ABI a...
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2763
QualType getCorrespondingUnsaturatedType(QualType Ty) const
comments::FullComment * getCommentForDecl(const Decl *D, const Preprocessor *PP) const
Return parsed documentation comment attached to a given declaration.
Definition: ASTContext.cpp:612
FunctionProtoType::ExceptionSpecInfo mergeExceptionSpecs(FunctionProtoType::ExceptionSpecInfo ESI1, FunctionProtoType::ExceptionSpecInfo ESI2, SmallVectorImpl< QualType > &ExceptionTypeStorage, bool AcceptDependent)
TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl) const
unsigned getTargetDefaultAlignForAttributeAligned() const
Return the default alignment for attribute((aligned)) on this target, to be used if no alignment valu...
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
llvm::DenseMap< CanQualType, SYCLKernelInfo > SYCLKernels
Map of SYCL kernels indexed by the unique type used to name the kernel.
Definition: ASTContext.h:1250
bool isSameTemplateParameterList(const TemplateParameterList *X, const TemplateParameterList *Y) const
Determine whether two template parameter lists are similar enough that they may be used in declaratio...
QualType getWritePipeType(QualType T) const
Return a write_only pipe type for the specified type.
const CXXRecordDecl * baseForVTableAuthentication(const CXXRecordDecl *ThisClass)
Resolve the root record to be used to derive the vtable pointer authentication policy for the specifi...
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2482
CanQualType UnsignedInt128Ty
Definition: ASTContext.h:1171
CanQualType BuiltinFnTy
Definition: ASTContext.h:1190
ObjCInterfaceDecl * getObjCProtocolDecl() const
Retrieve the Objective-C class declaration corresponding to the predefined Protocol class.
unsigned NumImplicitDefaultConstructors
The number of implicitly-declared default constructors.
Definition: ASTContext.h:3368
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
unsigned NumImplicitMoveAssignmentOperatorsDeclared
The number of implicitly-declared move assignment operators for which declarations were built.
Definition: ASTContext.h:3400
void setManglingNumber(const NamedDecl *ND, unsigned Number)
llvm::DenseMap< const Decl *, const RawComment * > DeclRawComments
Mapping from declaration to directly attached comment.
Definition: ASTContext.h:876
CanQualType OCLSamplerTy
Definition: ASTContext.h:1197
TypedefDecl * getBuiltinVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_va_list type.
CanQualType VoidTy
Definition: ASTContext.h:1160
CanQualType UnsignedCharTy
Definition: ASTContext.h:1170
CanQualType UnsignedShortFractTy
Definition: ASTContext.h:1177
BuiltinTemplateDecl * buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, const IdentifierInfo *II) const
void * Allocate(size_t Size, unsigned Align=8) const
Definition: ASTContext.h:754
bool canBuiltinBeRedeclared(const FunctionDecl *) const
Return whether a declaration to a builtin is allowed to be overloaded/redeclared.
CanQualType UnsignedIntTy
Definition: ASTContext.h:1170
TemplateName getDependentTemplateName(NestedNameSpecifier *NNS, const IdentifierInfo *Name) const
Retrieve the template name that represents a dependent template name such as MetaFun::template apply.
unsigned NumImplicitMoveConstructors
The number of implicitly-declared move constructors.
Definition: ASTContext.h:3382
QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl, ArrayRef< ObjCProtocolDecl * > protocols) const
QualType getVolatileType(QualType T) const
Return the uniqued reference to the type for a volatile qualified type.
Definition: ASTContext.h:1381
void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, QualType T, std::string &S, bool Extended) const
getObjCEncodingForMethodParameter - Return the encoded type for a single method parameter or return t...
void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD)
unsigned overridden_methods_size(const CXXMethodDecl *Method) const
std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const
Return the encoded type for this block declaration.
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
QualType getExceptionObjectType(QualType T) const
CanQualType UnknownAnyTy
Definition: ASTContext.h:1189
void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
Note that the static data member Inst is an instantiation of the static data member template Tmpl of ...
FieldDecl * getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const
DeclaratorDecl * getDeclaratorForUnnamedTagDecl(const TagDecl *TD)
bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl)
ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's protocol list adopt all protocols in Q...
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1171
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
QualType getCommonSugaredType(QualType X, QualType Y, bool Unqualified=false)
CanQualType OCLReserveIDTy
Definition: ASTContext.h:1198
bool isSameTemplateParameter(const NamedDecl *X, const NamedDecl *Y) const
Determine whether two template parameters are similar enough that they may be used in declarations of...
void registerSYCLEntryPointFunction(FunctionDecl *FD)
Generates and stores SYCL kernel metadata for the provided SYCL kernel entry point function.
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
overridden_cxx_method_iterator overridden_methods_begin(const CXXMethodDecl *Method) const
CanQualType UnsignedShortTy
Definition: ASTContext.h:1170
unsigned getTypeAlignIfKnown(QualType T, bool NeedsPreferredAlignment=false) const
Return the alignment of a type, in bits, or 0 if the type is incomplete and we cannot determine the a...
void UnwrapSimilarArrayTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true) const
Attempt to unwrap two types that may both be array types with the same bound (or both be array types ...
bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1681
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
bool canAssignObjCInterfacesInBlockPointer(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT, bool BlockReturnType)
canAssignObjCInterfacesInBlockPointer - This routine is specifically written for providing type-safet...
CanQualType SatUnsignedLongFractTy
Definition: ASTContext.h:1183
const CXXConstructorDecl * getCopyConstructorForExceptionObject(CXXRecordDecl *RD)
QualType getDependentAddressSpaceType(QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttrLoc) const
QualType getPackIndexingType(QualType Pattern, Expr *IndexExpr, bool FullySubstituted=false, ArrayRef< QualType > Expansions={}, int Index=-1) const
RawComment * getRawCommentForDeclNoCache(const Decl *D) const
Return the documentation comment attached to a given declaration, without looking into cache.
Definition: ASTContext.cpp:313
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
const VariableArrayType * getAsVariableArrayType(QualType T) const
Definition: ASTContext.h:2918
QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType, UnaryTransformType::UTTKind UKind) const
Unary type transforms.
void setExternalSource(IntrusiveRefCntPtr< ExternalASTSource > Source)
Attach an external AST source to the AST context.
Definition: ASTContext.cpp:990
const ObjCInterfaceDecl * getObjContainingInterface(const NamedDecl *ND) const
Returns the Objective-C interface that ND belongs to if it is an Objective-C method/property/ivar etc...
CanQualType ShortTy
Definition: ASTContext.h:1169
StringLiteral * getPredefinedStringLiteralFromCache(StringRef Key) const
Return a string representing the human readable name for the specified function declaration or file n...
bool hasSimilarType(QualType T1, QualType T2) const
Determine if two types are similar, according to the C++ rules.
llvm::APFixedPoint getFixedPointMax(QualType Ty) const
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type.
bool areCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an SVE builtin and a VectorType that is a fixed-length representat...
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
CanQualType FractTy
Definition: ASTContext.h:1176
Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const
Recurses in pointer/array types until it finds an Objective-C retainable type and returns its ownersh...
void addCopyConstructorForExceptionObject(CXXRecordDecl *RD, CXXConstructorDecl *CD)
DiagnosticsEngine & getDiagnostics() const
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
void ResetObjCLayout(const ObjCContainerDecl *CD)
CanQualType LongAccumTy
Definition: ASTContext.h:1174
interp::Context & getInterpContext()
Returns the clang bytecode interpreter context.
Definition: ASTContext.cpp:887
CanQualType Char32Ty
Definition: ASTContext.h:1168
UnnamedGlobalConstantDecl * getUnnamedGlobalConstantDecl(QualType Ty, const APValue &Value) const
Return a declaration for a uniquified anonymous global constant corresponding to a given APValue.
CanQualType SatFractTy
Definition: ASTContext.h:1181
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec)
Return true if the given vector types are of the same unqualified type or if they are equivalent to t...
void getOverriddenMethods(const NamedDecl *Method, SmallVectorImpl< const NamedDecl * > &Overridden) const
Return C++ or ObjC overridden methods for the given Method.
DeclarationNameInfo getNameForTemplate(TemplateName Name, SourceLocation NameLoc) const
bool hasSameTemplateName(const TemplateName &X, const TemplateName &Y, bool IgnoreDeduced=false) const
Determine whether the given template names refer to the same template.
CanQualType SatLongFractTy
Definition: ASTContext.h:1181
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:799
void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl)
CanQualType OCLQueueTy
Definition: ASTContext.h:1198
CanQualType LongFractTy
Definition: ASTContext.h:1176
CanQualType SatShortAccumTy
Definition: ASTContext.h:1178
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CanQualType BFloat16Ty
Definition: ASTContext.h:1185
unsigned NumImplicitCopyConstructors
The number of implicitly-declared copy constructors.
Definition: ASTContext.h:3375
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType IncompleteMatrixIdxTy
Definition: ASTContext.h:1199
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
CanQualType getNSIntegerType() const
QualType getCorrespondingUnsignedType(QualType T) const
void setBlockVarCopyInit(const VarDecl *VD, Expr *CopyExpr, bool CanThrow)
Set the copy initialization expression of a block var decl.
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const
Retrieve the template name that corresponds to a non-empty lookup.
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
TemplateName getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack, Decl *AssociatedDecl, unsigned Index, bool Final) const
TargetCXXABI::Kind getCXXABIKind() const
Return the C++ ABI kind that should be used.
Definition: ASTContext.cpp:861
QualType getHLSLAttributedResourceType(QualType Wrapped, QualType Contained, const HLSLAttributedResourceType::Attributes &Attrs)
bool UnwrapSimilarTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true) const
Attempt to unwrap two types that may be similar (C++ [conv.qual]).
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
Definition: ASTContext.h:1274
uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const
Return number of constant array elements.
BuiltinTemplateDecl * getTypePackElementDecl() const
CanQualType SatUnsignedLongAccumTy
Definition: ASTContext.h:1180
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
CanQualType LongLongTy
Definition: ASTContext.h:1169
QualType getTypeOfType(QualType QT, TypeOfKind Kind) const
getTypeOfType - Unlike many "get<Type>" functions, we don't unique TypeOfType nodes.
QualType getCorrespondingSignedType(QualType T) const
QualType mergeObjCGCQualifiers(QualType, QualType)
mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 'RHS' attributes and ret...
llvm::DenseMap< const Decl *, const Decl * > CommentlessRedeclChains
Keeps track of redeclaration chains that don't have any comment attached.
Definition: ASTContext.h:892
uint64_t getArrayInitLoopExprElementCount(const ArrayInitLoopExpr *AILE) const
Return number of elements initialized in an ArrayInitLoopExpr.
void deduplicateMergedDefinitonsFor(NamedDecl *ND)
Clean up the merged definition list.
unsigned getTargetAddressSpace(LangAS AS) const
QualType getWideCharType() const
Return the type of wide characters.
Definition: ASTContext.h:1920
QualType getIntPtrType() const
Return a type compatible with "intptr_t" (C99 7.18.1.4), as defined by the target.
void mergeDefinitionIntoModule(NamedDecl *ND, Module *M, bool NotifyListeners=true)
Note that the definition ND has been merged into module M, and should be visible whenever M is visibl...
void addTranslationUnitDecl()
Definition: ASTContext.h:1144
CanQualType WCharTy
Definition: ASTContext.h:1163
void getObjCEncodingForPropertyType(QualType T, std::string &S) const
Emit the Objective-C property type encoding for the given type T into S.
unsigned NumImplicitCopyAssignmentOperators
The number of implicitly-declared copy assignment operators.
Definition: ASTContext.h:3389
void CollectInheritedProtocols(const Decl *CDecl, llvm::SmallPtrSet< ObjCProtocolDecl *, 8 > &Protocols)
CollectInheritedProtocols - Collect all protocols in current class and those inherited by it.
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
llvm::DenseMap< const Decl *, const Decl * > RedeclChainComments
Mapping from canonical declaration to the first redeclaration in chain that has a comment attached.
Definition: ASTContext.h:883
CanQualType getSignedSizeType() const
Return the unique signed counterpart of the integer type corresponding to size_t.
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const
Return the uniqued reference to the type for an Objective-C gc-qualified type.
QualType getDecltypeType(Expr *e, QualType UnderlyingType) const
C++11 decltype.
NestedNameSpecifier * getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const
Retrieves the "canonical" nested name specifier for a given nested name specifier.
QualType getTypedefType(const TypedefNameDecl *Decl, QualType Underlying=QualType()) const
Return the unique reference to the type for the specified typedef-name decl.
InlineVariableDefinitionKind getInlineVariableDefinitionKind(const VarDecl *VD) const
Determine whether a definition of this inline variable should be treated as a weak or strong definiti...
CanQualType getUIntMaxType() const
Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in <stdint.h>.
uint16_t getPointerAuthVTablePointerDiscriminator(const CXXRecordDecl *RD)
Return the "other" discriminator used for the pointer auth schema used for vtable pointers in instanc...
CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const
Loading virtual member pointers using the virtual inheritance model always results in an adjustment u...
LangAS getLangASForBuiltinAddressSpace(unsigned AS) const
bool hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U)
Determine whether two function types are the same, ignoring pointer sizes in the return type and para...
unsigned char getFixedPointScale(QualType Ty) const
QualType getIncompleteArrayType(QualType EltTy, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a unique reference to the type for an incomplete array of the specified element type.
QualType getDependentSizedExtVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc) const
QualType DecodeTypeStr(const char *&Str, const ASTContext &Context, ASTContext::GetBuiltinTypeError &Error, bool &RequireICE, bool AllowTypeModifiers) const
TemplateName getAssumedTemplateName(DeclarationName Name) const
Retrieve a template name representing an unqualified-id that has been assumed to name a template for ...
@ GE_None
No error.
Definition: ASTContext.h:2384
@ GE_Missing_stdio
Missing a type from <stdio.h>
Definition: ASTContext.h:2390
@ GE_Missing_type
Missing a type.
Definition: ASTContext.h:2387
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
Definition: ASTContext.h:2396
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
Definition: ASTContext.h:2393
QualType adjustStringLiteralBaseType(QualType StrLTy) const
uint16_t getPointerAuthTypeDiscriminator(QualType T)
Return the "other" type-specific discriminator for the given type.
QualType getTypeOfExprType(Expr *E, TypeOfKind Kind) const
C23 feature and GCC extension.
CanQualType Char8Ty
Definition: ASTContext.h:1166
QualType getSignedWCharType() const
Return the type of "signed wchar_t".
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
bool hasCvrSimilarType(QualType T1, QualType T2)
Determine if two types are similar, ignoring only CVR qualifiers.
TemplateName getDeducedTemplateName(TemplateName Underlying, DefaultArguments DefaultArgs) const
Represents a TemplateName which had some of its default arguments deduced.
ObjCImplementationDecl * getObjCImplementation(ObjCInterfaceDecl *D)
Get the implementation of the ObjCInterfaceDecl D, or nullptr if none exists.
CanQualType HalfTy
Definition: ASTContext.h:1184
CanQualType UnsignedAccumTy
Definition: ASTContext.h:1175
void setObjCMethodRedeclaration(const ObjCMethodDecl *MD, const ObjCMethodDecl *Redecl)
void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND)
QualType getConstantMatrixType(QualType ElementType, unsigned NumRows, unsigned NumColumns) const
Return the unique reference to the matrix type of the specified element type and size.
QualType getVariableArrayDecayedType(QualType Ty) const
Returns a vla type where known sizes are replaced with [*].
bool isInSameModule(const Module *M1, const Module *M2)
If the two module M1 and M2 are in the same module.
void setCFConstantStringType(QualType T)
unsigned getParameterIndex(const ParmVarDecl *D) const
Used by ParmVarDecl to retrieve on the side the index of the parameter when it exceeds the size of th...
CanQualType OCLEventTy
Definition: ASTContext.h:1197
void AddDeallocation(void(*Callback)(void *), void *Data) const
Add a deallocation callback that will be invoked when the ASTContext is destroyed.
Definition: ASTContext.cpp:985
AttrVec & getDeclAttrs(const Decl *D)
Retrieve the attributes for the given declaration.
CXXMethodVector::const_iterator overridden_cxx_method_iterator
Definition: ASTContext.h:1053
RawComment * getRawCommentForDeclNoCacheImpl(const Decl *D, const SourceLocation RepresentativeLocForDecl, const std::map< unsigned, RawComment * > &CommentsInFile) const
Definition: ASTContext.cpp:235
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
Definition: ASTContext.h:2513
QualType mergeTransparentUnionType(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false)
mergeTransparentUnionType - if T is a transparent union type and a member of T is compatible with Sub...
QualType isPromotableBitField(Expr *E) const
Whether this is a promotable bitfield reference according to C99 6.3.1.1p2, bullet 2 (and GCC extensi...
bool isSentinelNullExpr(const Expr *E)
CanQualType getNSUIntegerType() const
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2486
QualType getBitIntType(bool Unsigned, unsigned NumBits) const
Return a bit-precise integer type with the specified signedness and bit count.
unsigned NumImplicitMoveAssignmentOperators
The number of implicitly-declared move assignment operators.
Definition: ASTContext.h:3396
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
virtual void AddedStaticLocalNumbers(const Decl *D, unsigned Number)
An static local number was added to a Decl.
virtual void RedefinedHiddenDefinition(const NamedDecl *D, Module *M)
A definition has been made visible by being redefined locally.
virtual void AddedManglingNumber(const Decl *D, unsigned Number)
An mangling number was added to a Decl.
virtual void DeducedReturnType(const FunctionDecl *FD, QualType ReturnType)
A function's return type has been deduced.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
CharUnits getAlignment() const
getAlignment - Get the record alignment in characters.
Definition: RecordLayout.h:182
const CXXRecordDecl * getBaseSharingVBPtr() const
Definition: RecordLayout.h:329
CharUnits getSize() const
getSize - Get the record size in characters.
Definition: RecordLayout.h:193
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:200
CharUnits getDataSize() const
getDataSize() - Get the record data size, which is the record size without tail padding,...
Definition: RecordLayout.h:206
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:249
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:259
CharUnits getNonVirtualSize() const
getNonVirtualSize - Get the non-virtual size (in chars) of an object, which is the size of the object...
Definition: RecordLayout.h:210
CharUnits getUnadjustedAlignment() const
getUnadjustedAlignment - Get the record alignment in characters, before alignment adjustement.
Definition: RecordLayout.h:190
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition: Type.h:3357
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3376
Represents a loop initializing the elements of an array.
Definition: Expr.h:5752
llvm::APInt getArraySize() const
Definition: Expr.h:5774
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition: Expr.h:5772
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition: Type.h:3747
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3577
ArraySizeModifier getSizeModifier() const
Definition: Type.h:3591
Qualifiers getIndexTypeQualifiers() const
Definition: Type.h:3595
QualType getElementType() const
Definition: Type.h:3589
unsigned getIndexTypeCVRQualifiers() const
Definition: Type.h:3599
A structure for storing the information associated with a name that has been assumed to be a template...
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition: Expr.h:6678
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:7761
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7766
Attr - This represents one attribute.
Definition: Attr.h:43
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:6127
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6199
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:6556
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.cpp:5204
bool isConstrained() const
Definition: Type.h:6575
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6236
A fixed int type of a specified bitwidth.
Definition: Type.h:7814
void Profile(llvm::FoldingSetNodeID &ID) const
Definition: Type.h:7831
unsigned getNumBits() const
Definition: Type.h:7826
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4474
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6414
Pointer to a block type.
Definition: Type.h:3408
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3425
Represents the builtin template declaration which is used to implement __make_integer_seq and other b...
static BuiltinTemplateDecl * Create(const ASTContext &C, DeclContext *DC, DeclarationName Name, BuiltinTemplateKind BTK)
This class is used for builtin types like 'int'.
Definition: Type.h:3034
Kind getKind() const
Definition: Type.h:3082
StringRef getName(const PrintingPolicy &Policy) const
Definition: Type.cpp:3328
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition: Builtins.h:85
const char * getTypeString(unsigned ID) const
Get the type descriptor string for the specified builtin.
Definition: Builtins.h:106
bool hasCustomTypechecking(unsigned ID) const
Determines whether this builtin has custom typechecking.
Definition: Builtins.h:194
bool canBeRedeclared(unsigned ID) const
Returns true if this is a builtin that can be redeclared.
Definition: Builtins.cpp:242
bool isNoReturn(unsigned ID) const
Return true if we know this builtin never returns.
Definition: Builtins.h:130
bool isNoThrow(unsigned ID) const
Return true if we know this builtin never throws an exception.
Definition: Builtins.h:125
Implements C++ ABI-specific semantic analysis functions.
Definition: CXXABI.h:29
virtual ~CXXABI()
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2553
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2078
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2174
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition: DeclCXX.h:1226
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr, bool DelayTypeCreation=false)
Definition: DeclCXX.cpp:131
bool isDynamicClass() const
Definition: DeclCXX.h:586
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition: DeclCXX.h:1198
SplitQualType split() const
static CanQual< Type > CreateUnsafe(QualType Other)
Builds a canonical type from a QualType.
QualType withConst() const
Retrieves a version of this type with const applied.
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
bool isNull() const
Definition: CanonicalType.h:98
Qualifiers getQualifiers() const
Retrieve all qualifiers.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:84
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
bool isPositive() const
isPositive - Test whether the quantity is greater than zero.
Definition: CharUnits.h:128
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:53
Declaration of a class template.
llvm::PointerUnion< ClassTemplateDecl *, ClassTemplatePartialSpecializationDecl * > getSpecializedTemplateOrPartial() const
Retrieve the class template or class template partial specialization which was specialized by this.
Complex values, per C99 6.2.5p11.
Definition: Type.h:3145
QualType getElementType() const
Definition: Type.h:3155
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3160
Declaration of a C++20 concept.
ConceptDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
bool hasExplicitTemplateArgs() const
Whether or not template arguments were explicitly specified in the concept reference (they might not ...
Definition: ASTConcept.h:209
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Definition: ASTConcept.h:203
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3615
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition: Type.h:3711
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3671
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.h:3730
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition: Type.h:3691
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:4232
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition: Type.h:4253
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4270
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition: Type.h:4250
static constexpr bool isDimensionValid(size_t NumElements)
Returns true if NumElements is a valid matrix dimension.
Definition: Type.h:4261
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition: Type.h:3306
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3342
Represents a pointer type decayed from an array or function type.
Definition: Type.h:3391
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1435
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2089
bool isFileContext() const
Definition: DeclBase.h:2160
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1334
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:2105
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1854
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1990
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1768
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1050
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:314
T * getAttr() const
Definition: DeclBase.h:576
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:520
void addAttr(Attr *A)
Definition: DeclBase.cpp:1010
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:596
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition: DeclBase.cpp:534
static Decl * castFromDeclContext(const DeclContext *)
Definition: DeclBase.cpp:1038
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition: DeclBase.cpp:281
bool isCanonicalDecl() const
Whether this particular Decl is a canonical one.
Definition: DeclBase.h:973
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:246
ObjCDeclQualifier
ObjCDeclQualifier - 'Qualifiers' written next to the return and parameter types in method declaration...
Definition: DeclBase.h:198
@ OBJC_TQ_Byref
Definition: DeclBase.h:204
@ OBJC_TQ_Oneway
Definition: DeclBase.h:205
@ OBJC_TQ_Bycopy
Definition: DeclBase.h:203
@ OBJC_TQ_None
Definition: DeclBase.h:199
@ OBJC_TQ_Inout
Definition: DeclBase.h:201
bool isInvalidDecl() const
Definition: DeclBase.h:591
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:562
SourceLocation getLocation() const
Definition: DeclBase.h:442
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition: DeclBase.cpp:229
void setImplicit(bool I=true)
Definition: DeclBase.h:597
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: DeclBase.h:1038
DeclContext * getDeclContext()
Definition: DeclBase.h:451
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:434
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:355
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:907
bool hasAttr() const
Definition: DeclBase.h:580
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:967
Kind getKind() const
Definition: DeclBase.h:445
DeclarationNameLoc - Additional source/type location info for a declaration name.
static DeclarationNameLoc makeCXXOperatorNameLoc(SourceLocation BeginLoc, SourceLocation EndLoc)
Construct location information for a non-literal C++ operator.
DeclarationName getIdentifier(const IdentifierInfo *ID)
Create a declaration name that is a simple identifier.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
The name of a declaration.
static int compare(DeclarationName LHS, DeclarationName RHS)
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:735
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:764
Represents the type decltype(expr) (C++11).
Definition: Type.h:5874
Represents a C++17 deduced template specialization type.
Definition: Type.h:6604
void Profile(llvm::FoldingSetNodeID &ID) const
Definition: Type.h:6625
TemplateName getUnderlying() const
Definition: TemplateName.h:458
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) const
DefaultArguments getDefaultArguments() const
Definition: TemplateName.h:460
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:6522
Represents an extended address space qualifier where the input address space value is dependent.
Definition: Type.h:3920
Expr * getAddrSpaceExpr() const
Definition: Type.h:3931
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:3942
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:7859
Internal representation of canonical, dependent decltype(expr) types.
Definition: Type.h:5902
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:5906
Represents a qualified type name for which the type name is dependent.
Definition: Type.h:7024
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7056
Represents an array type in C++ whose size is a value-dependent expression.
Definition: Type.h:3862
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:3899
Expr * getSizeExpr() const
Definition: Type.h:3882
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3960
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:3985
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition: Type.h:4291
Expr * getRowExpr() const
Definition: Type.h:4303
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:4311
Represents a dependent template name that cannot be resolved prior to template instantiation.
Definition: TemplateName.h:548
OverloadedOperatorKind getOperator() const
Return the overloaded operator to which this template name refers.
Definition: TemplateName.h:620
bool isIdentifier() const
Determine whether this template name refers to an identifier.
Definition: TemplateName.h:607
const IdentifierInfo * getIdentifier() const
Returns the identifier to which this template name refers.
Definition: TemplateName.h:610
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TemplateName.h:626
Represents a template specialization type whose template cannot be resolved, e.g.
Definition: Type.h:7076
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:7103
Internal representation of canonical, dependent typeof(expr) types.
Definition: Type.h:5831
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:5836
Internal representation of canonical, dependent __underlying_type(type) types.
Definition: Type.h:6032
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6037
Represents a vector type where either the type or size is dependent.
Definition: Type.h:4086
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:4111
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:231
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1493
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition: Diagnostic.h:896
Wrap a function effect's condition expression in another struct so that FunctionProtoType's TrailingO...
Definition: Type.h:4823
Represents a type that was referred to using an elaborated type keyword, e.g., struct S,...
Definition: Type.h:6943
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6996
Represents an enum.
Definition: Decl.h:3847
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4052
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:4066
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4007
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:4961
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:6098
EnumDecl * getDecl() const
Definition: Type.h:6105
This represents one expression.
Definition: Expr.h:110
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3095
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:437
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition: Expr.cpp:4124
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:826
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition: Expr.h:221
bool isIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3070
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:3963
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
QualType getType() const
Definition: Expr.h:142
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition: Expr.h:427
We can encode up to four bits in the low bits of a type pointer, but there are many more type qualifi...
Definition: Type.h:1703
void Profile(llvm::FoldingSetNodeID &ID) const
Definition: Type.h:1750
ExtVectorType - Extended vector type.
Definition: Type.h:4126
Declaration context for names declared as extern "C" in C++.
Definition: Decl.h:226
static ExternCContextDecl * Create(const ASTContext &C, TranslationUnitDecl *TU)
Definition: Decl.cpp:5355
Abstract interface for external sources of AST nodes.
virtual ExtKind hasExternalDefinitions(const Decl *D)
virtual void ReadComments()
Loads comment ranges.
virtual void CompleteRedeclChain(const Decl *D)
Gives the external AST source an opportunity to complete the redeclaration chain for a declaration.
virtual void PrintStats()
Print any statistics that have been gathered regarding the external AST source.
Represents a member of a struct/union/class.
Definition: Decl.h:3033
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3124
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.cpp:4654
unsigned getBitWidthValue(const ASTContext &Ctx) const
Computes the bit width of this field, if this is a bit field.
Definition: Decl.cpp:4602
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3250
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:4555
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Represents a function declaration or definition.
Definition: Decl.h:1935
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2565
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3638
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2796
bool isMSExternInline() const
The combination of the extern and inline keywords under MSVC forces the function to be required.
Definition: Decl.cpp:3767
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4276
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition: Decl.h:2338
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4024
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:3937
static FunctionEffectSet getIntersection(FunctionEffectsRef LHS, FunctionEffectsRef RHS)
Definition: Type.cpp:5335
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition: Type.cpp:5373
Represents an abstract function effect, using just an enumeration describing its kind.
Definition: Type.h:4716
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition: Type.h:4903
size_t size() const
Definition: Type.h:4934
ArrayRef< EffectConditionExpr > conditions() const
Definition: Type.h:4937
bool empty() const
Definition: Type.h:4933
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition: Type.h:4681
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4697
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5102
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:5568
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:5382
unsigned getNumParams() const
Definition: Type.h:5355
QualType getParamType(unsigned i) const
Definition: Type.h:5357
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.cpp:3867
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:5388
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5479
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5366
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5362
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition: Type.h:5544
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition: Type.h:5540
Declaration of a template function.
Definition: DeclTemplate.h:959
A class which abstracts out some details necessary for making a call.
Definition: Type.h:4432
CallingConv getCC() const
Definition: Type.h:4494
bool getNoCfCheck() const
Definition: Type.h:4484
unsigned getRegParm() const
Definition: Type.h:4487
bool getNoCallerSavedRegs() const
Definition: Type.h:4483
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4506
bool getHasRegParm() const
Definition: Type.h:4485
bool getNoReturn() const
Definition: Type.h:4480
bool getProducesResult() const
Definition: Type.h:4481
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition: Type.h:4347
ExtParameterInfo withIsNoEscape(bool NoEscape) const
Definition: Type.h:4387
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4321
ExtInfo getExtInfo() const
Definition: Type.h:4655
QualType getReturnType() const
Definition: Type.h:4643
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:56
unsigned getMultiVersionIndex() const
Definition: GlobalDecl.h:122
CXXDtorType getDtorType() const
Definition: GlobalDecl.h:110
const Decl * getDecl() const
Definition: GlobalDecl.h:103
QualType getWrappedType() const
Definition: Type.h:6293
const Attributes & getAttrs() const
Definition: Type.h:6296
QualType getContainedType() const
Definition: Type.h:6294
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6301
One of these records is kept for each identifier that is lexed.
unsigned getLength() const
Efficiently return the length of this identifier info.
StringRef getName() const
Return the actual identifier string.
Implements an efficient mapping from strings to IdentifierInfo nodes.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition: Decl.h:4786
Represents a C array with an unspecified size.
Definition: Type.h:3764
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3781
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:6793
static ItaniumMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
@ Relative
Components in the vtable are relative offsets between the vtable and the other structs/functions.
@ Pointer
Components in the vtable are pointers to other structs/functions.
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3483
@ Swift
Interoperability with the latest known version of the Swift runtime.
@ Swift4_2
Interoperability with the Swift 4.2 runtime.
@ Swift4_1
Interoperability with the Swift 4.1 runtime.
@ Integer
Permit vector bitcasts between integer vectors with different numbers of elements but the same total ...
@ All
Permit vector bitcasts between all vectors with the same total bit-width.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:499
std::optional< TargetCXXABI::Kind > CXXABI
C++ ABI to compile with, if specified by the frontend through -fc++-abi=.
Definition: LangOptions.h:587
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:534
CoreFoundationABI CFRuntime
Definition: LangOptions.h:536
CommentOptions CommentOpts
Options for parsing comments.
Definition: LangOptions.h:563
std::string CUID
The user provided compilation unit ID, if non-empty.
Definition: LangOptions.h:583
A global _GUID constant.
Definition: DeclCXX.h:4307
static void Profile(llvm::FoldingSetNodeID &ID, Parts P)
Definition: DeclCXX.h:4344
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition: Type.h:5765
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
Definition: Mangle.h:45
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition: Type.h:4210
static bool isValidElementType(QualType T)
Valid elements types are the following:
Definition: Type.h:4217
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3519
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3555
QualType getPointeeType() const
Definition: Type.h:3535
const Type * getClass() const
Definition: Type.h:3549
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:620
static MicrosoftMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
Describes a module or submodule.
Definition: Module.h:115
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition: Module.h:195
This represents a decl that may have a name.
Definition: Decl.h:253
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:274
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition: Decl.cpp:1089
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:319
std::string getNameAsString() const
Get a human-readable name for the declaration, even if it is one of the special kinds of names (C++ c...
Definition: Decl.h:296
bool isExternallyVisible() const
Definition: Decl.h:412
NamespaceDecl * getNamespace()
Retrieve the namespace declaration aliased by this directive.
Definition: DeclCXX.h:3210
Represent a C++ namespace.
Definition: Decl.h:551
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl, bool Nested)
Definition: DeclCXX.cpp:3067
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, const IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
NamespaceAliasDecl * getAsNamespaceAlias() const
Retrieve the namespace alias stored in this nested name specifier.
IdentifierInfo * getAsIdentifier() const
Retrieve the identifier stored in this nested name specifier.
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
@ NamespaceAlias
A namespace alias, stored as a NamespaceAliasDecl*.
@ TypeSpec
A type, stored as a Type*.
@ TypeSpecWithTemplate
A type that was preceded by the 'template' keyword, stored as a Type*.
@ Super
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Identifier
An identifier, stored as an IdentifierInfo*.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace, stored as a NamespaceDecl*.
NamespaceDecl * getAsNamespace() const
Retrieve the namespace stored in this nested name specifier.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, unsigned D, unsigned P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
Helper data structure representing the traits in a match clause of an declare variant or metadirectiv...
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:2328
ObjCCategoryImplDecl - An object of this class encapsulates a category @implementation declaration.
Definition: DeclObjC.h:2544
ObjCContainerDecl - Represents a container for method declarations.
Definition: DeclObjC.h:947
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2596
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
ObjCTypeParamList * getTypeParamList() const
Retrieve the type parameters of this class.
Definition: DeclObjC.cpp:320
static ObjCInterfaceDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation atLoc, const IdentifierInfo *Id, ObjCTypeParamList *typeParamList, ObjCInterfaceDecl *PrevDecl, SourceLocation ClassLoc=SourceLocation(), bool isInternal=false)
Definition: DeclObjC.cpp:1540
bool hasDefinition() const
Determine whether this class has been defined.
Definition: DeclObjC.h:1527
ivar_range ivars() const
Definition: DeclObjC.h:1450
bool ClassImplementsProtocol(ObjCProtocolDecl *lProto, bool lookupCategory, bool RHSIsQualifiedID=false)
ClassImplementsProtocol - Checks that 'lProto' protocol has been implemented in IDecl class,...
Definition: DeclObjC.cpp:1786
StringRef getObjCRuntimeNameAsString() const
Produce a name to be used for class's metadata.
Definition: DeclObjC.cpp:1611
ObjCImplementationDecl * getImplementation() const
Definition: DeclObjC.cpp:1627
ObjCInterfaceDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this Objective-C class.
Definition: DeclObjC.h:1914
ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.cpp:350
bool isSuperClassOf(const ObjCInterfaceDecl *I) const
isSuperClassOf - Return true if this class is the specified class or is a super class of the specifie...
Definition: DeclObjC.h:1809
known_extensions_range known_extensions() const
Definition: DeclObjC.h:1761
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:7524
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition: Type.cpp:936
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1951
ObjCIvarDecl * getNextIvar()
Definition: DeclObjC.h:1986
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: DeclObjC.h:246
unsigned param_size() const
Definition: DeclObjC.h:347
param_const_iterator param_end() const
Definition: DeclObjC.h:358
param_const_iterator param_begin() const
Definition: DeclObjC.h:354
bool isVariadic() const
Definition: DeclObjC.h:431
const ParmVarDecl *const * param_const_iterator
Definition: DeclObjC.h:349
Selector getSelector() const
Definition: DeclObjC.h:327
bool isInstanceMethod() const
Definition: DeclObjC.h:426
QualType getReturnType() const
Definition: DeclObjC.h:329
Represents a pointer to an Objective C object.
Definition: Type.h:7580
bool isObjCQualifiedClassType() const
True if this is equivalent to 'Class.
Definition: Type.h:7661
const ObjCObjectPointerType * stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const
Strip off the Objective-C "kindof" type and (with it) any protocol qualifiers.
Definition: Type.cpp:943
bool isObjCQualifiedIdType() const
True if this is equivalent to 'id.
Definition: Type.h:7655
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7737
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:7617
bool qual_empty() const
Definition: Type.h:7709
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition: Type.h:7638
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:7592
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition: Type.h:7632
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1833
qual_range quals() const
Definition: Type.h:7699
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition: Type.h:7644
A class providing a concrete implementation of ObjCObjectType, so as to not increase the footprint of...
Definition: Type.h:7477
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:4450
Represents a class type in Objective C.
Definition: Type.h:7326
bool isKindOfTypeAsWritten() const
Whether this is a "__kindof" type as written.
Definition: Type.h:7441
bool isSpecialized() const
Determine whether this object type is "specialized", meaning that it has type arguments.
Definition: Type.cpp:865
ArrayRef< QualType > getTypeArgsAsWritten() const
Retrieve the type arguments of this object type as they were written.
Definition: Type.h:7436
bool isObjCQualifiedClass() const
Definition: Type.h:7408
QualType getBaseType() const
Gets the base type of this object type.
Definition: Type.h:7388
bool isObjCClass() const
Definition: Type.h:7394
bool isKindOfType() const
Whether this ia a "__kindof" type (semantically).
Definition: Type.cpp:901
bool isObjCQualifiedId() const
Definition: Type.h:7407
ArrayRef< QualType > getTypeArgs() const
Retrieve the type arguments of this object type (semantically).
Definition: Type.cpp:883
bool isObjCUnqualifiedId() const
Definition: Type.h:7398
ObjCInterfaceDecl * getInterface() const
Gets the interface declaration for this object type, if the base type really is an interface.
Definition: Type.h:7559
QualType getSuperClassType() const
Retrieve the type of the superclass of this object type.
Definition: Type.h:7452
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:730
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
Definition: DeclObjC.h:837
static ObjCPropertyDecl * findPropertyDecl(const DeclContext *DC, const IdentifierInfo *propertyID, ObjCPropertyQueryKind queryKind)
Lookup a property by name in the specified DeclContext.
Definition: DeclObjC.cpp:177
bool isOptional() const
Definition: DeclObjC.h:915
SetterKind getSetterKind() const
getSetterKind - Return the method used for doing assignment in the property setter.
Definition: DeclObjC.h:872
Selector getSetterName() const
Definition: DeclObjC.h:892
QualType getType() const
Definition: DeclObjC.h:803
Selector getGetterName() const
Definition: DeclObjC.h:884
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition: DeclObjC.h:814
ObjCPropertyImplDecl - Represents implementation declaration of a property in a class or category imp...
Definition: DeclObjC.h:2804
ObjCIvarDecl * getPropertyIvarDecl() const
Definition: DeclObjC.h:2878
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2083
protocol_range protocols() const
Definition: DeclObjC.h:2160
unsigned getNumProtocols() const
Return the number of qualifying protocols in this type, or 0 if there are none.
Definition: Type.h:7232
qual_iterator qual_end() const
Definition: Type.h:7226
qual_iterator qual_begin() const
Definition: Type.h:7225
qual_range quals() const
Definition: Type.h:7224
bool isGNUFamily() const
Is this runtime basically of the GNU family of runtimes?
Definition: ObjCRuntime.h:127
Represents the declaration of an Objective-C type parameter.
Definition: DeclObjC.h:578
ObjCTypeParamVariance getVariance() const
Determine the variance of this type parameter.
Definition: DeclObjC.h:623
Stores a list of Objective-C type parameters for a parameterized class or a category/extension thereo...
Definition: DeclObjC.h:659
Represents a type parameter type in Objective C.
Definition: Type.h:7252
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:4467
A structure for storing the information associated with an overloaded template name.
Definition: TemplateName.h:116
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition: ExprCXX.h:4180
Represents a pack expansion of types.
Definition: Type.h:7141
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7175
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5968
Sugar for parentheses used when specifying types.
Definition: Type.h:3172
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3186
void clear()
Clear parent maps.
Represents a parameter to a function.
Definition: Decl.h:1725
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: Decl.h:1789
QualType getOriginalType() const
Definition: Decl.cpp:2931
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:129
PipeType - OpenCL20.
Definition: Type.h:7780
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7797
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3198
QualType getPointeeType() const
Definition: Type.h:3208
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3213
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:138
A (possibly-)qualified type.
Definition: Type.h:929
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:8015
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2796
Qualifiers::GC getObjCGCAttr() const
Returns gc attribute of this type.
Definition: Type.h:8062
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:8020
QualType withConst() const
Definition: Type.h:1154
bool hasLocalQualifiers() const
Determine whether this particular QualType instance has any qualifiers, without looking through any t...
Definition: Type.h:1056
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:996
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7931
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:8057
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7971
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1433
QualType getCanonicalType() const
Definition: Type.h:7983
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:8025
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition: Type.h:7952
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:8004
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1531
bool isCanonical() const
Definition: Type.h:7988
const Type * getTypePtrOrNull() const
Definition: Type.h:7935
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1327
PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const
Check if this is a non-trivial type that would cause a C struct transitively containing this type to ...
Definition: Type.cpp:2933
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:7963
Represents a template name as written in source code.
Definition: TemplateName.h:491
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TemplateName.h:528
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:7871
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:7878
The collection of all-type qualifiers we support.
Definition: Type.h:324
unsigned getCVRQualifiers() const
Definition: Type.h:481
void removeCVRQualifiers(unsigned mask)
Definition: Type.h:488
GC getObjCGCAttr() const
Definition: Type.h:512
void addAddressSpace(LangAS space)
Definition: Type.h:590
static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R)
Returns the common set of qualifiers while removing them from the given sets.
Definition: Type.h:377
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:354
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:347
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:343
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:357
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:360
void removeObjCLifetime()
Definition: Type.h:544
bool hasNonFastQualifiers() const
Return true if the set contains any qualifiers which require an ExtQuals node to be allocated.
Definition: Type.h:631
void addConsistentQualifiers(Qualifiers qs)
Add the qualifiers from the given set to this set, given that they don't conflict.
Definition: Type.h:682
void removeFastQualifiers(unsigned mask)
Definition: Type.h:617
bool hasUnaligned() const
Definition: Type.h:504
bool hasAddressSpace() const
Definition: Type.h:563
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B, const ASTContext &Ctx)
Returns true if address space A is equal to or a superset of B.
Definition: Type.h:701
unsigned getFastQualifiers() const
Definition: Type.h:612
void removeAddressSpace()
Definition: Type.h:589
void setAddressSpace(LangAS space)
Definition: Type.h:584
bool hasObjCGCAttr() const
Definition: Type.h:511
uint64_t getAsOpaqueValue() const
Definition: Type.h:448
bool hasObjCLifetime() const
Definition: Type.h:537
ObjCLifetime getObjCLifetime() const
Definition: Type.h:538
bool empty() const
Definition: Type.h:640
void addObjCGCAttr(GC type)
Definition: Type.h:517
LangAS getAddressSpace() const
Definition: Type.h:564
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3501
unsigned getCommentBeginLine(RawComment *C, FileID File, unsigned Offset) const
const std::map< unsigned, RawComment * > * getCommentsInFile(FileID File) const
unsigned getCommentEndOffset(RawComment *C) const
void addComment(const RawComment &RC, const CommentOptions &CommentOpts, llvm::BumpPtrAllocator &Allocator)
bool isTrailingComment() const LLVM_READONLY
Returns true if it is a comment that should be put after a member:
SourceRange getSourceRange() const LLVM_READONLY
bool isDocumentation() const LLVM_READONLY
Returns true if this comment any kind of a documentation comment.
comments::FullComment * parse(const ASTContext &Context, const Preprocessor *PP, const Decl *D) const
Parse the comment, assuming it is attached to decl D.
Represents a struct/union/class.
Definition: Decl.h:4148
bool hasFlexibleArrayMember() const
Definition: Decl.h:4181
field_range fields() const
Definition: Decl.h:4354
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition: Decl.cpp:5038
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition: Decl.cpp:5104
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4339
bool field_empty() const
Definition: Decl.h:4362
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6072
RecordDecl * getDecl() const
Definition: Type.h:6082
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:215
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:203
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:225
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:295
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3439
QualType getPointeeType() const
Definition: Type.h:3457
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3465
This table allows us to fully hide how we implement multi-keyword caching.
std::string getAsString() const
Derive the full selector name (e.g.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
DiagnosticsEngine & getDiagnostics() const
StringRef getBufferData(FileID FID, bool *Invalid=nullptr) const
Return a StringRef to the source buffer data for the specified FileID.
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
unsigned getLineNumber(FileID FID, unsigned FilePos, bool *Invalid=nullptr) const
Given a SourceLocation, return the spelling line number for the position indicated.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
std::pair< FileID, unsigned > getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
The streaming interface shared between DiagnosticBuilder and PartialDiagnostic.
Definition: Diagnostic.h:1102
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1778
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, const SourceLocation *Loc, unsigned NumConcatenated)
This is the "fully general" constructor that allows representation of strings formed from multiple co...
Definition: Expr.cpp:1187
A structure for storing an already-substituted template template parameter pack.
Definition: TemplateName.h:149
Decl * getAssociatedDecl() const
A template-like entity which owns the whole pattern being substituted.
void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context)
TemplateTemplateParmDecl * getParameterPack() const
Retrieve the template template parameter pack being substituted.
TemplateArgument getArgumentPack() const
Retrieve the template template argument pack with which this parameter was substituted.
unsigned getIndex() const
Returns the index of the replaced parameter in the associated declaration.
Definition: TemplateName.h:164
A structure for storing the information associated with a substituted template template parameter.
Definition: TemplateName.h:408
void Profile(llvm::FoldingSetNodeID &ID)
TemplateTemplateParmDecl * getParameter() const
Represents the result of substituting a set of types for a template type parameter pack.
Definition: Type.h:6464
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:4311
Represents the result of substituting a type for a template type parameter.
Definition: Type.h:6383
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6428
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3564
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition: Decl.h:3792
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4760
bool isUnion() const
Definition: Decl.h:3770
TagDecl * getDecl() const
Definition: Type.cpp:4122
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
Kind
The basic C++ ABI kind.
Definition: TargetCXXABI.h:31
static Kind getKind(StringRef Name)
Definition: TargetCXXABI.h:59
Exposes information about the current target.
Definition: TargetInfo.h:220
TargetOptions & getTargetOpts() const
Retrieve the target options.
Definition: TargetInfo.h:311
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1262
IntType getInt64Type() const
Definition: TargetInfo.h:411
unsigned getMaxAtomicInlineWidth() const
Return the maximum width lock-free atomic operation which can be inlined given the supported features...
Definition: TargetInfo.h:844
virtual LangAS getCUDABuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
Definition: TargetInfo.h:1646
virtual LangAS getOpenCLBuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
Definition: TargetInfo.h:1640
unsigned getDefaultAlignForAttributeAligned() const
Return the default alignment for attribute((aligned)) on this target, to be used if no alignment valu...
Definition: TargetInfo.h:737
unsigned getBFloat16Width() const
getBFloat16Width/Align/Format - Return the size/align/format of '__bf16'.
Definition: TargetInfo.h:782
BuiltinVaListKind
The different kinds of __builtin_va_list types defined by the target implementation.
Definition: TargetInfo.h:318
@ AArch64ABIBuiltinVaList
__builtin_va_list as defined by the AArch64 ABI http://infocenter.arm.com/help/topic/com....
Definition: TargetInfo.h:327
@ PNaClABIBuiltinVaList
__builtin_va_list as defined by the PNaCl ABI: http://www.chromium.org/nativeclient/pnacl/bitcode-abi...
Definition: TargetInfo.h:331
@ PowerABIBuiltinVaList
__builtin_va_list as defined by the Power ABI: https://www.power.org /resources/downloads/Power-Arch-...
Definition: TargetInfo.h:336
@ AAPCSABIBuiltinVaList
__builtin_va_list as defined by ARM AAPCS ABI http://infocenter.arm.com
Definition: TargetInfo.h:345
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition: TargetInfo.h:320
@ VoidPtrBuiltinVaList
typedef void* __builtin_va_list;
Definition: TargetInfo.h:323
@ X86_64ABIBuiltinVaList
__builtin_va_list as defined by the x86-64 ABI: http://refspecs.linuxbase.org/elf/x86_64-abi-0....
Definition: TargetInfo.h:340
virtual uint64_t getNullPointerValue(LangAS AddrSpace) const
Get integer value for null pointer.
Definition: TargetInfo.h:494
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:478
static bool isTypeSigned(IntType T)
Returns true if the type is signed; false otherwise.
Definition: TargetInfo.cpp:386
unsigned getHalfAlign() const
Definition: TargetInfo.h:773
unsigned getBFloat16Align() const
Definition: TargetInfo.h:783
FloatModeKind getRealTypeByWidth(unsigned BitWidth, FloatModeKind ExplicitType) const
Return floating point type with specified width.
Definition: TargetInfo.cpp:332
virtual IntType getIntTypeByWidth(unsigned BitWidth, bool IsSigned) const
Return integer type with specified width.
Definition: TargetInfo.cpp:302
unsigned getHalfWidth() const
getHalfWidth/Align/Format - Return the size/align/format of 'half'.
Definition: TargetInfo.h:772
unsigned getMaxAlignedAttribute() const
Get the maximum alignment in bits for a static variable with aligned attribute.
Definition: TargetInfo.h:957
virtual unsigned getMinGlobalAlign(uint64_t Size, bool HasNonWeakDef) const
getMinGlobalAlign - Return the minimum alignment of a global variable, unless its alignment is explic...
Definition: TargetInfo.h:745
unsigned getTargetAddressSpace(LangAS AS) const
Definition: TargetInfo.h:1627
unsigned getFloat128Width() const
getFloat128Width/Align/Format - Return the size/align/format of '__float128'.
Definition: TargetInfo.h:801
const llvm::fltSemantics & getLongDoubleFormat() const
Definition: TargetInfo.h:795
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1333
bool hasAArch64SVETypes() const
Returns whether or not the AArch64 SVE built-in types are available on this target.
Definition: TargetInfo.h:1046
bool useAddressSpaceMapMangling() const
Specify if mangling based on address space map should be used or not for language specific address sp...
Definition: TargetInfo.h:1008
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
Definition: TargetInfo.h:524
unsigned getFloat128Align() const
Definition: TargetInfo.h:802
virtual bool hasBFloat16Type() const
Determine whether the _BFloat16 type is supported on this target.
Definition: TargetInfo.h:709
const llvm::fltSemantics & getFloat128Format() const
Definition: TargetInfo.h:803
unsigned getLongDoubleWidth() const
getLongDoubleWidth/Align/Format - Return the size/align/format of 'long double'.
Definition: TargetInfo.h:793
unsigned getLongDoubleAlign() const
Definition: TargetInfo.h:794
virtual std::optional< std::pair< unsigned, unsigned > > getVScaleRange(const LangOptions &LangOpts) const
Returns target-specific min and max values VScale_Range.
Definition: TargetInfo.h:1026
llvm::StringMap< bool > FeatureMap
The map of which features have been enabled disabled based on the command line.
Definition: TargetOptions.h:62
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
SourceLocation getRAngleLoc() const
Definition: TemplateBase.h:648
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:659
SourceLocation getLAngleLoc() const
Definition: TemplateBase.h:647
A template argument list.
Definition: DeclTemplate.h:250
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:280
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
Represents a template argument.
Definition: TemplateBase.h:61
QualType getStructuralValueType() const
Get the type of a StructuralValue.
Definition: TemplateBase.h:399
QualType getParamTypeForDecl() const
Definition: TemplateBase.h:331
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:408
std::optional< unsigned > getNumTemplateExpansions() const
Retrieve the number of expansions that a template template argument expansion will produce,...
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:319
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
Definition: TemplateBase.h:337
static TemplateArgument CreatePackCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument pack by copying the given set of template arguments.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:343
bool structurallyEquals(const TemplateArgument &Other) const
Determines whether two template arguments are superficially the same.
QualType getIntegralType() const
Retrieve the type of the integral value.
Definition: TemplateBase.h:377
bool getIsDefaulted() const
If returns 'true', this TemplateArgument corresponds to a default template parameter.
Definition: TemplateBase.h:393
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:326
ArrayRef< TemplateArgument > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
Definition: TemplateBase.h:432
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
Definition: TemplateBase.h:89
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
Definition: TemplateBase.h:97
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:78
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:67
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:82
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:103
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
Definition: TemplateBase.h:350
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
Definition: TemplateBase.h:396
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:399
bool isTypeAlias() const
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:418
Represents a C++ template name within the type system.
Definition: TemplateName.h:220
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
NameKind getKind() const
void * getAsVoidPointer() const
Retrieve the template name as a void pointer.
Definition: TemplateName.h:388
@ UsingTemplate
A template name that refers to a template declaration found through a specific using shadow declarati...
Definition: TemplateName.h:265
@ OverloadedTemplate
A set of overloaded template declarations.
Definition: TemplateName.h:240
@ Template
A single template declaration.
Definition: TemplateName.h:237
@ DependentTemplate
A dependent template name that has not been resolved to a template (or set of templates).
Definition: TemplateName.h:252
@ SubstTemplateTemplateParm
A template template parameter that has been substituted for some other template name.
Definition: TemplateName.h:256
@ SubstTemplateTemplateParmPack
A template template parameter pack that has been substituted for a template template argument pack,...
Definition: TemplateName.h:261
@ DeducedTemplate
A template name that refers to another TemplateName with deduced default arguments.
Definition: TemplateName.h:269
@ QualifiedTemplate
A qualified template name, where the qualification is kept to describe the source code as written.
Definition: TemplateName.h:248
@ AssumedTemplate
An unqualified-id that has been assumed to name a function template that will be found by ADL.
Definition: TemplateName.h:244
A template parameter object.
static void Profile(llvm::FoldingSetNodeID &ID, QualType T, const APValue &V)
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:147
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
NamedDecl *const * const_iterator
Iterates through the template parameters in this list.
Definition: DeclTemplate.h:132
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
Definition: DeclTemplate.h:183
ArrayRef< NamedDecl * > asArray()
Definition: DeclTemplate.h:142
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:1718
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1694
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1735
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1702
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1710
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6661
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.cpp:4402
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
bool isParameterPack() const
Whether this template template parameter is a template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
bool isExpandedParameterPack() const
Whether this parameter is a template template parameter pack that has a known list of different templ...
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, bool Typename, TemplateParameterList *Params)
Declaration of a template type parameter.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, std::optional< unsigned > NumExpanded=std::nullopt)
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6355
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition: ASTConcept.h:227
ConceptDecl * getNamedConcept() const
Definition: ASTConcept.h:250
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition: ASTConcept.h:242
ConceptReference * getConceptReference() const
Definition: ASTConcept.h:246
Represents a declaration of a type.
Definition: Decl.h:3370
void setTypeForDecl(const Type *TD)
Definition: Decl.h:3396
const Type * getTypeForDecl() const
Definition: Decl.h:3395
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition: TypeLoc.h:78
static unsigned getFullDataSizeForType(QualType Ty)
Returns the size of type source info data block for the given type.
Definition: TypeLoc.cpp:94
void initialize(ASTContext &Context, SourceLocation Loc) const
Initializes this to state that every location in this type is the given location.
Definition: TypeLoc.h:200
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition: Type.h:5797
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition: Type.h:5847
A container of type source information.
Definition: Type.h:7902
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
The base class of the type hierarchy.
Definition: Type.h:1828
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1916
bool isBlockPointerType() const
Definition: Type.h:8200
bool isVoidType() const
Definition: Type.h:8510
bool isBooleanType() const
Definition: Type.h:8638
bool isFunctionReferenceType() const
Definition: Type.h:8233
bool isObjCBuiltinType() const
Definition: Type.h:8379
QualType getRVVEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an RVV builtin type.
Definition: Type.cpp:2624
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:773
bool isIncompleteArrayType() const
Definition: Type.h:8266
bool isPlaceholderType() const
Test for a type which does not represent an actual type-system type but is instead used as a placehol...
Definition: Type.h:8486
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2180
bool isConstantArrayType() const
Definition: Type.h:8262
bool hasIntegerRepresentation() const
Determine whether this type has an integer representation of some sort, e.g., it is an integer type o...
Definition: Type.cpp:2055
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition: Type.cpp:2386
bool isArrayType() const
Definition: Type.h:8258
bool isCharType() const
Definition: Type.cpp:2123
QualType getLocallyUnqualifiedSingleStepDesugaredType() const
Pull a single level of sugar off of this locally-unqualified type.
Definition: Type.cpp:509
bool isFunctionPointerType() const
Definition: Type.h:8226
bool isPointerType() const
Definition: Type.h:8186
bool isArrayParameterType() const
Definition: Type.h:8274
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8550
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8800
bool isSpecificPlaceholderType(unsigned K) const
Test for a specific placeholder type.
Definition: Type.h:8499
bool isSignedFixedPointType() const
Return true if this is a fixed point type that is signed according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8591
bool isEnumeralType() const
Definition: Type.h:8290
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2554
bool isObjCQualifiedIdType() const
Definition: Type.h:8349
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:738
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8625
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition: Type.cpp:2270
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition: Type.cpp:2593
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2811
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2714
bool isBitIntType() const
Definition: Type.h:8424
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:8479
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:8282
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2706
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8563
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8579
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2361
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition: Type.cpp:2220
QualType getCanonicalTypeInternal() const
Definition: Type.h:2989
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8681
bool isMemberPointerType() const
Definition: Type.h:8240
bool isObjCIdType() const
Definition: Type.h:8361
bool isUnsaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8587
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:8786
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2396
bool isFunctionType() const
Definition: Type.h:8182
bool isObjCObjectPointerType() const
Definition: Type.h:8328
bool isUnsignedFixedPointType() const
Return true if this is a fixed point type that is unsigned according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8605
bool isVectorType() const
Definition: Type.h:8298
bool isObjCClassType() const
Definition: Type.h:8367
bool isRVVVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'riscv_rvv_vector_bits' type attribute,...
Definition: Type.cpp:2606
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2541
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition: Type.cpp:2230
bool isAnyPointerType() const
Definition: Type.h:8194
TypeClass getTypeClass() const
Definition: Type.h:2341
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition: Type.h:2367
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8731
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition: Type.cpp:638
bool isNullPtrType() const
Definition: Type.h:8543
bool isRecordType() const
Definition: Type.h:8286
bool isObjCRetainableType() const
Definition: Type.cpp:5028
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4763
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition: Decl.h:3514
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5525
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3413
QualType getUnderlyingType() const
Definition: Decl.h:3468
void setTypeSourceInfo(TypeSourceInfo *newType)
Definition: Decl.h:3474
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5750
A unary type transform, which is a type constructed from another.
Definition: Type.h:5989
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition: DeclCXX.h:4364
static void Profile(llvm::FoldingSetNodeID &ID, QualType Ty, const APValue &APVal)
Definition: DeclCXX.h:4392
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition: Type.h:5667
Represents a dependent using declaration which was marked with typename.
Definition: DeclCXX.h:3977
Represents a C++ using-enum-declaration.
Definition: DeclCXX.h:3731
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3338
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5718
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:671
void setType(QualType newType)
Definition: Decl.h:683
QualType getType() const
Definition: Decl.h:682
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition: Decl.cpp:5388
void clear()
Definition: Value.cpp:218
Represents a variable declaration or definition.
Definition: Decl.h:882
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2786
bool hasInit() const
Definition: Decl.cpp:2387
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a static data member.
Definition: Decl.cpp:2433
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1234
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1159
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition: Decl.cpp:2748
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1495
@ DeclarationOnly
This declaration is only a declaration.
Definition: Decl.h:1246
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition: Decl.cpp:2364
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2755
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3808
Expr * getSizeExpr() const
Definition: Type.h:3827
Represents a GCC generic vector type.
Definition: Type.h:4034
unsigned getNumElements() const
Definition: Type.h:4049
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4058
VectorKind getVectorKind() const
Definition: Type.h:4054
QualType getElementType() const
Definition: Type.h:4048
A full comment attached to a declaration, contains block content.
Definition: Comment.h:1083
ArrayRef< BlockContentComment * > getBlocks() const
Definition: Comment.h:1121
const DeclInfo * getDeclInfo() const LLVM_READONLY
Definition: Comment.h:1115
const Decl * getDecl() const LLVM_READONLY
Definition: Comment.h:1111
Holds all information required to evaluate constexpr code in a module.
Definition: Context.h:40
Defines the Linkage enumeration and various utility functions.
Defines the clang::TargetInfo interface.
const internal::VariadicAllOfMatcher< Attr > attr
Matches attributes.
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ArrayType > arrayType
Matches all kinds of arrays.
const AstTypeMatcher< TagType > tagType
Matches tag types (record and enum types).
The JSON file list parser is used to communicate input to InstallAPI.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ OpenCL
Definition: LangStandard.h:65
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
GVALinkage
A more specific kind of linkage than enum Linkage.
Definition: Linkage.h:72
@ GVA_StrongODR
Definition: Linkage.h:77
@ GVA_StrongExternal
Definition: Linkage.h:76
@ GVA_AvailableExternally
Definition: Linkage.h:74
@ GVA_DiscardableODR
Definition: Linkage.h:75
@ GVA_Internal
Definition: Linkage.h:73
AutoTypeKeyword
Which keyword(s) were used to create an AutoType.
Definition: Type.h:1778
OpenCLTypeKind
OpenCL type kinds.
Definition: TargetInfo.h:206
@ OCLTK_ReserveID
Definition: TargetInfo.h:213
@ OCLTK_Sampler
Definition: TargetInfo.h:214
@ OCLTK_Pipe
Definition: TargetInfo.h:211
@ OCLTK_ClkEvent
Definition: TargetInfo.h:208
@ OCLTK_Event
Definition: TargetInfo.h:209
@ OCLTK_Default
Definition: TargetInfo.h:207
@ OCLTK_Queue
Definition: TargetInfo.h:212
FunctionType::ExtInfo getFunctionExtInfo(const Type &t)
Definition: Type.h:8084
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
NullabilityKind
Describes the nullability of a particular type.
Definition: Specifiers.h:336
@ Nullable
Values of this type can be null.
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
@ NonNull
Values of this type can never be null.
@ ICIS_NoInit
No in-class initializer.
Definition: Specifiers.h:272
CXXABI * CreateMicrosoftCXXABI(ASTContext &Ctx)
@ Vector
'vector' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
TypeOfKind
The kind of 'typeof' expression we're after.
Definition: Type.h:910
@ SC_Register
Definition: Specifiers.h:257
@ SC_Static
Definition: Specifiers.h:252
CXXABI * CreateItaniumCXXABI(ASTContext &Ctx)
Creates an instance of a C++ ABI class.
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ASTContext::SectionInfo &Section)
Insertion operator for diagnostics.
@ TypeAlignment
Definition: Type.h:76
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition: Linkage.h:24
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
@ Result
The result type of a method or function.
ArraySizeModifier
Capture whether this is a normal array (e.g.
Definition: Type.h:3574
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
SubstTemplateTypeParmTypeFlag
Definition: Type.h:1789
TagTypeKind
The kind of a tag type.
Definition: Type.h:6871
@ Interface
The "__interface" keyword.
@ Struct
The "struct" keyword.
@ Class
The "class" keyword.
bool isDiscardableGVALinkage(GVALinkage L)
Definition: Linkage.h:80
BuiltinTemplateKind
Kinds of BuiltinTemplateDecl.
Definition: Builtins.h:305
@ BTK__type_pack_element
This names the __type_pack_element BuiltinTemplateDecl.
Definition: Builtins.h:310
@ BTK__builtin_common_type
This names the __builtin_common_type BuiltinTemplateDecl.
Definition: Builtins.h:313
@ BTK__make_integer_seq
This names the __make_integer_seq BuiltinTemplateDecl.
Definition: Builtins.h:307
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
TranslationUnitKind
Describes the kind of translation unit being processed.
Definition: LangOptions.h:1096
FloatModeKind
Definition: TargetInfo.h:73
bool isPtrSizeAddressSpace(LangAS AS)
Definition: AddressSpaces.h:91
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:139
const FunctionProtoType * T
void printTemplateArgumentList(raw_ostream &OS, ArrayRef< TemplateArgument > Args, const PrintingPolicy &Policy, const TemplateParameterList *TPL=nullptr)
Print a template argument list, including the '<' and '>' enclosing the template arguments.
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1274
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:191
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:278
@ CC_C
Definition: Specifiers.h:279
@ CC_M68kRTD
Definition: Specifiers.h:300
@ CC_X86RegCall
Definition: Specifiers.h:287
@ CC_X86VectorCall
Definition: Specifiers.h:283
@ CC_X86StdCall
Definition: Specifiers.h:280
@ CC_X86FastCall
Definition: Specifiers.h:281
@ Invariant
The parameter is invariant: must match exactly.
@ Contravariant
The parameter is contravariant, e.g., X<T> is a subtype of X when the type parameter is covariant and...
@ Covariant
The parameter is covariant, e.g., X<T> is a subtype of X when the type parameter is covariant and T i...
VectorKind
Definition: Type.h:3993
@ AltiVecBool
is AltiVec 'vector bool ...'
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
@ AltiVecPixel
is AltiVec 'vector Pixel'
@ Generic
not a target-specific vector type
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
LangAS getLangASFromTargetAS(unsigned TargetAS)
Definition: AddressSpaces.h:86
AlignRequirementKind
Definition: ASTContext.h:144
@ None
The alignment was not explicit in code.
@ RequiredByEnum
The alignment comes from an alignment attribute on a enum type.
@ RequiredByTypedef
The alignment comes from an alignment attribute on a typedef.
@ RequiredByRecord
The alignment comes from an alignment attribute on a record type.
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:6846
@ None
No keyword precedes the qualified type name.
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_DependentNoexcept
noexcept(expression), value-dependent
@ EST_DynamicNone
throw()
@ EST_Uninstantiated
not instantiated yet
@ EST_Unparsed
not parsed yet
@ EST_NoThrow
Microsoft __declspec(nothrow) extension.
@ EST_None
no exception specification
@ EST_MSAny
Microsoft throw(...) extension.
@ EST_BasicNoexcept
noexcept
@ EST_NoexceptFalse
noexcept(expression), evals to 'false'
@ EST_Unevaluated
not evaluated yet, for special member function
@ EST_NoexceptTrue
noexcept(expression), evals to 'true'
@ EST_Dynamic
throw(T1, T2)
@ AS_public
Definition: Specifiers.h:124
unsigned long uint64_t
Diagnostic wrappers for TextAPI types for error reporting.
Definition: Dominators.h:30
unsigned NumTemplateArgs
The number of template arguments in TemplateArgs.
Definition: TemplateBase.h:694
Copy initialization expr of a __block variable and a boolean flag that indicates whether the expressi...
Definition: Expr.h:6460
Expr * getCopyExpr() const
Definition: Expr.h:6467
bool ParseAllComments
Treat ordinary comments as documentation comments.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
ArrayRef< TemplateArgument > Args
Definition: TemplateName.h:187
Holds information about the various types of exception specification.
Definition: Type.h:5159
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:5161
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition: Type.h:5164
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition: Type.h:5167
Extra information about a function prototype.
Definition: Type.h:5187
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:5194
bool requiresFunctionProtoTypeArmAttributes() const
Definition: Type.h:5219
FunctionEffectsRef FunctionEffects
Definition: Type.h:5197
const ExtParameterInfo * ExtParameterInfos
Definition: Type.h:5195
bool requiresFunctionProtoTypeExtraBitfields() const
Definition: Type.h:5213
FunctionType::ExtInfo ExtInfo
Definition: Type.h:5188
A simple holder for a QualType representing a type in an exception specification.
Definition: Type.h:4559
A holder for Arm type attributes as described in the Arm C/C++ Language extensions which are not part...
Definition: Type.h:4620
A simple holder for various uncommon bits which do not fit in FunctionTypeBitfields.
Definition: Type.h:4564
A lazy value (of type T) that is within an AST node of type Owner, where the value might change in la...
Parts of a decomposed MSGuidDecl.
Definition: DeclCXX.h:4282
Contains information gathered from parsing the contents of TargetAttr.
Definition: TargetInfo.h:58
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition: Type.h:862
const Type * Ty
The locally-unqualified type.
Definition: Type.h:864
Qualifiers Quals
The local qualifiers.
Definition: Type.h:867
A this pointer adjustment.
Definition: Thunk.h:92
IntType
===-— Target Data Type Query Methods ----------------------------—===//
Definition: TargetInfo.h:144
AlignRequirementKind AlignRequirement
Definition: ASTContext.h:175
bool isAlignRequired()
Definition: ASTContext.h:167
AlignRequirementKind AlignRequirement
Definition: ASTContext.h:161
uint64_t Width
Definition: ASTContext.h:159
unsigned Align
Definition: ASTContext.h:160
Information about the declaration, useful to clients of FullComment.
Definition: Comment.h:962
const TemplateParameterList * TemplateParameters
Template parameters that can be referenced by \tparam if CommentDecl is a template (IsTemplateDecl or...
Definition: Comment.h:988
const Decl * CommentDecl
Declaration the comment is actually attached to (in the source).
Definition: Comment.h:965
static bool isEqual(const FoldingSetNodeID &LHS, const FoldingSetNodeID &RHS)
Definition: ASTContext.cpp:130
static FoldingSetNodeID getTombstoneKey()
Definition: ASTContext.cpp:118
static unsigned getHashValue(const FoldingSetNodeID &Val)
Definition: ASTContext.cpp:126