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();
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.getCanonicalType(), IndexExpr,
6252 FullySubstituted);
6253 void *InsertPos = nullptr;
6254 PackIndexingType *Canon =
6255 DependentPackIndexingTypes.FindNodeOrInsertPos(ID, InsertPos);
6256 if (!Canon) {
6257 void *Mem = Allocate(
6258 PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6260 Canon = new (Mem)
6261 PackIndexingType(*this, QualType(), Pattern.getCanonicalType(),
6262 IndexExpr, FullySubstituted, Expansions);
6263 DependentPackIndexingTypes.InsertNode(Canon, InsertPos);
6264 }
6265 Canonical = QualType(Canon, 0);
6266 }
6267
6268 void *Mem =
6269 Allocate(PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6271 auto *T = new (Mem) PackIndexingType(*this, Canonical, Pattern, IndexExpr,
6272 FullySubstituted, Expansions);
6273 Types.push_back(T);
6274 return QualType(T, 0);
6275}
6276
6277/// getUnaryTransformationType - We don't unique these, since the memory
6278/// savings are minimal and these are rare.
6280 QualType UnderlyingType,
6282 const {
6283 UnaryTransformType *ut = nullptr;
6284
6285 if (BaseType->isDependentType()) {
6286 // Look in the folding set for an existing type.
6287 llvm::FoldingSetNodeID ID;
6289
6290 void *InsertPos = nullptr;
6292 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
6293
6294 if (!Canon) {
6295 // Build a new, canonical __underlying_type(type) type.
6296 Canon = new (*this, alignof(DependentUnaryTransformType))
6297 DependentUnaryTransformType(*this, getCanonicalType(BaseType), Kind);
6298 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
6299 }
6300 ut = new (*this, alignof(UnaryTransformType))
6301 UnaryTransformType(BaseType, QualType(), Kind, QualType(Canon, 0));
6302 } else {
6303 QualType CanonType = getCanonicalType(UnderlyingType);
6304 ut = new (*this, alignof(UnaryTransformType))
6305 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
6306 }
6307 Types.push_back(ut);
6308 return QualType(ut, 0);
6309}
6310
6311QualType ASTContext::getAutoTypeInternal(
6312 QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent,
6313 bool IsPack, ConceptDecl *TypeConstraintConcept,
6314 ArrayRef<TemplateArgument> TypeConstraintArgs, bool IsCanon) const {
6315 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
6316 !TypeConstraintConcept && !IsDependent)
6317 return getAutoDeductType();
6318
6319 // Look in the folding set for an existing type.
6320 llvm::FoldingSetNodeID ID;
6321 bool IsDeducedDependent =
6322 !DeducedType.isNull() && DeducedType->isDependentType();
6323 AutoType::Profile(ID, *this, DeducedType, Keyword,
6324 IsDependent || IsDeducedDependent, TypeConstraintConcept,
6325 TypeConstraintArgs);
6326 if (auto const AT_iter = AutoTypes.find(ID); AT_iter != AutoTypes.end())
6327 return QualType(AT_iter->getSecond(), 0);
6328
6329 QualType Canon;
6330 if (!IsCanon) {
6331 if (!DeducedType.isNull()) {
6332 Canon = DeducedType.getCanonicalType();
6333 } else if (TypeConstraintConcept) {
6334 bool AnyNonCanonArgs = false;
6335 ConceptDecl *CanonicalConcept = TypeConstraintConcept->getCanonicalDecl();
6336 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
6337 *this, TypeConstraintArgs, AnyNonCanonArgs);
6338 if (CanonicalConcept != TypeConstraintConcept || AnyNonCanonArgs) {
6339 Canon =
6340 getAutoTypeInternal(QualType(), Keyword, IsDependent, IsPack,
6341 CanonicalConcept, CanonicalConceptArgs, true);
6342 }
6343 }
6344 }
6345
6346 void *Mem = Allocate(sizeof(AutoType) +
6347 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
6348 alignof(AutoType));
6349 auto *AT = new (Mem) AutoType(
6350 DeducedType, Keyword,
6351 (IsDependent ? TypeDependence::DependentInstantiation
6352 : TypeDependence::None) |
6353 (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None),
6354 Canon, TypeConstraintConcept, TypeConstraintArgs);
6355#ifndef NDEBUG
6356 llvm::FoldingSetNodeID InsertedID;
6357 AT->Profile(InsertedID, *this);
6358 assert(InsertedID == ID && "ID does not match");
6359#endif
6360 Types.push_back(AT);
6361 AutoTypes.try_emplace(ID, AT);
6362 return QualType(AT, 0);
6363}
6364
6365/// getAutoType - Return the uniqued reference to the 'auto' type which has been
6366/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
6367/// canonical deduced-but-dependent 'auto' type.
6370 bool IsDependent, bool IsPack,
6371 ConceptDecl *TypeConstraintConcept,
6372 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
6373 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
6374 assert((!IsDependent || DeducedType.isNull()) &&
6375 "A dependent auto should be undeduced");
6376 return getAutoTypeInternal(DeducedType, Keyword, IsDependent, IsPack,
6377 TypeConstraintConcept, TypeConstraintArgs);
6378}
6379
6381 QualType CanonT = T.getNonPackExpansionType().getCanonicalType();
6382
6383 // Remove a type-constraint from a top-level auto or decltype(auto).
6384 if (auto *AT = CanonT->getAs<AutoType>()) {
6385 if (!AT->isConstrained())
6386 return T;
6387 return getQualifiedType(getAutoType(QualType(), AT->getKeyword(),
6388 AT->isDependentType(),
6389 AT->containsUnexpandedParameterPack()),
6390 T.getQualifiers());
6391 }
6392
6393 // FIXME: We only support constrained auto at the top level in the type of a
6394 // non-type template parameter at the moment. Once we lift that restriction,
6395 // we'll need to recursively build types containing auto here.
6396 assert(!CanonT->getContainedAutoType() ||
6397 !CanonT->getContainedAutoType()->isConstrained());
6398 return T;
6399}
6400
6401QualType ASTContext::getDeducedTemplateSpecializationTypeInternal(
6402 TemplateName Template, QualType DeducedType, bool IsDependent,
6403 QualType Canon) const {
6404 // Look in the folding set for an existing type.
6405 void *InsertPos = nullptr;
6406 llvm::FoldingSetNodeID ID;
6408 IsDependent);
6410 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6411 return QualType(DTST, 0);
6412
6413 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
6414 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent,
6415 Canon);
6416 llvm::FoldingSetNodeID TempID;
6417 DTST->Profile(TempID);
6418 assert(ID == TempID && "ID does not match");
6419 Types.push_back(DTST);
6420 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
6421 return QualType(DTST, 0);
6422}
6423
6424/// Return the uniqued reference to the deduced template specialization type
6425/// which has been deduced to the given type, or to the canonical undeduced
6426/// such type, or the canonical deduced-but-dependent such type.
6428 TemplateName Template, QualType DeducedType, bool IsDependent) const {
6429 QualType Canon = DeducedType.isNull()
6430 ? getDeducedTemplateSpecializationTypeInternal(
6432 IsDependent, QualType())
6433 : DeducedType.getCanonicalType();
6434 return getDeducedTemplateSpecializationTypeInternal(Template, DeducedType,
6435 IsDependent, Canon);
6436}
6437
6438/// getAtomicType - Return the uniqued reference to the atomic type for
6439/// the given value type.
6441 // Unique pointers, to guarantee there is only one pointer of a particular
6442 // structure.
6443 llvm::FoldingSetNodeID ID;
6445
6446 void *InsertPos = nullptr;
6447 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
6448 return QualType(AT, 0);
6449
6450 // If the atomic value type isn't canonical, this won't be a canonical type
6451 // either, so fill in the canonical type field.
6452 QualType Canonical;
6453 if (!T.isCanonical()) {
6454 Canonical = getAtomicType(getCanonicalType(T));
6455
6456 // Get the new insert position for the node we care about.
6457 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
6458 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
6459 }
6460 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
6461 Types.push_back(New);
6462 AtomicTypes.InsertNode(New, InsertPos);
6463 return QualType(New, 0);
6464}
6465
6466/// getAutoDeductType - Get type pattern for deducing against 'auto'.
6468 if (AutoDeductTy.isNull())
6469 AutoDeductTy = QualType(new (*this, alignof(AutoType))
6471 TypeDependence::None, QualType(),
6472 /*concept*/ nullptr, /*args*/ {}),
6473 0);
6474 return AutoDeductTy;
6475}
6476
6477/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
6481 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
6482 return AutoRRefDeductTy;
6483}
6484
6485/// getTagDeclType - Return the unique reference to the type for the
6486/// specified TagDecl (struct/union/class/enum) decl.
6488 assert(Decl);
6489 // FIXME: What is the design on getTagDeclType when it requires casting
6490 // away const? mutable?
6491 return getTypeDeclType(const_cast<TagDecl*>(Decl));
6492}
6493
6494/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
6495/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
6496/// needs to agree with the definition in <stddef.h>.
6498 return getFromTargetType(Target->getSizeType());
6499}
6500
6501/// Return the unique signed counterpart of the integer type
6502/// corresponding to size_t.
6504 return getFromTargetType(Target->getSignedSizeType());
6505}
6506
6507/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
6509 return getFromTargetType(Target->getIntMaxType());
6510}
6511
6512/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
6514 return getFromTargetType(Target->getUIntMaxType());
6515}
6516
6517/// getSignedWCharType - Return the type of "signed wchar_t".
6518/// Used when in C++, as a GCC extension.
6520 // FIXME: derive from "Target" ?
6521 return WCharTy;
6522}
6523
6524/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
6525/// Used when in C++, as a GCC extension.
6527 // FIXME: derive from "Target" ?
6528 return UnsignedIntTy;
6529}
6530
6532 return getFromTargetType(Target->getIntPtrType());
6533}
6534
6537}
6538
6539/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
6540/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
6542 return getFromTargetType(Target->getPtrDiffType(LangAS::Default));
6543}
6544
6545/// Return the unique unsigned counterpart of "ptrdiff_t"
6546/// integer type. The standard (C11 7.21.6.1p7) refers to this type
6547/// in the definition of %tu format specifier.
6549 return getFromTargetType(Target->getUnsignedPtrDiffType(LangAS::Default));
6550}
6551
6552/// Return the unique type for "pid_t" defined in
6553/// <sys/types.h>. We need this to compute the correct type for vfork().
6555 return getFromTargetType(Target->getProcessIDType());
6556}
6557
6558//===----------------------------------------------------------------------===//
6559// Type Operators
6560//===----------------------------------------------------------------------===//
6561
6563 // Push qualifiers into arrays, and then discard any remaining
6564 // qualifiers.
6565 T = getCanonicalType(T);
6567 const Type *Ty = T.getTypePtr();
6569 if (getLangOpts().HLSL && isa<ConstantArrayType>(Ty)) {
6571 } else if (isa<ArrayType>(Ty)) {
6573 } else if (isa<FunctionType>(Ty)) {
6574 Result = getPointerType(QualType(Ty, 0));
6575 } else {
6576 Result = QualType(Ty, 0);
6577 }
6578
6580}
6581
6583 Qualifiers &quals) const {
6584 SplitQualType splitType = type.getSplitUnqualifiedType();
6585
6586 // FIXME: getSplitUnqualifiedType() actually walks all the way to
6587 // the unqualified desugared type and then drops it on the floor.
6588 // We then have to strip that sugar back off with
6589 // getUnqualifiedDesugaredType(), which is silly.
6590 const auto *AT =
6591 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
6592
6593 // If we don't have an array, just use the results in splitType.
6594 if (!AT) {
6595 quals = splitType.Quals;
6596 return QualType(splitType.Ty, 0);
6597 }
6598
6599 // Otherwise, recurse on the array's element type.
6600 QualType elementType = AT->getElementType();
6601 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
6602
6603 // If that didn't change the element type, AT has no qualifiers, so we
6604 // can just use the results in splitType.
6605 if (elementType == unqualElementType) {
6606 assert(quals.empty()); // from the recursive call
6607 quals = splitType.Quals;
6608 return QualType(splitType.Ty, 0);
6609 }
6610
6611 // Otherwise, add in the qualifiers from the outermost type, then
6612 // build the type back up.
6613 quals.addConsistentQualifiers(splitType.Quals);
6614
6615 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
6616 return getConstantArrayType(unqualElementType, CAT->getSize(),
6617 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
6618 }
6619
6620 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
6621 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
6622 }
6623
6624 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
6625 return getVariableArrayType(unqualElementType,
6626 VAT->getSizeExpr(),
6627 VAT->getSizeModifier(),
6628 VAT->getIndexTypeCVRQualifiers(),
6629 VAT->getBracketsRange());
6630 }
6631
6632 const auto *DSAT = cast<DependentSizedArrayType>(AT);
6633 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
6634 DSAT->getSizeModifier(), 0,
6635 SourceRange());
6636}
6637
6638/// Attempt to unwrap two types that may both be array types with the same bound
6639/// (or both be array types of unknown bound) for the purpose of comparing the
6640/// cv-decomposition of two types per C++ [conv.qual].
6641///
6642/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
6643/// C++20 [conv.qual], if permitted by the current language mode.
6645 bool AllowPiMismatch) const {
6646 while (true) {
6647 auto *AT1 = getAsArrayType(T1);
6648 if (!AT1)
6649 return;
6650
6651 auto *AT2 = getAsArrayType(T2);
6652 if (!AT2)
6653 return;
6654
6655 // If we don't have two array types with the same constant bound nor two
6656 // incomplete array types, we've unwrapped everything we can.
6657 // C++20 also permits one type to be a constant array type and the other
6658 // to be an incomplete array type.
6659 // FIXME: Consider also unwrapping array of unknown bound and VLA.
6660 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
6661 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
6662 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
6663 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
6664 isa<IncompleteArrayType>(AT2))))
6665 return;
6666 } else if (isa<IncompleteArrayType>(AT1)) {
6667 if (!(isa<IncompleteArrayType>(AT2) ||
6668 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
6669 isa<ConstantArrayType>(AT2))))
6670 return;
6671 } else {
6672 return;
6673 }
6674
6675 T1 = AT1->getElementType();
6676 T2 = AT2->getElementType();
6677 }
6678}
6679
6680/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
6681///
6682/// If T1 and T2 are both pointer types of the same kind, or both array types
6683/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
6684/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
6685///
6686/// This function will typically be called in a loop that successively
6687/// "unwraps" pointer and pointer-to-member types to compare them at each
6688/// level.
6689///
6690/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
6691/// C++20 [conv.qual], if permitted by the current language mode.
6692///
6693/// \return \c true if a pointer type was unwrapped, \c false if we reached a
6694/// pair of types that can't be unwrapped further.
6696 bool AllowPiMismatch) const {
6697 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
6698
6699 const auto *T1PtrType = T1->getAs<PointerType>();
6700 const auto *T2PtrType = T2->getAs<PointerType>();
6701 if (T1PtrType && T2PtrType) {
6702 T1 = T1PtrType->getPointeeType();
6703 T2 = T2PtrType->getPointeeType();
6704 return true;
6705 }
6706
6707 const auto *T1MPType = T1->getAs<MemberPointerType>();
6708 const auto *T2MPType = T2->getAs<MemberPointerType>();
6709 if (T1MPType && T2MPType &&
6710 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
6711 QualType(T2MPType->getClass(), 0))) {
6712 T1 = T1MPType->getPointeeType();
6713 T2 = T2MPType->getPointeeType();
6714 return true;
6715 }
6716
6717 if (getLangOpts().ObjC) {
6718 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
6719 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
6720 if (T1OPType && T2OPType) {
6721 T1 = T1OPType->getPointeeType();
6722 T2 = T2OPType->getPointeeType();
6723 return true;
6724 }
6725 }
6726
6727 // FIXME: Block pointers, too?
6728
6729 return false;
6730}
6731
6733 while (true) {
6734 Qualifiers Quals;
6735 T1 = getUnqualifiedArrayType(T1, Quals);
6736 T2 = getUnqualifiedArrayType(T2, Quals);
6737 if (hasSameType(T1, T2))
6738 return true;
6739 if (!UnwrapSimilarTypes(T1, T2))
6740 return false;
6741 }
6742}
6743
6745 while (true) {
6746 Qualifiers Quals1, Quals2;
6747 T1 = getUnqualifiedArrayType(T1, Quals1);
6748 T2 = getUnqualifiedArrayType(T2, Quals2);
6749
6750 Quals1.removeCVRQualifiers();
6751 Quals2.removeCVRQualifiers();
6752 if (Quals1 != Quals2)
6753 return false;
6754
6755 if (hasSameType(T1, T2))
6756 return true;
6757
6758 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
6759 return false;
6760 }
6761}
6762
6765 SourceLocation NameLoc) const {
6766 switch (Name.getKind()) {
6769 // DNInfo work in progress: CHECKME: what about DNLoc?
6770 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
6771 NameLoc);
6772
6774 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
6775 // DNInfo work in progress: CHECKME: what about DNLoc?
6776 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
6777 }
6778
6780 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
6781 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
6782 }
6783
6785 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
6786 DeclarationName DName;
6787 if (DTN->isIdentifier()) {
6789 return DeclarationNameInfo(DName, NameLoc);
6790 } else {
6792 // DNInfo work in progress: FIXME: source locations?
6793 DeclarationNameLoc DNLoc =
6795 return DeclarationNameInfo(DName, NameLoc, DNLoc);
6796 }
6797 }
6798
6801 = Name.getAsSubstTemplateTemplateParm();
6802 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
6803 NameLoc);
6804 }
6805
6808 = Name.getAsSubstTemplateTemplateParmPack();
6810 NameLoc);
6811 }
6813 return DeclarationNameInfo(Name.getAsUsingShadowDecl()->getDeclName(),
6814 NameLoc);
6816 DeducedTemplateStorage *DTS = Name.getAsDeducedTemplateName();
6817 return getNameForTemplate(DTS->getUnderlying(), NameLoc);
6818 }
6819 }
6820
6821 llvm_unreachable("bad template name kind!");
6822}
6823
6824static const TemplateArgument *
6826 auto handleParam = [](auto *TP) -> const TemplateArgument * {
6827 if (!TP->hasDefaultArgument())
6828 return nullptr;
6829 return &TP->getDefaultArgument().getArgument();
6830 };
6831 switch (P->getKind()) {
6832 case NamedDecl::TemplateTypeParm:
6833 return handleParam(cast<TemplateTypeParmDecl>(P));
6834 case NamedDecl::NonTypeTemplateParm:
6835 return handleParam(cast<NonTypeTemplateParmDecl>(P));
6836 case NamedDecl::TemplateTemplateParm:
6837 return handleParam(cast<TemplateTemplateParmDecl>(P));
6838 default:
6839 llvm_unreachable("Unexpected template parameter kind");
6840 }
6841}
6842
6844 bool IgnoreDeduced) const {
6845 while (std::optional<TemplateName> UnderlyingOrNone =
6846 Name.desugar(IgnoreDeduced))
6847 Name = *UnderlyingOrNone;
6848
6849 switch (Name.getKind()) {
6851 TemplateDecl *Template = Name.getAsTemplateDecl();
6852 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
6853 Template = getCanonicalTemplateTemplateParmDecl(TTP);
6854
6855 // The canonical template name is the canonical template declaration.
6856 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
6857 }
6858
6861 llvm_unreachable("cannot canonicalize unresolved template");
6862
6864 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
6865 assert(DTN && "Non-dependent template names must refer to template decls.");
6866 return DTN->CanonicalTemplateName;
6867 }
6868
6871 Name.getAsSubstTemplateTemplateParmPack();
6872 TemplateArgument canonArgPack =
6875 canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
6876 subst->getFinal(), subst->getIndex());
6877 }
6879 assert(IgnoreDeduced == false);
6880 DeducedTemplateStorage *DTS = Name.getAsDeducedTemplateName();
6881 DefaultArguments DefArgs = DTS->getDefaultArguments();
6882 TemplateName Underlying = DTS->getUnderlying();
6883
6884 TemplateName CanonUnderlying =
6885 getCanonicalTemplateName(Underlying, /*IgnoreDeduced=*/true);
6886 bool NonCanonical = CanonUnderlying != Underlying;
6887 auto CanonArgs =
6888 getCanonicalTemplateArguments(*this, DefArgs.Args, NonCanonical);
6889
6890 ArrayRef<NamedDecl *> Params =
6891 CanonUnderlying.getAsTemplateDecl()->getTemplateParameters()->asArray();
6892 assert(CanonArgs.size() <= Params.size());
6893 // A deduced template name which deduces the same default arguments already
6894 // declared in the underlying template is the same template as the
6895 // underlying template. We need need to note any arguments which differ from
6896 // the corresponding declaration. If any argument differs, we must build a
6897 // deduced template name.
6898 for (int I = CanonArgs.size() - 1; I >= 0; --I) {
6900 if (!A)
6901 break;
6902 auto CanonParamDefArg = getCanonicalTemplateArgument(*A);
6903 TemplateArgument &CanonDefArg = CanonArgs[I];
6904 if (CanonDefArg.structurallyEquals(CanonParamDefArg))
6905 continue;
6906 // Keep popping from the back any deault arguments which are the same.
6907 if (I == int(CanonArgs.size() - 1))
6908 CanonArgs.pop_back();
6909 NonCanonical = true;
6910 }
6911 return NonCanonical ? getDeducedTemplateName(
6912 CanonUnderlying,
6913 /*DefaultArgs=*/{DefArgs.StartPos, CanonArgs})
6914 : Name;
6915 }
6919 llvm_unreachable("always sugar node");
6920 }
6921
6922 llvm_unreachable("bad template name!");
6923}
6924
6926 const TemplateName &Y,
6927 bool IgnoreDeduced) const {
6928 return getCanonicalTemplateName(X, IgnoreDeduced) ==
6929 getCanonicalTemplateName(Y, IgnoreDeduced);
6930}
6931
6932bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
6933 if (!XCE != !YCE)
6934 return false;
6935
6936 if (!XCE)
6937 return true;
6938
6939 llvm::FoldingSetNodeID XCEID, YCEID;
6940 XCE->Profile(XCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
6941 YCE->Profile(YCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
6942 return XCEID == YCEID;
6943}
6944
6946 const TypeConstraint *YTC) const {
6947 if (!XTC != !YTC)
6948 return false;
6949
6950 if (!XTC)
6951 return true;
6952
6953 auto *NCX = XTC->getNamedConcept();
6954 auto *NCY = YTC->getNamedConcept();
6955 if (!NCX || !NCY || !isSameEntity(NCX, NCY))
6956 return false;
6959 return false;
6961 if (XTC->getConceptReference()
6963 ->NumTemplateArgs !=
6965 return false;
6966
6967 // Compare slowly by profiling.
6968 //
6969 // We couldn't compare the profiling result for the template
6970 // args here. Consider the following example in different modules:
6971 //
6972 // template <__integer_like _Tp, C<_Tp> Sentinel>
6973 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
6974 // return __t;
6975 // }
6976 //
6977 // When we compare the profiling result for `C<_Tp>` in different
6978 // modules, it will compare the type of `_Tp` in different modules.
6979 // However, the type of `_Tp` in different modules refer to different
6980 // types here naturally. So we couldn't compare the profiling result
6981 // for the template args directly.
6984}
6985
6987 const NamedDecl *Y) const {
6988 if (X->getKind() != Y->getKind())
6989 return false;
6990
6991 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
6992 auto *TY = cast<TemplateTypeParmDecl>(Y);
6993 if (TX->isParameterPack() != TY->isParameterPack())
6994 return false;
6995 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
6996 return false;
6997 return isSameTypeConstraint(TX->getTypeConstraint(),
6998 TY->getTypeConstraint());
6999 }
7000
7001 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7002 auto *TY = cast<NonTypeTemplateParmDecl>(Y);
7003 return TX->isParameterPack() == TY->isParameterPack() &&
7004 TX->getASTContext().hasSameType(TX->getType(), TY->getType()) &&
7005 isSameConstraintExpr(TX->getPlaceholderTypeConstraint(),
7006 TY->getPlaceholderTypeConstraint());
7007 }
7008
7009 auto *TX = cast<TemplateTemplateParmDecl>(X);
7010 auto *TY = cast<TemplateTemplateParmDecl>(Y);
7011 return TX->isParameterPack() == TY->isParameterPack() &&
7012 isSameTemplateParameterList(TX->getTemplateParameters(),
7013 TY->getTemplateParameters());
7014}
7015
7017 const TemplateParameterList *X, const TemplateParameterList *Y) const {
7018 if (X->size() != Y->size())
7019 return false;
7020
7021 for (unsigned I = 0, N = X->size(); I != N; ++I)
7022 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
7023 return false;
7024
7025 return isSameConstraintExpr(X->getRequiresClause(), Y->getRequiresClause());
7026}
7027
7029 const NamedDecl *Y) const {
7030 // If the type parameter isn't the same already, we don't need to check the
7031 // default argument further.
7032 if (!isSameTemplateParameter(X, Y))
7033 return false;
7034
7035 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(X)) {
7036 auto *TTPY = cast<TemplateTypeParmDecl>(Y);
7037 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7038 return false;
7039
7040 return hasSameType(TTPX->getDefaultArgument().getArgument().getAsType(),
7041 TTPY->getDefaultArgument().getArgument().getAsType());
7042 }
7043
7044 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7045 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Y);
7046 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
7047 return false;
7048
7049 Expr *DefaultArgumentX =
7050 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7051 Expr *DefaultArgumentY =
7052 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7053 llvm::FoldingSetNodeID XID, YID;
7054 DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true);
7055 DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true);
7056 return XID == YID;
7057 }
7058
7059 auto *TTPX = cast<TemplateTemplateParmDecl>(X);
7060 auto *TTPY = cast<TemplateTemplateParmDecl>(Y);
7061
7062 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7063 return false;
7064
7065 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
7066 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
7067 return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate());
7068}
7069
7071 if (auto *NS = X->getAsNamespace())
7072 return NS;
7073 if (auto *NAS = X->getAsNamespaceAlias())
7074 return NAS->getNamespace();
7075 return nullptr;
7076}
7077
7079 const NestedNameSpecifier *Y) {
7080 if (auto *NSX = getNamespace(X)) {
7081 auto *NSY = getNamespace(Y);
7082 if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl())
7083 return false;
7084 } else if (X->getKind() != Y->getKind())
7085 return false;
7086
7087 // FIXME: For namespaces and types, we're permitted to check that the entity
7088 // is named via the same tokens. We should probably do so.
7089 switch (X->getKind()) {
7091 if (X->getAsIdentifier() != Y->getAsIdentifier())
7092 return false;
7093 break;
7096 // We've already checked that we named the same namespace.
7097 break;
7100 if (X->getAsType()->getCanonicalTypeInternal() !=
7102 return false;
7103 break;
7106 return true;
7107 }
7108
7109 // Recurse into earlier portion of NNS, if any.
7110 auto *PX = X->getPrefix();
7111 auto *PY = Y->getPrefix();
7112 if (PX && PY)
7113 return isSameQualifier(PX, PY);
7114 return !PX && !PY;
7115}
7116
7117/// Determine whether the attributes we can overload on are identical for A and
7118/// B. Will ignore any overloadable attrs represented in the type of A and B.
7120 const FunctionDecl *B) {
7121 // Note that pass_object_size attributes are represented in the function's
7122 // ExtParameterInfo, so we don't need to check them here.
7123
7124 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
7125 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
7126 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
7127
7128 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
7129 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
7130 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
7131
7132 // Return false if the number of enable_if attributes is different.
7133 if (!Cand1A || !Cand2A)
7134 return false;
7135
7136 Cand1ID.clear();
7137 Cand2ID.clear();
7138
7139 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
7140 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
7141
7142 // Return false if any of the enable_if expressions of A and B are
7143 // different.
7144 if (Cand1ID != Cand2ID)
7145 return false;
7146 }
7147 return true;
7148}
7149
7150bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
7151 // Caution: this function is called by the AST reader during deserialization,
7152 // so it cannot rely on AST invariants being met. Non-trivial accessors
7153 // should be avoided, along with any traversal of redeclaration chains.
7154
7155 if (X == Y)
7156 return true;
7157
7158 if (X->getDeclName() != Y->getDeclName())
7159 return false;
7160
7161 // Must be in the same context.
7162 //
7163 // Note that we can't use DeclContext::Equals here, because the DeclContexts
7164 // could be two different declarations of the same function. (We will fix the
7165 // semantic DC to refer to the primary definition after merging.)
7166 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
7167 cast<Decl>(Y->getDeclContext()->getRedeclContext())))
7168 return false;
7169
7170 // Two typedefs refer to the same entity if they have the same underlying
7171 // type.
7172 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
7173 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
7174 return hasSameType(TypedefX->getUnderlyingType(),
7175 TypedefY->getUnderlyingType());
7176
7177 // Must have the same kind.
7178 if (X->getKind() != Y->getKind())
7179 return false;
7180
7181 // Objective-C classes and protocols with the same name always match.
7182 if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
7183 return true;
7184
7185 if (isa<ClassTemplateSpecializationDecl>(X)) {
7186 // No need to handle these here: we merge them when adding them to the
7187 // template.
7188 return false;
7189 }
7190
7191 // Compatible tags match.
7192 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
7193 const auto *TagY = cast<TagDecl>(Y);
7194 return (TagX->getTagKind() == TagY->getTagKind()) ||
7195 ((TagX->getTagKind() == TagTypeKind::Struct ||
7196 TagX->getTagKind() == TagTypeKind::Class ||
7197 TagX->getTagKind() == TagTypeKind::Interface) &&
7198 (TagY->getTagKind() == TagTypeKind::Struct ||
7199 TagY->getTagKind() == TagTypeKind::Class ||
7200 TagY->getTagKind() == TagTypeKind::Interface));
7201 }
7202
7203 // Functions with the same type and linkage match.
7204 // FIXME: This needs to cope with merging of prototyped/non-prototyped
7205 // functions, etc.
7206 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
7207 const auto *FuncY = cast<FunctionDecl>(Y);
7208 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
7209 const auto *CtorY = cast<CXXConstructorDecl>(Y);
7210 if (CtorX->getInheritedConstructor() &&
7211 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
7212 CtorY->getInheritedConstructor().getConstructor()))
7213 return false;
7214 }
7215
7216 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
7217 return false;
7218
7219 // Multiversioned functions with different feature strings are represented
7220 // as separate declarations.
7221 if (FuncX->isMultiVersion()) {
7222 const auto *TAX = FuncX->getAttr<TargetAttr>();
7223 const auto *TAY = FuncY->getAttr<TargetAttr>();
7224 assert(TAX && TAY && "Multiversion Function without target attribute");
7225
7226 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
7227 return false;
7228 }
7229
7230 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
7231 // not the same entity if they are constrained.
7232 if ((FuncX->isMemberLikeConstrainedFriend() ||
7233 FuncY->isMemberLikeConstrainedFriend()) &&
7234 !FuncX->getLexicalDeclContext()->Equals(
7235 FuncY->getLexicalDeclContext())) {
7236 return false;
7237 }
7238
7239 if (!isSameConstraintExpr(FuncX->getTrailingRequiresClause(),
7240 FuncY->getTrailingRequiresClause()))
7241 return false;
7242
7243 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
7244 // Map to the first declaration that we've already merged into this one.
7245 // The TSI of redeclarations might not match (due to calling conventions
7246 // being inherited onto the type but not the TSI), but the TSI type of
7247 // the first declaration of the function should match across modules.
7248 FD = FD->getCanonicalDecl();
7249 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
7250 : FD->getType();
7251 };
7252 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
7253 if (!hasSameType(XT, YT)) {
7254 // We can get functions with different types on the redecl chain in C++17
7255 // if they have differing exception specifications and at least one of
7256 // the excpetion specs is unresolved.
7257 auto *XFPT = XT->getAs<FunctionProtoType>();
7258 auto *YFPT = YT->getAs<FunctionProtoType>();
7259 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
7260 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
7263 return true;
7264 return false;
7265 }
7266
7267 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
7268 hasSameOverloadableAttrs(FuncX, FuncY);
7269 }
7270
7271 // Variables with the same type and linkage match.
7272 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
7273 const auto *VarY = cast<VarDecl>(Y);
7274 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
7275 // During deserialization, we might compare variables before we load
7276 // their types. Assume the types will end up being the same.
7277 if (VarX->getType().isNull() || VarY->getType().isNull())
7278 return true;
7279
7280 if (hasSameType(VarX->getType(), VarY->getType()))
7281 return true;
7282
7283 // We can get decls with different types on the redecl chain. Eg.
7284 // template <typename T> struct S { static T Var[]; }; // #1
7285 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
7286 // Only? happens when completing an incomplete array type. In this case
7287 // when comparing #1 and #2 we should go through their element type.
7288 const ArrayType *VarXTy = getAsArrayType(VarX->getType());
7289 const ArrayType *VarYTy = getAsArrayType(VarY->getType());
7290 if (!VarXTy || !VarYTy)
7291 return false;
7292 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
7293 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
7294 }
7295 return false;
7296 }
7297
7298 // Namespaces with the same name and inlinedness match.
7299 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
7300 const auto *NamespaceY = cast<NamespaceDecl>(Y);
7301 return NamespaceX->isInline() == NamespaceY->isInline();
7302 }
7303
7304 // Identical template names and kinds match if their template parameter lists
7305 // and patterns match.
7306 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
7307 const auto *TemplateY = cast<TemplateDecl>(Y);
7308
7309 // ConceptDecl wouldn't be the same if their constraint expression differs.
7310 if (const auto *ConceptX = dyn_cast<ConceptDecl>(X)) {
7311 const auto *ConceptY = cast<ConceptDecl>(Y);
7312 if (!isSameConstraintExpr(ConceptX->getConstraintExpr(),
7313 ConceptY->getConstraintExpr()))
7314 return false;
7315 }
7316
7317 return isSameEntity(TemplateX->getTemplatedDecl(),
7318 TemplateY->getTemplatedDecl()) &&
7319 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
7320 TemplateY->getTemplateParameters());
7321 }
7322
7323 // Fields with the same name and the same type match.
7324 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
7325 const auto *FDY = cast<FieldDecl>(Y);
7326 // FIXME: Also check the bitwidth is odr-equivalent, if any.
7327 return hasSameType(FDX->getType(), FDY->getType());
7328 }
7329
7330 // Indirect fields with the same target field match.
7331 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
7332 const auto *IFDY = cast<IndirectFieldDecl>(Y);
7333 return IFDX->getAnonField()->getCanonicalDecl() ==
7334 IFDY->getAnonField()->getCanonicalDecl();
7335 }
7336
7337 // Enumerators with the same name match.
7338 if (isa<EnumConstantDecl>(X))
7339 // FIXME: Also check the value is odr-equivalent.
7340 return true;
7341
7342 // Using shadow declarations with the same target match.
7343 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
7344 const auto *USY = cast<UsingShadowDecl>(Y);
7345 return declaresSameEntity(USX->getTargetDecl(), USY->getTargetDecl());
7346 }
7347
7348 // Using declarations with the same qualifier match. (We already know that
7349 // the name matches.)
7350 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
7351 const auto *UY = cast<UsingDecl>(Y);
7352 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7353 UX->hasTypename() == UY->hasTypename() &&
7354 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7355 }
7356 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
7357 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
7358 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7359 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7360 }
7361 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
7362 return isSameQualifier(
7363 UX->getQualifier(),
7364 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
7365 }
7366
7367 // Using-pack declarations are only created by instantiation, and match if
7368 // they're instantiated from matching UnresolvedUsing...Decls.
7369 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
7370 return declaresSameEntity(
7371 UX->getInstantiatedFromUsingDecl(),
7372 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
7373 }
7374
7375 // Namespace alias definitions with the same target match.
7376 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
7377 const auto *NAY = cast<NamespaceAliasDecl>(Y);
7378 return NAX->getNamespace()->Equals(NAY->getNamespace());
7379 }
7380
7381 return false;
7382}
7383
7386 switch (Arg.getKind()) {
7388 return Arg;
7389
7391 return Arg;
7392
7394 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
7396 Arg.getIsDefaulted());
7397 }
7398
7401 /*isNullPtr*/ true, Arg.getIsDefaulted());
7402
7405 Arg.getIsDefaulted());
7406
7408 return TemplateArgument(
7411
7414
7416 return TemplateArgument(*this,
7419
7422 /*isNullPtr*/ false, Arg.getIsDefaulted());
7423
7425 bool AnyNonCanonArgs = false;
7426 auto CanonArgs = ::getCanonicalTemplateArguments(
7427 *this, Arg.pack_elements(), AnyNonCanonArgs);
7428 if (!AnyNonCanonArgs)
7429 return Arg;
7431 const_cast<ASTContext &>(*this), CanonArgs);
7432 NewArg.setIsDefaulted(Arg.getIsDefaulted());
7433 return NewArg;
7434 }
7435 }
7436
7437 // Silence GCC warning
7438 llvm_unreachable("Unhandled template argument kind");
7439}
7440
7443 if (!NNS)
7444 return nullptr;
7445
7446 switch (NNS->getKind()) {
7448 // Canonicalize the prefix but keep the identifier the same.
7449 return NestedNameSpecifier::Create(*this,
7451 NNS->getAsIdentifier());
7452
7454 // A namespace is canonical; build a nested-name-specifier with
7455 // this namespace and no prefix.
7456 return NestedNameSpecifier::Create(*this, nullptr,
7457 NNS->getAsNamespace()->getFirstDecl());
7458
7460 // A namespace is canonical; build a nested-name-specifier with
7461 // this namespace and no prefix.
7463 *this, nullptr,
7465
7466 // The difference between TypeSpec and TypeSpecWithTemplate is that the
7467 // latter will have the 'template' keyword when printed.
7470 const Type *T = getCanonicalType(NNS->getAsType());
7471
7472 // If we have some kind of dependent-named type (e.g., "typename T::type"),
7473 // break it apart into its prefix and identifier, then reconsititute those
7474 // as the canonical nested-name-specifier. This is required to canonicalize
7475 // a dependent nested-name-specifier involving typedefs of dependent-name
7476 // types, e.g.,
7477 // typedef typename T::type T1;
7478 // typedef typename T1::type T2;
7479 if (const auto *DNT = T->getAs<DependentNameType>())
7480 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
7481 DNT->getIdentifier());
7482 if (const auto *DTST = T->getAs<DependentTemplateSpecializationType>())
7483 return NestedNameSpecifier::Create(*this, DTST->getQualifier(), true, T);
7484
7485 // TODO: Set 'Template' parameter to true for other template types.
7486 return NestedNameSpecifier::Create(*this, nullptr, false, T);
7487 }
7488
7491 // The global specifier and __super specifer are canonical and unique.
7492 return NNS;
7493 }
7494
7495 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
7496}
7497
7499 // Handle the non-qualified case efficiently.
7500 if (!T.hasLocalQualifiers()) {
7501 // Handle the common positive case fast.
7502 if (const auto *AT = dyn_cast<ArrayType>(T))
7503 return AT;
7504 }
7505
7506 // Handle the common negative case fast.
7507 if (!isa<ArrayType>(T.getCanonicalType()))
7508 return nullptr;
7509
7510 // Apply any qualifiers from the array type to the element type. This
7511 // implements C99 6.7.3p8: "If the specification of an array type includes
7512 // any type qualifiers, the element type is so qualified, not the array type."
7513
7514 // If we get here, we either have type qualifiers on the type, or we have
7515 // sugar such as a typedef in the way. If we have type qualifiers on the type
7516 // we must propagate them down into the element type.
7517
7518 SplitQualType split = T.getSplitDesugaredType();
7519 Qualifiers qs = split.Quals;
7520
7521 // If we have a simple case, just return now.
7522 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
7523 if (!ATy || qs.empty())
7524 return ATy;
7525
7526 // Otherwise, we have an array and we have qualifiers on it. Push the
7527 // qualifiers into the array element type and return a new array type.
7528 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
7529
7530 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
7531 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
7532 CAT->getSizeExpr(),
7533 CAT->getSizeModifier(),
7534 CAT->getIndexTypeCVRQualifiers()));
7535 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
7536 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
7537 IAT->getSizeModifier(),
7538 IAT->getIndexTypeCVRQualifiers()));
7539
7540 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
7541 return cast<ArrayType>(
7543 DSAT->getSizeExpr(),
7544 DSAT->getSizeModifier(),
7545 DSAT->getIndexTypeCVRQualifiers(),
7546 DSAT->getBracketsRange()));
7547
7548 const auto *VAT = cast<VariableArrayType>(ATy);
7549 return cast<ArrayType>(getVariableArrayType(NewEltTy,
7550 VAT->getSizeExpr(),
7551 VAT->getSizeModifier(),
7552 VAT->getIndexTypeCVRQualifiers(),
7553 VAT->getBracketsRange()));
7554}
7555
7558 return getArrayParameterType(T);
7559 if (T->isArrayType() || T->isFunctionType())
7560 return getDecayedType(T);
7561 return T;
7562}
7563
7567 return T.getUnqualifiedType();
7568}
7569
7571 // C++ [except.throw]p3:
7572 // A throw-expression initializes a temporary object, called the exception
7573 // object, the type of which is determined by removing any top-level
7574 // cv-qualifiers from the static type of the operand of throw and adjusting
7575 // the type from "array of T" or "function returning T" to "pointer to T"
7576 // or "pointer to function returning T", [...]
7578 if (T->isArrayType() || T->isFunctionType())
7579 T = getDecayedType(T);
7580 return T.getUnqualifiedType();
7581}
7582
7583/// getArrayDecayedType - Return the properly qualified result of decaying the
7584/// specified array type to a pointer. This operation is non-trivial when
7585/// handling typedefs etc. The canonical type of "T" must be an array type,
7586/// this returns a pointer to a properly qualified element of the array.
7587///
7588/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
7590 // Get the element type with 'getAsArrayType' so that we don't lose any
7591 // typedefs in the element type of the array. This also handles propagation
7592 // of type qualifiers from the array type into the element type if present
7593 // (C99 6.7.3p8).
7594 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
7595 assert(PrettyArrayType && "Not an array type!");
7596
7597 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
7598
7599 // int x[restrict 4] -> int *restrict
7601 PrettyArrayType->getIndexTypeQualifiers());
7602
7603 // int x[_Nullable] -> int * _Nullable
7604 if (auto Nullability = Ty->getNullability()) {
7605 Result = const_cast<ASTContext *>(this)->getAttributedType(*Nullability,
7606 Result, Result);
7607 }
7608 return Result;
7609}
7610
7612 return getBaseElementType(array->getElementType());
7613}
7614
7616 Qualifiers qs;
7617 while (true) {
7618 SplitQualType split = type.getSplitDesugaredType();
7619 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
7620 if (!array) break;
7621
7622 type = array->getElementType();
7624 }
7625
7626 return getQualifiedType(type, qs);
7627}
7628
7629/// getConstantArrayElementCount - Returns number of constant array elements.
7630uint64_t
7632 uint64_t ElementCount = 1;
7633 do {
7634 ElementCount *= CA->getZExtSize();
7635 CA = dyn_cast_or_null<ConstantArrayType>(
7637 } while (CA);
7638 return ElementCount;
7639}
7640
7642 const ArrayInitLoopExpr *AILE) const {
7643 if (!AILE)
7644 return 0;
7645
7646 uint64_t ElementCount = 1;
7647
7648 do {
7649 ElementCount *= AILE->getArraySize().getZExtValue();
7650 AILE = dyn_cast<ArrayInitLoopExpr>(AILE->getSubExpr());
7651 } while (AILE);
7652
7653 return ElementCount;
7654}
7655
7656/// getFloatingRank - Return a relative rank for floating point types.
7657/// This routine will assert if passed a built-in type that isn't a float.
7659 if (const auto *CT = T->getAs<ComplexType>())
7660 return getFloatingRank(CT->getElementType());
7661
7662 switch (T->castAs<BuiltinType>()->getKind()) {
7663 default: llvm_unreachable("getFloatingRank(): not a floating type");
7664 case BuiltinType::Float16: return Float16Rank;
7665 case BuiltinType::Half: return HalfRank;
7666 case BuiltinType::Float: return FloatRank;
7667 case BuiltinType::Double: return DoubleRank;
7668 case BuiltinType::LongDouble: return LongDoubleRank;
7669 case BuiltinType::Float128: return Float128Rank;
7670 case BuiltinType::BFloat16: return BFloat16Rank;
7671 case BuiltinType::Ibm128: return Ibm128Rank;
7672 }
7673}
7674
7675/// getFloatingTypeOrder - Compare the rank of the two specified floating
7676/// point types, ignoring the domain of the type (i.e. 'double' ==
7677/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
7678/// LHS < RHS, return -1.
7680 FloatingRank LHSR = getFloatingRank(LHS);
7681 FloatingRank RHSR = getFloatingRank(RHS);
7682
7683 if (LHSR == RHSR)
7684 return 0;
7685 if (LHSR > RHSR)
7686 return 1;
7687 return -1;
7688}
7689
7692 return 0;
7693 return getFloatingTypeOrder(LHS, RHS);
7694}
7695
7696/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
7697/// routine will assert if passed a built-in type that isn't an integer or enum,
7698/// or if it is not canonicalized.
7699unsigned ASTContext::getIntegerRank(const Type *T) const {
7700 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
7701
7702 // Results in this 'losing' to any type of the same size, but winning if
7703 // larger.
7704 if (const auto *EIT = dyn_cast<BitIntType>(T))
7705 return 0 + (EIT->getNumBits() << 3);
7706
7707 switch (cast<BuiltinType>(T)->getKind()) {
7708 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
7709 case BuiltinType::Bool:
7710 return 1 + (getIntWidth(BoolTy) << 3);
7711 case BuiltinType::Char_S:
7712 case BuiltinType::Char_U:
7713 case BuiltinType::SChar:
7714 case BuiltinType::UChar:
7715 return 2 + (getIntWidth(CharTy) << 3);
7716 case BuiltinType::Short:
7717 case BuiltinType::UShort:
7718 return 3 + (getIntWidth(ShortTy) << 3);
7719 case BuiltinType::Int:
7720 case BuiltinType::UInt:
7721 return 4 + (getIntWidth(IntTy) << 3);
7722 case BuiltinType::Long:
7723 case BuiltinType::ULong:
7724 return 5 + (getIntWidth(LongTy) << 3);
7725 case BuiltinType::LongLong:
7726 case BuiltinType::ULongLong:
7727 return 6 + (getIntWidth(LongLongTy) << 3);
7728 case BuiltinType::Int128:
7729 case BuiltinType::UInt128:
7730 return 7 + (getIntWidth(Int128Ty) << 3);
7731
7732 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
7733 // their underlying types" [c++20 conv.rank]
7734 case BuiltinType::Char8:
7735 return getIntegerRank(UnsignedCharTy.getTypePtr());
7736 case BuiltinType::Char16:
7737 return getIntegerRank(
7738 getFromTargetType(Target->getChar16Type()).getTypePtr());
7739 case BuiltinType::Char32:
7740 return getIntegerRank(
7741 getFromTargetType(Target->getChar32Type()).getTypePtr());
7742 case BuiltinType::WChar_S:
7743 case BuiltinType::WChar_U:
7744 return getIntegerRank(
7745 getFromTargetType(Target->getWCharType()).getTypePtr());
7746 }
7747}
7748
7749/// Whether this is a promotable bitfield reference according
7750/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
7751///
7752/// \returns the type this bit-field will promote to, or NULL if no
7753/// promotion occurs.
7755 if (E->isTypeDependent() || E->isValueDependent())
7756 return {};
7757
7758 // C++ [conv.prom]p5:
7759 // If the bit-field has an enumerated type, it is treated as any other
7760 // value of that type for promotion purposes.
7762 return {};
7763
7764 // FIXME: We should not do this unless E->refersToBitField() is true. This
7765 // matters in C where getSourceBitField() will find bit-fields for various
7766 // cases where the source expression is not a bit-field designator.
7767
7768 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
7769 if (!Field)
7770 return {};
7771
7772 QualType FT = Field->getType();
7773
7774 uint64_t BitWidth = Field->getBitWidthValue();
7775 uint64_t IntSize = getTypeSize(IntTy);
7776 // C++ [conv.prom]p5:
7777 // A prvalue for an integral bit-field can be converted to a prvalue of type
7778 // int if int can represent all the values of the bit-field; otherwise, it
7779 // can be converted to unsigned int if unsigned int can represent all the
7780 // values of the bit-field. If the bit-field is larger yet, no integral
7781 // promotion applies to it.
7782 // C11 6.3.1.1/2:
7783 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
7784 // If an int can represent all values of the original type (as restricted by
7785 // the width, for a bit-field), the value is converted to an int; otherwise,
7786 // it is converted to an unsigned int.
7787 //
7788 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
7789 // We perform that promotion here to match GCC and C++.
7790 // FIXME: C does not permit promotion of an enum bit-field whose rank is
7791 // greater than that of 'int'. We perform that promotion to match GCC.
7792 //
7793 // C23 6.3.1.1p2:
7794 // The value from a bit-field of a bit-precise integer type is converted to
7795 // the corresponding bit-precise integer type. (The rest is the same as in
7796 // C11.)
7797 if (QualType QT = Field->getType(); QT->isBitIntType())
7798 return QT;
7799
7800 if (BitWidth < IntSize)
7801 return IntTy;
7802
7803 if (BitWidth == IntSize)
7804 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
7805
7806 // Bit-fields wider than int are not subject to promotions, and therefore act
7807 // like the base type. GCC has some weird bugs in this area that we
7808 // deliberately do not follow (GCC follows a pre-standard resolution to
7809 // C's DR315 which treats bit-width as being part of the type, and this leaks
7810 // into their semantics in some cases).
7811 return {};
7812}
7813
7814/// getPromotedIntegerType - Returns the type that Promotable will
7815/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
7816/// integer type.
7818 assert(!Promotable.isNull());
7819 assert(isPromotableIntegerType(Promotable));
7820 if (const auto *ET = Promotable->getAs<EnumType>())
7821 return ET->getDecl()->getPromotionType();
7822
7823 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
7824 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
7825 // (3.9.1) can be converted to a prvalue of the first of the following
7826 // types that can represent all the values of its underlying type:
7827 // int, unsigned int, long int, unsigned long int, long long int, or
7828 // unsigned long long int [...]
7829 // FIXME: Is there some better way to compute this?
7830 if (BT->getKind() == BuiltinType::WChar_S ||
7831 BT->getKind() == BuiltinType::WChar_U ||
7832 BT->getKind() == BuiltinType::Char8 ||
7833 BT->getKind() == BuiltinType::Char16 ||
7834 BT->getKind() == BuiltinType::Char32) {
7835 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
7836 uint64_t FromSize = getTypeSize(BT);
7837 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
7839 for (const auto &PT : PromoteTypes) {
7840 uint64_t ToSize = getTypeSize(PT);
7841 if (FromSize < ToSize ||
7842 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
7843 return PT;
7844 }
7845 llvm_unreachable("char type should fit into long long");
7846 }
7847 }
7848
7849 // At this point, we should have a signed or unsigned integer type.
7850 if (Promotable->isSignedIntegerType())
7851 return IntTy;
7852 uint64_t PromotableSize = getIntWidth(Promotable);
7853 uint64_t IntSize = getIntWidth(IntTy);
7854 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
7855 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
7856}
7857
7858/// Recurses in pointer/array types until it finds an objc retainable
7859/// type and returns its ownership.
7861 while (!T.isNull()) {
7862 if (T.getObjCLifetime() != Qualifiers::OCL_None)
7863 return T.getObjCLifetime();
7864 if (T->isArrayType())
7866 else if (const auto *PT = T->getAs<PointerType>())
7867 T = PT->getPointeeType();
7868 else if (const auto *RT = T->getAs<ReferenceType>())
7869 T = RT->getPointeeType();
7870 else
7871 break;
7872 }
7873
7874 return Qualifiers::OCL_None;
7875}
7876
7877static const Type *getIntegerTypeForEnum(const EnumType *ET) {
7878 // Incomplete enum types are not treated as integer types.
7879 // FIXME: In C++, enum types are never integer types.
7880 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
7881 return ET->getDecl()->getIntegerType().getTypePtr();
7882 return nullptr;
7883}
7884
7885/// getIntegerTypeOrder - Returns the highest ranked integer type:
7886/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
7887/// LHS < RHS, return -1.
7889 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
7890 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
7891
7892 // Unwrap enums to their underlying type.
7893 if (const auto *ET = dyn_cast<EnumType>(LHSC))
7894 LHSC = getIntegerTypeForEnum(ET);
7895 if (const auto *ET = dyn_cast<EnumType>(RHSC))
7896 RHSC = getIntegerTypeForEnum(ET);
7897
7898 if (LHSC == RHSC) return 0;
7899
7900 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
7901 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
7902
7903 unsigned LHSRank = getIntegerRank(LHSC);
7904 unsigned RHSRank = getIntegerRank(RHSC);
7905
7906 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
7907 if (LHSRank == RHSRank) return 0;
7908 return LHSRank > RHSRank ? 1 : -1;
7909 }
7910
7911 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
7912 if (LHSUnsigned) {
7913 // If the unsigned [LHS] type is larger, return it.
7914 if (LHSRank >= RHSRank)
7915 return 1;
7916
7917 // If the signed type can represent all values of the unsigned type, it
7918 // wins. Because we are dealing with 2's complement and types that are
7919 // powers of two larger than each other, this is always safe.
7920 return -1;
7921 }
7922
7923 // If the unsigned [RHS] type is larger, return it.
7924 if (RHSRank >= LHSRank)
7925 return -1;
7926
7927 // If the signed type can represent all values of the unsigned type, it
7928 // wins. Because we are dealing with 2's complement and types that are
7929 // powers of two larger than each other, this is always safe.
7930 return 1;
7931}
7932
7934 if (CFConstantStringTypeDecl)
7935 return CFConstantStringTypeDecl;
7936
7937 assert(!CFConstantStringTagDecl &&
7938 "tag and typedef should be initialized together");
7939 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
7940 CFConstantStringTagDecl->startDefinition();
7941
7942 struct {
7943 QualType Type;
7944 const char *Name;
7945 } Fields[5];
7946 unsigned Count = 0;
7947
7948 /// Objective-C ABI
7949 ///
7950 /// typedef struct __NSConstantString_tag {
7951 /// const int *isa;
7952 /// int flags;
7953 /// const char *str;
7954 /// long length;
7955 /// } __NSConstantString;
7956 ///
7957 /// Swift ABI (4.1, 4.2)
7958 ///
7959 /// typedef struct __NSConstantString_tag {
7960 /// uintptr_t _cfisa;
7961 /// uintptr_t _swift_rc;
7962 /// _Atomic(uint64_t) _cfinfoa;
7963 /// const char *_ptr;
7964 /// uint32_t _length;
7965 /// } __NSConstantString;
7966 ///
7967 /// Swift ABI (5.0)
7968 ///
7969 /// typedef struct __NSConstantString_tag {
7970 /// uintptr_t _cfisa;
7971 /// uintptr_t _swift_rc;
7972 /// _Atomic(uint64_t) _cfinfoa;
7973 /// const char *_ptr;
7974 /// uintptr_t _length;
7975 /// } __NSConstantString;
7976
7977 const auto CFRuntime = getLangOpts().CFRuntime;
7978 if (static_cast<unsigned>(CFRuntime) <
7979 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
7980 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
7981 Fields[Count++] = { IntTy, "flags" };
7982 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
7983 Fields[Count++] = { LongTy, "length" };
7984 } else {
7985 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
7986 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
7987 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
7988 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
7991 Fields[Count++] = { IntTy, "_ptr" };
7992 else
7993 Fields[Count++] = { getUIntPtrType(), "_ptr" };
7994 }
7995
7996 // Create fields
7997 for (unsigned i = 0; i < Count; ++i) {
7998 FieldDecl *Field =
7999 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
8000 SourceLocation(), &Idents.get(Fields[i].Name),
8001 Fields[i].Type, /*TInfo=*/nullptr,
8002 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8003 Field->setAccess(AS_public);
8004 CFConstantStringTagDecl->addDecl(Field);
8005 }
8006
8007 CFConstantStringTagDecl->completeDefinition();
8008 // This type is designed to be compatible with NSConstantString, but cannot
8009 // use the same name, since NSConstantString is an interface.
8010 auto tagType = getTagDeclType(CFConstantStringTagDecl);
8011 CFConstantStringTypeDecl =
8012 buildImplicitTypedef(tagType, "__NSConstantString");
8013
8014 return CFConstantStringTypeDecl;
8015}
8016
8018 if (!CFConstantStringTagDecl)
8019 getCFConstantStringDecl(); // Build the tag and the typedef.
8020 return CFConstantStringTagDecl;
8021}
8022
8023// getCFConstantStringType - Return the type used for constant CFStrings.
8026}
8027
8029 if (ObjCSuperType.isNull()) {
8030 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
8031 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
8032 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
8033 }
8034 return ObjCSuperType;
8035}
8036
8038 const auto *TD = T->castAs<TypedefType>();
8039 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
8040 const auto *TagType =
8041 CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>();
8042 CFConstantStringTagDecl = TagType->getDecl();
8043}
8044
8046 if (BlockDescriptorType)
8047 return getTagDeclType(BlockDescriptorType);
8048
8049 RecordDecl *RD;
8050 // FIXME: Needs the FlagAppleBlock bit.
8051 RD = buildImplicitRecord("__block_descriptor");
8052 RD->startDefinition();
8053
8054 QualType FieldTypes[] = {
8057 };
8058
8059 static const char *const FieldNames[] = {
8060 "reserved",
8061 "Size"
8062 };
8063
8064 for (size_t i = 0; i < 2; ++i) {
8066 *this, RD, SourceLocation(), SourceLocation(),
8067 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8068 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8069 Field->setAccess(AS_public);
8070 RD->addDecl(Field);
8071 }
8072
8073 RD->completeDefinition();
8074
8075 BlockDescriptorType = RD;
8076
8077 return getTagDeclType(BlockDescriptorType);
8078}
8079
8081 if (BlockDescriptorExtendedType)
8082 return getTagDeclType(BlockDescriptorExtendedType);
8083
8084 RecordDecl *RD;
8085 // FIXME: Needs the FlagAppleBlock bit.
8086 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
8087 RD->startDefinition();
8088
8089 QualType FieldTypes[] = {
8094 };
8095
8096 static const char *const FieldNames[] = {
8097 "reserved",
8098 "Size",
8099 "CopyFuncPtr",
8100 "DestroyFuncPtr"
8101 };
8102
8103 for (size_t i = 0; i < 4; ++i) {
8105 *this, RD, SourceLocation(), SourceLocation(),
8106 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8107 /*BitWidth=*/nullptr,
8108 /*Mutable=*/false, ICIS_NoInit);
8109 Field->setAccess(AS_public);
8110 RD->addDecl(Field);
8111 }
8112
8113 RD->completeDefinition();
8114
8115 BlockDescriptorExtendedType = RD;
8116 return getTagDeclType(BlockDescriptorExtendedType);
8117}
8118
8120 const auto *BT = dyn_cast<BuiltinType>(T);
8121
8122 if (!BT) {
8123 if (isa<PipeType>(T))
8124 return OCLTK_Pipe;
8125
8126 return OCLTK_Default;
8127 }
8128
8129 switch (BT->getKind()) {
8130#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8131 case BuiltinType::Id: \
8132 return OCLTK_Image;
8133#include "clang/Basic/OpenCLImageTypes.def"
8134
8135 case BuiltinType::OCLClkEvent:
8136 return OCLTK_ClkEvent;
8137
8138 case BuiltinType::OCLEvent:
8139 return OCLTK_Event;
8140
8141 case BuiltinType::OCLQueue:
8142 return OCLTK_Queue;
8143
8144 case BuiltinType::OCLReserveID:
8145 return OCLTK_ReserveID;
8146
8147 case BuiltinType::OCLSampler:
8148 return OCLTK_Sampler;
8149
8150 default:
8151 return OCLTK_Default;
8152 }
8153}
8154
8156 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
8157}
8158
8159/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
8160/// requires copy/dispose. Note that this must match the logic
8161/// in buildByrefHelpers.
8163 const VarDecl *D) {
8164 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
8165 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
8166 if (!copyExpr && record->hasTrivialDestructor()) return false;
8167
8168 return true;
8169 }
8170
8171 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
8172 // move or destroy.
8174 return true;
8175
8176 if (!Ty->isObjCRetainableType()) return false;
8177
8178 Qualifiers qs = Ty.getQualifiers();
8179
8180 // If we have lifetime, that dominates.
8181 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
8182 switch (lifetime) {
8183 case Qualifiers::OCL_None: llvm_unreachable("impossible");
8184
8185 // These are just bits as far as the runtime is concerned.
8188 return false;
8189
8190 // These cases should have been taken care of when checking the type's
8191 // non-triviality.
8194 llvm_unreachable("impossible");
8195 }
8196 llvm_unreachable("fell out of lifetime switch!");
8197 }
8198 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
8200}
8201
8203 Qualifiers::ObjCLifetime &LifeTime,
8204 bool &HasByrefExtendedLayout) const {
8205 if (!getLangOpts().ObjC ||
8206 getLangOpts().getGC() != LangOptions::NonGC)
8207 return false;
8208
8209 HasByrefExtendedLayout = false;
8210 if (Ty->isRecordType()) {
8211 HasByrefExtendedLayout = true;
8212 LifeTime = Qualifiers::OCL_None;
8213 } else if ((LifeTime = Ty.getObjCLifetime())) {
8214 // Honor the ARC qualifiers.
8215 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
8216 // The MRR rule.
8218 } else {
8219 LifeTime = Qualifiers::OCL_None;
8220 }
8221 return true;
8222}
8223
8225 assert(Target && "Expected target to be initialized");
8226 const llvm::Triple &T = Target->getTriple();
8227 // Windows is LLP64 rather than LP64
8228 if (T.isOSWindows() && T.isArch64Bit())
8229 return UnsignedLongLongTy;
8230 return UnsignedLongTy;
8231}
8232
8234 assert(Target && "Expected target to be initialized");
8235 const llvm::Triple &T = Target->getTriple();
8236 // Windows is LLP64 rather than LP64
8237 if (T.isOSWindows() && T.isArch64Bit())
8238 return LongLongTy;
8239 return LongTy;
8240}
8241
8243 if (!ObjCInstanceTypeDecl)
8244 ObjCInstanceTypeDecl =
8245 buildImplicitTypedef(getObjCIdType(), "instancetype");
8246 return ObjCInstanceTypeDecl;
8247}
8248
8249// This returns true if a type has been typedefed to BOOL:
8250// typedef <type> BOOL;
8252 if (const auto *TT = dyn_cast<TypedefType>(T))
8253 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
8254 return II->isStr("BOOL");
8255
8256 return false;
8257}
8258
8259/// getObjCEncodingTypeSize returns size of type for objective-c encoding
8260/// purpose.
8262 if (!type->isIncompleteArrayType() && type->isIncompleteType())
8263 return CharUnits::Zero();
8264
8266
8267 // Make all integer and enum types at least as large as an int
8268 if (sz.isPositive() && type->isIntegralOrEnumerationType())
8269 sz = std::max(sz, getTypeSizeInChars(IntTy));
8270 // Treat arrays as pointers, since that's how they're passed in.
8271 else if (type->isArrayType())
8273 return sz;
8274}
8275
8277 return getTargetInfo().getCXXABI().isMicrosoft() &&
8278 VD->isStaticDataMember() &&
8280 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
8281}
8282
8285 if (!VD->isInline())
8287
8288 // In almost all cases, it's a weak definition.
8289 auto *First = VD->getFirstDecl();
8290 if (First->isInlineSpecified() || !First->isStaticDataMember())
8292
8293 // If there's a file-context declaration in this translation unit, it's a
8294 // non-discardable definition.
8295 for (auto *D : VD->redecls())
8297 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
8299
8300 // If we've not seen one yet, we don't know.
8302}
8303
8304static std::string charUnitsToString(const CharUnits &CU) {
8305 return llvm::itostr(CU.getQuantity());
8306}
8307
8308/// getObjCEncodingForBlock - Return the encoded type for this block
8309/// declaration.
8311 std::string S;
8312
8313 const BlockDecl *Decl = Expr->getBlockDecl();
8314 QualType BlockTy =
8316 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
8317 // Encode result type.
8318 if (getLangOpts().EncodeExtendedBlockSig)
8320 true /*Extended*/);
8321 else
8322 getObjCEncodingForType(BlockReturnTy, S);
8323 // Compute size of all parameters.
8324 // Start with computing size of a pointer in number of bytes.
8325 // FIXME: There might(should) be a better way of doing this computation!
8327 CharUnits ParmOffset = PtrSize;
8328 for (auto *PI : Decl->parameters()) {
8329 QualType PType = PI->getType();
8331 if (sz.isZero())
8332 continue;
8333 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
8334 ParmOffset += sz;
8335 }
8336 // Size of the argument frame
8337 S += charUnitsToString(ParmOffset);
8338 // Block pointer and offset.
8339 S += "@?0";
8340
8341 // Argument types.
8342 ParmOffset = PtrSize;
8343 for (auto *PVDecl : Decl->parameters()) {
8344 QualType PType = PVDecl->getOriginalType();
8345 if (const auto *AT =
8346 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8347 // Use array's original type only if it has known number of
8348 // elements.
8349 if (!isa<ConstantArrayType>(AT))
8350 PType = PVDecl->getType();
8351 } else if (PType->isFunctionType())
8352 PType = PVDecl->getType();
8353 if (getLangOpts().EncodeExtendedBlockSig)
8355 S, true /*Extended*/);
8356 else
8357 getObjCEncodingForType(PType, S);
8358 S += charUnitsToString(ParmOffset);
8359 ParmOffset += getObjCEncodingTypeSize(PType);
8360 }
8361
8362 return S;
8363}
8364
8365std::string
8367 std::string S;
8368 // Encode result type.
8369 getObjCEncodingForType(Decl->getReturnType(), S);
8370 CharUnits ParmOffset;
8371 // Compute size of all parameters.
8372 for (auto *PI : Decl->parameters()) {
8373 QualType PType = PI->getType();
8375 if (sz.isZero())
8376 continue;
8377
8378 assert(sz.isPositive() &&
8379 "getObjCEncodingForFunctionDecl - Incomplete param type");
8380 ParmOffset += sz;
8381 }
8382 S += charUnitsToString(ParmOffset);
8383 ParmOffset = CharUnits::Zero();
8384
8385 // Argument types.
8386 for (auto *PVDecl : Decl->parameters()) {
8387 QualType PType = PVDecl->getOriginalType();
8388 if (const auto *AT =
8389 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8390 // Use array's original type only if it has known number of
8391 // elements.
8392 if (!isa<ConstantArrayType>(AT))
8393 PType = PVDecl->getType();
8394 } else if (PType->isFunctionType())
8395 PType = PVDecl->getType();
8396 getObjCEncodingForType(PType, S);
8397 S += charUnitsToString(ParmOffset);
8398 ParmOffset += getObjCEncodingTypeSize(PType);
8399 }
8400
8401 return S;
8402}
8403
8404/// getObjCEncodingForMethodParameter - Return the encoded type for a single
8405/// method parameter or return type. If Extended, include class names and
8406/// block object types.
8408 QualType T, std::string& S,
8409 bool Extended) const {
8410 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
8412 // Encode parameter type.
8413 ObjCEncOptions Options = ObjCEncOptions()
8414 .setExpandPointedToStructures()
8415 .setExpandStructures()
8416 .setIsOutermostType();
8417 if (Extended)
8418 Options.setEncodeBlockParameters().setEncodeClassNames();
8419 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
8420}
8421
8422/// getObjCEncodingForMethodDecl - Return the encoded type for this method
8423/// declaration.
8425 bool Extended) const {
8426 // FIXME: This is not very efficient.
8427 // Encode return type.
8428 std::string S;
8429 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
8430 Decl->getReturnType(), S, Extended);
8431 // Compute size of all parameters.
8432 // Start with computing size of a pointer in number of bytes.
8433 // FIXME: There might(should) be a better way of doing this computation!
8435 // The first two arguments (self and _cmd) are pointers; account for
8436 // their size.
8437 CharUnits ParmOffset = 2 * PtrSize;
8438 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8439 E = Decl->sel_param_end(); PI != E; ++PI) {
8440 QualType PType = (*PI)->getType();
8442 if (sz.isZero())
8443 continue;
8444
8445 assert(sz.isPositive() &&
8446 "getObjCEncodingForMethodDecl - Incomplete param type");
8447 ParmOffset += sz;
8448 }
8449 S += charUnitsToString(ParmOffset);
8450 S += "@0:";
8451 S += charUnitsToString(PtrSize);
8452
8453 // Argument types.
8454 ParmOffset = 2 * PtrSize;
8455 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8456 E = Decl->sel_param_end(); PI != E; ++PI) {
8457 const ParmVarDecl *PVDecl = *PI;
8458 QualType PType = PVDecl->getOriginalType();
8459 if (const auto *AT =
8460 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8461 // Use array's original type only if it has known number of
8462 // elements.
8463 if (!isa<ConstantArrayType>(AT))
8464 PType = PVDecl->getType();
8465 } else if (PType->isFunctionType())
8466 PType = PVDecl->getType();
8468 PType, S, Extended);
8469 S += charUnitsToString(ParmOffset);
8470 ParmOffset += getObjCEncodingTypeSize(PType);
8471 }
8472
8473 return S;
8474}
8475
8478 const ObjCPropertyDecl *PD,
8479 const Decl *Container) const {
8480 if (!Container)
8481 return nullptr;
8482 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
8483 for (auto *PID : CID->property_impls())
8484 if (PID->getPropertyDecl() == PD)
8485 return PID;
8486 } else {
8487 const auto *OID = cast<ObjCImplementationDecl>(Container);
8488 for (auto *PID : OID->property_impls())
8489 if (PID->getPropertyDecl() == PD)
8490 return PID;
8491 }
8492 return nullptr;
8493}
8494
8495/// getObjCEncodingForPropertyDecl - Return the encoded type for this
8496/// property declaration. If non-NULL, Container must be either an
8497/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
8498/// NULL when getting encodings for protocol properties.
8499/// Property attributes are stored as a comma-delimited C string. The simple
8500/// attributes readonly and bycopy are encoded as single characters. The
8501/// parametrized attributes, getter=name, setter=name, and ivar=name, are
8502/// encoded as single characters, followed by an identifier. Property types
8503/// are also encoded as a parametrized attribute. The characters used to encode
8504/// these attributes are defined by the following enumeration:
8505/// @code
8506/// enum PropertyAttributes {
8507/// kPropertyReadOnly = 'R', // property is read-only.
8508/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
8509/// kPropertyByref = '&', // property is a reference to the value last assigned
8510/// kPropertyDynamic = 'D', // property is dynamic
8511/// kPropertyGetter = 'G', // followed by getter selector name
8512/// kPropertySetter = 'S', // followed by setter selector name
8513/// kPropertyInstanceVariable = 'V' // followed by instance variable name
8514/// kPropertyType = 'T' // followed by old-style type encoding.
8515/// kPropertyWeak = 'W' // 'weak' property
8516/// kPropertyStrong = 'P' // property GC'able
8517/// kPropertyNonAtomic = 'N' // property non-atomic
8518/// kPropertyOptional = '?' // property optional
8519/// };
8520/// @endcode
8521std::string
8523 const Decl *Container) const {
8524 // Collect information from the property implementation decl(s).
8525 bool Dynamic = false;
8526 ObjCPropertyImplDecl *SynthesizePID = nullptr;
8527
8528 if (ObjCPropertyImplDecl *PropertyImpDecl =
8530 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
8531 Dynamic = true;
8532 else
8533 SynthesizePID = PropertyImpDecl;
8534 }
8535
8536 // FIXME: This is not very efficient.
8537 std::string S = "T";
8538
8539 // Encode result type.
8540 // GCC has some special rules regarding encoding of properties which
8541 // closely resembles encoding of ivars.
8543
8544 if (PD->isOptional())
8545 S += ",?";
8546
8547 if (PD->isReadOnly()) {
8548 S += ",R";
8550 S += ",C";
8552 S += ",&";
8554 S += ",W";
8555 } else {
8556 switch (PD->getSetterKind()) {
8557 case ObjCPropertyDecl::Assign: break;
8558 case ObjCPropertyDecl::Copy: S += ",C"; break;
8559 case ObjCPropertyDecl::Retain: S += ",&"; break;
8560 case ObjCPropertyDecl::Weak: S += ",W"; break;
8561 }
8562 }
8563
8564 // It really isn't clear at all what this means, since properties
8565 // are "dynamic by default".
8566 if (Dynamic)
8567 S += ",D";
8568
8570 S += ",N";
8571
8573 S += ",G";
8574 S += PD->getGetterName().getAsString();
8575 }
8576
8578 S += ",S";
8579 S += PD->getSetterName().getAsString();
8580 }
8581
8582 if (SynthesizePID) {
8583 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
8584 S += ",V";
8585 S += OID->getNameAsString();
8586 }
8587
8588 // FIXME: OBJCGC: weak & strong
8589 return S;
8590}
8591
8592/// getLegacyIntegralTypeEncoding -
8593/// Another legacy compatibility encoding: 32-bit longs are encoded as
8594/// 'l' or 'L' , but not always. For typedefs, we need to use
8595/// 'i' or 'I' instead if encoding a struct field, or a pointer!
8597 if (PointeeTy->getAs<TypedefType>()) {
8598 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
8599 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
8600 PointeeTy = UnsignedIntTy;
8601 else
8602 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
8603 PointeeTy = IntTy;
8604 }
8605 }
8606}
8607
8609 const FieldDecl *Field,
8610 QualType *NotEncodedT) const {
8611 // We follow the behavior of gcc, expanding structures which are
8612 // directly pointed to, and expanding embedded structures. Note that
8613 // these rules are sufficient to prevent recursive encoding of the
8614 // same type.
8615 getObjCEncodingForTypeImpl(T, S,
8616 ObjCEncOptions()
8617 .setExpandPointedToStructures()
8618 .setExpandStructures()
8619 .setIsOutermostType(),
8620 Field, NotEncodedT);
8621}
8622
8624 std::string& S) const {
8625 // Encode result type.
8626 // GCC has some special rules regarding encoding of properties which
8627 // closely resembles encoding of ivars.
8628 getObjCEncodingForTypeImpl(T, S,
8629 ObjCEncOptions()
8630 .setExpandPointedToStructures()
8631 .setExpandStructures()
8632 .setIsOutermostType()
8633 .setEncodingProperty(),
8634 /*Field=*/nullptr);
8635}
8636
8638 const BuiltinType *BT) {
8639 BuiltinType::Kind kind = BT->getKind();
8640 switch (kind) {
8641 case BuiltinType::Void: return 'v';
8642 case BuiltinType::Bool: return 'B';
8643 case BuiltinType::Char8:
8644 case BuiltinType::Char_U:
8645 case BuiltinType::UChar: return 'C';
8646 case BuiltinType::Char16:
8647 case BuiltinType::UShort: return 'S';
8648 case BuiltinType::Char32:
8649 case BuiltinType::UInt: return 'I';
8650 case BuiltinType::ULong:
8651 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
8652 case BuiltinType::UInt128: return 'T';
8653 case BuiltinType::ULongLong: return 'Q';
8654 case BuiltinType::Char_S:
8655 case BuiltinType::SChar: return 'c';
8656 case BuiltinType::Short: return 's';
8657 case BuiltinType::WChar_S:
8658 case BuiltinType::WChar_U:
8659 case BuiltinType::Int: return 'i';
8660 case BuiltinType::Long:
8661 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
8662 case BuiltinType::LongLong: return 'q';
8663 case BuiltinType::Int128: return 't';
8664 case BuiltinType::Float: return 'f';
8665 case BuiltinType::Double: return 'd';
8666 case BuiltinType::LongDouble: return 'D';
8667 case BuiltinType::NullPtr: return '*'; // like char*
8668
8669 case BuiltinType::BFloat16:
8670 case BuiltinType::Float16:
8671 case BuiltinType::Float128:
8672 case BuiltinType::Ibm128:
8673 case BuiltinType::Half:
8674 case BuiltinType::ShortAccum:
8675 case BuiltinType::Accum:
8676 case BuiltinType::LongAccum:
8677 case BuiltinType::UShortAccum:
8678 case BuiltinType::UAccum:
8679 case BuiltinType::ULongAccum:
8680 case BuiltinType::ShortFract:
8681 case BuiltinType::Fract:
8682 case BuiltinType::LongFract:
8683 case BuiltinType::UShortFract:
8684 case BuiltinType::UFract:
8685 case BuiltinType::ULongFract:
8686 case BuiltinType::SatShortAccum:
8687 case BuiltinType::SatAccum:
8688 case BuiltinType::SatLongAccum:
8689 case BuiltinType::SatUShortAccum:
8690 case BuiltinType::SatUAccum:
8691 case BuiltinType::SatULongAccum:
8692 case BuiltinType::SatShortFract:
8693 case BuiltinType::SatFract:
8694 case BuiltinType::SatLongFract:
8695 case BuiltinType::SatUShortFract:
8696 case BuiltinType::SatUFract:
8697 case BuiltinType::SatULongFract:
8698 // FIXME: potentially need @encodes for these!
8699 return ' ';
8700
8701#define SVE_TYPE(Name, Id, SingletonId) \
8702 case BuiltinType::Id:
8703#include "clang/Basic/AArch64SVEACLETypes.def"
8704#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
8705#include "clang/Basic/RISCVVTypes.def"
8706#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
8707#include "clang/Basic/WebAssemblyReferenceTypes.def"
8708#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
8709#include "clang/Basic/AMDGPUTypes.def"
8710 {
8711 DiagnosticsEngine &Diags = C->getDiagnostics();
8712 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
8713 "cannot yet @encode type %0");
8714 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
8715 return ' ';
8716 }
8717
8718 case BuiltinType::ObjCId:
8719 case BuiltinType::ObjCClass:
8720 case BuiltinType::ObjCSel:
8721 llvm_unreachable("@encoding ObjC primitive type");
8722
8723 // OpenCL and placeholder types don't need @encodings.
8724#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8725 case BuiltinType::Id:
8726#include "clang/Basic/OpenCLImageTypes.def"
8727#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
8728 case BuiltinType::Id:
8729#include "clang/Basic/OpenCLExtensionTypes.def"
8730 case BuiltinType::OCLEvent:
8731 case BuiltinType::OCLClkEvent:
8732 case BuiltinType::OCLQueue:
8733 case BuiltinType::OCLReserveID:
8734 case BuiltinType::OCLSampler:
8735 case BuiltinType::Dependent:
8736#define PPC_VECTOR_TYPE(Name, Id, Size) \
8737 case BuiltinType::Id:
8738#include "clang/Basic/PPCTypes.def"
8739#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
8740#include "clang/Basic/HLSLIntangibleTypes.def"
8741#define BUILTIN_TYPE(KIND, ID)
8742#define PLACEHOLDER_TYPE(KIND, ID) \
8743 case BuiltinType::KIND:
8744#include "clang/AST/BuiltinTypes.def"
8745 llvm_unreachable("invalid builtin type for @encode");
8746 }
8747 llvm_unreachable("invalid BuiltinType::Kind value");
8748}
8749
8750static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
8751 EnumDecl *Enum = ET->getDecl();
8752
8753 // The encoding of an non-fixed enum type is always 'i', regardless of size.
8754 if (!Enum->isFixed())
8755 return 'i';
8756
8757 // The encoding of a fixed enum type matches its fixed underlying type.
8758 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
8760}
8761
8762static void EncodeBitField(const ASTContext *Ctx, std::string& S,
8763 QualType T, const FieldDecl *FD) {
8764 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
8765 S += 'b';
8766 // The NeXT runtime encodes bit fields as b followed by the number of bits.
8767 // The GNU runtime requires more information; bitfields are encoded as b,
8768 // then the offset (in bits) of the first element, then the type of the
8769 // bitfield, then the size in bits. For example, in this structure:
8770 //
8771 // struct
8772 // {
8773 // int integer;
8774 // int flags:2;
8775 // };
8776 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
8777 // runtime, but b32i2 for the GNU runtime. The reason for this extra
8778 // information is not especially sensible, but we're stuck with it for
8779 // compatibility with GCC, although providing it breaks anything that
8780 // actually uses runtime introspection and wants to work on both runtimes...
8781 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
8782 uint64_t Offset;
8783
8784 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
8785 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
8786 IVD);
8787 } else {
8788 const RecordDecl *RD = FD->getParent();
8789 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
8790 Offset = RL.getFieldOffset(FD->getFieldIndex());
8791 }
8792
8793 S += llvm::utostr(Offset);
8794
8795 if (const auto *ET = T->getAs<EnumType>())
8796 S += ObjCEncodingForEnumType(Ctx, ET);
8797 else {
8798 const auto *BT = T->castAs<BuiltinType>();
8799 S += getObjCEncodingForPrimitiveType(Ctx, BT);
8800 }
8801 }
8802 S += llvm::utostr(FD->getBitWidthValue());
8803}
8804
8805// Helper function for determining whether the encoded type string would include
8806// a template specialization type.
8808 bool VisitBasesAndFields) {
8810
8811 if (auto *PT = T->getAs<PointerType>())
8813 PT->getPointeeType().getTypePtr(), false);
8814
8815 auto *CXXRD = T->getAsCXXRecordDecl();
8816
8817 if (!CXXRD)
8818 return false;
8819
8820 if (isa<ClassTemplateSpecializationDecl>(CXXRD))
8821 return true;
8822
8823 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
8824 return false;
8825
8826 for (const auto &B : CXXRD->bases())
8827 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
8828 true))
8829 return true;
8830
8831 for (auto *FD : CXXRD->fields())
8832 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
8833 true))
8834 return true;
8835
8836 return false;
8837}
8838
8839// FIXME: Use SmallString for accumulating string.
8840void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
8841 const ObjCEncOptions Options,
8842 const FieldDecl *FD,
8843 QualType *NotEncodedT) const {
8845 switch (CT->getTypeClass()) {
8846 case Type::Builtin:
8847 case Type::Enum:
8848 if (FD && FD->isBitField())
8849 return EncodeBitField(this, S, T, FD);
8850 if (const auto *BT = dyn_cast<BuiltinType>(CT))
8851 S += getObjCEncodingForPrimitiveType(this, BT);
8852 else
8853 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
8854 return;
8855
8856 case Type::Complex:
8857 S += 'j';
8858 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
8859 ObjCEncOptions(),
8860 /*Field=*/nullptr);
8861 return;
8862
8863 case Type::Atomic:
8864 S += 'A';
8865 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
8866 ObjCEncOptions(),
8867 /*Field=*/nullptr);
8868 return;
8869
8870 // encoding for pointer or reference types.
8871 case Type::Pointer:
8872 case Type::LValueReference:
8873 case Type::RValueReference: {
8874 QualType PointeeTy;
8875 if (isa<PointerType>(CT)) {
8876 const auto *PT = T->castAs<PointerType>();
8877 if (PT->isObjCSelType()) {
8878 S += ':';
8879 return;
8880 }
8881 PointeeTy = PT->getPointeeType();
8882 } else {
8883 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
8884 }
8885
8886 bool isReadOnly = false;
8887 // For historical/compatibility reasons, the read-only qualifier of the
8888 // pointee gets emitted _before_ the '^'. The read-only qualifier of
8889 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
8890 // Also, do not emit the 'r' for anything but the outermost type!
8891 if (T->getAs<TypedefType>()) {
8892 if (Options.IsOutermostType() && T.isConstQualified()) {
8893 isReadOnly = true;
8894 S += 'r';
8895 }
8896 } else if (Options.IsOutermostType()) {
8897 QualType P = PointeeTy;
8898 while (auto PT = P->getAs<PointerType>())
8899 P = PT->getPointeeType();
8900 if (P.isConstQualified()) {
8901 isReadOnly = true;
8902 S += 'r';
8903 }
8904 }
8905 if (isReadOnly) {
8906 // Another legacy compatibility encoding. Some ObjC qualifier and type
8907 // combinations need to be rearranged.
8908 // Rewrite "in const" from "nr" to "rn"
8909 if (StringRef(S).ends_with("nr"))
8910 S.replace(S.end()-2, S.end(), "rn");
8911 }
8912
8913 if (PointeeTy->isCharType()) {
8914 // char pointer types should be encoded as '*' unless it is a
8915 // type that has been typedef'd to 'BOOL'.
8916 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
8917 S += '*';
8918 return;
8919 }
8920 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
8921 // GCC binary compat: Need to convert "struct objc_class *" to "#".
8922 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
8923 S += '#';
8924 return;
8925 }
8926 // GCC binary compat: Need to convert "struct objc_object *" to "@".
8927 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
8928 S += '@';
8929 return;
8930 }
8931 // If the encoded string for the class includes template names, just emit
8932 // "^v" for pointers to the class.
8933 if (getLangOpts().CPlusPlus &&
8934 (!getLangOpts().EncodeCXXClassTemplateSpec &&
8936 RTy, Options.ExpandPointedToStructures()))) {
8937 S += "^v";
8938 return;
8939 }
8940 // fall through...
8941 }
8942 S += '^';
8944
8945 ObjCEncOptions NewOptions;
8946 if (Options.ExpandPointedToStructures())
8947 NewOptions.setExpandStructures();
8948 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
8949 /*Field=*/nullptr, NotEncodedT);
8950 return;
8951 }
8952
8953 case Type::ConstantArray:
8954 case Type::IncompleteArray:
8955 case Type::VariableArray: {
8956 const auto *AT = cast<ArrayType>(CT);
8957
8958 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
8959 // Incomplete arrays are encoded as a pointer to the array element.
8960 S += '^';
8961
8962 getObjCEncodingForTypeImpl(
8963 AT->getElementType(), S,
8964 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
8965 } else {
8966 S += '[';
8967
8968 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
8969 S += llvm::utostr(CAT->getZExtSize());
8970 else {
8971 //Variable length arrays are encoded as a regular array with 0 elements.
8972 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
8973 "Unknown array type!");
8974 S += '0';
8975 }
8976
8977 getObjCEncodingForTypeImpl(
8978 AT->getElementType(), S,
8979 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
8980 NotEncodedT);
8981 S += ']';
8982 }
8983 return;
8984 }
8985
8986 case Type::FunctionNoProto:
8987 case Type::FunctionProto:
8988 S += '?';
8989 return;
8990
8991 case Type::Record: {
8992 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
8993 S += RDecl->isUnion() ? '(' : '{';
8994 // Anonymous structures print as '?'
8995 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
8996 S += II->getName();
8997 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
8998 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
8999 llvm::raw_string_ostream OS(S);
9000 printTemplateArgumentList(OS, TemplateArgs.asArray(),
9002 }
9003 } else {
9004 S += '?';
9005 }
9006 if (Options.ExpandStructures()) {
9007 S += '=';
9008 if (!RDecl->isUnion()) {
9009 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
9010 } else {
9011 for (const auto *Field : RDecl->fields()) {
9012 if (FD) {
9013 S += '"';
9014 S += Field->getNameAsString();
9015 S += '"';
9016 }
9017
9018 // Special case bit-fields.
9019 if (Field->isBitField()) {
9020 getObjCEncodingForTypeImpl(Field->getType(), S,
9021 ObjCEncOptions().setExpandStructures(),
9022 Field);
9023 } else {
9024 QualType qt = Field->getType();
9026 getObjCEncodingForTypeImpl(
9027 qt, S,
9028 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
9029 NotEncodedT);
9030 }
9031 }
9032 }
9033 }
9034 S += RDecl->isUnion() ? ')' : '}';
9035 return;
9036 }
9037
9038 case Type::BlockPointer: {
9039 const auto *BT = T->castAs<BlockPointerType>();
9040 S += "@?"; // Unlike a pointer-to-function, which is "^?".
9041 if (Options.EncodeBlockParameters()) {
9042 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
9043
9044 S += '<';
9045 // Block return type
9046 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
9047 Options.forComponentType(), FD, NotEncodedT);
9048 // Block self
9049 S += "@?";
9050 // Block parameters
9051 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
9052 for (const auto &I : FPT->param_types())
9053 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
9054 NotEncodedT);
9055 }
9056 S += '>';
9057 }
9058 return;
9059 }
9060
9061 case Type::ObjCObject: {
9062 // hack to match legacy encoding of *id and *Class
9064 if (Ty->isObjCIdType()) {
9065 S += "{objc_object=}";
9066 return;
9067 }
9068 else if (Ty->isObjCClassType()) {
9069 S += "{objc_class=}";
9070 return;
9071 }
9072 // TODO: Double check to make sure this intentionally falls through.
9073 [[fallthrough]];
9074 }
9075
9076 case Type::ObjCInterface: {
9077 // Ignore protocol qualifiers when mangling at this level.
9078 // @encode(class_name)
9079 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
9080 S += '{';
9081 S += OI->getObjCRuntimeNameAsString();
9082 if (Options.ExpandStructures()) {
9083 S += '=';
9085 DeepCollectObjCIvars(OI, true, Ivars);
9086 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
9087 const FieldDecl *Field = Ivars[i];
9088 if (Field->isBitField())
9089 getObjCEncodingForTypeImpl(Field->getType(), S,
9090 ObjCEncOptions().setExpandStructures(),
9091 Field);
9092 else
9093 getObjCEncodingForTypeImpl(Field->getType(), S,
9094 ObjCEncOptions().setExpandStructures(), FD,
9095 NotEncodedT);
9096 }
9097 }
9098 S += '}';
9099 return;
9100 }
9101
9102 case Type::ObjCObjectPointer: {
9103 const auto *OPT = T->castAs<ObjCObjectPointerType>();
9104 if (OPT->isObjCIdType()) {
9105 S += '@';
9106 return;
9107 }
9108
9109 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
9110 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
9111 // Since this is a binary compatibility issue, need to consult with
9112 // runtime folks. Fortunately, this is a *very* obscure construct.
9113 S += '#';
9114 return;
9115 }
9116
9117 if (OPT->isObjCQualifiedIdType()) {
9118 getObjCEncodingForTypeImpl(
9119 getObjCIdType(), S,
9120 Options.keepingOnly(ObjCEncOptions()
9121 .setExpandPointedToStructures()
9122 .setExpandStructures()),
9123 FD);
9124 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
9125 // Note that we do extended encoding of protocol qualifier list
9126 // Only when doing ivar or property encoding.
9127 S += '"';
9128 for (const auto *I : OPT->quals()) {
9129 S += '<';
9130 S += I->getObjCRuntimeNameAsString();
9131 S += '>';
9132 }
9133 S += '"';
9134 }
9135 return;
9136 }
9137
9138 S += '@';
9139 if (OPT->getInterfaceDecl() &&
9140 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
9141 S += '"';
9142 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
9143 for (const auto *I : OPT->quals()) {
9144 S += '<';
9145 S += I->getObjCRuntimeNameAsString();
9146 S += '>';
9147 }
9148 S += '"';
9149 }
9150 return;
9151 }
9152
9153 // gcc just blithely ignores member pointers.
9154 // FIXME: we should do better than that. 'M' is available.
9155 case Type::MemberPointer:
9156 // This matches gcc's encoding, even though technically it is insufficient.
9157 //FIXME. We should do a better job than gcc.
9158 case Type::Vector:
9159 case Type::ExtVector:
9160 // Until we have a coherent encoding of these three types, issue warning.
9161 if (NotEncodedT)
9162 *NotEncodedT = T;
9163 return;
9164
9165 case Type::ConstantMatrix:
9166 if (NotEncodedT)
9167 *NotEncodedT = T;
9168 return;
9169
9170 case Type::BitInt:
9171 if (NotEncodedT)
9172 *NotEncodedT = T;
9173 return;
9174
9175 // We could see an undeduced auto type here during error recovery.
9176 // Just ignore it.
9177 case Type::Auto:
9178 case Type::DeducedTemplateSpecialization:
9179 return;
9180
9181 case Type::HLSLAttributedResource:
9182 llvm_unreachable("unexpected type");
9183
9184 case Type::ArrayParameter:
9185 case Type::Pipe:
9186#define ABSTRACT_TYPE(KIND, BASE)
9187#define TYPE(KIND, BASE)
9188#define DEPENDENT_TYPE(KIND, BASE) \
9189 case Type::KIND:
9190#define NON_CANONICAL_TYPE(KIND, BASE) \
9191 case Type::KIND:
9192#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
9193 case Type::KIND:
9194#include "clang/AST/TypeNodes.inc"
9195 llvm_unreachable("@encode for dependent type!");
9196 }
9197 llvm_unreachable("bad type kind!");
9198}
9199
9200void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
9201 std::string &S,
9202 const FieldDecl *FD,
9203 bool includeVBases,
9204 QualType *NotEncodedT) const {
9205 assert(RDecl && "Expected non-null RecordDecl");
9206 assert(!RDecl->isUnion() && "Should not be called for unions");
9207 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
9208 return;
9209
9210 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
9211 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
9212 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
9213
9214 if (CXXRec) {
9215 for (const auto &BI : CXXRec->bases()) {
9216 if (!BI.isVirtual()) {
9217 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9218 if (base->isEmpty())
9219 continue;
9220 uint64_t offs = toBits(layout.getBaseClassOffset(base));
9221 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9222 std::make_pair(offs, base));
9223 }
9224 }
9225 }
9226
9227 for (FieldDecl *Field : RDecl->fields()) {
9228 if (!Field->isZeroLengthBitField() && Field->isZeroSize(*this))
9229 continue;
9230 uint64_t offs = layout.getFieldOffset(Field->getFieldIndex());
9231 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9232 std::make_pair(offs, Field));
9233 }
9234
9235 if (CXXRec && includeVBases) {
9236 for (const auto &BI : CXXRec->vbases()) {
9237 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9238 if (base->isEmpty())
9239 continue;
9240 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
9241 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
9242 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
9243 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
9244 std::make_pair(offs, base));
9245 }
9246 }
9247
9248 CharUnits size;
9249 if (CXXRec) {
9250 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
9251 } else {
9252 size = layout.getSize();
9253 }
9254
9255#ifndef NDEBUG
9256 uint64_t CurOffs = 0;
9257#endif
9258 std::multimap<uint64_t, NamedDecl *>::iterator
9259 CurLayObj = FieldOrBaseOffsets.begin();
9260
9261 if (CXXRec && CXXRec->isDynamicClass() &&
9262 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
9263 if (FD) {
9264 S += "\"_vptr$";
9265 std::string recname = CXXRec->getNameAsString();
9266 if (recname.empty()) recname = "?";
9267 S += recname;
9268 S += '"';
9269 }
9270 S += "^^?";
9271#ifndef NDEBUG
9272 CurOffs += getTypeSize(VoidPtrTy);
9273#endif
9274 }
9275
9276 if (!RDecl->hasFlexibleArrayMember()) {
9277 // Mark the end of the structure.
9278 uint64_t offs = toBits(size);
9279 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9280 std::make_pair(offs, nullptr));
9281 }
9282
9283 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
9284#ifndef NDEBUG
9285 assert(CurOffs <= CurLayObj->first);
9286 if (CurOffs < CurLayObj->first) {
9287 uint64_t padding = CurLayObj->first - CurOffs;
9288 // FIXME: There doesn't seem to be a way to indicate in the encoding that
9289 // packing/alignment of members is different that normal, in which case
9290 // the encoding will be out-of-sync with the real layout.
9291 // If the runtime switches to just consider the size of types without
9292 // taking into account alignment, we could make padding explicit in the
9293 // encoding (e.g. using arrays of chars). The encoding strings would be
9294 // longer then though.
9295 CurOffs += padding;
9296 }
9297#endif
9298
9299 NamedDecl *dcl = CurLayObj->second;
9300 if (!dcl)
9301 break; // reached end of structure.
9302
9303 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
9304 // We expand the bases without their virtual bases since those are going
9305 // in the initial structure. Note that this differs from gcc which
9306 // expands virtual bases each time one is encountered in the hierarchy,
9307 // making the encoding type bigger than it really is.
9308 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
9309 NotEncodedT);
9310 assert(!base->isEmpty());
9311#ifndef NDEBUG
9312 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
9313#endif
9314 } else {
9315 const auto *field = cast<FieldDecl>(dcl);
9316 if (FD) {
9317 S += '"';
9318 S += field->getNameAsString();
9319 S += '"';
9320 }
9321
9322 if (field->isBitField()) {
9323 EncodeBitField(this, S, field->getType(), field);
9324#ifndef NDEBUG
9325 CurOffs += field->getBitWidthValue();
9326#endif
9327 } else {
9328 QualType qt = field->getType();
9330 getObjCEncodingForTypeImpl(
9331 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
9332 FD, NotEncodedT);
9333#ifndef NDEBUG
9334 CurOffs += getTypeSize(field->getType());
9335#endif
9336 }
9337 }
9338 }
9339}
9340
9342 std::string& S) const {
9343 if (QT & Decl::OBJC_TQ_In)
9344 S += 'n';
9345 if (QT & Decl::OBJC_TQ_Inout)
9346 S += 'N';
9347 if (QT & Decl::OBJC_TQ_Out)
9348 S += 'o';
9349 if (QT & Decl::OBJC_TQ_Bycopy)
9350 S += 'O';
9351 if (QT & Decl::OBJC_TQ_Byref)
9352 S += 'R';
9353 if (QT & Decl::OBJC_TQ_Oneway)
9354 S += 'V';
9355}
9356
9358 if (!ObjCIdDecl) {
9361 ObjCIdDecl = buildImplicitTypedef(T, "id");
9362 }
9363 return ObjCIdDecl;
9364}
9365
9367 if (!ObjCSelDecl) {
9369 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
9370 }
9371 return ObjCSelDecl;
9372}
9373
9375 if (!ObjCClassDecl) {
9378 ObjCClassDecl = buildImplicitTypedef(T, "Class");
9379 }
9380 return ObjCClassDecl;
9381}
9382
9384 if (!ObjCProtocolClassDecl) {
9385 ObjCProtocolClassDecl
9388 &Idents.get("Protocol"),
9389 /*typeParamList=*/nullptr,
9390 /*PrevDecl=*/nullptr,
9391 SourceLocation(), true);
9392 }
9393
9394 return ObjCProtocolClassDecl;
9395}
9396
9397//===----------------------------------------------------------------------===//
9398// __builtin_va_list Construction Functions
9399//===----------------------------------------------------------------------===//
9400
9402 StringRef Name) {
9403 // typedef char* __builtin[_ms]_va_list;
9404 QualType T = Context->getPointerType(Context->CharTy);
9405 return Context->buildImplicitTypedef(T, Name);
9406}
9407
9409 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
9410}
9411
9413 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
9414}
9415
9417 // typedef void* __builtin_va_list;
9418 QualType T = Context->getPointerType(Context->VoidTy);
9419 return Context->buildImplicitTypedef(T, "__builtin_va_list");
9420}
9421
9422static TypedefDecl *
9424 // struct __va_list
9425 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
9426 if (Context->getLangOpts().CPlusPlus) {
9427 // namespace std { struct __va_list {
9428 auto *NS = NamespaceDecl::Create(
9429 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
9430 /*Inline=*/false, SourceLocation(), SourceLocation(),
9431 &Context->Idents.get("std"),
9432 /*PrevDecl=*/nullptr, /*Nested=*/false);
9433 NS->setImplicit();
9434 VaListTagDecl->setDeclContext(NS);
9435 }
9436
9437 VaListTagDecl->startDefinition();
9438
9439 const size_t NumFields = 5;
9440 QualType FieldTypes[NumFields];
9441 const char *FieldNames[NumFields];
9442
9443 // void *__stack;
9444 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
9445 FieldNames[0] = "__stack";
9446
9447 // void *__gr_top;
9448 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
9449 FieldNames[1] = "__gr_top";
9450
9451 // void *__vr_top;
9452 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9453 FieldNames[2] = "__vr_top";
9454
9455 // int __gr_offs;
9456 FieldTypes[3] = Context->IntTy;
9457 FieldNames[3] = "__gr_offs";
9458
9459 // int __vr_offs;
9460 FieldTypes[4] = Context->IntTy;
9461 FieldNames[4] = "__vr_offs";
9462
9463 // Create fields
9464 for (unsigned i = 0; i < NumFields; ++i) {
9465 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9466 VaListTagDecl,
9469 &Context->Idents.get(FieldNames[i]),
9470 FieldTypes[i], /*TInfo=*/nullptr,
9471 /*BitWidth=*/nullptr,
9472 /*Mutable=*/false,
9473 ICIS_NoInit);
9474 Field->setAccess(AS_public);
9475 VaListTagDecl->addDecl(Field);
9476 }
9477 VaListTagDecl->completeDefinition();
9478 Context->VaListTagDecl = VaListTagDecl;
9479 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9480
9481 // } __builtin_va_list;
9482 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
9483}
9484
9486 // typedef struct __va_list_tag {
9487 RecordDecl *VaListTagDecl;
9488
9489 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9490 VaListTagDecl->startDefinition();
9491
9492 const size_t NumFields = 5;
9493 QualType FieldTypes[NumFields];
9494 const char *FieldNames[NumFields];
9495
9496 // unsigned char gpr;
9497 FieldTypes[0] = Context->UnsignedCharTy;
9498 FieldNames[0] = "gpr";
9499
9500 // unsigned char fpr;
9501 FieldTypes[1] = Context->UnsignedCharTy;
9502 FieldNames[1] = "fpr";
9503
9504 // unsigned short reserved;
9505 FieldTypes[2] = Context->UnsignedShortTy;
9506 FieldNames[2] = "reserved";
9507
9508 // void* overflow_arg_area;
9509 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
9510 FieldNames[3] = "overflow_arg_area";
9511
9512 // void* reg_save_area;
9513 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
9514 FieldNames[4] = "reg_save_area";
9515
9516 // Create fields
9517 for (unsigned i = 0; i < NumFields; ++i) {
9518 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
9521 &Context->Idents.get(FieldNames[i]),
9522 FieldTypes[i], /*TInfo=*/nullptr,
9523 /*BitWidth=*/nullptr,
9524 /*Mutable=*/false,
9525 ICIS_NoInit);
9526 Field->setAccess(AS_public);
9527 VaListTagDecl->addDecl(Field);
9528 }
9529 VaListTagDecl->completeDefinition();
9530 Context->VaListTagDecl = VaListTagDecl;
9531 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9532
9533 // } __va_list_tag;
9534 TypedefDecl *VaListTagTypedefDecl =
9535 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
9536
9537 QualType VaListTagTypedefType =
9538 Context->getTypedefType(VaListTagTypedefDecl);
9539
9540 // typedef __va_list_tag __builtin_va_list[1];
9541 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9542 QualType VaListTagArrayType = Context->getConstantArrayType(
9543 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
9544 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9545}
9546
9547static TypedefDecl *
9549 // struct __va_list_tag {
9550 RecordDecl *VaListTagDecl;
9551 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9552 VaListTagDecl->startDefinition();
9553
9554 const size_t NumFields = 4;
9555 QualType FieldTypes[NumFields];
9556 const char *FieldNames[NumFields];
9557
9558 // unsigned gp_offset;
9559 FieldTypes[0] = Context->UnsignedIntTy;
9560 FieldNames[0] = "gp_offset";
9561
9562 // unsigned fp_offset;
9563 FieldTypes[1] = Context->UnsignedIntTy;
9564 FieldNames[1] = "fp_offset";
9565
9566 // void* overflow_arg_area;
9567 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9568 FieldNames[2] = "overflow_arg_area";
9569
9570 // void* reg_save_area;
9571 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
9572 FieldNames[3] = "reg_save_area";
9573
9574 // Create fields
9575 for (unsigned i = 0; i < NumFields; ++i) {
9576 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9577 VaListTagDecl,
9580 &Context->Idents.get(FieldNames[i]),
9581 FieldTypes[i], /*TInfo=*/nullptr,
9582 /*BitWidth=*/nullptr,
9583 /*Mutable=*/false,
9584 ICIS_NoInit);
9585 Field->setAccess(AS_public);
9586 VaListTagDecl->addDecl(Field);
9587 }
9588 VaListTagDecl->completeDefinition();
9589 Context->VaListTagDecl = VaListTagDecl;
9590 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9591
9592 // };
9593
9594 // typedef struct __va_list_tag __builtin_va_list[1];
9595 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9596 QualType VaListTagArrayType = Context->getConstantArrayType(
9597 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
9598 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9599}
9600
9602 // typedef int __builtin_va_list[4];
9603 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
9604 QualType IntArrayType = Context->getConstantArrayType(
9605 Context->IntTy, Size, nullptr, ArraySizeModifier::Normal, 0);
9606 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
9607}
9608
9609static TypedefDecl *
9611 // struct __va_list
9612 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
9613 if (Context->getLangOpts().CPlusPlus) {
9614 // namespace std { struct __va_list {
9615 NamespaceDecl *NS;
9616 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
9617 Context->getTranslationUnitDecl(),
9618 /*Inline=*/false, SourceLocation(),
9619 SourceLocation(), &Context->Idents.get("std"),
9620 /*PrevDecl=*/nullptr, /*Nested=*/false);
9621 NS->setImplicit();
9622 VaListDecl->setDeclContext(NS);
9623 }
9624
9625 VaListDecl->startDefinition();
9626
9627 // void * __ap;
9628 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9629 VaListDecl,
9632 &Context->Idents.get("__ap"),
9633 Context->getPointerType(Context->VoidTy),
9634 /*TInfo=*/nullptr,
9635 /*BitWidth=*/nullptr,
9636 /*Mutable=*/false,
9637 ICIS_NoInit);
9638 Field->setAccess(AS_public);
9639 VaListDecl->addDecl(Field);
9640
9641 // };
9642 VaListDecl->completeDefinition();
9643 Context->VaListTagDecl = VaListDecl;
9644
9645 // typedef struct __va_list __builtin_va_list;
9646 QualType T = Context->getRecordType(VaListDecl);
9647 return Context->buildImplicitTypedef(T, "__builtin_va_list");
9648}
9649
9650static TypedefDecl *
9652 // struct __va_list_tag {
9653 RecordDecl *VaListTagDecl;
9654 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9655 VaListTagDecl->startDefinition();
9656
9657 const size_t NumFields = 4;
9658 QualType FieldTypes[NumFields];
9659 const char *FieldNames[NumFields];
9660
9661 // long __gpr;
9662 FieldTypes[0] = Context->LongTy;
9663 FieldNames[0] = "__gpr";
9664
9665 // long __fpr;
9666 FieldTypes[1] = Context->LongTy;
9667 FieldNames[1] = "__fpr";
9668
9669 // void *__overflow_arg_area;
9670 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9671 FieldNames[2] = "__overflow_arg_area";
9672
9673 // void *__reg_save_area;
9674 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
9675 FieldNames[3] = "__reg_save_area";
9676
9677 // Create fields
9678 for (unsigned i = 0; i < NumFields; ++i) {
9679 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9680 VaListTagDecl,
9683 &Context->Idents.get(FieldNames[i]),
9684 FieldTypes[i], /*TInfo=*/nullptr,
9685 /*BitWidth=*/nullptr,
9686 /*Mutable=*/false,
9687 ICIS_NoInit);
9688 Field->setAccess(AS_public);
9689 VaListTagDecl->addDecl(Field);
9690 }
9691 VaListTagDecl->completeDefinition();
9692 Context->VaListTagDecl = VaListTagDecl;
9693 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9694
9695 // };
9696
9697 // typedef __va_list_tag __builtin_va_list[1];
9698 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9699 QualType VaListTagArrayType = Context->getConstantArrayType(
9700 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
9701
9702 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9703}
9704
9706 // typedef struct __va_list_tag {
9707 RecordDecl *VaListTagDecl;
9708 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9709 VaListTagDecl->startDefinition();
9710
9711 const size_t NumFields = 3;
9712 QualType FieldTypes[NumFields];
9713 const char *FieldNames[NumFields];
9714
9715 // void *CurrentSavedRegisterArea;
9716 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
9717 FieldNames[0] = "__current_saved_reg_area_pointer";
9718
9719 // void *SavedRegAreaEnd;
9720 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
9721 FieldNames[1] = "__saved_reg_area_end_pointer";
9722
9723 // void *OverflowArea;
9724 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9725 FieldNames[2] = "__overflow_area_pointer";
9726
9727 // Create fields
9728 for (unsigned i = 0; i < NumFields; ++i) {
9730 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
9731 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
9732 /*TInfo=*/nullptr,
9733 /*BitWidth=*/nullptr,
9734 /*Mutable=*/false, ICIS_NoInit);
9735 Field->setAccess(AS_public);
9736 VaListTagDecl->addDecl(Field);
9737 }
9738 VaListTagDecl->completeDefinition();
9739 Context->VaListTagDecl = VaListTagDecl;
9740 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9741
9742 // } __va_list_tag;
9743 TypedefDecl *VaListTagTypedefDecl =
9744 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
9745
9746 QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl);
9747
9748 // typedef __va_list_tag __builtin_va_list[1];
9749 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9750 QualType VaListTagArrayType = Context->getConstantArrayType(
9751 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
9752
9753 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9754}
9755
9756static TypedefDecl *
9758 // typedef struct __va_list_tag {
9759 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9760
9761 VaListTagDecl->startDefinition();
9762
9763 // int* __va_stk;
9764 // int* __va_reg;
9765 // int __va_ndx;
9766 constexpr size_t NumFields = 3;
9767 QualType FieldTypes[NumFields] = {Context->getPointerType(Context->IntTy),
9768 Context->getPointerType(Context->IntTy),
9769 Context->IntTy};
9770 const char *FieldNames[NumFields] = {"__va_stk", "__va_reg", "__va_ndx"};
9771
9772 // Create fields
9773 for (unsigned i = 0; i < NumFields; ++i) {
9775 *Context, VaListTagDecl, SourceLocation(), SourceLocation(),
9776 &Context->Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
9777 /*BitWidth=*/nullptr,
9778 /*Mutable=*/false, ICIS_NoInit);
9779 Field->setAccess(AS_public);
9780 VaListTagDecl->addDecl(Field);
9781 }
9782 VaListTagDecl->completeDefinition();
9783 Context->VaListTagDecl = VaListTagDecl;
9784 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9785
9786 // } __va_list_tag;
9787 TypedefDecl *VaListTagTypedefDecl =
9788 Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
9789
9790 return VaListTagTypedefDecl;
9791}
9792
9795 switch (Kind) {
9797 return CreateCharPtrBuiltinVaListDecl(Context);
9799 return CreateVoidPtrBuiltinVaListDecl(Context);
9801 return CreateAArch64ABIBuiltinVaListDecl(Context);
9803 return CreatePowerABIBuiltinVaListDecl(Context);
9805 return CreateX86_64ABIBuiltinVaListDecl(Context);
9807 return CreatePNaClABIBuiltinVaListDecl(Context);
9809 return CreateAAPCSABIBuiltinVaListDecl(Context);
9811 return CreateSystemZBuiltinVaListDecl(Context);
9813 return CreateHexagonBuiltinVaListDecl(Context);
9815 return CreateXtensaABIBuiltinVaListDecl(Context);
9816 }
9817
9818 llvm_unreachable("Unhandled __builtin_va_list type kind");
9819}
9820
9822 if (!BuiltinVaListDecl) {
9823 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
9824 assert(BuiltinVaListDecl->isImplicit());
9825 }
9826
9827 return BuiltinVaListDecl;
9828}
9829
9831 // Force the creation of VaListTagDecl by building the __builtin_va_list
9832 // declaration.
9833 if (!VaListTagDecl)
9834 (void)getBuiltinVaListDecl();
9835
9836 return VaListTagDecl;
9837}
9838
9840 if (!BuiltinMSVaListDecl)
9841 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
9842
9843 return BuiltinMSVaListDecl;
9844}
9845
9847 // Allow redecl custom type checking builtin for HLSL.
9848 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
9850 return true;
9852}
9853
9855 assert(ObjCConstantStringType.isNull() &&
9856 "'NSConstantString' type already set!");
9857
9858 ObjCConstantStringType = getObjCInterfaceType(Decl);
9859}
9860
9861/// Retrieve the template name that corresponds to a non-empty
9862/// lookup.
9865 UnresolvedSetIterator End) const {
9866 unsigned size = End - Begin;
9867 assert(size > 1 && "set is not overloaded!");
9868
9869 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
9870 size * sizeof(FunctionTemplateDecl*));
9871 auto *OT = new (memory) OverloadedTemplateStorage(size);
9872
9873 NamedDecl **Storage = OT->getStorage();
9874 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
9875 NamedDecl *D = *I;
9876 assert(isa<FunctionTemplateDecl>(D) ||
9877 isa<UnresolvedUsingValueDecl>(D) ||
9878 (isa<UsingShadowDecl>(D) &&
9879 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
9880 *Storage++ = D;
9881 }
9882
9883 return TemplateName(OT);
9884}
9885
9886/// Retrieve a template name representing an unqualified-id that has been
9887/// assumed to name a template for ADL purposes.
9889 auto *OT = new (*this) AssumedTemplateStorage(Name);
9890 return TemplateName(OT);
9891}
9892
9893/// Retrieve the template name that represents a qualified
9894/// template name such as \c std::vector.
9896 bool TemplateKeyword,
9897 TemplateName Template) const {
9898 assert(Template.getKind() == TemplateName::Template ||
9899 Template.getKind() == TemplateName::UsingTemplate);
9900
9901 // FIXME: Canonicalization?
9902 llvm::FoldingSetNodeID ID;
9903 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
9904
9905 void *InsertPos = nullptr;
9907 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9908 if (!QTN) {
9909 QTN = new (*this, alignof(QualifiedTemplateName))
9910 QualifiedTemplateName(NNS, TemplateKeyword, Template);
9911 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
9912 }
9913
9914 return TemplateName(QTN);
9915}
9916
9917/// Retrieve the template name that represents a dependent
9918/// template name such as \c MetaFun::template apply.
9921 const IdentifierInfo *Name) const {
9922 assert((!NNS || NNS->isDependent()) &&
9923 "Nested name specifier must be dependent");
9924
9925 llvm::FoldingSetNodeID ID;
9926 DependentTemplateName::Profile(ID, NNS, Name);
9927
9928 void *InsertPos = nullptr;
9930 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9931
9932 if (QTN)
9933 return TemplateName(QTN);
9934
9936 if (CanonNNS == NNS) {
9937 QTN = new (*this, alignof(DependentTemplateName))
9938 DependentTemplateName(NNS, Name);
9939 } else {
9940 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
9941 QTN = new (*this, alignof(DependentTemplateName))
9942 DependentTemplateName(NNS, Name, Canon);
9943 DependentTemplateName *CheckQTN =
9944 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9945 assert(!CheckQTN && "Dependent type name canonicalization broken");
9946 (void)CheckQTN;
9947 }
9948
9949 DependentTemplateNames.InsertNode(QTN, InsertPos);
9950 return TemplateName(QTN);
9951}
9952
9953/// Retrieve the template name that represents a dependent
9954/// template name such as \c MetaFun::template operator+.
9957 OverloadedOperatorKind Operator) const {
9958 assert((!NNS || NNS->isDependent()) &&
9959 "Nested name specifier must be dependent");
9960
9961 llvm::FoldingSetNodeID ID;
9962 DependentTemplateName::Profile(ID, NNS, Operator);
9963
9964 void *InsertPos = nullptr;
9966 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9967
9968 if (QTN)
9969 return TemplateName(QTN);
9970
9972 if (CanonNNS == NNS) {
9973 QTN = new (*this, alignof(DependentTemplateName))
9974 DependentTemplateName(NNS, Operator);
9975 } else {
9976 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
9977 QTN = new (*this, alignof(DependentTemplateName))
9978 DependentTemplateName(NNS, Operator, Canon);
9979
9980 DependentTemplateName *CheckQTN
9981 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9982 assert(!CheckQTN && "Dependent template name canonicalization broken");
9983 (void)CheckQTN;
9984 }
9985
9986 DependentTemplateNames.InsertNode(QTN, InsertPos);
9987 return TemplateName(QTN);
9988}
9989
9991 TemplateName Replacement, Decl *AssociatedDecl, unsigned Index,
9992 std::optional<unsigned> PackIndex) const {
9993 llvm::FoldingSetNodeID ID;
9994 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
9995 Index, PackIndex);
9996
9997 void *insertPos = nullptr;
9999 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
10000
10001 if (!subst) {
10002 subst = new (*this) SubstTemplateTemplateParmStorage(
10003 Replacement, AssociatedDecl, Index, PackIndex);
10004 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
10005 }
10006
10007 return TemplateName(subst);
10008}
10009
10012 Decl *AssociatedDecl,
10013 unsigned Index, bool Final) const {
10014 auto &Self = const_cast<ASTContext &>(*this);
10015 llvm::FoldingSetNodeID ID;
10017 AssociatedDecl, Index, Final);
10018
10019 void *InsertPos = nullptr;
10021 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
10022
10023 if (!Subst) {
10024 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
10025 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
10026 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
10027 }
10028
10029 return TemplateName(Subst);
10030}
10031
10032/// Retrieve the template name that represents a template name
10033/// deduced from a specialization.
10036 DefaultArguments DefaultArgs) const {
10037 if (!DefaultArgs)
10038 return Underlying;
10039
10040 llvm::FoldingSetNodeID ID;
10041 DeducedTemplateStorage::Profile(ID, *this, Underlying, DefaultArgs);
10042
10043 void *InsertPos = nullptr;
10045 DeducedTemplates.FindNodeOrInsertPos(ID, InsertPos);
10046 if (!DTS) {
10047 void *Mem = Allocate(sizeof(DeducedTemplateStorage) +
10048 sizeof(TemplateArgument) * DefaultArgs.Args.size(),
10049 alignof(DeducedTemplateStorage));
10050 DTS = new (Mem) DeducedTemplateStorage(Underlying, DefaultArgs);
10051 DeducedTemplates.InsertNode(DTS, InsertPos);
10052 }
10053 return TemplateName(DTS);
10054}
10055
10056/// getFromTargetType - Given one of the integer types provided by
10057/// TargetInfo, produce the corresponding type. The unsigned @p Type
10058/// is actually a value of type @c TargetInfo::IntType.
10059CanQualType ASTContext::getFromTargetType(unsigned Type) const {
10060 switch (Type) {
10061 case TargetInfo::NoInt: return {};
10064 case TargetInfo::SignedShort: return ShortTy;
10066 case TargetInfo::SignedInt: return IntTy;
10068 case TargetInfo::SignedLong: return LongTy;
10072 }
10073
10074 llvm_unreachable("Unhandled TargetInfo::IntType value");
10075}
10076
10077//===----------------------------------------------------------------------===//
10078// Type Predicates.
10079//===----------------------------------------------------------------------===//
10080
10081/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
10082/// garbage collection attribute.
10083///
10085 if (getLangOpts().getGC() == LangOptions::NonGC)
10086 return Qualifiers::GCNone;
10087
10088 assert(getLangOpts().ObjC);
10089 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
10090
10091 // Default behaviour under objective-C's gc is for ObjC pointers
10092 // (or pointers to them) be treated as though they were declared
10093 // as __strong.
10094 if (GCAttrs == Qualifiers::GCNone) {
10096 return Qualifiers::Strong;
10097 else if (Ty->isPointerType())
10099 } else {
10100 // It's not valid to set GC attributes on anything that isn't a
10101 // pointer.
10102#ifndef NDEBUG
10104 while (const auto *AT = dyn_cast<ArrayType>(CT))
10105 CT = AT->getElementType();
10106 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
10107#endif
10108 }
10109 return GCAttrs;
10110}
10111
10112//===----------------------------------------------------------------------===//
10113// Type Compatibility Testing
10114//===----------------------------------------------------------------------===//
10115
10116/// areCompatVectorTypes - Return true if the two specified vector types are
10117/// compatible.
10118static bool areCompatVectorTypes(const VectorType *LHS,
10119 const VectorType *RHS) {
10120 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10121 return LHS->getElementType() == RHS->getElementType() &&
10122 LHS->getNumElements() == RHS->getNumElements();
10123}
10124
10125/// areCompatMatrixTypes - Return true if the two specified matrix types are
10126/// compatible.
10128 const ConstantMatrixType *RHS) {
10129 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10130 return LHS->getElementType() == RHS->getElementType() &&
10131 LHS->getNumRows() == RHS->getNumRows() &&
10132 LHS->getNumColumns() == RHS->getNumColumns();
10133}
10134
10136 QualType SecondVec) {
10137 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
10138 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
10139
10140 if (hasSameUnqualifiedType(FirstVec, SecondVec))
10141 return true;
10142
10143 // Treat Neon vector types and most AltiVec vector types as if they are the
10144 // equivalent GCC vector types.
10145 const auto *First = FirstVec->castAs<VectorType>();
10146 const auto *Second = SecondVec->castAs<VectorType>();
10147 if (First->getNumElements() == Second->getNumElements() &&
10148 hasSameType(First->getElementType(), Second->getElementType()) &&
10149 First->getVectorKind() != VectorKind::AltiVecPixel &&
10150 First->getVectorKind() != VectorKind::AltiVecBool &&
10153 First->getVectorKind() != VectorKind::SveFixedLengthData &&
10154 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10157 First->getVectorKind() != VectorKind::RVVFixedLengthData &&
10159 First->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10161 First->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10163 First->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10165 First->getVectorKind() != VectorKind::RVVFixedLengthMask_4 &&
10167 return true;
10168
10169 return false;
10170}
10171
10172/// getSVETypeSize - Return SVE vector or predicate register size.
10173static uint64_t getSVETypeSize(ASTContext &Context, const BuiltinType *Ty) {
10174 assert(Ty->isSveVLSBuiltinType() && "Invalid SVE Type");
10175 if (Ty->getKind() == BuiltinType::SveBool ||
10176 Ty->getKind() == BuiltinType::SveCount)
10177 return (Context.getLangOpts().VScaleMin * 128) / Context.getCharWidth();
10178 return Context.getLangOpts().VScaleMin * 128;
10179}
10180
10182 QualType SecondType) {
10183 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10184 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10185 if (const auto *VT = SecondType->getAs<VectorType>()) {
10186 // Predicates have the same representation as uint8 so we also have to
10187 // check the kind to make these types incompatible.
10188 if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
10189 return BT->getKind() == BuiltinType::SveBool;
10190 else if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
10191 return VT->getElementType().getCanonicalType() ==
10192 FirstType->getSveEltType(*this);
10193 else if (VT->getVectorKind() == VectorKind::Generic)
10194 return getTypeSize(SecondType) == getSVETypeSize(*this, BT) &&
10195 hasSameType(VT->getElementType(),
10196 getBuiltinVectorTypeInfo(BT).ElementType);
10197 }
10198 }
10199 return false;
10200 };
10201
10202 return IsValidCast(FirstType, SecondType) ||
10203 IsValidCast(SecondType, FirstType);
10204}
10205
10207 QualType SecondType) {
10208 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10209 const auto *BT = FirstType->getAs<BuiltinType>();
10210 if (!BT)
10211 return false;
10212
10213 const auto *VecTy = SecondType->getAs<VectorType>();
10214 if (VecTy && (VecTy->getVectorKind() == VectorKind::SveFixedLengthData ||
10215 VecTy->getVectorKind() == VectorKind::Generic)) {
10217 getLangOpts().getLaxVectorConversions();
10218
10219 // Can not convert between sve predicates and sve vectors because of
10220 // different size.
10221 if (BT->getKind() == BuiltinType::SveBool &&
10222 VecTy->getVectorKind() == VectorKind::SveFixedLengthData)
10223 return false;
10224
10225 // If __ARM_FEATURE_SVE_BITS != N do not allow GNU vector lax conversion.
10226 // "Whenever __ARM_FEATURE_SVE_BITS==N, GNUT implicitly
10227 // converts to VLAT and VLAT implicitly converts to GNUT."
10228 // ACLE Spec Version 00bet6, 3.7.3.2. Behavior common to vectors and
10229 // predicates.
10230 if (VecTy->getVectorKind() == VectorKind::Generic &&
10231 getTypeSize(SecondType) != getSVETypeSize(*this, BT))
10232 return false;
10233
10234 // If -flax-vector-conversions=all is specified, the types are
10235 // certainly compatible.
10237 return true;
10238
10239 // If -flax-vector-conversions=integer is specified, the types are
10240 // compatible if the elements are integer types.
10242 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10243 FirstType->getSveEltType(*this)->isIntegerType();
10244 }
10245
10246 return false;
10247 };
10248
10249 return IsLaxCompatible(FirstType, SecondType) ||
10250 IsLaxCompatible(SecondType, FirstType);
10251}
10252
10253/// getRVVTypeSize - Return RVV vector register size.
10254static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
10255 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
10256 auto VScale = Context.getTargetInfo().getVScaleRange(Context.getLangOpts());
10257 if (!VScale)
10258 return 0;
10259
10261
10262 uint64_t EltSize = Context.getTypeSize(Info.ElementType);
10263 if (Info.ElementType == Context.BoolTy)
10264 EltSize = 1;
10265
10266 uint64_t MinElts = Info.EC.getKnownMinValue();
10267 return VScale->first * MinElts * EltSize;
10268}
10269
10271 QualType SecondType) {
10272 assert(
10273 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10274 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10275 "Expected RVV builtin type and vector type!");
10276
10277 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10278 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10279 if (const auto *VT = SecondType->getAs<VectorType>()) {
10280 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10282 return FirstType->isRVVVLSBuiltinType() &&
10283 Info.ElementType == BoolTy &&
10284 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)));
10285 }
10286 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1) {
10288 return FirstType->isRVVVLSBuiltinType() &&
10289 Info.ElementType == BoolTy &&
10290 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT) * 8));
10291 }
10292 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2) {
10294 return FirstType->isRVVVLSBuiltinType() &&
10295 Info.ElementType == BoolTy &&
10296 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 4);
10297 }
10298 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10300 return FirstType->isRVVVLSBuiltinType() &&
10301 Info.ElementType == BoolTy &&
10302 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 2);
10303 }
10304 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
10305 VT->getVectorKind() == VectorKind::Generic)
10306 return FirstType->isRVVVLSBuiltinType() &&
10307 getTypeSize(SecondType) == getRVVTypeSize(*this, BT) &&
10308 hasSameType(VT->getElementType(),
10309 getBuiltinVectorTypeInfo(BT).ElementType);
10310 }
10311 }
10312 return false;
10313 };
10314
10315 return IsValidCast(FirstType, SecondType) ||
10316 IsValidCast(SecondType, FirstType);
10317}
10318
10320 QualType SecondType) {
10321 assert(
10322 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10323 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10324 "Expected RVV builtin type and vector type!");
10325
10326 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10327 const auto *BT = FirstType->getAs<BuiltinType>();
10328 if (!BT)
10329 return false;
10330
10331 if (!BT->isRVVVLSBuiltinType())
10332 return false;
10333
10334 const auto *VecTy = SecondType->getAs<VectorType>();
10335 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
10337 getLangOpts().getLaxVectorConversions();
10338
10339 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
10340 if (getTypeSize(SecondType) != getRVVTypeSize(*this, BT))
10341 return false;
10342
10343 // If -flax-vector-conversions=all is specified, the types are
10344 // certainly compatible.
10346 return true;
10347
10348 // If -flax-vector-conversions=integer is specified, the types are
10349 // compatible if the elements are integer types.
10351 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10352 FirstType->getRVVEltType(*this)->isIntegerType();
10353 }
10354
10355 return false;
10356 };
10357
10358 return IsLaxCompatible(FirstType, SecondType) ||
10359 IsLaxCompatible(SecondType, FirstType);
10360}
10361
10363 while (true) {
10364 // __strong id
10365 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
10366 if (Attr->getAttrKind() == attr::ObjCOwnership)
10367 return true;
10368
10369 Ty = Attr->getModifiedType();
10370
10371 // X *__strong (...)
10372 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
10373 Ty = Paren->getInnerType();
10374
10375 // We do not want to look through typedefs, typeof(expr),
10376 // typeof(type), or any other way that the type is somehow
10377 // abstracted.
10378 } else {
10379 return false;
10380 }
10381 }
10382}
10383
10384//===----------------------------------------------------------------------===//
10385// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
10386//===----------------------------------------------------------------------===//
10387
10388/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
10389/// inheritance hierarchy of 'rProto'.
10390bool
10392 ObjCProtocolDecl *rProto) const {
10393 if (declaresSameEntity(lProto, rProto))
10394 return true;
10395 for (auto *PI : rProto->protocols())
10396 if (ProtocolCompatibleWithProtocol(lProto, PI))
10397 return true;
10398 return false;
10399}
10400
10401/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
10402/// Class<pr1, ...>.
10404 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
10405 for (auto *lhsProto : lhs->quals()) {
10406 bool match = false;
10407 for (auto *rhsProto : rhs->quals()) {
10408 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
10409 match = true;
10410 break;
10411 }
10412 }
10413 if (!match)
10414 return false;
10415 }
10416 return true;
10417}
10418
10419/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
10420/// ObjCQualifiedIDType.
10422 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
10423 bool compare) {
10424 // Allow id<P..> and an 'id' in all cases.
10425 if (lhs->isObjCIdType() || rhs->isObjCIdType())
10426 return true;
10427
10428 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
10429 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
10431 return false;
10432
10433 if (lhs->isObjCQualifiedIdType()) {
10434 if (rhs->qual_empty()) {
10435 // If the RHS is a unqualified interface pointer "NSString*",
10436 // make sure we check the class hierarchy.
10437 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10438 for (auto *I : lhs->quals()) {
10439 // when comparing an id<P> on lhs with a static type on rhs,
10440 // see if static class implements all of id's protocols, directly or
10441 // through its super class and categories.
10442 if (!rhsID->ClassImplementsProtocol(I, true))
10443 return false;
10444 }
10445 }
10446 // If there are no qualifiers and no interface, we have an 'id'.
10447 return true;
10448 }
10449 // Both the right and left sides have qualifiers.
10450 for (auto *lhsProto : lhs->quals()) {
10451 bool match = false;
10452
10453 // when comparing an id<P> on lhs with a static type on rhs,
10454 // see if static class implements all of id's protocols, directly or
10455 // through its super class and categories.
10456 for (auto *rhsProto : rhs->quals()) {
10457 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10458 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10459 match = true;
10460 break;
10461 }
10462 }
10463 // If the RHS is a qualified interface pointer "NSString<P>*",
10464 // make sure we check the class hierarchy.
10465 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10466 for (auto *I : lhs->quals()) {
10467 // when comparing an id<P> on lhs with a static type on rhs,
10468 // see if static class implements all of id's protocols, directly or
10469 // through its super class and categories.
10470 if (rhsID->ClassImplementsProtocol(I, true)) {
10471 match = true;
10472 break;
10473 }
10474 }
10475 }
10476 if (!match)
10477 return false;
10478 }
10479
10480 return true;
10481 }
10482
10483 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
10484
10485 if (lhs->getInterfaceType()) {
10486 // If both the right and left sides have qualifiers.
10487 for (auto *lhsProto : lhs->quals()) {
10488 bool match = false;
10489
10490 // when comparing an id<P> on rhs with a static type on lhs,
10491 // see if static class implements all of id's protocols, directly or
10492 // through its super class and categories.
10493 // First, lhs protocols in the qualifier list must be found, direct
10494 // or indirect in rhs's qualifier list or it is a mismatch.
10495 for (auto *rhsProto : rhs->quals()) {
10496 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10497 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10498 match = true;
10499 break;
10500 }
10501 }
10502 if (!match)
10503 return false;
10504 }
10505
10506 // Static class's protocols, or its super class or category protocols
10507 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
10508 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
10509 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
10510 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
10511 // This is rather dubious but matches gcc's behavior. If lhs has
10512 // no type qualifier and its class has no static protocol(s)
10513 // assume that it is mismatch.
10514 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
10515 return false;
10516 for (auto *lhsProto : LHSInheritedProtocols) {
10517 bool match = false;
10518 for (auto *rhsProto : rhs->quals()) {
10519 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10520 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10521 match = true;
10522 break;
10523 }
10524 }
10525 if (!match)
10526 return false;
10527 }
10528 }
10529 return true;
10530 }
10531 return false;
10532}
10533
10534/// canAssignObjCInterfaces - Return true if the two interface types are
10535/// compatible for assignment from RHS to LHS. This handles validation of any
10536/// protocol qualifiers on the LHS or RHS.
10538 const ObjCObjectPointerType *RHSOPT) {
10539 const ObjCObjectType* LHS = LHSOPT->getObjectType();
10540 const ObjCObjectType* RHS = RHSOPT->getObjectType();
10541
10542 // If either type represents the built-in 'id' type, return true.
10543 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
10544 return true;
10545
10546 // Function object that propagates a successful result or handles
10547 // __kindof types.
10548 auto finish = [&](bool succeeded) -> bool {
10549 if (succeeded)
10550 return true;
10551
10552 if (!RHS->isKindOfType())
10553 return false;
10554
10555 // Strip off __kindof and protocol qualifiers, then check whether
10556 // we can assign the other way.
10558 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
10559 };
10560
10561 // Casts from or to id<P> are allowed when the other side has compatible
10562 // protocols.
10563 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
10564 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
10565 }
10566
10567 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
10568 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
10569 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
10570 }
10571
10572 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
10573 if (LHS->isObjCClass() && RHS->isObjCClass()) {
10574 return true;
10575 }
10576
10577 // If we have 2 user-defined types, fall into that path.
10578 if (LHS->getInterface() && RHS->getInterface()) {
10579 return finish(canAssignObjCInterfaces(LHS, RHS));
10580 }
10581
10582 return false;
10583}
10584
10585/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
10586/// for providing type-safety for objective-c pointers used to pass/return
10587/// arguments in block literals. When passed as arguments, passing 'A*' where
10588/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
10589/// not OK. For the return type, the opposite is not OK.
10591 const ObjCObjectPointerType *LHSOPT,
10592 const ObjCObjectPointerType *RHSOPT,
10593 bool BlockReturnType) {
10594
10595 // Function object that propagates a successful result or handles
10596 // __kindof types.
10597 auto finish = [&](bool succeeded) -> bool {
10598 if (succeeded)
10599 return true;
10600
10601 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
10602 if (!Expected->isKindOfType())
10603 return false;
10604
10605 // Strip off __kindof and protocol qualifiers, then check whether
10606 // we can assign the other way.
10608 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
10609 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
10610 BlockReturnType);
10611 };
10612
10613 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
10614 return true;
10615
10616 if (LHSOPT->isObjCBuiltinType()) {
10617 return finish(RHSOPT->isObjCBuiltinType() ||
10618 RHSOPT->isObjCQualifiedIdType());
10619 }
10620
10621 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
10622 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
10623 // Use for block parameters previous type checking for compatibility.
10624 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
10625 // Or corrected type checking as in non-compat mode.
10626 (!BlockReturnType &&
10627 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
10628 else
10630 (BlockReturnType ? LHSOPT : RHSOPT),
10631 (BlockReturnType ? RHSOPT : LHSOPT), false));
10632 }
10633
10634 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
10635 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
10636 if (LHS && RHS) { // We have 2 user-defined types.
10637 if (LHS != RHS) {
10638 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
10639 return finish(BlockReturnType);
10640 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
10641 return finish(!BlockReturnType);
10642 }
10643 else
10644 return true;
10645 }
10646 return false;
10647}
10648
10649/// Comparison routine for Objective-C protocols to be used with
10650/// llvm::array_pod_sort.
10652 ObjCProtocolDecl * const *rhs) {
10653 return (*lhs)->getName().compare((*rhs)->getName());
10654}
10655
10656/// getIntersectionOfProtocols - This routine finds the intersection of set
10657/// of protocols inherited from two distinct objective-c pointer objects with
10658/// the given common base.
10659/// It is used to build composite qualifier list of the composite type of
10660/// the conditional expression involving two objective-c pointer objects.
10661static
10663 const ObjCInterfaceDecl *CommonBase,
10664 const ObjCObjectPointerType *LHSOPT,
10665 const ObjCObjectPointerType *RHSOPT,
10666 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
10667
10668 const ObjCObjectType* LHS = LHSOPT->getObjectType();
10669 const ObjCObjectType* RHS = RHSOPT->getObjectType();
10670 assert(LHS->getInterface() && "LHS must have an interface base");
10671 assert(RHS->getInterface() && "RHS must have an interface base");
10672
10673 // Add all of the protocols for the LHS.
10675
10676 // Start with the protocol qualifiers.
10677 for (auto *proto : LHS->quals()) {
10678 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
10679 }
10680
10681 // Also add the protocols associated with the LHS interface.
10682 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
10683
10684 // Add all of the protocols for the RHS.
10686
10687 // Start with the protocol qualifiers.
10688 for (auto *proto : RHS->quals()) {
10689 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
10690 }
10691
10692 // Also add the protocols associated with the RHS interface.
10693 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
10694
10695 // Compute the intersection of the collected protocol sets.
10696 for (auto *proto : LHSProtocolSet) {
10697 if (RHSProtocolSet.count(proto))
10698 IntersectionSet.push_back(proto);
10699 }
10700
10701 // Compute the set of protocols that is implied by either the common type or
10702 // the protocols within the intersection.
10704 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
10705
10706 // Remove any implied protocols from the list of inherited protocols.
10707 if (!ImpliedProtocols.empty()) {
10708 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
10709 return ImpliedProtocols.contains(proto);
10710 });
10711 }
10712
10713 // Sort the remaining protocols by name.
10714 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
10716}
10717
10718/// Determine whether the first type is a subtype of the second.
10720 QualType rhs) {
10721 // Common case: two object pointers.
10722 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
10723 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
10724 if (lhsOPT && rhsOPT)
10725 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
10726
10727 // Two block pointers.
10728 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
10729 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
10730 if (lhsBlock && rhsBlock)
10731 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
10732
10733 // If either is an unqualified 'id' and the other is a block, it's
10734 // acceptable.
10735 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
10736 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
10737 return true;
10738
10739 return false;
10740}
10741
10742// Check that the given Objective-C type argument lists are equivalent.
10744 const ObjCInterfaceDecl *iface,
10745 ArrayRef<QualType> lhsArgs,
10746 ArrayRef<QualType> rhsArgs,
10747 bool stripKindOf) {
10748 if (lhsArgs.size() != rhsArgs.size())
10749 return false;
10750
10751 ObjCTypeParamList *typeParams = iface->getTypeParamList();
10752 if (!typeParams)
10753 return false;
10754
10755 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
10756 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
10757 continue;
10758
10759 switch (typeParams->begin()[i]->getVariance()) {
10761 if (!stripKindOf ||
10762 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
10763 rhsArgs[i].stripObjCKindOfType(ctx))) {
10764 return false;
10765 }
10766 break;
10767
10769 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
10770 return false;
10771 break;
10772
10774 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
10775 return false;
10776 break;
10777 }
10778 }
10779
10780 return true;
10781}
10782
10784 const ObjCObjectPointerType *Lptr,
10785 const ObjCObjectPointerType *Rptr) {
10786 const ObjCObjectType *LHS = Lptr->getObjectType();
10787 const ObjCObjectType *RHS = Rptr->getObjectType();
10788 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
10789 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
10790
10791 if (!LDecl || !RDecl)
10792 return {};
10793
10794 // When either LHS or RHS is a kindof type, we should return a kindof type.
10795 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
10796 // kindof(A).
10797 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
10798
10799 // Follow the left-hand side up the class hierarchy until we either hit a
10800 // root or find the RHS. Record the ancestors in case we don't find it.
10801 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
10802 LHSAncestors;
10803 while (true) {
10804 // Record this ancestor. We'll need this if the common type isn't in the
10805 // path from the LHS to the root.
10806 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
10807
10808 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
10809 // Get the type arguments.
10810 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
10811 bool anyChanges = false;
10812 if (LHS->isSpecialized() && RHS->isSpecialized()) {
10813 // Both have type arguments, compare them.
10814 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
10815 LHS->getTypeArgs(), RHS->getTypeArgs(),
10816 /*stripKindOf=*/true))
10817 return {};
10818 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
10819 // If only one has type arguments, the result will not have type
10820 // arguments.
10821 LHSTypeArgs = {};
10822 anyChanges = true;
10823 }
10824
10825 // Compute the intersection of protocols.
10827 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
10828 Protocols);
10829 if (!Protocols.empty())
10830 anyChanges = true;
10831
10832 // If anything in the LHS will have changed, build a new result type.
10833 // If we need to return a kindof type but LHS is not a kindof type, we
10834 // build a new result type.
10835 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
10837 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
10838 anyKindOf || LHS->isKindOfType());
10840 }
10841
10842 return getObjCObjectPointerType(QualType(LHS, 0));
10843 }
10844
10845 // Find the superclass.
10846 QualType LHSSuperType = LHS->getSuperClassType();
10847 if (LHSSuperType.isNull())
10848 break;
10849
10850 LHS = LHSSuperType->castAs<ObjCObjectType>();
10851 }
10852
10853 // We didn't find anything by following the LHS to its root; now check
10854 // the RHS against the cached set of ancestors.
10855 while (true) {
10856 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
10857 if (KnownLHS != LHSAncestors.end()) {
10858 LHS = KnownLHS->second;
10859
10860 // Get the type arguments.
10861 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
10862 bool anyChanges = false;
10863 if (LHS->isSpecialized() && RHS->isSpecialized()) {
10864 // Both have type arguments, compare them.
10865 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
10866 LHS->getTypeArgs(), RHS->getTypeArgs(),
10867 /*stripKindOf=*/true))
10868 return {};
10869 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
10870 // If only one has type arguments, the result will not have type
10871 // arguments.
10872 RHSTypeArgs = {};
10873 anyChanges = true;
10874 }
10875
10876 // Compute the intersection of protocols.
10878 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
10879 Protocols);
10880 if (!Protocols.empty())
10881 anyChanges = true;
10882
10883 // If we need to return a kindof type but RHS is not a kindof type, we
10884 // build a new result type.
10885 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
10887 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
10888 anyKindOf || RHS->isKindOfType());
10890 }
10891
10892 return getObjCObjectPointerType(QualType(RHS, 0));
10893 }
10894
10895 // Find the superclass of the RHS.
10896 QualType RHSSuperType = RHS->getSuperClassType();
10897 if (RHSSuperType.isNull())
10898 break;
10899
10900 RHS = RHSSuperType->castAs<ObjCObjectType>();
10901 }
10902
10903 return {};
10904}
10905
10907 const ObjCObjectType *RHS) {
10908 assert(LHS->getInterface() && "LHS is not an interface type");
10909 assert(RHS->getInterface() && "RHS is not an interface type");
10910
10911 // Verify that the base decls are compatible: the RHS must be a subclass of
10912 // the LHS.
10913 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
10914 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
10915 if (!IsSuperClass)
10916 return false;
10917
10918 // If the LHS has protocol qualifiers, determine whether all of them are
10919 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
10920 // LHS).
10921 if (LHS->getNumProtocols() > 0) {
10922 // OK if conversion of LHS to SuperClass results in narrowing of types
10923 // ; i.e., SuperClass may implement at least one of the protocols
10924 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
10925 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
10926 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
10927 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
10928 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
10929 // qualifiers.
10930 for (auto *RHSPI : RHS->quals())
10931 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
10932 // If there is no protocols associated with RHS, it is not a match.
10933 if (SuperClassInheritedProtocols.empty())
10934 return false;
10935
10936 for (const auto *LHSProto : LHS->quals()) {
10937 bool SuperImplementsProtocol = false;
10938 for (auto *SuperClassProto : SuperClassInheritedProtocols)
10939 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
10940 SuperImplementsProtocol = true;
10941 break;
10942 }
10943 if (!SuperImplementsProtocol)
10944 return false;
10945 }
10946 }
10947
10948 // If the LHS is specialized, we may need to check type arguments.
10949 if (LHS->isSpecialized()) {
10950 // Follow the superclass chain until we've matched the LHS class in the
10951 // hierarchy. This substitutes type arguments through.
10952 const ObjCObjectType *RHSSuper = RHS;
10953 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
10954 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
10955
10956 // If the RHS is specializd, compare type arguments.
10957 if (RHSSuper->isSpecialized() &&
10958 !sameObjCTypeArgs(*this, LHS->getInterface(),
10959 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
10960 /*stripKindOf=*/true)) {
10961 return false;
10962 }
10963 }
10964
10965 return true;
10966}
10967
10969 // get the "pointed to" types
10970 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
10971 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
10972
10973 if (!LHSOPT || !RHSOPT)
10974 return false;
10975
10976 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
10977 canAssignObjCInterfaces(RHSOPT, LHSOPT);
10978}
10979
10982 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
10983 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
10984}
10985
10986/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
10987/// both shall have the identically qualified version of a compatible type.
10988/// C99 6.2.7p1: Two types have compatible types if their types are the
10989/// same. See 6.7.[2,3,5] for additional rules.
10991 bool CompareUnqualified) {
10992 if (getLangOpts().CPlusPlus)
10993 return hasSameType(LHS, RHS);
10994
10995 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
10996}
10997
10999 return typesAreCompatible(LHS, RHS);
11000}
11001
11003 return !mergeTypes(LHS, RHS, true).isNull();
11004}
11005
11006/// mergeTransparentUnionType - if T is a transparent union type and a member
11007/// of T is compatible with SubType, return the merged type, else return
11008/// QualType()
11010 bool OfBlockPointer,
11011 bool Unqualified) {
11012 if (const RecordType *UT = T->getAsUnionType()) {
11013 RecordDecl *UD = UT->getDecl();
11014 if (UD->hasAttr<TransparentUnionAttr>()) {
11015 for (const auto *I : UD->fields()) {
11016 QualType ET = I->getType().getUnqualifiedType();
11017 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
11018 if (!MT.isNull())
11019 return MT;
11020 }
11021 }
11022 }
11023
11024 return {};
11025}
11026
11027/// mergeFunctionParameterTypes - merge two types which appear as function
11028/// parameter types
11030 bool OfBlockPointer,
11031 bool Unqualified) {
11032 // GNU extension: two types are compatible if they appear as a function
11033 // argument, one of the types is a transparent union type and the other
11034 // type is compatible with a union member
11035 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
11036 Unqualified);
11037 if (!lmerge.isNull())
11038 return lmerge;
11039
11040 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
11041 Unqualified);
11042 if (!rmerge.isNull())
11043 return rmerge;
11044
11045 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
11046}
11047
11049 bool OfBlockPointer, bool Unqualified,
11050 bool AllowCXX,
11051 bool IsConditionalOperator) {
11052 const auto *lbase = lhs->castAs<FunctionType>();
11053 const auto *rbase = rhs->castAs<FunctionType>();
11054 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
11055 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
11056 bool allLTypes = true;
11057 bool allRTypes = true;
11058
11059 // Check return type
11060 QualType retType;
11061 if (OfBlockPointer) {
11062 QualType RHS = rbase->getReturnType();
11063 QualType LHS = lbase->getReturnType();
11064 bool UnqualifiedResult = Unqualified;
11065 if (!UnqualifiedResult)
11066 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
11067 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
11068 }
11069 else
11070 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
11071 Unqualified);
11072 if (retType.isNull())
11073 return {};
11074
11075 if (Unqualified)
11076 retType = retType.getUnqualifiedType();
11077
11078 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
11079 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
11080 if (Unqualified) {
11081 LRetType = LRetType.getUnqualifiedType();
11082 RRetType = RRetType.getUnqualifiedType();
11083 }
11084
11085 if (getCanonicalType(retType) != LRetType)
11086 allLTypes = false;
11087 if (getCanonicalType(retType) != RRetType)
11088 allRTypes = false;
11089
11090 // FIXME: double check this
11091 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
11092 // rbase->getRegParmAttr() != 0 &&
11093 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
11094 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
11095 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
11096
11097 // Compatible functions must have compatible calling conventions
11098 if (lbaseInfo.getCC() != rbaseInfo.getCC())
11099 return {};
11100
11101 // Regparm is part of the calling convention.
11102 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
11103 return {};
11104 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
11105 return {};
11106
11107 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
11108 return {};
11109 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
11110 return {};
11111 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
11112 return {};
11113
11114 // When merging declarations, it's common for supplemental information like
11115 // attributes to only be present in one of the declarations, and we generally
11116 // want type merging to preserve the union of information. So a merged
11117 // function type should be noreturn if it was noreturn in *either* operand
11118 // type.
11119 //
11120 // But for the conditional operator, this is backwards. The result of the
11121 // operator could be either operand, and its type should conservatively
11122 // reflect that. So a function type in a composite type is noreturn only
11123 // if it's noreturn in *both* operand types.
11124 //
11125 // Arguably, noreturn is a kind of subtype, and the conditional operator
11126 // ought to produce the most specific common supertype of its operand types.
11127 // That would differ from this rule in contravariant positions. However,
11128 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
11129 // as a practical matter, it would only affect C code that does abstraction of
11130 // higher-order functions (taking noreturn callbacks!), which is uncommon to
11131 // say the least. So we use the simpler rule.
11132 bool NoReturn = IsConditionalOperator
11133 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
11134 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
11135 if (lbaseInfo.getNoReturn() != NoReturn)
11136 allLTypes = false;
11137 if (rbaseInfo.getNoReturn() != NoReturn)
11138 allRTypes = false;
11139
11140 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
11141
11142 std::optional<FunctionEffectSet> MergedFX;
11143
11144 if (lproto && rproto) { // two C99 style function prototypes
11145 assert((AllowCXX ||
11146 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
11147 "C++ shouldn't be here");
11148 // Compatible functions must have the same number of parameters
11149 if (lproto->getNumParams() != rproto->getNumParams())
11150 return {};
11151
11152 // Variadic and non-variadic functions aren't compatible
11153 if (lproto->isVariadic() != rproto->isVariadic())
11154 return {};
11155
11156 if (lproto->getMethodQuals() != rproto->getMethodQuals())
11157 return {};
11158
11159 // Function effects are handled similarly to noreturn, see above.
11160 FunctionEffectsRef LHSFX = lproto->getFunctionEffects();
11161 FunctionEffectsRef RHSFX = rproto->getFunctionEffects();
11162 if (LHSFX != RHSFX) {
11163 if (IsConditionalOperator)
11164 MergedFX = FunctionEffectSet::getIntersection(LHSFX, RHSFX);
11165 else {
11167 MergedFX = FunctionEffectSet::getUnion(LHSFX, RHSFX, Errs);
11168 // Here we're discarding a possible error due to conflicts in the effect
11169 // sets. But we're not in a context where we can report it. The
11170 // operation does however guarantee maintenance of invariants.
11171 }
11172 if (*MergedFX != LHSFX)
11173 allLTypes = false;
11174 if (*MergedFX != RHSFX)
11175 allRTypes = false;
11176 }
11177
11179 bool canUseLeft, canUseRight;
11180 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
11181 newParamInfos))
11182 return {};
11183
11184 if (!canUseLeft)
11185 allLTypes = false;
11186 if (!canUseRight)
11187 allRTypes = false;
11188
11189 // Check parameter type compatibility
11191 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
11192 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
11193 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
11195 lParamType, rParamType, OfBlockPointer, Unqualified);
11196 if (paramType.isNull())
11197 return {};
11198
11199 if (Unqualified)
11200 paramType = paramType.getUnqualifiedType();
11201
11202 types.push_back(paramType);
11203 if (Unqualified) {
11204 lParamType = lParamType.getUnqualifiedType();
11205 rParamType = rParamType.getUnqualifiedType();
11206 }
11207
11208 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
11209 allLTypes = false;
11210 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
11211 allRTypes = false;
11212 }
11213
11214 if (allLTypes) return lhs;
11215 if (allRTypes) return rhs;
11216
11217 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
11218 EPI.ExtInfo = einfo;
11219 EPI.ExtParameterInfos =
11220 newParamInfos.empty() ? nullptr : newParamInfos.data();
11221 if (MergedFX)
11222 EPI.FunctionEffects = *MergedFX;
11223 return getFunctionType(retType, types, EPI);
11224 }
11225
11226 if (lproto) allRTypes = false;
11227 if (rproto) allLTypes = false;
11228
11229 const FunctionProtoType *proto = lproto ? lproto : rproto;
11230 if (proto) {
11231 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
11232 if (proto->isVariadic())
11233 return {};
11234 // Check that the types are compatible with the types that
11235 // would result from default argument promotions (C99 6.7.5.3p15).
11236 // The only types actually affected are promotable integer
11237 // types and floats, which would be passed as a different
11238 // type depending on whether the prototype is visible.
11239 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
11240 QualType paramTy = proto->getParamType(i);
11241
11242 // Look at the converted type of enum types, since that is the type used
11243 // to pass enum values.
11244 if (const auto *Enum = paramTy->getAs<EnumType>()) {
11245 paramTy = Enum->getDecl()->getIntegerType();
11246 if (paramTy.isNull())
11247 return {};
11248 }
11249
11250 if (isPromotableIntegerType(paramTy) ||
11251 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
11252 return {};
11253 }
11254
11255 if (allLTypes) return lhs;
11256 if (allRTypes) return rhs;
11257
11259 EPI.ExtInfo = einfo;
11260 if (MergedFX)
11261 EPI.FunctionEffects = *MergedFX;
11262 return getFunctionType(retType, proto->getParamTypes(), EPI);
11263 }
11264
11265 if (allLTypes) return lhs;
11266 if (allRTypes) return rhs;
11267 return getFunctionNoProtoType(retType, einfo);
11268}
11269
11270/// Given that we have an enum type and a non-enum type, try to merge them.
11272 QualType other, bool isBlockReturnType) {
11273 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
11274 // a signed integer type, or an unsigned integer type.
11275 // Compatibility is based on the underlying type, not the promotion
11276 // type.
11277 QualType underlyingType = ET->getDecl()->getIntegerType();
11278 if (underlyingType.isNull())
11279 return {};
11280 if (Context.hasSameType(underlyingType, other))
11281 return other;
11282
11283 // In block return types, we're more permissive and accept any
11284 // integral type of the same size.
11285 if (isBlockReturnType && other->isIntegerType() &&
11286 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
11287 return other;
11288
11289 return {};
11290}
11291
11292QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
11293 bool Unqualified, bool BlockReturnType,
11294 bool IsConditionalOperator) {
11295 // For C++ we will not reach this code with reference types (see below),
11296 // for OpenMP variant call overloading we might.
11297 //
11298 // C++ [expr]: If an expression initially has the type "reference to T", the
11299 // type is adjusted to "T" prior to any further analysis, the expression
11300 // designates the object or function denoted by the reference, and the
11301 // expression is an lvalue unless the reference is an rvalue reference and
11302 // the expression is a function call (possibly inside parentheses).
11303 auto *LHSRefTy = LHS->getAs<ReferenceType>();
11304 auto *RHSRefTy = RHS->getAs<ReferenceType>();
11305 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
11306 LHS->getTypeClass() == RHS->getTypeClass())
11307 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
11308 OfBlockPointer, Unqualified, BlockReturnType);
11309 if (LHSRefTy || RHSRefTy)
11310 return {};
11311
11312 if (Unqualified) {
11313 LHS = LHS.getUnqualifiedType();
11314 RHS = RHS.getUnqualifiedType();
11315 }
11316
11317 QualType LHSCan = getCanonicalType(LHS),
11318 RHSCan = getCanonicalType(RHS);
11319
11320 // If two types are identical, they are compatible.
11321 if (LHSCan == RHSCan)
11322 return LHS;
11323
11324 // If the qualifiers are different, the types aren't compatible... mostly.
11325 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11326 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11327 if (LQuals != RQuals) {
11328 // If any of these qualifiers are different, we have a type
11329 // mismatch.
11330 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11331 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
11332 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
11333 LQuals.hasUnaligned() != RQuals.hasUnaligned())
11334 return {};
11335
11336 // Exactly one GC qualifier difference is allowed: __strong is
11337 // okay if the other type has no GC qualifier but is an Objective
11338 // C object pointer (i.e. implicitly strong by default). We fix
11339 // this by pretending that the unqualified type was actually
11340 // qualified __strong.
11341 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11342 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11343 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11344
11345 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11346 return {};
11347
11348 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
11350 }
11351 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
11353 }
11354 return {};
11355 }
11356
11357 // Okay, qualifiers are equal.
11358
11359 Type::TypeClass LHSClass = LHSCan->getTypeClass();
11360 Type::TypeClass RHSClass = RHSCan->getTypeClass();
11361
11362 // We want to consider the two function types to be the same for these
11363 // comparisons, just force one to the other.
11364 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
11365 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
11366
11367 // Same as above for arrays
11368 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
11369 LHSClass = Type::ConstantArray;
11370 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
11371 RHSClass = Type::ConstantArray;
11372
11373 // ObjCInterfaces are just specialized ObjCObjects.
11374 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
11375 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
11376
11377 // Canonicalize ExtVector -> Vector.
11378 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
11379 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
11380
11381 // If the canonical type classes don't match.
11382 if (LHSClass != RHSClass) {
11383 // Note that we only have special rules for turning block enum
11384 // returns into block int returns, not vice-versa.
11385 if (const auto *ETy = LHS->getAs<EnumType>()) {
11386 return mergeEnumWithInteger(*this, ETy, RHS, false);
11387 }
11388 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
11389 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
11390 }
11391 // allow block pointer type to match an 'id' type.
11392 if (OfBlockPointer && !BlockReturnType) {
11393 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
11394 return LHS;
11395 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
11396 return RHS;
11397 }
11398 // Allow __auto_type to match anything; it merges to the type with more
11399 // information.
11400 if (const auto *AT = LHS->getAs<AutoType>()) {
11401 if (!AT->isDeduced() && AT->isGNUAutoType())
11402 return RHS;
11403 }
11404 if (const auto *AT = RHS->getAs<AutoType>()) {
11405 if (!AT->isDeduced() && AT->isGNUAutoType())
11406 return LHS;
11407 }
11408 return {};
11409 }
11410
11411 // The canonical type classes match.
11412 switch (LHSClass) {
11413#define TYPE(Class, Base)
11414#define ABSTRACT_TYPE(Class, Base)
11415#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
11416#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
11417#define DEPENDENT_TYPE(Class, Base) case Type::Class:
11418#include "clang/AST/TypeNodes.inc"
11419 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
11420
11421 case Type::Auto:
11422 case Type::DeducedTemplateSpecialization:
11423 case Type::LValueReference:
11424 case Type::RValueReference:
11425 case Type::MemberPointer:
11426 llvm_unreachable("C++ should never be in mergeTypes");
11427
11428 case Type::ObjCInterface:
11429 case Type::IncompleteArray:
11430 case Type::VariableArray:
11431 case Type::FunctionProto:
11432 case Type::ExtVector:
11433 llvm_unreachable("Types are eliminated above");
11434
11435 case Type::Pointer:
11436 {
11437 // Merge two pointer types, while trying to preserve typedef info
11438 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
11439 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
11440 if (Unqualified) {
11441 LHSPointee = LHSPointee.getUnqualifiedType();
11442 RHSPointee = RHSPointee.getUnqualifiedType();
11443 }
11444 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
11445 Unqualified);
11446 if (ResultType.isNull())
11447 return {};
11448 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11449 return LHS;
11450 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
11451 return RHS;
11452 return getPointerType(ResultType);
11453 }
11454 case Type::BlockPointer:
11455 {
11456 // Merge two block pointer types, while trying to preserve typedef info
11457 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
11458 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
11459 if (Unqualified) {
11460 LHSPointee = LHSPointee.getUnqualifiedType();
11461 RHSPointee = RHSPointee.getUnqualifiedType();
11462 }
11463 if (getLangOpts().OpenCL) {
11464 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
11465 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
11466 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
11467 // 6.12.5) thus the following check is asymmetric.
11468 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual, *this))
11469 return {};
11470 LHSPteeQual.removeAddressSpace();
11471 RHSPteeQual.removeAddressSpace();
11472 LHSPointee =
11473 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
11474 RHSPointee =
11475 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
11476 }
11477 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
11478 Unqualified);
11479 if (ResultType.isNull())
11480 return {};
11481 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11482 return LHS;
11483 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
11484 return RHS;
11485 return getBlockPointerType(ResultType);
11486 }
11487 case Type::Atomic:
11488 {
11489 // Merge two pointer types, while trying to preserve typedef info
11490 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
11491 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
11492 if (Unqualified) {
11493 LHSValue = LHSValue.getUnqualifiedType();
11494 RHSValue = RHSValue.getUnqualifiedType();
11495 }
11496 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
11497 Unqualified);
11498 if (ResultType.isNull())
11499 return {};
11500 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
11501 return LHS;
11502 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
11503 return RHS;
11504 return getAtomicType(ResultType);
11505 }
11506 case Type::ConstantArray:
11507 {
11508 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
11509 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
11510 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
11511 return {};
11512
11513 QualType LHSElem = getAsArrayType(LHS)->getElementType();
11514 QualType RHSElem = getAsArrayType(RHS)->getElementType();
11515 if (Unqualified) {
11516 LHSElem = LHSElem.getUnqualifiedType();
11517 RHSElem = RHSElem.getUnqualifiedType();
11518 }
11519
11520 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
11521 if (ResultType.isNull())
11522 return {};
11523
11524 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
11525 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
11526
11527 // If either side is a variable array, and both are complete, check whether
11528 // the current dimension is definite.
11529 if (LVAT || RVAT) {
11530 auto SizeFetch = [this](const VariableArrayType* VAT,
11531 const ConstantArrayType* CAT)
11532 -> std::pair<bool,llvm::APInt> {
11533 if (VAT) {
11534 std::optional<llvm::APSInt> TheInt;
11535 Expr *E = VAT->getSizeExpr();
11536 if (E && (TheInt = E->getIntegerConstantExpr(*this)))
11537 return std::make_pair(true, *TheInt);
11538 return std::make_pair(false, llvm::APSInt());
11539 }
11540 if (CAT)
11541 return std::make_pair(true, CAT->getSize());
11542 return std::make_pair(false, llvm::APInt());
11543 };
11544
11545 bool HaveLSize, HaveRSize;
11546 llvm::APInt LSize, RSize;
11547 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
11548 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
11549 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
11550 return {}; // Definite, but unequal, array dimension
11551 }
11552
11553 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
11554 return LHS;
11555 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
11556 return RHS;
11557 if (LCAT)
11558 return getConstantArrayType(ResultType, LCAT->getSize(),
11559 LCAT->getSizeExpr(), ArraySizeModifier(), 0);
11560 if (RCAT)
11561 return getConstantArrayType(ResultType, RCAT->getSize(),
11562 RCAT->getSizeExpr(), ArraySizeModifier(), 0);
11563 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
11564 return LHS;
11565 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
11566 return RHS;
11567 if (LVAT) {
11568 // FIXME: This isn't correct! But tricky to implement because
11569 // the array's size has to be the size of LHS, but the type
11570 // has to be different.
11571 return LHS;
11572 }
11573 if (RVAT) {
11574 // FIXME: This isn't correct! But tricky to implement because
11575 // the array's size has to be the size of RHS, but the type
11576 // has to be different.
11577 return RHS;
11578 }
11579 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
11580 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
11581 return getIncompleteArrayType(ResultType, ArraySizeModifier(), 0);
11582 }
11583 case Type::FunctionNoProto:
11584 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified,
11585 /*AllowCXX=*/false, IsConditionalOperator);
11586 case Type::Record:
11587 case Type::Enum:
11588 return {};
11589 case Type::Builtin:
11590 // Only exactly equal builtin types are compatible, which is tested above.
11591 return {};
11592 case Type::Complex:
11593 // Distinct complex types are incompatible.
11594 return {};
11595 case Type::Vector:
11596 // FIXME: The merged type should be an ExtVector!
11597 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
11598 RHSCan->castAs<VectorType>()))
11599 return LHS;
11600 return {};
11601 case Type::ConstantMatrix:
11603 RHSCan->castAs<ConstantMatrixType>()))
11604 return LHS;
11605 return {};
11606 case Type::ObjCObject: {
11607 // Check if the types are assignment compatible.
11608 // FIXME: This should be type compatibility, e.g. whether
11609 // "LHS x; RHS x;" at global scope is legal.
11611 RHS->castAs<ObjCObjectType>()))
11612 return LHS;
11613 return {};
11614 }
11615 case Type::ObjCObjectPointer:
11616 if (OfBlockPointer) {
11619 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
11620 return LHS;
11621 return {};
11622 }
11625 return LHS;
11626 return {};
11627 case Type::Pipe:
11628 assert(LHS != RHS &&
11629 "Equivalent pipe types should have already been handled!");
11630 return {};
11631 case Type::ArrayParameter:
11632 assert(LHS != RHS &&
11633 "Equivalent ArrayParameter types should have already been handled!");
11634 return {};
11635 case Type::BitInt: {
11636 // Merge two bit-precise int types, while trying to preserve typedef info.
11637 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
11638 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
11639 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
11640 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
11641
11642 // Like unsigned/int, shouldn't have a type if they don't match.
11643 if (LHSUnsigned != RHSUnsigned)
11644 return {};
11645
11646 if (LHSBits != RHSBits)
11647 return {};
11648 return LHS;
11649 }
11650 case Type::HLSLAttributedResource: {
11651 const HLSLAttributedResourceType *LHSTy =
11653 const HLSLAttributedResourceType *RHSTy =
11655 assert(LHSTy->getWrappedType() == RHSTy->getWrappedType() &&
11656 LHSTy->getWrappedType()->isHLSLResourceType() &&
11657 "HLSLAttributedResourceType should always wrap __hlsl_resource_t");
11658
11659 if (LHSTy->getAttrs() == RHSTy->getAttrs() &&
11660 LHSTy->getContainedType() == RHSTy->getContainedType())
11661 return LHS;
11662 return {};
11663 }
11664 }
11665
11666 llvm_unreachable("Invalid Type::Class!");
11667}
11668
11670 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
11671 bool &CanUseFirst, bool &CanUseSecond,
11673 assert(NewParamInfos.empty() && "param info list not empty");
11674 CanUseFirst = CanUseSecond = true;
11675 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
11676 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
11677
11678 // Fast path: if the first type doesn't have ext parameter infos,
11679 // we match if and only if the second type also doesn't have them.
11680 if (!FirstHasInfo && !SecondHasInfo)
11681 return true;
11682
11683 bool NeedParamInfo = false;
11684 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
11685 : SecondFnType->getExtParameterInfos().size();
11686
11687 for (size_t I = 0; I < E; ++I) {
11688 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
11689 if (FirstHasInfo)
11690 FirstParam = FirstFnType->getExtParameterInfo(I);
11691 if (SecondHasInfo)
11692 SecondParam = SecondFnType->getExtParameterInfo(I);
11693
11694 // Cannot merge unless everything except the noescape flag matches.
11695 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
11696 return false;
11697
11698 bool FirstNoEscape = FirstParam.isNoEscape();
11699 bool SecondNoEscape = SecondParam.isNoEscape();
11700 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
11701 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
11702 if (NewParamInfos.back().getOpaqueValue())
11703 NeedParamInfo = true;
11704 if (FirstNoEscape != IsNoEscape)
11705 CanUseFirst = false;
11706 if (SecondNoEscape != IsNoEscape)
11707 CanUseSecond = false;
11708 }
11709
11710 if (!NeedParamInfo)
11711 NewParamInfos.clear();
11712
11713 return true;
11714}
11715
11717 ObjCLayouts[CD] = nullptr;
11718}
11719
11720/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
11721/// 'RHS' attributes and returns the merged version; including for function
11722/// return types.
11724 QualType LHSCan = getCanonicalType(LHS),
11725 RHSCan = getCanonicalType(RHS);
11726 // If two types are identical, they are compatible.
11727 if (LHSCan == RHSCan)
11728 return LHS;
11729 if (RHSCan->isFunctionType()) {
11730 if (!LHSCan->isFunctionType())
11731 return {};
11732 QualType OldReturnType =
11733 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
11734 QualType NewReturnType =
11735 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
11736 QualType ResReturnType =
11737 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
11738 if (ResReturnType.isNull())
11739 return {};
11740 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
11741 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
11742 // In either case, use OldReturnType to build the new function type.
11743 const auto *F = LHS->castAs<FunctionType>();
11744 if (const auto *FPT = cast<FunctionProtoType>(F)) {
11745 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11746 EPI.ExtInfo = getFunctionExtInfo(LHS);
11747 QualType ResultType =
11748 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
11749 return ResultType;
11750 }
11751 }
11752 return {};
11753 }
11754
11755 // If the qualifiers are different, the types can still be merged.
11756 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11757 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11758 if (LQuals != RQuals) {
11759 // If any of these qualifiers are different, we have a type mismatch.
11760 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11761 LQuals.getAddressSpace() != RQuals.getAddressSpace())
11762 return {};
11763
11764 // Exactly one GC qualifier difference is allowed: __strong is
11765 // okay if the other type has no GC qualifier but is an Objective
11766 // C object pointer (i.e. implicitly strong by default). We fix
11767 // this by pretending that the unqualified type was actually
11768 // qualified __strong.
11769 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11770 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11771 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11772
11773 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11774 return {};
11775
11776 if (GC_L == Qualifiers::Strong)
11777 return LHS;
11778 if (GC_R == Qualifiers::Strong)
11779 return RHS;
11780 return {};
11781 }
11782
11783 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
11784 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
11785 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
11786 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
11787 if (ResQT == LHSBaseQT)
11788 return LHS;
11789 if (ResQT == RHSBaseQT)
11790 return RHS;
11791 }
11792 return {};
11793}
11794
11795//===----------------------------------------------------------------------===//
11796// Integer Predicates
11797//===----------------------------------------------------------------------===//
11798
11800 if (const auto *ET = T->getAs<EnumType>())
11801 T = ET->getDecl()->getIntegerType();
11802 if (T->isBooleanType())
11803 return 1;
11804 if (const auto *EIT = T->getAs<BitIntType>())
11805 return EIT->getNumBits();
11806 // For builtin types, just use the standard type sizing method
11807 return (unsigned)getTypeSize(T);
11808}
11809
11811 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
11812 T->isFixedPointType()) &&
11813 "Unexpected type");
11814
11815 // Turn <4 x signed int> -> <4 x unsigned int>
11816 if (const auto *VTy = T->getAs<VectorType>())
11817 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
11818 VTy->getNumElements(), VTy->getVectorKind());
11819
11820 // For _BitInt, return an unsigned _BitInt with same width.
11821 if (const auto *EITy = T->getAs<BitIntType>())
11822 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
11823
11824 // For enums, get the underlying integer type of the enum, and let the general
11825 // integer type signchanging code handle it.
11826 if (const auto *ETy = T->getAs<EnumType>())
11827 T = ETy->getDecl()->getIntegerType();
11828
11829 switch (T->castAs<BuiltinType>()->getKind()) {
11830 case BuiltinType::Char_U:
11831 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
11832 case BuiltinType::Char_S:
11833 case BuiltinType::SChar:
11834 case BuiltinType::Char8:
11835 return UnsignedCharTy;
11836 case BuiltinType::Short:
11837 return UnsignedShortTy;
11838 case BuiltinType::Int:
11839 return UnsignedIntTy;
11840 case BuiltinType::Long:
11841 return UnsignedLongTy;
11842 case BuiltinType::LongLong:
11843 return UnsignedLongLongTy;
11844 case BuiltinType::Int128:
11845 return UnsignedInt128Ty;
11846 // wchar_t is special. It is either signed or not, but when it's signed,
11847 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
11848 // version of its underlying type instead.
11849 case BuiltinType::WChar_S:
11850 return getUnsignedWCharType();
11851
11852 case BuiltinType::ShortAccum:
11853 return UnsignedShortAccumTy;
11854 case BuiltinType::Accum:
11855 return UnsignedAccumTy;
11856 case BuiltinType::LongAccum:
11857 return UnsignedLongAccumTy;
11858 case BuiltinType::SatShortAccum:
11860 case BuiltinType::SatAccum:
11861 return SatUnsignedAccumTy;
11862 case BuiltinType::SatLongAccum:
11864 case BuiltinType::ShortFract:
11865 return UnsignedShortFractTy;
11866 case BuiltinType::Fract:
11867 return UnsignedFractTy;
11868 case BuiltinType::LongFract:
11869 return UnsignedLongFractTy;
11870 case BuiltinType::SatShortFract:
11872 case BuiltinType::SatFract:
11873 return SatUnsignedFractTy;
11874 case BuiltinType::SatLongFract:
11876 default:
11879 "Unexpected signed integer or fixed point type");
11880 return T;
11881 }
11882}
11883
11885 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
11886 T->isFixedPointType()) &&
11887 "Unexpected type");
11888
11889 // Turn <4 x unsigned int> -> <4 x signed int>
11890 if (const auto *VTy = T->getAs<VectorType>())
11891 return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
11892 VTy->getNumElements(), VTy->getVectorKind());
11893
11894 // For _BitInt, return a signed _BitInt with same width.
11895 if (const auto *EITy = T->getAs<BitIntType>())
11896 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
11897
11898 // For enums, get the underlying integer type of the enum, and let the general
11899 // integer type signchanging code handle it.
11900 if (const auto *ETy = T->getAs<EnumType>())
11901 T = ETy->getDecl()->getIntegerType();
11902
11903 switch (T->castAs<BuiltinType>()->getKind()) {
11904 case BuiltinType::Char_S:
11905 // Plain `char` is mapped to `signed char` even if it's already signed
11906 case BuiltinType::Char_U:
11907 case BuiltinType::UChar:
11908 case BuiltinType::Char8:
11909 return SignedCharTy;
11910 case BuiltinType::UShort:
11911 return ShortTy;
11912 case BuiltinType::UInt:
11913 return IntTy;
11914 case BuiltinType::ULong:
11915 return LongTy;
11916 case BuiltinType::ULongLong:
11917 return LongLongTy;
11918 case BuiltinType::UInt128:
11919 return Int128Ty;
11920 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
11921 // there's no matching "signed wchar_t". Therefore we return the signed
11922 // version of its underlying type instead.
11923 case BuiltinType::WChar_U:
11924 return getSignedWCharType();
11925
11926 case BuiltinType::UShortAccum:
11927 return ShortAccumTy;
11928 case BuiltinType::UAccum:
11929 return AccumTy;
11930 case BuiltinType::ULongAccum:
11931 return LongAccumTy;
11932 case BuiltinType::SatUShortAccum:
11933 return SatShortAccumTy;
11934 case BuiltinType::SatUAccum:
11935 return SatAccumTy;
11936 case BuiltinType::SatULongAccum:
11937 return SatLongAccumTy;
11938 case BuiltinType::UShortFract:
11939 return ShortFractTy;
11940 case BuiltinType::UFract:
11941 return FractTy;
11942 case BuiltinType::ULongFract:
11943 return LongFractTy;
11944 case BuiltinType::SatUShortFract:
11945 return SatShortFractTy;
11946 case BuiltinType::SatUFract:
11947 return SatFractTy;
11948 case BuiltinType::SatULongFract:
11949 return SatLongFractTy;
11950 default:
11951 assert(
11953 "Unexpected signed integer or fixed point type");
11954 return T;
11955 }
11956}
11957
11959
11961 QualType ReturnType) {}
11962
11963//===----------------------------------------------------------------------===//
11964// Builtin Type Computation
11965//===----------------------------------------------------------------------===//
11966
11967/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
11968/// pointer over the consumed characters. This returns the resultant type. If
11969/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
11970/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
11971/// a vector of "i*".
11972///
11973/// RequiresICE is filled in on return to indicate whether the value is required
11974/// to be an Integer Constant Expression.
11975static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
11977 bool &RequiresICE,
11978 bool AllowTypeModifiers) {
11979 // Modifiers.
11980 int HowLong = 0;
11981 bool Signed = false, Unsigned = false;
11982 RequiresICE = false;
11983
11984 // Read the prefixed modifiers first.
11985 bool Done = false;
11986 #ifndef NDEBUG
11987 bool IsSpecial = false;
11988 #endif
11989 while (!Done) {
11990 switch (*Str++) {
11991 default: Done = true; --Str; break;
11992 case 'I':
11993 RequiresICE = true;
11994 break;
11995 case 'S':
11996 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
11997 assert(!Signed && "Can't use 'S' modifier multiple times!");
11998 Signed = true;
11999 break;
12000 case 'U':
12001 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
12002 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
12003 Unsigned = true;
12004 break;
12005 case 'L':
12006 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
12007 assert(HowLong <= 2 && "Can't have LLLL modifier");
12008 ++HowLong;
12009 break;
12010 case 'N':
12011 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
12012 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12013 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
12014 #ifndef NDEBUG
12015 IsSpecial = true;
12016 #endif
12017 if (Context.getTargetInfo().getLongWidth() == 32)
12018 ++HowLong;
12019 break;
12020 case 'W':
12021 // This modifier represents int64 type.
12022 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12023 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
12024 #ifndef NDEBUG
12025 IsSpecial = true;
12026 #endif
12027 switch (Context.getTargetInfo().getInt64Type()) {
12028 default:
12029 llvm_unreachable("Unexpected integer type");
12031 HowLong = 1;
12032 break;
12034 HowLong = 2;
12035 break;
12036 }
12037 break;
12038 case 'Z':
12039 // This modifier represents int32 type.
12040 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12041 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
12042 #ifndef NDEBUG
12043 IsSpecial = true;
12044 #endif
12045 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
12046 default:
12047 llvm_unreachable("Unexpected integer type");
12049 HowLong = 0;
12050 break;
12052 HowLong = 1;
12053 break;
12055 HowLong = 2;
12056 break;
12057 }
12058 break;
12059 case 'O':
12060 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12061 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
12062 #ifndef NDEBUG
12063 IsSpecial = true;
12064 #endif
12065 if (Context.getLangOpts().OpenCL)
12066 HowLong = 1;
12067 else
12068 HowLong = 2;
12069 break;
12070 }
12071 }
12072
12073 QualType Type;
12074
12075 // Read the base type.
12076 switch (*Str++) {
12077 default: llvm_unreachable("Unknown builtin type letter!");
12078 case 'x':
12079 assert(HowLong == 0 && !Signed && !Unsigned &&
12080 "Bad modifiers used with 'x'!");
12081 Type = Context.Float16Ty;
12082 break;
12083 case 'y':
12084 assert(HowLong == 0 && !Signed && !Unsigned &&
12085 "Bad modifiers used with 'y'!");
12086 Type = Context.BFloat16Ty;
12087 break;
12088 case 'v':
12089 assert(HowLong == 0 && !Signed && !Unsigned &&
12090 "Bad modifiers used with 'v'!");
12091 Type = Context.VoidTy;
12092 break;
12093 case 'h':
12094 assert(HowLong == 0 && !Signed && !Unsigned &&
12095 "Bad modifiers used with 'h'!");
12096 Type = Context.HalfTy;
12097 break;
12098 case 'f':
12099 assert(HowLong == 0 && !Signed && !Unsigned &&
12100 "Bad modifiers used with 'f'!");
12101 Type = Context.FloatTy;
12102 break;
12103 case 'd':
12104 assert(HowLong < 3 && !Signed && !Unsigned &&
12105 "Bad modifiers used with 'd'!");
12106 if (HowLong == 1)
12107 Type = Context.LongDoubleTy;
12108 else if (HowLong == 2)
12109 Type = Context.Float128Ty;
12110 else
12111 Type = Context.DoubleTy;
12112 break;
12113 case 's':
12114 assert(HowLong == 0 && "Bad modifiers used with 's'!");
12115 if (Unsigned)
12116 Type = Context.UnsignedShortTy;
12117 else
12118 Type = Context.ShortTy;
12119 break;
12120 case 'i':
12121 if (HowLong == 3)
12122 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
12123 else if (HowLong == 2)
12124 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
12125 else if (HowLong == 1)
12126 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
12127 else
12128 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
12129 break;
12130 case 'c':
12131 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
12132 if (Signed)
12133 Type = Context.SignedCharTy;
12134 else if (Unsigned)
12135 Type = Context.UnsignedCharTy;
12136 else
12137 Type = Context.CharTy;
12138 break;
12139 case 'b': // boolean
12140 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
12141 Type = Context.BoolTy;
12142 break;
12143 case 'z': // size_t.
12144 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
12145 Type = Context.getSizeType();
12146 break;
12147 case 'w': // wchar_t.
12148 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
12149 Type = Context.getWideCharType();
12150 break;
12151 case 'F':
12152 Type = Context.getCFConstantStringType();
12153 break;
12154 case 'G':
12155 Type = Context.getObjCIdType();
12156 break;
12157 case 'H':
12158 Type = Context.getObjCSelType();
12159 break;
12160 case 'M':
12161 Type = Context.getObjCSuperType();
12162 break;
12163 case 'a':
12164 Type = Context.getBuiltinVaListType();
12165 assert(!Type.isNull() && "builtin va list type not initialized!");
12166 break;
12167 case 'A':
12168 // This is a "reference" to a va_list; however, what exactly
12169 // this means depends on how va_list is defined. There are two
12170 // different kinds of va_list: ones passed by value, and ones
12171 // passed by reference. An example of a by-value va_list is
12172 // x86, where va_list is a char*. An example of by-ref va_list
12173 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
12174 // we want this argument to be a char*&; for x86-64, we want
12175 // it to be a __va_list_tag*.
12176 Type = Context.getBuiltinVaListType();
12177 assert(!Type.isNull() && "builtin va list type not initialized!");
12178 if (Type->isArrayType())
12179 Type = Context.getArrayDecayedType(Type);
12180 else
12181 Type = Context.getLValueReferenceType(Type);
12182 break;
12183 case 'q': {
12184 char *End;
12185 unsigned NumElements = strtoul(Str, &End, 10);
12186 assert(End != Str && "Missing vector size");
12187 Str = End;
12188
12189 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12190 RequiresICE, false);
12191 assert(!RequiresICE && "Can't require vector ICE");
12192
12193 Type = Context.getScalableVectorType(ElementType, NumElements);
12194 break;
12195 }
12196 case 'Q': {
12197 switch (*Str++) {
12198 case 'a': {
12199 Type = Context.SveCountTy;
12200 break;
12201 }
12202 case 'b': {
12203 Type = Context.AMDGPUBufferRsrcTy;
12204 break;
12205 }
12206 default:
12207 llvm_unreachable("Unexpected target builtin type");
12208 }
12209 break;
12210 }
12211 case 'V': {
12212 char *End;
12213 unsigned NumElements = strtoul(Str, &End, 10);
12214 assert(End != Str && "Missing vector size");
12215 Str = End;
12216
12217 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12218 RequiresICE, false);
12219 assert(!RequiresICE && "Can't require vector ICE");
12220
12221 // TODO: No way to make AltiVec vectors in builtins yet.
12222 Type = Context.getVectorType(ElementType, NumElements, VectorKind::Generic);
12223 break;
12224 }
12225 case 'E': {
12226 char *End;
12227
12228 unsigned NumElements = strtoul(Str, &End, 10);
12229 assert(End != Str && "Missing vector size");
12230
12231 Str = End;
12232
12233 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12234 false);
12235 Type = Context.getExtVectorType(ElementType, NumElements);
12236 break;
12237 }
12238 case 'X': {
12239 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12240 false);
12241 assert(!RequiresICE && "Can't require complex ICE");
12242 Type = Context.getComplexType(ElementType);
12243 break;
12244 }
12245 case 'Y':
12246 Type = Context.getPointerDiffType();
12247 break;
12248 case 'P':
12249 Type = Context.getFILEType();
12250 if (Type.isNull()) {
12252 return {};
12253 }
12254 break;
12255 case 'J':
12256 if (Signed)
12257 Type = Context.getsigjmp_bufType();
12258 else
12259 Type = Context.getjmp_bufType();
12260
12261 if (Type.isNull()) {
12263 return {};
12264 }
12265 break;
12266 case 'K':
12267 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
12268 Type = Context.getucontext_tType();
12269
12270 if (Type.isNull()) {
12272 return {};
12273 }
12274 break;
12275 case 'p':
12276 Type = Context.getProcessIDType();
12277 break;
12278 }
12279
12280 // If there are modifiers and if we're allowed to parse them, go for it.
12281 Done = !AllowTypeModifiers;
12282 while (!Done) {
12283 switch (char c = *Str++) {
12284 default: Done = true; --Str; break;
12285 case '*':
12286 case '&': {
12287 // Both pointers and references can have their pointee types
12288 // qualified with an address space.
12289 char *End;
12290 unsigned AddrSpace = strtoul(Str, &End, 10);
12291 if (End != Str) {
12292 // Note AddrSpace == 0 is not the same as an unspecified address space.
12293 Type = Context.getAddrSpaceQualType(
12294 Type,
12295 Context.getLangASForBuiltinAddressSpace(AddrSpace));
12296 Str = End;
12297 }
12298 if (c == '*')
12299 Type = Context.getPointerType(Type);
12300 else
12301 Type = Context.getLValueReferenceType(Type);
12302 break;
12303 }
12304 // FIXME: There's no way to have a built-in with an rvalue ref arg.
12305 case 'C':
12306 Type = Type.withConst();
12307 break;
12308 case 'D':
12309 Type = Context.getVolatileType(Type);
12310 break;
12311 case 'R':
12312 Type = Type.withRestrict();
12313 break;
12314 }
12315 }
12316
12317 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
12318 "Integer constant 'I' type must be an integer");
12319
12320 return Type;
12321}
12322
12323// On some targets such as PowerPC, some of the builtins are defined with custom
12324// type descriptors for target-dependent types. These descriptors are decoded in
12325// other functions, but it may be useful to be able to fall back to default
12326// descriptor decoding to define builtins mixing target-dependent and target-
12327// independent types. This function allows decoding one type descriptor with
12328// default decoding.
12329QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
12330 GetBuiltinTypeError &Error, bool &RequireICE,
12331 bool AllowTypeModifiers) const {
12332 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
12333}
12334
12335/// GetBuiltinType - Return the type for the specified builtin.
12337 GetBuiltinTypeError &Error,
12338 unsigned *IntegerConstantArgs) const {
12339 const char *TypeStr = BuiltinInfo.getTypeString(Id);
12340 if (TypeStr[0] == '\0') {
12341 Error = GE_Missing_type;
12342 return {};
12343 }
12344
12345 SmallVector<QualType, 8> ArgTypes;
12346
12347 bool RequiresICE = false;
12348 Error = GE_None;
12349 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
12350 RequiresICE, true);
12351 if (Error != GE_None)
12352 return {};
12353
12354 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
12355
12356 while (TypeStr[0] && TypeStr[0] != '.') {
12357 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
12358 if (Error != GE_None)
12359 return {};
12360
12361 // If this argument is required to be an IntegerConstantExpression and the
12362 // caller cares, fill in the bitmask we return.
12363 if (RequiresICE && IntegerConstantArgs)
12364 *IntegerConstantArgs |= 1 << ArgTypes.size();
12365
12366 // Do array -> pointer decay. The builtin should use the decayed type.
12367 if (Ty->isArrayType())
12368 Ty = getArrayDecayedType(Ty);
12369
12370 ArgTypes.push_back(Ty);
12371 }
12372
12373 if (Id == Builtin::BI__GetExceptionInfo)
12374 return {};
12375
12376 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
12377 "'.' should only occur at end of builtin type list!");
12378
12379 bool Variadic = (TypeStr[0] == '.');
12380
12382 Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
12383 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
12384
12385
12386 // We really shouldn't be making a no-proto type here.
12387 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
12388 return getFunctionNoProtoType(ResType, EI);
12389
12391 EPI.ExtInfo = EI;
12392 EPI.Variadic = Variadic;
12394 EPI.ExceptionSpec.Type =
12396
12397 return getFunctionType(ResType, ArgTypes, EPI);
12398}
12399
12401 const FunctionDecl *FD) {
12402 if (!FD->isExternallyVisible())
12403 return GVA_Internal;
12404
12405 // Non-user-provided functions get emitted as weak definitions with every
12406 // use, no matter whether they've been explicitly instantiated etc.
12407 if (!FD->isUserProvided())
12408 return GVA_DiscardableODR;
12409
12411 switch (FD->getTemplateSpecializationKind()) {
12412 case TSK_Undeclared:
12415 break;
12416
12418 return GVA_StrongODR;
12419
12420 // C++11 [temp.explicit]p10:
12421 // [ Note: The intent is that an inline function that is the subject of
12422 // an explicit instantiation declaration will still be implicitly
12423 // instantiated when used so that the body can be considered for
12424 // inlining, but that no out-of-line copy of the inline function would be
12425 // generated in the translation unit. -- end note ]
12428
12431 break;
12432 }
12433
12434 if (!FD->isInlined())
12435 return External;
12436
12437 if ((!Context.getLangOpts().CPlusPlus &&
12438 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12439 !FD->hasAttr<DLLExportAttr>()) ||
12440 FD->hasAttr<GNUInlineAttr>()) {
12441 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
12442
12443 // GNU or C99 inline semantics. Determine whether this symbol should be
12444 // externally visible.
12446 return External;
12447
12448 // C99 inline semantics, where the symbol is not externally visible.
12450 }
12451
12452 // Functions specified with extern and inline in -fms-compatibility mode
12453 // forcibly get emitted. While the body of the function cannot be later
12454 // replaced, the function definition cannot be discarded.
12455 if (FD->isMSExternInline())
12456 return GVA_StrongODR;
12457
12458 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12459 isa<CXXConstructorDecl>(FD) &&
12460 cast<CXXConstructorDecl>(FD)->isInheritingConstructor())
12461 // Our approach to inheriting constructors is fundamentally different from
12462 // that used by the MS ABI, so keep our inheriting constructor thunks
12463 // internal rather than trying to pick an unambiguous mangling for them.
12464 return GVA_Internal;
12465
12466 return GVA_DiscardableODR;
12467}
12468
12470 const Decl *D, GVALinkage L) {
12471 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
12472 // dllexport/dllimport on inline functions.
12473 if (D->hasAttr<DLLImportAttr>()) {
12474 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
12476 } else if (D->hasAttr<DLLExportAttr>()) {
12477 if (L == GVA_DiscardableODR)
12478 return GVA_StrongODR;
12479 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
12480 // Device-side functions with __global__ attribute must always be
12481 // visible externally so they can be launched from host.
12482 if (D->hasAttr<CUDAGlobalAttr>() &&
12483 (L == GVA_DiscardableODR || L == GVA_Internal))
12484 return GVA_StrongODR;
12485 // Single source offloading languages like CUDA/HIP need to be able to
12486 // access static device variables from host code of the same compilation
12487 // unit. This is done by externalizing the static variable with a shared
12488 // name between the host and device compilation which is the same for the
12489 // same compilation unit whereas different among different compilation
12490 // units.
12491 if (Context.shouldExternalize(D))
12492 return GVA_StrongExternal;
12493 }
12494 return L;
12495}
12496
12497/// Adjust the GVALinkage for a declaration based on what an external AST source
12498/// knows about whether there can be other definitions of this declaration.
12499static GVALinkage
12501 GVALinkage L) {
12502 ExternalASTSource *Source = Ctx.getExternalSource();
12503 if (!Source)
12504 return L;
12505
12506 switch (Source->hasExternalDefinitions(D)) {
12508 // Other translation units rely on us to provide the definition.
12509 if (L == GVA_DiscardableODR)
12510 return GVA_StrongODR;
12511 break;
12512
12515
12517 break;
12518 }
12519 return L;
12520}
12521
12525 basicGVALinkageForFunction(*this, FD)));
12526}
12527
12529 const VarDecl *VD) {
12530 // As an extension for interactive REPLs, make sure constant variables are
12531 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
12532 // marking them as internal.
12533 if (Context.getLangOpts().CPlusPlus &&
12534 Context.getLangOpts().IncrementalExtensions &&
12535 VD->getType().isConstQualified() &&
12536 !VD->getType().isVolatileQualified() && !VD->isInline() &&
12537 !isa<VarTemplateSpecializationDecl>(VD) && !VD->getDescribedVarTemplate())
12538 return GVA_DiscardableODR;
12539
12540 if (!VD->isExternallyVisible())
12541 return GVA_Internal;
12542
12543 if (VD->isStaticLocal()) {
12544 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
12545 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
12546 LexicalContext = LexicalContext->getLexicalParent();
12547
12548 // ObjC Blocks can create local variables that don't have a FunctionDecl
12549 // LexicalContext.
12550 if (!LexicalContext)
12551 return GVA_DiscardableODR;
12552
12553 // Otherwise, let the static local variable inherit its linkage from the
12554 // nearest enclosing function.
12555 auto StaticLocalLinkage =
12556 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
12557
12558 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
12559 // be emitted in any object with references to the symbol for the object it
12560 // contains, whether inline or out-of-line."
12561 // Similar behavior is observed with MSVC. An alternative ABI could use
12562 // StrongODR/AvailableExternally to match the function, but none are
12563 // known/supported currently.
12564 if (StaticLocalLinkage == GVA_StrongODR ||
12565 StaticLocalLinkage == GVA_AvailableExternally)
12566 return GVA_DiscardableODR;
12567 return StaticLocalLinkage;
12568 }
12569
12570 // MSVC treats in-class initialized static data members as definitions.
12571 // By giving them non-strong linkage, out-of-line definitions won't
12572 // cause link errors.
12574 return GVA_DiscardableODR;
12575
12576 // Most non-template variables have strong linkage; inline variables are
12577 // linkonce_odr or (occasionally, for compatibility) weak_odr.
12578 GVALinkage StrongLinkage;
12579 switch (Context.getInlineVariableDefinitionKind(VD)) {
12581 StrongLinkage = GVA_StrongExternal;
12582 break;
12585 StrongLinkage = GVA_DiscardableODR;
12586 break;
12588 StrongLinkage = GVA_StrongODR;
12589 break;
12590 }
12591
12592 switch (VD->getTemplateSpecializationKind()) {
12593 case TSK_Undeclared:
12594 return StrongLinkage;
12595
12597 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12598 VD->isStaticDataMember()
12600 : StrongLinkage;
12601
12603 return GVA_StrongODR;
12604
12607
12609 return GVA_DiscardableODR;
12610 }
12611
12612 llvm_unreachable("Invalid Linkage!");
12613}
12614
12618 basicGVALinkageForVariable(*this, VD)));
12619}
12620
12622 if (const auto *VD = dyn_cast<VarDecl>(D)) {
12623 if (!VD->isFileVarDecl())
12624 return false;
12625 // Global named register variables (GNU extension) are never emitted.
12626 if (VD->getStorageClass() == SC_Register)
12627 return false;
12628 if (VD->getDescribedVarTemplate() ||
12629 isa<VarTemplatePartialSpecializationDecl>(VD))
12630 return false;
12631 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
12632 // We never need to emit an uninstantiated function template.
12633 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12634 return false;
12635 } else if (isa<PragmaCommentDecl>(D))
12636 return true;
12637 else if (isa<PragmaDetectMismatchDecl>(D))
12638 return true;
12639 else if (isa<OMPRequiresDecl>(D))
12640 return true;
12641 else if (isa<OMPThreadPrivateDecl>(D))
12642 return !D->getDeclContext()->isDependentContext();
12643 else if (isa<OMPAllocateDecl>(D))
12644 return !D->getDeclContext()->isDependentContext();
12645 else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D))
12646 return !D->getDeclContext()->isDependentContext();
12647 else if (isa<ImportDecl>(D))
12648 return true;
12649 else
12650 return false;
12651
12652 // If this is a member of a class template, we do not need to emit it.
12654 return false;
12655
12656 // Weak references don't produce any output by themselves.
12657 if (D->hasAttr<WeakRefAttr>())
12658 return false;
12659
12660 // Aliases and used decls are required.
12661 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
12662 return true;
12663
12664 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
12665 // Forward declarations aren't required.
12666 if (!FD->doesThisDeclarationHaveABody())
12667 return FD->doesDeclarationForceExternallyVisibleDefinition();
12668
12669 // Constructors and destructors are required.
12670 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
12671 return true;
12672
12673 // The key function for a class is required. This rule only comes
12674 // into play when inline functions can be key functions, though.
12675 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
12676 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
12677 const CXXRecordDecl *RD = MD->getParent();
12678 if (MD->isOutOfLine() && RD->isDynamicClass()) {
12679 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
12680 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
12681 return true;
12682 }
12683 }
12684 }
12685
12687
12688 // static, static inline, always_inline, and extern inline functions can
12689 // always be deferred. Normal inline functions can be deferred in C99/C++.
12690 // Implicit template instantiations can also be deferred in C++.
12692 }
12693
12694 const auto *VD = cast<VarDecl>(D);
12695 assert(VD->isFileVarDecl() && "Expected file scoped var");
12696
12697 // If the decl is marked as `declare target to`, it should be emitted for the
12698 // host and for the device.
12699 if (LangOpts.OpenMP &&
12700 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
12701 return true;
12702
12703 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
12705 return false;
12706
12707 if (VD->shouldEmitInExternalSource())
12708 return false;
12709
12710 // Variables that can be needed in other TUs are required.
12713 return true;
12714
12715 // We never need to emit a variable that is available in another TU.
12717 return false;
12718
12719 // Variables that have destruction with side-effects are required.
12720 if (VD->needsDestruction(*this))
12721 return true;
12722
12723 // Variables that have initialization with side-effects are required.
12724 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
12725 // We can get a value-dependent initializer during error recovery.
12726 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
12727 return true;
12728
12729 // Likewise, variables with tuple-like bindings are required if their
12730 // bindings have side-effects.
12731 if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
12732 for (const auto *BD : DD->bindings())
12733 if (const auto *BindingVD = BD->getHoldingVar())
12734 if (DeclMustBeEmitted(BindingVD))
12735 return true;
12736
12737 return false;
12738}
12739
12741 const FunctionDecl *FD,
12742 llvm::function_ref<void(FunctionDecl *)> Pred) const {
12743 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
12744 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
12745 FD = FD->getMostRecentDecl();
12746 // FIXME: The order of traversal here matters and depends on the order of
12747 // lookup results, which happens to be (mostly) oldest-to-newest, but we
12748 // shouldn't rely on that.
12749 for (auto *CurDecl :
12751 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
12752 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
12753 SeenDecls.insert(CurFD).second) {
12754 Pred(CurFD);
12755 }
12756 }
12757}
12758
12760 bool IsCXXMethod,
12761 bool IsBuiltin) const {
12762 // Pass through to the C++ ABI object
12763 if (IsCXXMethod)
12764 return ABI->getDefaultMethodCallConv(IsVariadic);
12765
12766 // Builtins ignore user-specified default calling convention and remain the
12767 // Target's default calling convention.
12768 if (!IsBuiltin) {
12769 switch (LangOpts.getDefaultCallingConv()) {
12771 break;
12773 return CC_C;
12775 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
12776 return CC_X86FastCall;
12777 break;
12779 if (!IsVariadic)
12780 return CC_X86StdCall;
12781 break;
12783 // __vectorcall cannot be applied to variadic functions.
12784 if (!IsVariadic)
12785 return CC_X86VectorCall;
12786 break;
12788 // __regcall cannot be applied to variadic functions.
12789 if (!IsVariadic)
12790 return CC_X86RegCall;
12791 break;
12793 if (!IsVariadic)
12794 return CC_M68kRTD;
12795 break;
12796 }
12797 }
12798 return Target->getDefaultCallingConv();
12799}
12800
12802 // Pass through to the C++ ABI object
12803 return ABI->isNearlyEmpty(RD);
12804}
12805
12807 if (!VTContext.get()) {
12808 auto ABI = Target->getCXXABI();
12809 if (ABI.isMicrosoft())
12810 VTContext.reset(new MicrosoftVTableContext(*this));
12811 else {
12812 auto ComponentLayout = getLangOpts().RelativeCXXABIVTables
12815 VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout));
12816 }
12817 }
12818 return VTContext.get();
12819}
12820
12822 if (!T)
12823 T = Target;
12824 switch (T->getCXXABI().getKind()) {
12825 case TargetCXXABI::AppleARM64:
12826 case TargetCXXABI::Fuchsia:
12827 case TargetCXXABI::GenericAArch64:
12828 case TargetCXXABI::GenericItanium:
12829 case TargetCXXABI::GenericARM:
12830 case TargetCXXABI::GenericMIPS:
12831 case TargetCXXABI::iOS:
12832 case TargetCXXABI::WebAssembly:
12833 case TargetCXXABI::WatchOS:
12834 case TargetCXXABI::XL:
12836 case TargetCXXABI::Microsoft:
12838 }
12839 llvm_unreachable("Unsupported ABI");
12840}
12841
12843 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
12844 "Device mangle context does not support Microsoft mangling.");
12845 switch (T.getCXXABI().getKind()) {
12846 case TargetCXXABI::AppleARM64:
12847 case TargetCXXABI::Fuchsia:
12848 case TargetCXXABI::GenericAArch64:
12849 case TargetCXXABI::GenericItanium:
12850 case TargetCXXABI::GenericARM:
12851 case TargetCXXABI::GenericMIPS:
12852 case TargetCXXABI::iOS:
12853 case TargetCXXABI::WebAssembly:
12854 case TargetCXXABI::WatchOS:
12855 case TargetCXXABI::XL:
12857 *this, getDiagnostics(),
12858 [](ASTContext &, const NamedDecl *ND) -> std::optional<unsigned> {
12859 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
12860 return RD->getDeviceLambdaManglingNumber();
12861 return std::nullopt;
12862 },
12863 /*IsAux=*/true);
12864 case TargetCXXABI::Microsoft:
12866 /*IsAux=*/true);
12867 }
12868 llvm_unreachable("Unsupported ABI");
12869}
12870
12871CXXABI::~CXXABI() = default;
12872
12874 return ASTRecordLayouts.getMemorySize() +
12875 llvm::capacity_in_bytes(ObjCLayouts) +
12876 llvm::capacity_in_bytes(KeyFunctions) +
12877 llvm::capacity_in_bytes(ObjCImpls) +
12878 llvm::capacity_in_bytes(BlockVarCopyInits) +
12879 llvm::capacity_in_bytes(DeclAttrs) +
12880 llvm::capacity_in_bytes(TemplateOrInstantiation) +
12881 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
12882 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
12883 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
12884 llvm::capacity_in_bytes(OverriddenMethods) +
12885 llvm::capacity_in_bytes(Types) +
12886 llvm::capacity_in_bytes(VariableArrayTypes);
12887}
12888
12889/// getIntTypeForBitwidth -
12890/// sets integer QualTy according to specified details:
12891/// bitwidth, signed/unsigned.
12892/// Returns empty type if there is no appropriate target types.
12894 unsigned Signed) const {
12896 CanQualType QualTy = getFromTargetType(Ty);
12897 if (!QualTy && DestWidth == 128)
12898 return Signed ? Int128Ty : UnsignedInt128Ty;
12899 return QualTy;
12900}
12901
12902/// getRealTypeForBitwidth -
12903/// sets floating point QualTy according to specified bitwidth.
12904/// Returns empty type if there is no appropriate target types.
12906 FloatModeKind ExplicitType) const {
12907 FloatModeKind Ty =
12908 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
12909 switch (Ty) {
12911 return HalfTy;
12913 return FloatTy;
12915 return DoubleTy;
12917 return LongDoubleTy;
12919 return Float128Ty;
12921 return Ibm128Ty;
12923 return {};
12924 }
12925
12926 llvm_unreachable("Unhandled TargetInfo::RealType value");
12927}
12928
12929void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
12930 if (Number <= 1)
12931 return;
12932
12933 MangleNumbers[ND] = Number;
12934
12935 if (Listener)
12936 Listener->AddedManglingNumber(ND, Number);
12937}
12938
12940 bool ForAuxTarget) const {
12941 auto I = MangleNumbers.find(ND);
12942 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
12943 // CUDA/HIP host compilation encodes host and device mangling numbers
12944 // as lower and upper half of 32 bit integer.
12945 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
12946 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
12947 } else {
12948 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
12949 "number for aux target");
12950 }
12951 return Res > 1 ? Res : 1;
12952}
12953
12954void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
12955 if (Number <= 1)
12956 return;
12957
12958 StaticLocalNumbers[VD] = Number;
12959
12960 if (Listener)
12961 Listener->AddedStaticLocalNumbers(VD, Number);
12962}
12963
12965 auto I = StaticLocalNumbers.find(VD);
12966 return I != StaticLocalNumbers.end() ? I->second : 1;
12967}
12968
12971 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
12972 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
12973 if (!MCtx)
12975 return *MCtx;
12976}
12977
12980 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
12981 std::unique_ptr<MangleNumberingContext> &MCtx =
12982 ExtraMangleNumberingContexts[D];
12983 if (!MCtx)
12985 return *MCtx;
12986}
12987
12988std::unique_ptr<MangleNumberingContext>
12990 return ABI->createMangleNumberingContext();
12991}
12992
12993const CXXConstructorDecl *
12995 return ABI->getCopyConstructorForExceptionObject(
12996 cast<CXXRecordDecl>(RD->getFirstDecl()));
12997}
12998
13000 CXXConstructorDecl *CD) {
13001 return ABI->addCopyConstructorForExceptionObject(
13002 cast<CXXRecordDecl>(RD->getFirstDecl()),
13003 cast<CXXConstructorDecl>(CD->getFirstDecl()));
13004}
13005
13007 TypedefNameDecl *DD) {
13008 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
13009}
13010
13013 return ABI->getTypedefNameForUnnamedTagDecl(TD);
13014}
13015
13017 DeclaratorDecl *DD) {
13018 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
13019}
13020
13022 return ABI->getDeclaratorForUnnamedTagDecl(TD);
13023}
13024
13025void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
13026 ParamIndices[D] = index;
13027}
13028
13030 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
13031 assert(I != ParamIndices.end() &&
13032 "ParmIndices lacks entry set by ParmVarDecl");
13033 return I->second;
13034}
13035
13037 unsigned Length) const {
13038 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
13039 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
13040 EltTy = EltTy.withConst();
13041
13042 EltTy = adjustStringLiteralBaseType(EltTy);
13043
13044 // Get an array type for the string, according to C99 6.4.5. This includes
13045 // the null terminator character.
13046 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
13047 ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
13048}
13049
13052 StringLiteral *&Result = StringLiteralCache[Key];
13053 if (!Result)
13055 *this, Key, StringLiteralKind::Ordinary,
13056 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
13057 SourceLocation());
13058 return Result;
13059}
13060
13061MSGuidDecl *
13063 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
13064
13065 llvm::FoldingSetNodeID ID;
13066 MSGuidDecl::Profile(ID, Parts);
13067
13068 void *InsertPos;
13069 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
13070 return Existing;
13071
13072 QualType GUIDType = getMSGuidType().withConst();
13073 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
13074 MSGuidDecls.InsertNode(New, InsertPos);
13075 return New;
13076}
13077
13080 const APValue &APVal) const {
13081 llvm::FoldingSetNodeID ID;
13083
13084 void *InsertPos;
13085 if (UnnamedGlobalConstantDecl *Existing =
13086 UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos))
13087 return Existing;
13088
13090 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
13091 UnnamedGlobalConstantDecls.InsertNode(New, InsertPos);
13092 return New;
13093}
13094
13097 assert(T->isRecordType() && "template param object of unexpected type");
13098
13099 // C++ [temp.param]p8:
13100 // [...] a static storage duration object of type 'const T' [...]
13101 T.addConst();
13102
13103 llvm::FoldingSetNodeID ID;
13105
13106 void *InsertPos;
13107 if (TemplateParamObjectDecl *Existing =
13108 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
13109 return Existing;
13110
13111 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
13112 TemplateParamObjectDecls.InsertNode(New, InsertPos);
13113 return New;
13114}
13115
13117 const llvm::Triple &T = getTargetInfo().getTriple();
13118 if (!T.isOSDarwin())
13119 return false;
13120
13121 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
13122 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
13123 return false;
13124
13125 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
13126 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
13127 uint64_t Size = sizeChars.getQuantity();
13128 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
13129 unsigned Align = alignChars.getQuantity();
13130 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
13131 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
13132}
13133
13134bool
13136 const ObjCMethodDecl *MethodImpl) {
13137 // No point trying to match an unavailable/deprecated mothod.
13138 if (MethodDecl->hasAttr<UnavailableAttr>()
13139 || MethodDecl->hasAttr<DeprecatedAttr>())
13140 return false;
13141 if (MethodDecl->getObjCDeclQualifier() !=
13142 MethodImpl->getObjCDeclQualifier())
13143 return false;
13144 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
13145 return false;
13146
13147 if (MethodDecl->param_size() != MethodImpl->param_size())
13148 return false;
13149
13150 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
13151 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
13152 EF = MethodDecl->param_end();
13153 IM != EM && IF != EF; ++IM, ++IF) {
13154 const ParmVarDecl *DeclVar = (*IF);
13155 const ParmVarDecl *ImplVar = (*IM);
13156 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
13157 return false;
13158 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
13159 return false;
13160 }
13161
13162 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
13163}
13164
13166 LangAS AS;
13168 AS = LangAS::Default;
13169 else
13170 AS = QT->getPointeeType().getAddressSpace();
13171
13173}
13174
13177}
13178
13179bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
13180 if (X == Y)
13181 return true;
13182 if (!X || !Y)
13183 return false;
13184 llvm::FoldingSetNodeID IDX, IDY;
13185 X->Profile(IDX, *this, /*Canonical=*/true);
13186 Y->Profile(IDY, *this, /*Canonical=*/true);
13187 return IDX == IDY;
13188}
13189
13190// The getCommon* helpers return, for given 'same' X and Y entities given as
13191// inputs, another entity which is also the 'same' as the inputs, but which
13192// is closer to the canonical form of the inputs, each according to a given
13193// criteria.
13194// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
13195// the regular ones.
13196
13198 if (!declaresSameEntity(X, Y))
13199 return nullptr;
13200 for (const Decl *DX : X->redecls()) {
13201 // If we reach Y before reaching the first decl, that means X is older.
13202 if (DX == Y)
13203 return X;
13204 // If we reach the first decl, then Y is older.
13205 if (DX->isFirstDecl())
13206 return Y;
13207 }
13208 llvm_unreachable("Corrupt redecls chain");
13209}
13210
13211template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13212static T *getCommonDecl(T *X, T *Y) {
13213 return cast_or_null<T>(
13214 getCommonDecl(const_cast<Decl *>(cast_or_null<Decl>(X)),
13215 const_cast<Decl *>(cast_or_null<Decl>(Y))));
13216}
13217
13218template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13219static T *getCommonDeclChecked(T *X, T *Y) {
13220 return cast<T>(getCommonDecl(const_cast<Decl *>(cast<Decl>(X)),
13221 const_cast<Decl *>(cast<Decl>(Y))));
13222}
13223
13225 TemplateName Y,
13226 bool IgnoreDeduced = false) {
13227 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
13228 return X;
13229 // FIXME: There are cases here where we could find a common template name
13230 // with more sugar. For example one could be a SubstTemplateTemplate*
13231 // replacing the other.
13232 TemplateName CX = Ctx.getCanonicalTemplateName(X, IgnoreDeduced);
13233 if (CX.getAsVoidPointer() !=
13235 return TemplateName();
13236 return CX;
13237}
13238
13241 bool IgnoreDeduced) {
13242 TemplateName R = getCommonTemplateName(Ctx, X, Y, IgnoreDeduced);
13243 assert(R.getAsVoidPointer() != nullptr);
13244 return R;
13245}
13246
13248 ArrayRef<QualType> Ys, bool Unqualified = false) {
13249 assert(Xs.size() == Ys.size());
13250 SmallVector<QualType, 8> Rs(Xs.size());
13251 for (size_t I = 0; I < Rs.size(); ++I)
13252 Rs[I] = Ctx.getCommonSugaredType(Xs[I], Ys[I], Unqualified);
13253 return Rs;
13254}
13255
13256template <class T>
13257static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
13258 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
13259 : SourceLocation();
13260}
13261
13263 const TemplateArgument &X,
13264 const TemplateArgument &Y) {
13265 if (X.getKind() != Y.getKind())
13266 return TemplateArgument();
13267
13268 switch (X.getKind()) {
13270 if (!Ctx.hasSameType(X.getAsType(), Y.getAsType()))
13271 return TemplateArgument();
13272 return TemplateArgument(
13273 Ctx.getCommonSugaredType(X.getAsType(), Y.getAsType()));
13275 if (!Ctx.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
13276 return TemplateArgument();
13277 return TemplateArgument(
13278 Ctx.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
13279 /*Unqualified=*/true);
13281 if (!Ctx.hasSameType(X.getAsExpr()->getType(), Y.getAsExpr()->getType()))
13282 return TemplateArgument();
13283 // FIXME: Try to keep the common sugar.
13284 return X;
13286 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
13287 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13288 if (!CTN.getAsVoidPointer())
13289 return TemplateArgument();
13290 return TemplateArgument(CTN);
13291 }
13293 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
13295 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13296 if (!CTN.getAsVoidPointer())
13297 return TemplateName();
13298 auto NExpX = X.getNumTemplateExpansions();
13299 assert(NExpX == Y.getNumTemplateExpansions());
13300 return TemplateArgument(CTN, NExpX);
13301 }
13302 default:
13303 // FIXME: Handle the other argument kinds.
13304 return X;
13305 }
13306}
13307
13312 if (Xs.size() != Ys.size())
13313 return true;
13314 R.resize(Xs.size());
13315 for (size_t I = 0; I < R.size(); ++I) {
13316 R[I] = getCommonTemplateArgument(Ctx, Xs[I], Ys[I]);
13317 if (R[I].isNull())
13318 return true;
13319 }
13320 return false;
13321}
13322
13327 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
13328 assert(!Different);
13329 (void)Different;
13330 return R;
13331}
13332
13333template <class T>
13335 return X->getKeyword() == Y->getKeyword() ? X->getKeyword()
13337}
13338
13339template <class T>
13341 const T *Y) {
13342 // FIXME: Try to keep the common NNS sugar.
13343 return X->getQualifier() == Y->getQualifier()
13344 ? X->getQualifier()
13345 : Ctx.getCanonicalNestedNameSpecifier(X->getQualifier());
13346}
13347
13348template <class T>
13349static QualType getCommonElementType(ASTContext &Ctx, const T *X, const T *Y) {
13350 return Ctx.getCommonSugaredType(X->getElementType(), Y->getElementType());
13351}
13352
13353template <class T>
13355 Qualifiers &QX, const T *Y,
13356 Qualifiers &QY) {
13357 QualType EX = X->getElementType(), EY = Y->getElementType();
13358 QualType R = Ctx.getCommonSugaredType(EX, EY,
13359 /*Unqualified=*/true);
13360 Qualifiers RQ = R.getQualifiers();
13361 QX += EX.getQualifiers() - RQ;
13362 QY += EY.getQualifiers() - RQ;
13363 return R;
13364}
13365
13366template <class T>
13367static QualType getCommonPointeeType(ASTContext &Ctx, const T *X, const T *Y) {
13368 return Ctx.getCommonSugaredType(X->getPointeeType(), Y->getPointeeType());
13369}
13370
13371template <class T> static auto *getCommonSizeExpr(ASTContext &Ctx, T *X, T *Y) {
13372 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
13373 return X->getSizeExpr();
13374}
13375
13376static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
13377 assert(X->getSizeModifier() == Y->getSizeModifier());
13378 return X->getSizeModifier();
13379}
13380
13382 const ArrayType *Y) {
13383 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
13384 return X->getIndexTypeCVRQualifiers();
13385}
13386
13387// Merges two type lists such that the resulting vector will contain
13388// each type (in a canonical sense) only once, in the order they appear
13389// from X to Y. If they occur in both X and Y, the result will contain
13390// the common sugared type between them.
13393 llvm::DenseMap<QualType, unsigned> Found;
13394 for (auto Ts : {X, Y}) {
13395 for (QualType T : Ts) {
13396 auto Res = Found.try_emplace(Ctx.getCanonicalType(T), Out.size());
13397 if (!Res.second) {
13398 QualType &U = Out[Res.first->second];
13399 U = Ctx.getCommonSugaredType(U, T);
13400 } else {
13401 Out.emplace_back(T);
13402 }
13403 }
13404 }
13405}
13406
13410 SmallVectorImpl<QualType> &ExceptionTypeStorage,
13411 bool AcceptDependent) {
13412 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
13413
13414 // If either of them can throw anything, that is the result.
13415 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
13416 if (EST1 == I)
13417 return ESI1;
13418 if (EST2 == I)
13419 return ESI2;
13420 }
13421
13422 // If either of them is non-throwing, the result is the other.
13423 for (auto I :
13425 if (EST1 == I)
13426 return ESI2;
13427 if (EST2 == I)
13428 return ESI1;
13429 }
13430
13431 // If we're left with value-dependent computed noexcept expressions, we're
13432 // stuck. Before C++17, we can just drop the exception specification entirely,
13433 // since it's not actually part of the canonical type. And this should never
13434 // happen in C++17, because it would mean we were computing the composite
13435 // pointer type of dependent types, which should never happen.
13436 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
13437 assert(AcceptDependent &&
13438 "computing composite pointer type of dependent types");
13440 }
13441
13442 // Switch over the possibilities so that people adding new values know to
13443 // update this function.
13444 switch (EST1) {
13445 case EST_None:
13446 case EST_DynamicNone:
13447 case EST_MSAny:
13448 case EST_BasicNoexcept:
13450 case EST_NoexceptFalse:
13451 case EST_NoexceptTrue:
13452 case EST_NoThrow:
13453 llvm_unreachable("These ESTs should be handled above");
13454
13455 case EST_Dynamic: {
13456 // This is the fun case: both exception specifications are dynamic. Form
13457 // the union of the two lists.
13458 assert(EST2 == EST_Dynamic && "other cases should already be handled");
13459 mergeTypeLists(*this, ExceptionTypeStorage, ESI1.Exceptions,
13460 ESI2.Exceptions);
13462 Result.Exceptions = ExceptionTypeStorage;
13463 return Result;
13464 }
13465
13466 case EST_Unevaluated:
13467 case EST_Uninstantiated:
13468 case EST_Unparsed:
13469 llvm_unreachable("shouldn't see unresolved exception specifications here");
13470 }
13471
13472 llvm_unreachable("invalid ExceptionSpecificationType");
13473}
13474
13476 Qualifiers &QX, const Type *Y,
13477 Qualifiers &QY) {
13478 Type::TypeClass TC = X->getTypeClass();
13479 assert(TC == Y->getTypeClass());
13480 switch (TC) {
13481#define UNEXPECTED_TYPE(Class, Kind) \
13482 case Type::Class: \
13483 llvm_unreachable("Unexpected " Kind ": " #Class);
13484
13485#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
13486#define TYPE(Class, Base)
13487#include "clang/AST/TypeNodes.inc"
13488
13489#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
13490 SUGAR_FREE_TYPE(Builtin)
13491 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
13492 SUGAR_FREE_TYPE(DependentBitInt)
13495 SUGAR_FREE_TYPE(ObjCInterface)
13497 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
13498 SUGAR_FREE_TYPE(UnresolvedUsing)
13499 SUGAR_FREE_TYPE(HLSLAttributedResource)
13500#undef SUGAR_FREE_TYPE
13501#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
13502 NON_UNIQUE_TYPE(TypeOfExpr)
13503 NON_UNIQUE_TYPE(VariableArray)
13504#undef NON_UNIQUE_TYPE
13505
13506 UNEXPECTED_TYPE(TypeOf, "sugar")
13507
13508#undef UNEXPECTED_TYPE
13509
13510 case Type::Auto: {
13511 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
13512 assert(AX->getDeducedType().isNull());
13513 assert(AY->getDeducedType().isNull());
13514 assert(AX->getKeyword() == AY->getKeyword());
13515 assert(AX->isInstantiationDependentType() ==
13516 AY->isInstantiationDependentType());
13517 auto As = getCommonTemplateArguments(Ctx, AX->getTypeConstraintArguments(),
13518 AY->getTypeConstraintArguments());
13519 return Ctx.getAutoType(QualType(), AX->getKeyword(),
13521 AX->containsUnexpandedParameterPack(),
13522 getCommonDeclChecked(AX->getTypeConstraintConcept(),
13523 AY->getTypeConstraintConcept()),
13524 As);
13525 }
13526 case Type::IncompleteArray: {
13527 const auto *AX = cast<IncompleteArrayType>(X),
13528 *AY = cast<IncompleteArrayType>(Y);
13529 return Ctx.getIncompleteArrayType(
13530 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
13532 }
13533 case Type::DependentSizedArray: {
13534 const auto *AX = cast<DependentSizedArrayType>(X),
13535 *AY = cast<DependentSizedArrayType>(Y);
13536 return Ctx.getDependentSizedArrayType(
13537 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
13538 getCommonSizeExpr(Ctx, AX, AY), getCommonSizeModifier(AX, AY),
13540 AX->getBracketsRange() == AY->getBracketsRange()
13541 ? AX->getBracketsRange()
13542 : SourceRange());
13543 }
13544 case Type::ConstantArray: {
13545 const auto *AX = cast<ConstantArrayType>(X),
13546 *AY = cast<ConstantArrayType>(Y);
13547 assert(AX->getSize() == AY->getSize());
13548 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
13549 ? AX->getSizeExpr()
13550 : nullptr;
13551 return Ctx.getConstantArrayType(
13552 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
13554 }
13555 case Type::ArrayParameter: {
13556 const auto *AX = cast<ArrayParameterType>(X),
13557 *AY = cast<ArrayParameterType>(Y);
13558 assert(AX->getSize() == AY->getSize());
13559 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
13560 ? AX->getSizeExpr()
13561 : nullptr;
13562 auto ArrayTy = Ctx.getConstantArrayType(
13563 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
13565 return Ctx.getArrayParameterType(ArrayTy);
13566 }
13567 case Type::Atomic: {
13568 const auto *AX = cast<AtomicType>(X), *AY = cast<AtomicType>(Y);
13569 return Ctx.getAtomicType(
13570 Ctx.getCommonSugaredType(AX->getValueType(), AY->getValueType()));
13571 }
13572 case Type::Complex: {
13573 const auto *CX = cast<ComplexType>(X), *CY = cast<ComplexType>(Y);
13574 return Ctx.getComplexType(getCommonArrayElementType(Ctx, CX, QX, CY, QY));
13575 }
13576 case Type::Pointer: {
13577 const auto *PX = cast<PointerType>(X), *PY = cast<PointerType>(Y);
13578 return Ctx.getPointerType(getCommonPointeeType(Ctx, PX, PY));
13579 }
13580 case Type::BlockPointer: {
13581 const auto *PX = cast<BlockPointerType>(X), *PY = cast<BlockPointerType>(Y);
13582 return Ctx.getBlockPointerType(getCommonPointeeType(Ctx, PX, PY));
13583 }
13584 case Type::ObjCObjectPointer: {
13585 const auto *PX = cast<ObjCObjectPointerType>(X),
13586 *PY = cast<ObjCObjectPointerType>(Y);
13587 return Ctx.getObjCObjectPointerType(getCommonPointeeType(Ctx, PX, PY));
13588 }
13589 case Type::MemberPointer: {
13590 const auto *PX = cast<MemberPointerType>(X),
13591 *PY = cast<MemberPointerType>(Y);
13592 return Ctx.getMemberPointerType(
13593 getCommonPointeeType(Ctx, PX, PY),
13594 Ctx.getCommonSugaredType(QualType(PX->getClass(), 0),
13595 QualType(PY->getClass(), 0))
13596 .getTypePtr());
13597 }
13598 case Type::LValueReference: {
13599 const auto *PX = cast<LValueReferenceType>(X),
13600 *PY = cast<LValueReferenceType>(Y);
13601 // FIXME: Preserve PointeeTypeAsWritten.
13602 return Ctx.getLValueReferenceType(getCommonPointeeType(Ctx, PX, PY),
13603 PX->isSpelledAsLValue() ||
13604 PY->isSpelledAsLValue());
13605 }
13606 case Type::RValueReference: {
13607 const auto *PX = cast<RValueReferenceType>(X),
13608 *PY = cast<RValueReferenceType>(Y);
13609 // FIXME: Preserve PointeeTypeAsWritten.
13610 return Ctx.getRValueReferenceType(getCommonPointeeType(Ctx, PX, PY));
13611 }
13612 case Type::DependentAddressSpace: {
13613 const auto *PX = cast<DependentAddressSpaceType>(X),
13614 *PY = cast<DependentAddressSpaceType>(Y);
13615 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
13616 return Ctx.getDependentAddressSpaceType(getCommonPointeeType(Ctx, PX, PY),
13617 PX->getAddrSpaceExpr(),
13618 getCommonAttrLoc(PX, PY));
13619 }
13620 case Type::FunctionNoProto: {
13621 const auto *FX = cast<FunctionNoProtoType>(X),
13622 *FY = cast<FunctionNoProtoType>(Y);
13623 assert(FX->getExtInfo() == FY->getExtInfo());
13624 return Ctx.getFunctionNoProtoType(
13625 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType()),
13626 FX->getExtInfo());
13627 }
13628 case Type::FunctionProto: {
13629 const auto *FX = cast<FunctionProtoType>(X),
13630 *FY = cast<FunctionProtoType>(Y);
13631 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
13632 EPIY = FY->getExtProtoInfo();
13633 assert(EPIX.ExtInfo == EPIY.ExtInfo);
13634 assert(EPIX.ExtParameterInfos == EPIY.ExtParameterInfos);
13635 assert(EPIX.RefQualifier == EPIY.RefQualifier);
13636 assert(EPIX.TypeQuals == EPIY.TypeQuals);
13637 assert(EPIX.Variadic == EPIY.Variadic);
13638
13639 // FIXME: Can we handle an empty EllipsisLoc?
13640 // Use emtpy EllipsisLoc if X and Y differ.
13641
13642 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
13643
13644 QualType R =
13645 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType());
13646 auto P = getCommonTypes(Ctx, FX->param_types(), FY->param_types(),
13647 /*Unqualified=*/true);
13648
13649 SmallVector<QualType, 8> Exceptions;
13651 EPIX.ExceptionSpec, EPIY.ExceptionSpec, Exceptions, true);
13652 return Ctx.getFunctionType(R, P, EPIX);
13653 }
13654 case Type::ObjCObject: {
13655 const auto *OX = cast<ObjCObjectType>(X), *OY = cast<ObjCObjectType>(Y);
13656 assert(
13657 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
13658 OY->getProtocols().begin(), OY->getProtocols().end(),
13659 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
13660 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
13661 }) &&
13662 "protocol lists must be the same");
13663 auto TAs = getCommonTypes(Ctx, OX->getTypeArgsAsWritten(),
13664 OY->getTypeArgsAsWritten());
13665 return Ctx.getObjCObjectType(
13666 Ctx.getCommonSugaredType(OX->getBaseType(), OY->getBaseType()), TAs,
13667 OX->getProtocols(),
13668 OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
13669 }
13670 case Type::ConstantMatrix: {
13671 const auto *MX = cast<ConstantMatrixType>(X),
13672 *MY = cast<ConstantMatrixType>(Y);
13673 assert(MX->getNumRows() == MY->getNumRows());
13674 assert(MX->getNumColumns() == MY->getNumColumns());
13675 return Ctx.getConstantMatrixType(getCommonElementType(Ctx, MX, MY),
13676 MX->getNumRows(), MX->getNumColumns());
13677 }
13678 case Type::DependentSizedMatrix: {
13679 const auto *MX = cast<DependentSizedMatrixType>(X),
13680 *MY = cast<DependentSizedMatrixType>(Y);
13681 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
13682 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
13683 return Ctx.getDependentSizedMatrixType(
13684 getCommonElementType(Ctx, MX, MY), MX->getRowExpr(),
13685 MX->getColumnExpr(), getCommonAttrLoc(MX, MY));
13686 }
13687 case Type::Vector: {
13688 const auto *VX = cast<VectorType>(X), *VY = cast<VectorType>(Y);
13689 assert(VX->getNumElements() == VY->getNumElements());
13690 assert(VX->getVectorKind() == VY->getVectorKind());
13691 return Ctx.getVectorType(getCommonElementType(Ctx, VX, VY),
13692 VX->getNumElements(), VX->getVectorKind());
13693 }
13694 case Type::ExtVector: {
13695 const auto *VX = cast<ExtVectorType>(X), *VY = cast<ExtVectorType>(Y);
13696 assert(VX->getNumElements() == VY->getNumElements());
13697 return Ctx.getExtVectorType(getCommonElementType(Ctx, VX, VY),
13698 VX->getNumElements());
13699 }
13700 case Type::DependentSizedExtVector: {
13701 const auto *VX = cast<DependentSizedExtVectorType>(X),
13702 *VY = cast<DependentSizedExtVectorType>(Y);
13704 getCommonSizeExpr(Ctx, VX, VY),
13705 getCommonAttrLoc(VX, VY));
13706 }
13707 case Type::DependentVector: {
13708 const auto *VX = cast<DependentVectorType>(X),
13709 *VY = cast<DependentVectorType>(Y);
13710 assert(VX->getVectorKind() == VY->getVectorKind());
13711 return Ctx.getDependentVectorType(
13712 getCommonElementType(Ctx, VX, VY), getCommonSizeExpr(Ctx, VX, VY),
13713 getCommonAttrLoc(VX, VY), VX->getVectorKind());
13714 }
13715 case Type::InjectedClassName: {
13716 const auto *IX = cast<InjectedClassNameType>(X),
13717 *IY = cast<InjectedClassNameType>(Y);
13718 return Ctx.getInjectedClassNameType(
13719 getCommonDeclChecked(IX->getDecl(), IY->getDecl()),
13720 Ctx.getCommonSugaredType(IX->getInjectedSpecializationType(),
13721 IY->getInjectedSpecializationType()));
13722 }
13723 case Type::TemplateSpecialization: {
13724 const auto *TX = cast<TemplateSpecializationType>(X),
13725 *TY = cast<TemplateSpecializationType>(Y);
13726 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
13727 TY->template_arguments());
13729 ::getCommonTemplateNameChecked(Ctx, TX->getTemplateName(),
13730 TY->getTemplateName(),
13731 /*IgnoreDeduced=*/true),
13732 As, X->getCanonicalTypeInternal());
13733 }
13734 case Type::Decltype: {
13735 const auto *DX = cast<DecltypeType>(X);
13736 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Y);
13737 assert(DX->isDependentType());
13738 assert(DY->isDependentType());
13739 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
13740 // As Decltype is not uniqued, building a common type would be wasteful.
13741 return QualType(DX, 0);
13742 }
13743 case Type::PackIndexing: {
13744 const auto *DX = cast<PackIndexingType>(X);
13745 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Y);
13746 assert(DX->isDependentType());
13747 assert(DY->isDependentType());
13748 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
13749 return QualType(DX, 0);
13750 }
13751 case Type::DependentName: {
13752 const auto *NX = cast<DependentNameType>(X),
13753 *NY = cast<DependentNameType>(Y);
13754 assert(NX->getIdentifier() == NY->getIdentifier());
13755 return Ctx.getDependentNameType(
13756 getCommonTypeKeyword(NX, NY), getCommonNNS(Ctx, NX, NY),
13757 NX->getIdentifier(), NX->getCanonicalTypeInternal());
13758 }
13759 case Type::DependentTemplateSpecialization: {
13760 const auto *TX = cast<DependentTemplateSpecializationType>(X),
13761 *TY = cast<DependentTemplateSpecializationType>(Y);
13762 assert(TX->getIdentifier() == TY->getIdentifier());
13763 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
13764 TY->template_arguments());
13766 getCommonTypeKeyword(TX, TY), getCommonNNS(Ctx, TX, TY),
13767 TX->getIdentifier(), As);
13768 }
13769 case Type::UnaryTransform: {
13770 const auto *TX = cast<UnaryTransformType>(X),
13771 *TY = cast<UnaryTransformType>(Y);
13772 assert(TX->getUTTKind() == TY->getUTTKind());
13773 return Ctx.getUnaryTransformType(
13774 Ctx.getCommonSugaredType(TX->getBaseType(), TY->getBaseType()),
13775 Ctx.getCommonSugaredType(TX->getUnderlyingType(),
13776 TY->getUnderlyingType()),
13777 TX->getUTTKind());
13778 }
13779 case Type::PackExpansion: {
13780 const auto *PX = cast<PackExpansionType>(X),
13781 *PY = cast<PackExpansionType>(Y);
13782 assert(PX->getNumExpansions() == PY->getNumExpansions());
13783 return Ctx.getPackExpansionType(
13784 Ctx.getCommonSugaredType(PX->getPattern(), PY->getPattern()),
13785 PX->getNumExpansions(), false);
13786 }
13787 case Type::Pipe: {
13788 const auto *PX = cast<PipeType>(X), *PY = cast<PipeType>(Y);
13789 assert(PX->isReadOnly() == PY->isReadOnly());
13790 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
13792 return (Ctx.*MP)(getCommonElementType(Ctx, PX, PY));
13793 }
13794 case Type::TemplateTypeParm: {
13795 const auto *TX = cast<TemplateTypeParmType>(X),
13796 *TY = cast<TemplateTypeParmType>(Y);
13797 assert(TX->getDepth() == TY->getDepth());
13798 assert(TX->getIndex() == TY->getIndex());
13799 assert(TX->isParameterPack() == TY->isParameterPack());
13800 return Ctx.getTemplateTypeParmType(
13801 TX->getDepth(), TX->getIndex(), TX->isParameterPack(),
13802 getCommonDecl(TX->getDecl(), TY->getDecl()));
13803 }
13804 }
13805 llvm_unreachable("Unknown Type Class");
13806}
13807
13809 const Type *Y,
13810 SplitQualType Underlying) {
13811 Type::TypeClass TC = X->getTypeClass();
13812 if (TC != Y->getTypeClass())
13813 return QualType();
13814 switch (TC) {
13815#define UNEXPECTED_TYPE(Class, Kind) \
13816 case Type::Class: \
13817 llvm_unreachable("Unexpected " Kind ": " #Class);
13818#define TYPE(Class, Base)
13819#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
13820#include "clang/AST/TypeNodes.inc"
13821
13822#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
13825 CANONICAL_TYPE(BlockPointer)
13826 CANONICAL_TYPE(Builtin)
13828 CANONICAL_TYPE(ConstantArray)
13829 CANONICAL_TYPE(ArrayParameter)
13830 CANONICAL_TYPE(ConstantMatrix)
13832 CANONICAL_TYPE(ExtVector)
13833 CANONICAL_TYPE(FunctionNoProto)
13834 CANONICAL_TYPE(FunctionProto)
13835 CANONICAL_TYPE(IncompleteArray)
13836 CANONICAL_TYPE(HLSLAttributedResource)
13837 CANONICAL_TYPE(LValueReference)
13838 CANONICAL_TYPE(MemberPointer)
13839 CANONICAL_TYPE(ObjCInterface)
13840 CANONICAL_TYPE(ObjCObject)
13841 CANONICAL_TYPE(ObjCObjectPointer)
13845 CANONICAL_TYPE(RValueReference)
13846 CANONICAL_TYPE(VariableArray)
13848#undef CANONICAL_TYPE
13849
13850#undef UNEXPECTED_TYPE
13851
13852 case Type::Adjusted: {
13853 const auto *AX = cast<AdjustedType>(X), *AY = cast<AdjustedType>(Y);
13854 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
13855 if (!Ctx.hasSameType(OX, OY))
13856 return QualType();
13857 // FIXME: It's inefficient to have to unify the original types.
13858 return Ctx.getAdjustedType(Ctx.getCommonSugaredType(OX, OY),
13859 Ctx.getQualifiedType(Underlying));
13860 }
13861 case Type::Decayed: {
13862 const auto *DX = cast<DecayedType>(X), *DY = cast<DecayedType>(Y);
13863 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
13864 if (!Ctx.hasSameType(OX, OY))
13865 return QualType();
13866 // FIXME: It's inefficient to have to unify the original types.
13867 return Ctx.getDecayedType(Ctx.getCommonSugaredType(OX, OY),
13868 Ctx.getQualifiedType(Underlying));
13869 }
13870 case Type::Attributed: {
13871 const auto *AX = cast<AttributedType>(X), *AY = cast<AttributedType>(Y);
13872 AttributedType::Kind Kind = AX->getAttrKind();
13873 if (Kind != AY->getAttrKind())
13874 return QualType();
13875 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
13876 if (!Ctx.hasSameType(MX, MY))
13877 return QualType();
13878 // FIXME: It's inefficient to have to unify the modified types.
13879 return Ctx.getAttributedType(Kind, Ctx.getCommonSugaredType(MX, MY),
13880 Ctx.getQualifiedType(Underlying),
13881 AX->getAttr());
13882 }
13883 case Type::BTFTagAttributed: {
13884 const auto *BX = cast<BTFTagAttributedType>(X);
13885 const BTFTypeTagAttr *AX = BX->getAttr();
13886 // The attribute is not uniqued, so just compare the tag.
13887 if (AX->getBTFTypeTag() !=
13888 cast<BTFTagAttributedType>(Y)->getAttr()->getBTFTypeTag())
13889 return QualType();
13890 return Ctx.getBTFTagAttributedType(AX, Ctx.getQualifiedType(Underlying));
13891 }
13892 case Type::Auto: {
13893 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
13894
13895 AutoTypeKeyword KW = AX->getKeyword();
13896 if (KW != AY->getKeyword())
13897 return QualType();
13898
13899 ConceptDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(),
13900 AY->getTypeConstraintConcept());
13902 if (CD &&
13903 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
13904 AY->getTypeConstraintArguments())) {
13905 CD = nullptr; // The arguments differ, so make it unconstrained.
13906 As.clear();
13907 }
13908
13909 // Both auto types can't be dependent, otherwise they wouldn't have been
13910 // sugar. This implies they can't contain unexpanded packs either.
13911 return Ctx.getAutoType(Ctx.getQualifiedType(Underlying), AX->getKeyword(),
13912 /*IsDependent=*/false, /*IsPack=*/false, CD, As);
13913 }
13914 case Type::PackIndexing:
13915 case Type::Decltype:
13916 return QualType();
13917 case Type::DeducedTemplateSpecialization:
13918 // FIXME: Try to merge these.
13919 return QualType();
13920
13921 case Type::Elaborated: {
13922 const auto *EX = cast<ElaboratedType>(X), *EY = cast<ElaboratedType>(Y);
13923 return Ctx.getElaboratedType(
13924 ::getCommonTypeKeyword(EX, EY), ::getCommonNNS(Ctx, EX, EY),
13925 Ctx.getQualifiedType(Underlying),
13926 ::getCommonDecl(EX->getOwnedTagDecl(), EY->getOwnedTagDecl()));
13927 }
13928 case Type::MacroQualified: {
13929 const auto *MX = cast<MacroQualifiedType>(X),
13930 *MY = cast<MacroQualifiedType>(Y);
13931 const IdentifierInfo *IX = MX->getMacroIdentifier();
13932 if (IX != MY->getMacroIdentifier())
13933 return QualType();
13934 return Ctx.getMacroQualifiedType(Ctx.getQualifiedType(Underlying), IX);
13935 }
13936 case Type::SubstTemplateTypeParm: {
13937 const auto *SX = cast<SubstTemplateTypeParmType>(X),
13938 *SY = cast<SubstTemplateTypeParmType>(Y);
13939 Decl *CD =
13940 ::getCommonDecl(SX->getAssociatedDecl(), SY->getAssociatedDecl());
13941 if (!CD)
13942 return QualType();
13943 unsigned Index = SX->getIndex();
13944 if (Index != SY->getIndex())
13945 return QualType();
13946 auto PackIndex = SX->getPackIndex();
13947 if (PackIndex != SY->getPackIndex())
13948 return QualType();
13949 return Ctx.getSubstTemplateTypeParmType(Ctx.getQualifiedType(Underlying),
13950 CD, Index, PackIndex);
13951 }
13952 case Type::ObjCTypeParam:
13953 // FIXME: Try to merge these.
13954 return QualType();
13955 case Type::Paren:
13956 return Ctx.getParenType(Ctx.getQualifiedType(Underlying));
13957
13958 case Type::TemplateSpecialization: {
13959 const auto *TX = cast<TemplateSpecializationType>(X),
13960 *TY = cast<TemplateSpecializationType>(Y);
13961 TemplateName CTN =
13962 ::getCommonTemplateName(Ctx, TX->getTemplateName(),
13963 TY->getTemplateName(), /*IgnoreDeduced=*/true);
13964 if (!CTN.getAsVoidPointer())
13965 return QualType();
13967 if (getCommonTemplateArguments(Ctx, Args, TX->template_arguments(),
13968 TY->template_arguments()))
13969 return QualType();
13970 return Ctx.getTemplateSpecializationType(CTN, Args,
13971 Ctx.getQualifiedType(Underlying));
13972 }
13973 case Type::Typedef: {
13974 const auto *TX = cast<TypedefType>(X), *TY = cast<TypedefType>(Y);
13975 const TypedefNameDecl *CD = ::getCommonDecl(TX->getDecl(), TY->getDecl());
13976 if (!CD)
13977 return QualType();
13978 return Ctx.getTypedefType(CD, Ctx.getQualifiedType(Underlying));
13979 }
13980 case Type::TypeOf: {
13981 // The common sugar between two typeof expressions, where one is
13982 // potentially a typeof_unqual and the other is not, we unify to the
13983 // qualified type as that retains the most information along with the type.
13984 // We only return a typeof_unqual type when both types are unqual types.
13986 if (cast<TypeOfType>(X)->getKind() == cast<TypeOfType>(Y)->getKind() &&
13987 cast<TypeOfType>(X)->getKind() == TypeOfKind::Unqualified)
13989 return Ctx.getTypeOfType(Ctx.getQualifiedType(Underlying), Kind);
13990 }
13991 case Type::TypeOfExpr:
13992 return QualType();
13993
13994 case Type::UnaryTransform: {
13995 const auto *UX = cast<UnaryTransformType>(X),
13996 *UY = cast<UnaryTransformType>(Y);
13997 UnaryTransformType::UTTKind KX = UX->getUTTKind();
13998 if (KX != UY->getUTTKind())
13999 return QualType();
14000 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
14001 if (!Ctx.hasSameType(BX, BY))
14002 return QualType();
14003 // FIXME: It's inefficient to have to unify the base types.
14004 return Ctx.getUnaryTransformType(Ctx.getCommonSugaredType(BX, BY),
14005 Ctx.getQualifiedType(Underlying), KX);
14006 }
14007 case Type::Using: {
14008 const auto *UX = cast<UsingType>(X), *UY = cast<UsingType>(Y);
14009 const UsingShadowDecl *CD =
14010 ::getCommonDecl(UX->getFoundDecl(), UY->getFoundDecl());
14011 if (!CD)
14012 return QualType();
14013 return Ctx.getUsingType(CD, Ctx.getQualifiedType(Underlying));
14014 }
14015 case Type::CountAttributed: {
14016 const auto *DX = cast<CountAttributedType>(X),
14017 *DY = cast<CountAttributedType>(Y);
14018 if (DX->isCountInBytes() != DY->isCountInBytes())
14019 return QualType();
14020 if (DX->isOrNull() != DY->isOrNull())
14021 return QualType();
14022 Expr *CEX = DX->getCountExpr();
14023 Expr *CEY = DY->getCountExpr();
14024 llvm::ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
14025 if (Ctx.hasSameExpr(CEX, CEY))
14026 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14027 DX->isCountInBytes(), DX->isOrNull(),
14028 CDX);
14029 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
14030 return QualType();
14031 // Two declarations with the same integer constant may still differ in their
14032 // expression pointers, so we need to evaluate them.
14033 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
14034 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
14035 if (VX != VY)
14036 return QualType();
14037 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14038 DX->isCountInBytes(), DX->isOrNull(),
14039 CDX);
14040 }
14041 }
14042 llvm_unreachable("Unhandled Type Class");
14043}
14044
14045static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
14047 while (true) {
14048 QTotal.addConsistentQualifiers(T.Quals);
14050 if (NT == QualType(T.Ty, 0))
14051 break;
14052 R.push_back(T);
14053 T = NT.split();
14054 }
14055 return R;
14056}
14057
14059 bool Unqualified) {
14060 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
14061 if (X == Y)
14062 return X;
14063 if (!Unqualified) {
14064 if (X.isCanonical())
14065 return X;
14066 if (Y.isCanonical())
14067 return Y;
14068 }
14069
14070 SplitQualType SX = X.split(), SY = Y.split();
14071 Qualifiers QX, QY;
14072 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
14073 // until we reach their underlying "canonical nodes". Note these are not
14074 // necessarily canonical types, as they may still have sugared properties.
14075 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
14076 auto Xs = ::unwrapSugar(SX, QX), Ys = ::unwrapSugar(SY, QY);
14077 if (SX.Ty != SY.Ty) {
14078 // The canonical nodes differ. Build a common canonical node out of the two,
14079 // unifying their sugar. This may recurse back here.
14080 SX.Ty =
14081 ::getCommonNonSugarTypeNode(*this, SX.Ty, QX, SY.Ty, QY).getTypePtr();
14082 } else {
14083 // The canonical nodes were identical: We may have desugared too much.
14084 // Add any common sugar back in.
14085 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
14086 QX -= SX.Quals;
14087 QY -= SY.Quals;
14088 SX = Xs.pop_back_val();
14089 SY = Ys.pop_back_val();
14090 }
14091 }
14092 if (Unqualified)
14094 else
14095 assert(QX == QY);
14096
14097 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
14098 // related. Walk up these nodes, unifying them and adding the result.
14099 while (!Xs.empty() && !Ys.empty()) {
14100 auto Underlying = SplitQualType(
14101 SX.Ty, Qualifiers::removeCommonQualifiers(SX.Quals, SY.Quals));
14102 SX = Xs.pop_back_val();
14103 SY = Ys.pop_back_val();
14104 SX.Ty = ::getCommonSugarTypeNode(*this, SX.Ty, SY.Ty, Underlying)
14106 // Stop at the first pair which is unrelated.
14107 if (!SX.Ty) {
14108 SX.Ty = Underlying.Ty;
14109 break;
14110 }
14111 QX -= Underlying.Quals;
14112 };
14113
14114 // Add back the missing accumulated qualifiers, which were stripped off
14115 // with the sugar nodes we could not unify.
14116 QualType R = getQualifiedType(SX.Ty, QX);
14117 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
14118 return R;
14119}
14120
14122 assert(Ty->isFixedPointType());
14123
14125 return Ty;
14126
14127 switch (Ty->castAs<BuiltinType>()->getKind()) {
14128 default:
14129 llvm_unreachable("Not a saturated fixed point type!");
14130 case BuiltinType::SatShortAccum:
14131 return ShortAccumTy;
14132 case BuiltinType::SatAccum:
14133 return AccumTy;
14134 case BuiltinType::SatLongAccum:
14135 return LongAccumTy;
14136 case BuiltinType::SatUShortAccum:
14137 return UnsignedShortAccumTy;
14138 case BuiltinType::SatUAccum:
14139 return UnsignedAccumTy;
14140 case BuiltinType::SatULongAccum:
14141 return UnsignedLongAccumTy;
14142 case BuiltinType::SatShortFract:
14143 return ShortFractTy;
14144 case BuiltinType::SatFract:
14145 return FractTy;
14146 case BuiltinType::SatLongFract:
14147 return LongFractTy;
14148 case BuiltinType::SatUShortFract:
14149 return UnsignedShortFractTy;
14150 case BuiltinType::SatUFract:
14151 return UnsignedFractTy;
14152 case BuiltinType::SatULongFract:
14153 return UnsignedLongFractTy;
14154 }
14155}
14156
14158 assert(Ty->isFixedPointType());
14159
14160 if (Ty->isSaturatedFixedPointType()) return Ty;
14161
14162 switch (Ty->castAs<BuiltinType>()->getKind()) {
14163 default:
14164 llvm_unreachable("Not a fixed point type!");
14165 case BuiltinType::ShortAccum:
14166 return SatShortAccumTy;
14167 case BuiltinType::Accum:
14168 return SatAccumTy;
14169 case BuiltinType::LongAccum:
14170 return SatLongAccumTy;
14171 case BuiltinType::UShortAccum:
14173 case BuiltinType::UAccum:
14174 return SatUnsignedAccumTy;
14175 case BuiltinType::ULongAccum:
14177 case BuiltinType::ShortFract:
14178 return SatShortFractTy;
14179 case BuiltinType::Fract:
14180 return SatFractTy;
14181 case BuiltinType::LongFract:
14182 return SatLongFractTy;
14183 case BuiltinType::UShortFract:
14185 case BuiltinType::UFract:
14186 return SatUnsignedFractTy;
14187 case BuiltinType::ULongFract:
14189 }
14190}
14191
14193 if (LangOpts.OpenCL)
14195
14196 if (LangOpts.CUDA)
14198
14199 return getLangASFromTargetAS(AS);
14200}
14201
14202// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
14203// doesn't include ASTContext.h
14204template
14206 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
14208 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
14209 const clang::ASTContext &Ctx, Decl *Value);
14210
14212 assert(Ty->isFixedPointType());
14213
14214 const TargetInfo &Target = getTargetInfo();
14215 switch (Ty->castAs<BuiltinType>()->getKind()) {
14216 default:
14217 llvm_unreachable("Not a fixed point type!");
14218 case BuiltinType::ShortAccum:
14219 case BuiltinType::SatShortAccum:
14220 return Target.getShortAccumScale();
14221 case BuiltinType::Accum:
14222 case BuiltinType::SatAccum:
14223 return Target.getAccumScale();
14224 case BuiltinType::LongAccum:
14225 case BuiltinType::SatLongAccum:
14226 return Target.getLongAccumScale();
14227 case BuiltinType::UShortAccum:
14228 case BuiltinType::SatUShortAccum:
14229 return Target.getUnsignedShortAccumScale();
14230 case BuiltinType::UAccum:
14231 case BuiltinType::SatUAccum:
14232 return Target.getUnsignedAccumScale();
14233 case BuiltinType::ULongAccum:
14234 case BuiltinType::SatULongAccum:
14235 return Target.getUnsignedLongAccumScale();
14236 case BuiltinType::ShortFract:
14237 case BuiltinType::SatShortFract:
14238 return Target.getShortFractScale();
14239 case BuiltinType::Fract:
14240 case BuiltinType::SatFract:
14241 return Target.getFractScale();
14242 case BuiltinType::LongFract:
14243 case BuiltinType::SatLongFract:
14244 return Target.getLongFractScale();
14245 case BuiltinType::UShortFract:
14246 case BuiltinType::SatUShortFract:
14247 return Target.getUnsignedShortFractScale();
14248 case BuiltinType::UFract:
14249 case BuiltinType::SatUFract:
14250 return Target.getUnsignedFractScale();
14251 case BuiltinType::ULongFract:
14252 case BuiltinType::SatULongFract:
14253 return Target.getUnsignedLongFractScale();
14254 }
14255}
14256
14258 assert(Ty->isFixedPointType());
14259
14260 const TargetInfo &Target = getTargetInfo();
14261 switch (Ty->castAs<BuiltinType>()->getKind()) {
14262 default:
14263 llvm_unreachable("Not a fixed point type!");
14264 case BuiltinType::ShortAccum:
14265 case BuiltinType::SatShortAccum:
14266 return Target.getShortAccumIBits();
14267 case BuiltinType::Accum:
14268 case BuiltinType::SatAccum:
14269 return Target.getAccumIBits();
14270 case BuiltinType::LongAccum:
14271 case BuiltinType::SatLongAccum:
14272 return Target.getLongAccumIBits();
14273 case BuiltinType::UShortAccum:
14274 case BuiltinType::SatUShortAccum:
14275 return Target.getUnsignedShortAccumIBits();
14276 case BuiltinType::UAccum:
14277 case BuiltinType::SatUAccum:
14278 return Target.getUnsignedAccumIBits();
14279 case BuiltinType::ULongAccum:
14280 case BuiltinType::SatULongAccum:
14281 return Target.getUnsignedLongAccumIBits();
14282 case BuiltinType::ShortFract:
14283 case BuiltinType::SatShortFract:
14284 case BuiltinType::Fract:
14285 case BuiltinType::SatFract:
14286 case BuiltinType::LongFract:
14287 case BuiltinType::SatLongFract:
14288 case BuiltinType::UShortFract:
14289 case BuiltinType::SatUShortFract:
14290 case BuiltinType::UFract:
14291 case BuiltinType::SatUFract:
14292 case BuiltinType::ULongFract:
14293 case BuiltinType::SatULongFract:
14294 return 0;
14295 }
14296}
14297
14298llvm::FixedPointSemantics
14300 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
14301 "Can only get the fixed point semantics for a "
14302 "fixed point or integer type.");
14303 if (Ty->isIntegerType())
14304 return llvm::FixedPointSemantics::GetIntegerSemantics(
14305 getIntWidth(Ty), Ty->isSignedIntegerType());
14306
14307 bool isSigned = Ty->isSignedFixedPointType();
14308 return llvm::FixedPointSemantics(
14309 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
14311 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
14312}
14313
14314llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
14315 assert(Ty->isFixedPointType());
14316 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
14317}
14318
14319llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
14320 assert(Ty->isFixedPointType());
14321 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
14322}
14323
14325 assert(Ty->isUnsignedFixedPointType() &&
14326 "Expected unsigned fixed point type");
14327
14328 switch (Ty->castAs<BuiltinType>()->getKind()) {
14329 case BuiltinType::UShortAccum:
14330 return ShortAccumTy;
14331 case BuiltinType::UAccum:
14332 return AccumTy;
14333 case BuiltinType::ULongAccum:
14334 return LongAccumTy;
14335 case BuiltinType::SatUShortAccum:
14336 return SatShortAccumTy;
14337 case BuiltinType::SatUAccum:
14338 return SatAccumTy;
14339 case BuiltinType::SatULongAccum:
14340 return SatLongAccumTy;
14341 case BuiltinType::UShortFract:
14342 return ShortFractTy;
14343 case BuiltinType::UFract:
14344 return FractTy;
14345 case BuiltinType::ULongFract:
14346 return LongFractTy;
14347 case BuiltinType::SatUShortFract:
14348 return SatShortFractTy;
14349 case BuiltinType::SatUFract:
14350 return SatFractTy;
14351 case BuiltinType::SatULongFract:
14352 return SatLongFractTy;
14353 default:
14354 llvm_unreachable("Unexpected unsigned fixed point type");
14355 }
14356}
14357
14358// Given a list of FMV features, return a concatenated list of the
14359// corresponding backend features (which may contain duplicates).
14360static std::vector<std::string> getFMVBackendFeaturesFor(
14361 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) {
14362 std::vector<std::string> BackendFeats;
14363 llvm::AArch64::ExtensionSet FeatureBits;
14364 for (StringRef F : FMVFeatStrings)
14365 if (auto FMVExt = llvm::AArch64::parseFMVExtension(F))
14366 if (FMVExt->ID)
14367 FeatureBits.enable(*FMVExt->ID);
14368 FeatureBits.toLLVMFeatureList(BackendFeats);
14369 return BackendFeats;
14370}
14371
14373ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
14374 assert(TD != nullptr);
14375 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TD->getFeaturesStr());
14376
14377 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
14378 return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
14379 });
14380 return ParsedAttr;
14381}
14382
14383void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
14384 const FunctionDecl *FD) const {
14385 if (FD)
14386 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
14387 else
14388 Target->initFeatureMap(FeatureMap, getDiagnostics(),
14389 Target->getTargetOpts().CPU,
14390 Target->getTargetOpts().Features);
14391}
14392
14393// Fills in the supplied string map with the set of target features for the
14394// passed in function.
14395void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
14396 GlobalDecl GD) const {
14397 StringRef TargetCPU = Target->getTargetOpts().CPU;
14398 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
14399 if (const auto *TD = FD->getAttr<TargetAttr>()) {
14401
14402 // Make a copy of the features as passed on the command line into the
14403 // beginning of the additional features from the function to override.
14404 // AArch64 handles command line option features in parseTargetAttr().
14405 if (!Target->getTriple().isAArch64())
14406 ParsedAttr.Features.insert(
14407 ParsedAttr.Features.begin(),
14408 Target->getTargetOpts().FeaturesAsWritten.begin(),
14409 Target->getTargetOpts().FeaturesAsWritten.end());
14410
14411 if (ParsedAttr.CPU != "" && Target->isValidCPUName(ParsedAttr.CPU))
14412 TargetCPU = ParsedAttr.CPU;
14413
14414 // Now populate the feature map, first with the TargetCPU which is either
14415 // the default or a new one from the target attribute string. Then we'll use
14416 // the passed in features (FeaturesAsWritten) along with the new ones from
14417 // the attribute.
14418 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
14419 ParsedAttr.Features);
14420 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
14422 Target->getCPUSpecificCPUDispatchFeatures(
14423 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
14424 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
14425 Features.insert(Features.begin(),
14426 Target->getTargetOpts().FeaturesAsWritten.begin(),
14427 Target->getTargetOpts().FeaturesAsWritten.end());
14428 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14429 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
14430 if (Target->getTriple().isAArch64()) {
14432 TC->getFeatures(Feats, GD.getMultiVersionIndex());
14433 std::vector<std::string> Features = getFMVBackendFeaturesFor(Feats);
14434 Features.insert(Features.begin(),
14435 Target->getTargetOpts().FeaturesAsWritten.begin(),
14436 Target->getTargetOpts().FeaturesAsWritten.end());
14437 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14438 } else if (Target->getTriple().isRISCV()) {
14439 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
14440 std::vector<std::string> Features;
14441 if (VersionStr != "default") {
14442 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(VersionStr);
14443 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
14444 ParsedAttr.Features.end());
14445 }
14446 Features.insert(Features.begin(),
14447 Target->getTargetOpts().FeaturesAsWritten.begin(),
14448 Target->getTargetOpts().FeaturesAsWritten.end());
14449 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14450 } else {
14451 std::vector<std::string> Features;
14452 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
14453 if (VersionStr.starts_with("arch="))
14454 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
14455 else if (VersionStr != "default")
14456 Features.push_back((StringRef{"+"} + VersionStr).str());
14457 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14458 }
14459 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
14460 std::vector<std::string> Features;
14461 if (Target->getTriple().isRISCV()) {
14462 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TV->getName());
14463 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
14464 ParsedAttr.Features.end());
14465 } else {
14466 assert(Target->getTriple().isAArch64());
14468 TV->getFeatures(Feats);
14469 Features = getFMVBackendFeaturesFor(Feats);
14470 }
14471 Features.insert(Features.begin(),
14472 Target->getTargetOpts().FeaturesAsWritten.begin(),
14473 Target->getTargetOpts().FeaturesAsWritten.end());
14474 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14475 } else {
14476 FeatureMap = Target->getTargetOpts().FeatureMap;
14477 }
14478}
14479
14481 const FunctionDecl *FD) {
14482 return {KernelNameType, FD};
14483}
14484
14486 // If the function declaration to register is invalid or dependent, the
14487 // registration attempt is ignored.
14488 if (FD->isInvalidDecl() || FD->isTemplated())
14489 return;
14490
14491 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
14492 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
14493
14494 // Be tolerant of multiple registration attempts so long as each attempt
14495 // is for the same entity. Callers are obligated to detect and diagnose
14496 // conflicting kernel names prior to calling this function.
14497 CanQualType KernelNameType = getCanonicalType(SKEPAttr->getKernelName());
14498 auto IT = SYCLKernels.find(KernelNameType);
14499 assert((IT == SYCLKernels.end() ||
14500 declaresSameEntity(FD, IT->second.getKernelEntryPointDecl())) &&
14501 "SYCL kernel name conflict");
14502 (void)IT;
14503 SYCLKernels.insert(
14504 std::make_pair(KernelNameType, BuildSYCLKernelInfo(KernelNameType, FD)));
14505}
14506
14508 CanQualType KernelNameType = getCanonicalType(T);
14509 return SYCLKernels.at(KernelNameType);
14510}
14511
14513 CanQualType KernelNameType = getCanonicalType(T);
14514 auto IT = SYCLKernels.find(KernelNameType);
14515 if (IT != SYCLKernels.end())
14516 return &IT->second;
14517 return nullptr;
14518}
14519
14521 OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
14522 return *OMPTraitInfoVector.back();
14523}
14524
14527 const ASTContext::SectionInfo &Section) {
14528 if (Section.Decl)
14529 return DB << Section.Decl;
14530 return DB << "a prior #pragma section";
14531}
14532
14534 bool IsInternalVar =
14535 isa<VarDecl>(D) &&
14536 basicGVALinkageForVariable(*this, cast<VarDecl>(D)) == GVA_Internal;
14537 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
14538 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
14539 (D->hasAttr<CUDAConstantAttr>() &&
14540 !D->getAttr<CUDAConstantAttr>()->isImplicit());
14541 // CUDA/HIP: managed variables need to be externalized since it is
14542 // a declaration in IR, therefore cannot have internal linkage. Kernels in
14543 // anonymous name space needs to be externalized to avoid duplicate symbols.
14544 return (IsInternalVar &&
14545 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
14546 (D->hasAttr<CUDAGlobalAttr>() &&
14547 basicGVALinkageForFunction(*this, cast<FunctionDecl>(D)) ==
14548 GVA_Internal);
14549}
14550
14552 return mayExternalize(D) &&
14553 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
14554 CUDADeviceVarODRUsedByHost.count(cast<VarDecl>(D)));
14555}
14556
14557StringRef ASTContext::getCUIDHash() const {
14558 if (!CUIDHash.empty())
14559 return CUIDHash;
14560 if (LangOpts.CUID.empty())
14561 return StringRef();
14562 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
14563 return CUIDHash;
14564}
14565
14566const CXXRecordDecl *
14568 assert(ThisClass);
14569 assert(ThisClass->isPolymorphic());
14570 const CXXRecordDecl *PrimaryBase = ThisClass;
14571 while (1) {
14572 assert(PrimaryBase);
14573 assert(PrimaryBase->isPolymorphic());
14574 auto &Layout = getASTRecordLayout(PrimaryBase);
14575 auto Base = Layout.getPrimaryBase();
14576 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
14577 break;
14578 PrimaryBase = Base;
14579 }
14580 return PrimaryBase;
14581}
14582
14584 StringRef MangledName) {
14585 auto *Method = cast<CXXMethodDecl>(VirtualMethodDecl.getDecl());
14586 assert(Method->isVirtual());
14587 bool DefaultIncludesPointerAuth =
14588 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics;
14589
14590 if (!DefaultIncludesPointerAuth)
14591 return true;
14592
14593 auto Existing = ThunksToBeAbbreviated.find(VirtualMethodDecl);
14594 if (Existing != ThunksToBeAbbreviated.end())
14595 return Existing->second.contains(MangledName.str());
14596
14597 std::unique_ptr<MangleContext> Mangler(createMangleContext());
14598 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks;
14599 auto VtableContext = getVTableContext();
14600 if (const auto *ThunkInfos = VtableContext->getThunkInfo(VirtualMethodDecl)) {
14601 auto *Destructor = dyn_cast<CXXDestructorDecl>(Method);
14602 for (const auto &Thunk : *ThunkInfos) {
14603 SmallString<256> ElidedName;
14604 llvm::raw_svector_ostream ElidedNameStream(ElidedName);
14605 if (Destructor)
14606 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
14607 Thunk, /* elideOverrideInfo */ true,
14608 ElidedNameStream);
14609 else
14610 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ true,
14611 ElidedNameStream);
14612 SmallString<256> MangledName;
14613 llvm::raw_svector_ostream mangledNameStream(MangledName);
14614 if (Destructor)
14615 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
14616 Thunk, /* elideOverrideInfo */ false,
14617 mangledNameStream);
14618 else
14619 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ false,
14620 mangledNameStream);
14621
14622 Thunks[ElidedName].push_back(std::string(MangledName));
14623 }
14624 }
14625 llvm::StringSet<> SimplifiedThunkNames;
14626 for (auto &ThunkList : Thunks) {
14627 llvm::sort(ThunkList.second);
14628 SimplifiedThunkNames.insert(ThunkList.second[0]);
14629 }
14630 bool Result = SimplifiedThunkNames.contains(MangledName);
14631 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames);
14632 return Result;
14633}
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:3453
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:3052
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:3403
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:3417
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:3382
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:3396
unsigned NumImplicitCopyConstructorsDeclared
The number of implicitly-declared copy constructors for which declarations were built.
Definition: ASTContext.h:3389
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:3413
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:3378
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:3410
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:3392
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
const SYCLKernelInfo & getSYCLKernelInfo(QualType T) const
Given a type used as a SYCL kernel name, returns a reference to the metadata generated from the corre...
bool canAssignObjCInterfacesInBlockPointer(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT, bool BlockReturnType)
canAssignObjCInterfacesInBlockPointer - This routine is specifically written for providing type-safet...
CanQualType SatUnsignedLongFractTy
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:3385
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:3399
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)
const SYCLKernelInfo * findSYCLKernelInfo(QualType T) const
Returns a pointer to the metadata generated from the corresponding SYCLkernel entry point if the prov...
unsigned getParameterIndex(const ParmVarDecl *D) const
Used by ParmVarDecl to retrieve on the side the index of the parameter when it exceeds the size of th...
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:3406
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:7766
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7771
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:6132
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6204
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:6561
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.cpp:5204
bool isConstrained() const
Definition: Type.h:6580
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6241
A fixed int type of a specified bitwidth.
Definition: Type.h:7819
void Profile(llvm::FoldingSetNodeID &ID) const
Definition: Type.h:7836
unsigned getNumBits() const
Definition: Type.h:7831
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4496
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:109
bool hasCustomTypechecking(unsigned ID) const
Determines whether this builtin has custom typechecking.
Definition: Builtins.h:197
bool canBeRedeclared(unsigned ID) const
Returns true if this is a builtin that can be redeclared.
Definition: Builtins.cpp:246
bool isNoReturn(unsigned ID) const
Return true if we know this builtin never returns.
Definition: Builtins.h:133
bool isNoThrow(unsigned ID) const
Return true if we know this builtin never throws an exception.
Definition: Builtins.h:128
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:132
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:2100
bool isFileContext() const
Definition: DeclBase.h:2171
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:2116
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:1998
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:5879
Represents a C++17 deduced template specialization type.
Definition: Type.h:6609
void Profile(llvm::FoldingSetNodeID &ID) const
Definition: Type.h:6630
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:6527
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:7864
Internal representation of canonical, dependent decltype(expr) types.
Definition: Type.h:5907
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:5911
Represents a qualified type name for which the type name is dependent.
Definition: Type.h:7029
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7061
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:7081
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:7108
Internal representation of canonical, dependent typeof(expr) types.
Definition: Type.h:5836
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:5841
Internal representation of canonical, dependent __underlying_type(type) types.
Definition: Type.h:6037
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6042
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:4828
Represents a type that was referred to using an elaborated type keyword, e.g., struct S,...
Definition: Type.h:6948
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7001
Represents an enum.
Definition: Decl.h:3861
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4066
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:4080
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4021
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:4963
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:6103
EnumDecl * getDecl() const
Definition: Type.h:6110
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:3102
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:4131
@ 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:3077
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition: Expr.cpp:3970
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:5359
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:3136
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition: Decl.cpp:4602
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.h:3118
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3264
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:4721
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition: Type.h:4908
size_t size() const
Definition: Type.h:4939
ArrayRef< EffectConditionExpr > conditions() const
Definition: Type.h:4942
bool empty() const
Definition: Type.h:4938
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition: Type.h:4686
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4702
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5107
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:5573
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:5387
unsigned getNumParams() const
Definition: Type.h:5360
QualType getParamType(unsigned i) const
Definition: Type.h:5362
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:5393
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5484
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5371
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5367
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition: Type.h:5549
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition: Type.h:5545
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:4660
QualType getReturnType() const
Definition: Type.h:4648
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:6298
const Attributes & getAttrs() const
Definition: Type.h:6301
QualType getContainedType() const
Definition: Type.h:6299
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6306
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:4808
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:6798
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:4312
static void Profile(llvm::FoldingSetNodeID &ID, Parts P)
Definition: DeclCXX.h:4349
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition: Type.h:5770
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:3215
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:3128
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:7529
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:7585
bool isObjCQualifiedClassType() const
True if this is equivalent to 'Class.
Definition: Type.h:7666
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:7660
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7742
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:7622
bool qual_empty() const
Definition: Type.h:7714
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition: Type.h:7643
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:7597
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition: Type.h:7637
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:7704
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition: Type.h:7649
A class providing a concrete implementation of ObjCObjectType, so as to not increase the footprint of...
Definition: Type.h:7482
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:4450
Represents a class type in Objective C.
Definition: Type.h:7331
bool isKindOfTypeAsWritten() const
Whether this is a "__kindof" type as written.
Definition: Type.h:7446
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:7441
bool isObjCQualifiedClass() const
Definition: Type.h:7413
QualType getBaseType() const
Gets the base type of this object type.
Definition: Type.h:7393
bool isObjCClass() const
Definition: Type.h:7399
bool isKindOfType() const
Whether this ia a "__kindof" type (semantically).
Definition: Type.cpp:901
bool isObjCQualifiedId() const
Definition: Type.h:7412
ArrayRef< QualType > getTypeArgs() const
Retrieve the type arguments of this object type (semantically).
Definition: Type.cpp:883
bool isObjCUnqualifiedId() const
Definition: Type.h:7403
ObjCInterfaceDecl * getInterface() const
Gets the interface declaration for this object type, if the base type really is an interface.
Definition: Type.h:7564
QualType getSuperClassType() const
Retrieve the type of the superclass of this object type.
Definition: Type.h:7457
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:7237
qual_iterator qual_end() const
Definition: Type.h:7231
qual_iterator qual_begin() const
Definition: Type.h:7230
qual_range quals() const
Definition: Type.h:7229
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:7257
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:7146
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7180
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5973
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:7785
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7802
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:8020
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:8067
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:8025
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:7936
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:8062
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7976
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1433
QualType getCanonicalType() const
Definition: Type.h:7988
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:8030
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition: Type.h:7957
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:8009
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:7993
const Type * getTypePtrOrNull() const
Definition: Type.h:7940
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:7968
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:7876
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:7883
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:4162
bool hasFlexibleArrayMember() const
Definition: Decl.h:4195
field_range fields() const
Definition: Decl.h:4376
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition: Decl.cpp:5041
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition: Decl.cpp:5107
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4361
bool field_empty() const
Definition: Decl.h:4384
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6077
RecordDecl * getDecl() const
Definition: Type.h:6087
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:1194
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:6469
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:4311
Represents the result of substituting a type for a template type parameter.
Definition: Type.h:6388
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6433
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3578
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition: Decl.h:3806
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4762
bool isUnion() const
Definition: Decl.h:3784
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:6666
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:6360
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:3384
void setTypeForDecl(const Type *TD)
Definition: Decl.h:3410
const Type * getTypeForDecl() const
Definition: Decl.h:3409
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:5802
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition: Type.h:5852
A container of type source information.
Definition: Type.h:7907
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:8205
bool isVoidType() const
Definition: Type.h:8515
bool isBooleanType() const
Definition: Type.h:8643
bool isFunctionReferenceType() const
Definition: Type.h:8238
bool isObjCBuiltinType() const
Definition: Type.h:8384
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:8271
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:8491
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:8267
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:8263
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:8231
bool isPointerType() const
Definition: Type.h:8191
bool isArrayParameterType() const
Definition: Type.h:8279
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8555
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8805
bool isSpecificPlaceholderType(unsigned K) const
Test for a specific placeholder type.
Definition: Type.h:8504
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:8596
bool isEnumeralType() const
Definition: Type.h:8295
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:8354
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:8630
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:8429
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:8484
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:8287
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:8568
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8584
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:8686
bool isMemberPointerType() const
Definition: Type.h:8245
bool isObjCIdType() const
Definition: Type.h:8366
bool isUnsaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8592
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:8791
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:8187
bool isObjCObjectPointerType() const
Definition: Type.h:8333
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:8610
bool isVectorType() const
Definition: Type.h:8303
bool isObjCClassType() const
Definition: Type.h:8372
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:8199
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:8736
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:8548
bool isRecordType() const
Definition: Type.h:8291
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:3528
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5529
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3427
QualType getUnderlyingType() const
Definition: Decl.h:3482
void setTypeSourceInfo(TypeSourceInfo *newType)
Definition: Decl.h:3488
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5755
A unary type transform, which is a type constructed from another.
Definition: Type.h:5994
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition: DeclCXX.h:4369
static void Profile(llvm::FoldingSetNodeID &ID, QualType Ty, const APValue &APVal)
Definition: DeclCXX.h:4397
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition: Type.h:5672
Represents a dependent using declaration which was marked with typename.
Definition: DeclCXX.h:3982
Represents a C++ using-enum-declaration.
Definition: DeclCXX.h:3736
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3343
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5723
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:5392
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:8089
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.
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:6876
@ 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:308
@ BTK__type_pack_element
This names the __type_pack_element BuiltinTemplateDecl.
Definition: Builtins.h:313
@ BTK__builtin_common_type
This names the __builtin_common_type BuiltinTemplateDecl.
Definition: Builtins.h:316
@ BTK__make_integer_seq
This names the __make_integer_seq BuiltinTemplateDecl.
Definition: Builtins.h:310
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
@ TypeAlignment
Definition: Type.h:76
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:6851
@ 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:5164
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:5166
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition: Type.h:5169
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition: Type.h:5172
Extra information about a function prototype.
Definition: Type.h:5192
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:5199
bool requiresFunctionProtoTypeArmAttributes() const
Definition: Type.h:5224
FunctionEffectsRef FunctionEffects
Definition: Type.h:5202
const ExtParameterInfo * ExtParameterInfos
Definition: Type.h:5200
bool requiresFunctionProtoTypeExtraBitfields() const
Definition: Type.h:5218
FunctionType::ExtInfo ExtInfo
Definition: Type.h:5193
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:4625
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:4287
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