Debian Codegraph @

clang/lib/AST/ASTContext.cpp

raw
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
13 #include "clang/AST/ASTContext.h"
14 #include "ByteCode/Context.h"
15 #include "CXXABI.h"
16 #include "clang/AST/APValue.h"
17 #include "clang/AST/ASTConcept.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/ASTStructuralEquivalence.h"
20 #include "clang/AST/ASTTypeTraits.h"
21 #include "clang/AST/Attr.h"
22 #include "clang/AST/AttrIterator.h"
23 #include "clang/AST/CharUnits.h"
24 #include "clang/AST/Comment.h"
25 #include "clang/AST/Decl.h"
26 #include "clang/AST/DeclBase.h"
27 #include "clang/AST/DeclCXX.h"
28 #include "clang/AST/DeclContextInternals.h"
29 #include "clang/AST/DeclObjC.h"
30 #include "clang/AST/DeclOpenMP.h"
31 #include "clang/AST/DeclTemplate.h"
32 #include "clang/AST/DeclarationName.h"
33 #include "clang/AST/DependenceFlags.h"
34 #include "clang/AST/Expr.h"
35 #include "clang/AST/ExprCXX.h"
36 #include "clang/AST/ExternalASTSource.h"
37 #include "clang/AST/Mangle.h"
38 #include "clang/AST/MangleNumberingContext.h"
39 #include "clang/AST/NestedNameSpecifier.h"
40 #include "clang/AST/ParentMapContext.h"
41 #include "clang/AST/RawCommentList.h"
42 #include "clang/AST/RecordLayout.h"
43 #include "clang/AST/Stmt.h"
44 #include "clang/AST/TemplateBase.h"
45 #include "clang/AST/TemplateName.h"
46 #include "clang/AST/Type.h"
47 #include "clang/AST/TypeLoc.h"
48 #include "clang/AST/UnresolvedSet.h"
49 #include "clang/AST/VTableBuilder.h"
50 #include "clang/Basic/AddressSpaces.h"
51 #include "clang/Basic/Builtins.h"
52 #include "clang/Basic/CommentOptions.h"
53 #include "clang/Basic/ExceptionSpecificationType.h"
54 #include "clang/Basic/IdentifierTable.h"
55 #include "clang/Basic/LLVM.h"
56 #include "clang/Basic/LangOptions.h"
57 #include "clang/Basic/Linkage.h"
58 #include "clang/Basic/Module.h"
59 #include "clang/Basic/NoSanitizeList.h"
60 #include "clang/Basic/ObjCRuntime.h"
61 #include "clang/Basic/ProfileList.h"
62 #include "clang/Basic/SourceLocation.h"
63 #include "clang/Basic/SourceManager.h"
64 #include "clang/Basic/Specifiers.h"
65 #include "clang/Basic/TargetCXXABI.h"
66 #include "clang/Basic/TargetInfo.h"
67 #include "clang/Basic/XRayLists.h"
68 #include "llvm/ADT/APFixedPoint.h"
69 #include "llvm/ADT/APInt.h"
70 #include "llvm/ADT/APSInt.h"
71 #include "llvm/ADT/ArrayRef.h"
72 #include "llvm/ADT/DenseMap.h"
73 #include "llvm/ADT/DenseSet.h"
74 #include "llvm/ADT/FoldingSet.h"
75 #include "llvm/ADT/PointerUnion.h"
76 #include "llvm/ADT/STLExtras.h"
77 #include "llvm/ADT/SmallPtrSet.h"
78 #include "llvm/ADT/SmallVector.h"
79 #include "llvm/ADT/StringExtras.h"
80 #include "llvm/ADT/StringRef.h"
81 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
82 #include "llvm/Support/Capacity.h"
83 #include "llvm/Support/Casting.h"
84 #include "llvm/Support/Compiler.h"
85 #include "llvm/Support/ErrorHandling.h"
86 #include "llvm/Support/MD5.h"
87 #include "llvm/Support/MathExtras.h"
88 #include "llvm/Support/SipHash.h"
89 #include "llvm/Support/raw_ostream.h"
90 #include "llvm/TargetParser/AArch64TargetParser.h"
91 #include "llvm/TargetParser/Triple.h"
92 #include <algorithm>
93 #include <cassert>
94 #include <cstddef>
95 #include <cstdint>
96 #include <cstdlib>
97 #include <map>
98 #include <memory>
99 #include <optional>
100 #include <string>
101 #include <tuple>
102 #include <utility>
103
104 using namespace clang;
105
106 enum FloatingRank {
107 BFloat16Rank,
108 Float16Rank,
109 HalfRank,
110 FloatRank,
111 DoubleRank,
112 LongDoubleRank,
113 Float128Rank,
114 Ibm128Rank
115 };
116
117 /// \returns The locations that are relevant when searching for Doc comments
118 /// related to \p D.
119 static SmallVector<SourceLocation, 2>
120 getDeclLocsForCommentSearch(const Decl *D, SourceManager &SourceMgr) {
121 assert(D);
122
123 // User can not attach documentation to implicit declarations.
124 if (D->isImplicit())
125 return {};
126
127 // User can not attach documentation to implicit instantiations.
128 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
129 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
130 return {};
131 }
132
133 if (const auto *VD = dyn_cast<VarDecl>(D)) {
134 if (VD->isStaticDataMember() &&
135 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
136 return {};
137 }
138
139 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
140 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
141 return {};
142 }
143
144 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
145 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
146 if (TSK == TSK_ImplicitInstantiation ||
147 TSK == TSK_Undeclared)
148 return {};
149 }
150
151 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
152 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
153 return {};
154 }
155 if (const auto *TD = dyn_cast<TagDecl>(D)) {
156 // When tag declaration (but not definition!) is part of the
157 // decl-specifier-seq of some other declaration, it doesn't get comment
158 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
159 return {};
160 }
161 // TODO: handle comments for function parameters properly.
162 if (isa<ParmVarDecl>(D))
163 return {};
164
165 // TODO: we could look up template parameter documentation in the template
166 // documentation.
167 if (isa<TemplateTypeParmDecl>(D) ||
168 isa<NonTypeTemplateParmDecl>(D) ||
169 isa<TemplateTemplateParmDecl>(D))
170 return {};
171
172 SmallVector<SourceLocation, 2> Locations;
173 // Find declaration location.
174 // For Objective-C declarations we generally don't expect to have multiple
175 // declarators, thus use declaration starting location as the "declaration
176 // location".
177 // For all other declarations multiple declarators are used quite frequently,
178 // so we use the location of the identifier as the "declaration location".
179 SourceLocation BaseLocation;
180 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
181 isa<ObjCPropertyDecl>(D) || isa<RedeclarableTemplateDecl>(D) ||
182 isa<ClassTemplateSpecializationDecl>(D) ||
183 // Allow association with Y across {} in `typedef struct X {} Y`.
184 isa<TypedefDecl>(D))
185 BaseLocation = D->getBeginLoc();
186 else
187 BaseLocation = D->getLocation();
188
189 if (!D->getLocation().isMacroID()) {
190 Locations.emplace_back(BaseLocation);
191 } else {
192 const auto *DeclCtx = D->getDeclContext();
193
194 // When encountering definitions generated from a macro (that are not
195 // contained by another declaration in the macro) we need to try and find
196 // the comment at the location of the expansion but if there is no comment
197 // there we should retry to see if there is a comment inside the macro as
198 // well. To this end we return first BaseLocation to first look at the
199 // expansion site, the second value is the spelling location of the
200 // beginning of the declaration defined inside the macro.
201 if (!(DeclCtx &&
202 Decl::castFromDeclContext(DeclCtx)->getLocation().isMacroID())) {
203 Locations.emplace_back(SourceMgr.getExpansionLoc(BaseLocation));
204 }
205
206 // We use Decl::getBeginLoc() and not just BaseLocation here to ensure that
207 // we don't refer to the macro argument location at the expansion site (this
208 // can happen if the name's spelling is provided via macro argument), and
209 // always to the declaration itself.
210 Locations.emplace_back(SourceMgr.getSpellingLoc(D->getBeginLoc()));
211 }
212
213 return Locations;
214 }
215
216 RawComment *ASTContext::getRawCommentForDeclNoCacheImpl(
217 const Decl *D, const SourceLocation RepresentativeLocForDecl,
218 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
219 // If the declaration doesn't map directly to a location in a file, we
220 // can't find the comment.
221 if (RepresentativeLocForDecl.isInvalid() ||
222 !RepresentativeLocForDecl.isFileID())
223 return nullptr;
224
225 // If there are no comments anywhere, we won't find anything.
226 if (CommentsInTheFile.empty())
227 return nullptr;
228
229 // Decompose the location for the declaration and find the beginning of the
230 // file buffer.
231 const FileIDAndOffset DeclLocDecomp =
232 SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
233
234 // Slow path.
235 auto OffsetCommentBehindDecl =
236 CommentsInTheFile.lower_bound(DeclLocDecomp.second);
237
238 // First check whether we have a trailing comment.
239 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
240 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
241 if ((CommentBehindDecl->isDocumentation() ||
242 LangOpts.CommentOpts.ParseAllComments) &&
243 CommentBehindDecl->isTrailingComment() &&
244 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
245 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
246
247 // Check that Doxygen trailing comment comes after the declaration, starts
248 // on the same line and in the same file as the declaration.
249 if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
250 Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
251 OffsetCommentBehindDecl->first)) {
252 return CommentBehindDecl;
253 }
254 }
255 }
256
257 // The comment just after the declaration was not a trailing comment.
258 // Let's look at the previous comment.
259 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
260 return nullptr;
261
262 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
263 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
264
265 // Check that we actually have a non-member Doxygen comment.
266 if (!(CommentBeforeDecl->isDocumentation() ||
267 LangOpts.CommentOpts.ParseAllComments) ||
268 CommentBeforeDecl->isTrailingComment())
269 return nullptr;
270
271 // Decompose the end of the comment.
272 const unsigned CommentEndOffset =
273 Comments.getCommentEndOffset(CommentBeforeDecl);
274
275 // Get the corresponding buffer.
276 bool Invalid = false;
277 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
278 &Invalid).data();
279 if (Invalid)
280 return nullptr;
281
282 // Extract text between the comment and declaration.
283 StringRef Text(Buffer + CommentEndOffset,
284 DeclLocDecomp.second - CommentEndOffset);
285
286 // There should be no other declarations or preprocessor directives between
287 // comment and declaration.
288 if (Text.find_last_of(";{}#@") != StringRef::npos)
289 return nullptr;
290
291 return CommentBeforeDecl;
292 }
293
294 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
295 const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr);
296
297 for (const auto DeclLoc : DeclLocs) {
298 // If the declaration doesn't map directly to a location in a file, we
299 // can't find the comment.
300 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
301 continue;
302
303 if (ExternalSource && !CommentsLoaded) {
304 ExternalSource->ReadComments();
305 CommentsLoaded = true;
306 }
307
308 if (Comments.empty())
309 continue;
310
311 const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
312 if (!File.isValid())
313 continue;
314
315 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
316 if (!CommentsInThisFile || CommentsInThisFile->empty())
317 continue;
318
319 if (RawComment *Comment =
320 getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile))
321 return Comment;
322 }
323
324 return nullptr;
325 }
326
327 void ASTContext::addComment(const RawComment &RC) {
328 assert(LangOpts.RetainCommentsFromSystemHeaders ||
329 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
330 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
331 }
332
333 const RawComment *ASTContext::getRawCommentForAnyRedecl(
334 const Decl *D,
335 const Decl **OriginalDecl) const {
336 if (!D) {
337 if (OriginalDecl)
338 OriginalDecl = nullptr;
339 return nullptr;
340 }
341
342 D = &adjustDeclToTemplate(*D);
343
344 // Any comment directly attached to D?
345 {
346 auto DeclComment = DeclRawComments.find(D);
347 if (DeclComment != DeclRawComments.end()) {
348 if (OriginalDecl)
349 *OriginalDecl = D;
350 return DeclComment->second;
351 }
352 }
353
354 // Any comment attached to any redeclaration of D?
355 const Decl *CanonicalD = D->getCanonicalDecl();
356 if (!CanonicalD)
357 return nullptr;
358
359 {
360 auto RedeclComment = RedeclChainComments.find(CanonicalD);
361 if (RedeclComment != RedeclChainComments.end()) {
362 if (OriginalDecl)
363 *OriginalDecl = RedeclComment->second;
364 auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
365 assert(CommentAtRedecl != DeclRawComments.end() &&
366 "This decl is supposed to have comment attached.");
367 return CommentAtRedecl->second;
368 }
369 }
370
371 // Any redeclarations of D that we haven't checked for comments yet?
372 const Decl *LastCheckedRedecl = [&]() {
373 const Decl *LastChecked = CommentlessRedeclChains.lookup(CanonicalD);
374 bool CanUseCommentlessCache = false;
375 if (LastChecked) {
376 for (auto *Redecl : CanonicalD->redecls()) {
377 if (Redecl == D) {
378 CanUseCommentlessCache = true;
379 break;
380 }
381 if (Redecl == LastChecked)
382 break;
383 }
384 }
385 // FIXME: This could be improved so that even if CanUseCommentlessCache
386 // is false, once we've traversed past CanonicalD we still skip ahead
387 // LastChecked.
388 return CanUseCommentlessCache ? LastChecked : nullptr;
389 }();
390
391 for (const Decl *Redecl : D->redecls()) {
392 assert(Redecl);
393 // Skip all redeclarations that have been checked previously.
394 if (LastCheckedRedecl) {
395 if (LastCheckedRedecl == Redecl) {
396 LastCheckedRedecl = nullptr;
397 }
398 continue;
399 }
400 const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
401 if (RedeclComment) {
402 cacheRawCommentForDecl(*Redecl, *RedeclComment);
403 if (OriginalDecl)
404 *OriginalDecl = Redecl;
405 return RedeclComment;
406 }
407 CommentlessRedeclChains[CanonicalD] = Redecl;
408 }
409
410 if (OriginalDecl)
411 *OriginalDecl = nullptr;
412 return nullptr;
413 }
414
415 void ASTContext::cacheRawCommentForDecl(const Decl &OriginalD,
416 const RawComment &Comment) const {
417 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
418 DeclRawComments.try_emplace(&OriginalD, &Comment);
419 const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
420 RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
421 CommentlessRedeclChains.erase(CanonicalDecl);
422 }
423
424 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
425 SmallVectorImpl<const NamedDecl *> &Redeclared) {
426 const DeclContext *DC = ObjCMethod->getDeclContext();
427 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
428 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
429 if (!ID)
430 return;
431 // Add redeclared method here.
432 for (const auto *Ext : ID->known_extensions()) {
433 if (ObjCMethodDecl *RedeclaredMethod =
434 Ext->getMethod(ObjCMethod->getSelector(),
435 ObjCMethod->isInstanceMethod()))
436 Redeclared.push_back(RedeclaredMethod);
437 }
438 }
439 }
440
441 void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
442 const Preprocessor *PP) {
443 if (Comments.empty() || Decls.empty())
444 return;
445
446 FileID File;
447 for (const Decl *D : Decls) {
448 if (D->isInvalidDecl())
449 continue;
450
451 D = &adjustDeclToTemplate(*D);
452 SourceLocation Loc = D->getLocation();
453 if (Loc.isValid()) {
454 // See if there are any new comments that are not attached to a decl.
455 // The location doesn't have to be precise - we care only about the file.
456 File = SourceMgr.getDecomposedLoc(Loc).first;
457 break;
458 }
459 }
460
461 if (File.isInvalid())
462 return;
463
464 auto CommentsInThisFile = Comments.getCommentsInFile(File);
465 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
466 CommentsInThisFile->rbegin()->second->isAttached())
467 return;
468
469 // There is at least one comment not attached to a decl.
470 // Maybe it should be attached to one of Decls?
471 //
472 // Note that this way we pick up not only comments that precede the
473 // declaration, but also comments that *follow* the declaration -- thanks to
474 // the lookahead in the lexer: we've consumed the semicolon and looked
475 // ahead through comments.
476 for (const Decl *D : Decls) {
477 assert(D);
478 if (D->isInvalidDecl())
479 continue;
480
481 D = &adjustDeclToTemplate(*D);
482
483 if (DeclRawComments.count(D) > 0)
484 continue;
485
486 const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr);
487
488 for (const auto DeclLoc : DeclLocs) {
489 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
490 continue;
491
492 if (RawComment *const DocComment = getRawCommentForDeclNoCacheImpl(
493 D, DeclLoc, *CommentsInThisFile)) {
494 cacheRawCommentForDecl(*D, *DocComment);
495 comments::FullComment *FC = DocComment->parse(*this, PP, D);
496 ParsedComments[D->getCanonicalDecl()] = FC;
497 break;
498 }
499 }
500 }
501 }
502
503 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
504 const Decl *D) const {
505 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
506 ThisDeclInfo->CommentDecl = D;
507 ThisDeclInfo->IsFilled = false;
508 ThisDeclInfo->fill();
509 ThisDeclInfo->CommentDecl = FC->getDecl();
510 if (!ThisDeclInfo->TemplateParameters)
511 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
512 comments::FullComment *CFC =
513 new (*this) comments::FullComment(FC->getBlocks(),
514 ThisDeclInfo);
515 return CFC;
516 }
517
518 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
519 const RawComment *RC = getRawCommentForDeclNoCache(D);
520 return RC ? RC->parse(*this, nullptr, D) : nullptr;
521 }
522
523 comments::FullComment *ASTContext::getCommentForDecl(
524 const Decl *D,
525 const Preprocessor *PP) const {
526 if (!D || D->isInvalidDecl())
527 return nullptr;
528 D = &adjustDeclToTemplate(*D);
529
530 const Decl *Canonical = D->getCanonicalDecl();
531 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
532 ParsedComments.find(Canonical);
533
534 if (Pos != ParsedComments.end()) {
535 if (Canonical != D) {
536 comments::FullComment *FC = Pos->second;
537 comments::FullComment *CFC = cloneFullComment(FC, D);
538 return CFC;
539 }
540 return Pos->second;
541 }
542
543 const Decl *OriginalDecl = nullptr;
544
545 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
546 if (!RC) {
547 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
548 SmallVector<const NamedDecl*, 8> Overridden;
549 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
550 if (OMD && OMD->isPropertyAccessor())
551 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
552 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
553 return cloneFullComment(FC, D);
554 if (OMD)
555 addRedeclaredMethods(OMD, Overridden);
556 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
557 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
558 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
559 return cloneFullComment(FC, D);
560 }
561 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
562 // Attach any tag type's documentation to its typedef if latter
563 // does not have one of its own.
564 QualType QT = TD->getUnderlyingType();
565 if (const auto *TT = QT->getAs<TagType>())
566 if (comments::FullComment *FC = getCommentForDecl(TT->getDecl(), PP))
567 return cloneFullComment(FC, D);
568 }
569 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
570 while (IC->getSuperClass()) {
571 IC = IC->getSuperClass();
572 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
573 return cloneFullComment(FC, D);
574 }
575 }
576 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
577 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
578 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
579 return cloneFullComment(FC, D);
580 }
581 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
582 if (!(RD = RD->getDefinition()))
583 return nullptr;
584 // Check non-virtual bases.
585 for (const auto &I : RD->bases()) {
586 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
587 continue;
588 QualType Ty = I.getType();
589 if (Ty.isNull())
590 continue;
591 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
592 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
593 continue;
594
595 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
596 return cloneFullComment(FC, D);
597 }
598 }
599 // Check virtual bases.
600 for (const auto &I : RD->vbases()) {
601 if (I.getAccessSpecifier() != AS_public)
602 continue;
603 QualType Ty = I.getType();
604 if (Ty.isNull())
605 continue;
606 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
607 if (!(VirtualBase= VirtualBase->getDefinition()))
608 continue;
609 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
610 return cloneFullComment(FC, D);
611 }
612 }
613 }
614 return nullptr;
615 }
616
617 // If the RawComment was attached to other redeclaration of this Decl, we
618 // should parse the comment in context of that other Decl. This is important
619 // because comments can contain references to parameter names which can be
620 // different across redeclarations.
621 if (D != OriginalDecl && OriginalDecl)
622 return getCommentForDecl(OriginalDecl, PP);
623
624 comments::FullComment *FC = RC->parse(*this, PP, D);
625 ParsedComments[Canonical] = FC;
626 return FC;
627 }
628
629 void ASTContext::CanonicalTemplateTemplateParm::Profile(
630 llvm::FoldingSetNodeID &ID, const ASTContext &C,
631 TemplateTemplateParmDecl *Parm) {
632 ID.AddInteger(Parm->getDepth());
633 ID.AddInteger(Parm->getPosition());
634 ID.AddBoolean(Parm->isParameterPack());
635 ID.AddInteger(Parm->templateParameterKind());
636
637 TemplateParameterList *Params = Parm->getTemplateParameters();
638 ID.AddInteger(Params->size());
639 for (TemplateParameterList::const_iterator P = Params->begin(),
640 PEnd = Params->end();
641 P != PEnd; ++P) {
642 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
643 ID.AddInteger(0);
644 ID.AddBoolean(TTP->isParameterPack());
645 ID.AddInteger(
646 TTP->getNumExpansionParameters().toInternalRepresentation());
647 continue;
648 }
649
650 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
651 ID.AddInteger(1);
652 ID.AddBoolean(NTTP->isParameterPack());
653 ID.AddPointer(C.getUnconstrainedType(C.getCanonicalType(NTTP->getType()))
654 .getAsOpaquePtr());
655 if (NTTP->isExpandedParameterPack()) {
656 ID.AddBoolean(true);
657 ID.AddInteger(NTTP->getNumExpansionTypes());
658 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
659 QualType T = NTTP->getExpansionType(I);
660 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
661 }
662 } else
663 ID.AddBoolean(false);
664 continue;
665 }
666
667 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
668 ID.AddInteger(2);
669 Profile(ID, C, TTP);
670 }
671 }
672
673 TemplateTemplateParmDecl *
674 ASTContext::getCanonicalTemplateTemplateParmDecl(
675 TemplateTemplateParmDecl *TTP) const {
676 // Check if we already have a canonical template template parameter.
677 llvm::FoldingSetNodeID ID;
678 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
679 void *InsertPos = nullptr;
680 CanonicalTemplateTemplateParm *Canonical
681 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
682 if (Canonical)
683 return Canonical->getParam();
684
685 // Build a canonical template parameter list.
686 TemplateParameterList *Params = TTP->getTemplateParameters();
687 SmallVector<NamedDecl *, 4> CanonParams;
688 CanonParams.reserve(Params->size());
689 for (TemplateParameterList::const_iterator P = Params->begin(),
690 PEnd = Params->end();
691 P != PEnd; ++P) {
692 // Note that, per C++20 [temp.over.link]/6, when determining whether
693 // template-parameters are equivalent, constraints are ignored.
694 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
695 TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create(
696 *this, getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
697 TTP->getDepth(), TTP->getIndex(), nullptr, false,
698 TTP->isParameterPack(), /*HasTypeConstraint=*/false,
699 TTP->getNumExpansionParameters());
700 CanonParams.push_back(NewTTP);
701 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
702 QualType T = getUnconstrainedType(getCanonicalType(NTTP->getType()));
703 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
704 NonTypeTemplateParmDecl *Param;
705 if (NTTP->isExpandedParameterPack()) {
706 SmallVector<QualType, 2> ExpandedTypes;
707 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
708 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
709 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
710 ExpandedTInfos.push_back(
711 getTrivialTypeSourceInfo(ExpandedTypes.back()));
712 }
713
714 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
715 SourceLocation(),
716 SourceLocation(),
717 NTTP->getDepth(),
718 NTTP->getPosition(), nullptr,
719 T,
720 TInfo,
721 ExpandedTypes,
722 ExpandedTInfos);
723 } else {
724 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
725 SourceLocation(),
726 SourceLocation(),
727 NTTP->getDepth(),
728 NTTP->getPosition(), nullptr,
729 T,
730 NTTP->isParameterPack(),
731 TInfo);
732 }
733 CanonParams.push_back(Param);
734 } else
735 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
736 cast<TemplateTemplateParmDecl>(*P)));
737 }
738
739 TemplateTemplateParmDecl *CanonTTP = TemplateTemplateParmDecl::Create(
740 *this, getTranslationUnitDecl(), SourceLocation(), TTP->getDepth(),
741 TTP->getPosition(), TTP->isParameterPack(), nullptr,
742 TTP->templateParameterKind(),
743 /*Typename=*/false,
744 TemplateParameterList::Create(*this, SourceLocation(), SourceLocation(),
745 CanonParams, SourceLocation(),
746 /*RequiresClause=*/nullptr));
747
748 // Get the new insert position for the node we care about.
749 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
750 assert(!Canonical && "Shouldn't be in the map!");
751 (void)Canonical;
752
753 // Create the canonical template template parameter entry.
754 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
755 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
756 return CanonTTP;
757 }
758
759 TemplateTemplateParmDecl *
760 ASTContext::findCanonicalTemplateTemplateParmDeclInternal(
761 TemplateTemplateParmDecl *TTP) const {
762 llvm::FoldingSetNodeID ID;
763 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
764 void *InsertPos = nullptr;
765 CanonicalTemplateTemplateParm *Canonical =
766 CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
767 return Canonical ? Canonical->getParam() : nullptr;
768 }
769
770 TemplateTemplateParmDecl *
771 ASTContext::insertCanonicalTemplateTemplateParmDeclInternal(
772 TemplateTemplateParmDecl *CanonTTP) const {
773 llvm::FoldingSetNodeID ID;
774 CanonicalTemplateTemplateParm::Profile(ID, *this, CanonTTP);
775 void *InsertPos = nullptr;
776 if (auto *Existing =
777 CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos))
778 return Existing->getParam();
779 CanonTemplateTemplateParms.InsertNode(
780 new (*this) CanonicalTemplateTemplateParm(CanonTTP), InsertPos);
781 return CanonTTP;
782 }
783
784 /// Check if a type can have its sanitizer instrumentation elided based on its
785 /// presence within an ignorelist.
786 bool ASTContext::isTypeIgnoredBySanitizer(const SanitizerMask &Mask,
787 const QualType &Ty) const {
788 std::string TyName = Ty.getUnqualifiedType().getAsString(getPrintingPolicy());
789 return NoSanitizeL->containsType(Mask, TyName);
790 }
791
792 TargetCXXABI::Kind ASTContext::getCXXABIKind() const {
793 auto Kind = getTargetInfo().getCXXABI().getKind();
794 return getLangOpts().CXXABI.value_or(Kind);
795 }
796
797 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
798 if (!LangOpts.CPlusPlus) return nullptr;
799
800 switch (getCXXABIKind()) {
801 case TargetCXXABI::AppleARM64:
802 case TargetCXXABI::Fuchsia:
803 case TargetCXXABI::GenericARM: // Same as Itanium at this level
804 case TargetCXXABI::iOS:
805 case TargetCXXABI::WatchOS:
806 case TargetCXXABI::GenericAArch64:
807 case TargetCXXABI::GenericMIPS:
808 case TargetCXXABI::GenericItanium:
809 case TargetCXXABI::WebAssembly:
810 case TargetCXXABI::XL:
811 return CreateItaniumCXXABI(*this);
812 case TargetCXXABI::Microsoft:
813 return CreateMicrosoftCXXABI(*this);
814 }
815 llvm_unreachable("Invalid CXXABI type!");
816 }
817
818 interp::Context &ASTContext::getInterpContext() {
819 if (!InterpContext) {
820 InterpContext.reset(new interp::Context(*this));
821 }
822 return *InterpContext;
823 }
824
825 ParentMapContext &ASTContext::getParentMapContext() {
826 if (!ParentMapCtx)
827 ParentMapCtx.reset(new ParentMapContext(*this));
828 return *ParentMapCtx;
829 }
830
831 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
832 const LangOptions &LangOpts) {
833 switch (LangOpts.getAddressSpaceMapMangling()) {
834 case LangOptions::ASMM_Target:
835 return TI.useAddressSpaceMapMangling();
836 case LangOptions::ASMM_On:
837 return true;
838 case LangOptions::ASMM_Off:
839 return false;
840 }
841 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
842 }
843
844 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
845 IdentifierTable &idents, SelectorTable &sels,
846 Builtin::Context &builtins, TranslationUnitKind TUKind)
847 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize),
848 DependentSizedArrayTypes(this_()), DependentSizedExtVectorTypes(this_()),
849 DependentAddressSpaceTypes(this_()), DependentVectorTypes(this_()),
850 DependentSizedMatrixTypes(this_()),
851 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize),
852 DependentTypeOfExprTypes(this_()), DependentDecltypeTypes(this_()),
853 DependentPackIndexingTypes(this_()), TemplateSpecializationTypes(this_()),
854 DependentBitIntTypes(this_()), SubstTemplateTemplateParmPacks(this_()),
855 DeducedTemplates(this_()), ArrayParameterTypes(this_()),
856 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
857 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
858 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
859 LangOpts.XRayNeverInstrumentFiles,
860 LangOpts.XRayAttrListFiles, SM)),
861 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
862 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
863 BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this),
864 Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
865 CompCategories(this_()), LastSDM(nullptr, 0) {
866 addTranslationUnitDecl();
867 }
868
869 void ASTContext::cleanup() {
870 // Release the DenseMaps associated with DeclContext objects.
871 // FIXME: Is this the ideal solution?
872 ReleaseDeclContextMaps();
873
874 // Call all of the deallocation functions on all of their targets.
875 for (auto &Pair : Deallocations)
876 (Pair.first)(Pair.second);
877 Deallocations.clear();
878
879 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
880 // because they can contain DenseMaps.
881 for (llvm::DenseMap<const ObjCInterfaceDecl *,
882 const ASTRecordLayout *>::iterator
883 I = ObjCLayouts.begin(),
884 E = ObjCLayouts.end();
885 I != E;)
886 // Increment in loop to prevent using deallocated memory.
887 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
888 R->Destroy(*this);
889 ObjCLayouts.clear();
890
891 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
892 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
893 // Increment in loop to prevent using deallocated memory.
894 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
895 R->Destroy(*this);
896 }
897 ASTRecordLayouts.clear();
898
899 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
900 AEnd = DeclAttrs.end();
901 A != AEnd; ++A)
902 A->second->~AttrVec();
903 DeclAttrs.clear();
904
905 for (const auto &Value : ModuleInitializers)
906 Value.second->~PerModuleInitializers();
907 ModuleInitializers.clear();
908
909 XRayFilter.reset();
910 NoSanitizeL.reset();
911 }
912
913 ASTContext::~ASTContext() { cleanup(); }
914
915 void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
916 TraversalScope = TopLevelDecls;
917 getParentMapContext().clear();
918 }
919
920 void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
921 Deallocations.push_back({Callback, Data});
922 }
923
924 void
925 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
926 ExternalSource = std::move(Source);
927 }
928
929 void ASTContext::PrintStats() const {
930 llvm::errs() << "\n*** AST Context Stats:\n";
931 llvm::errs() << " " << Types.size() << " types total.\n";
932
933 unsigned counts[] = {
934 #define TYPE(Name, Parent) 0,
935 #define ABSTRACT_TYPE(Name, Parent)
936 #include "clang/AST/TypeNodes.inc"
937 0 // Extra
938 };
939
940 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
941 Type *T = Types[i];
942 counts[(unsigned)T->getTypeClass()]++;
943 }
944
945 unsigned Idx = 0;
946 unsigned TotalBytes = 0;
947 #define TYPE(Name, Parent) \
948 if (counts[Idx]) \
949 llvm::errs() << " " << counts[Idx] << " " << #Name \
950 << " types, " << sizeof(Name##Type) << " each " \
951 << "(" << counts[Idx] * sizeof(Name##Type) \
952 << " bytes)\n"; \
953 TotalBytes += counts[Idx] * sizeof(Name##Type); \
954 ++Idx;
955 #define ABSTRACT_TYPE(Name, Parent)
956 #include "clang/AST/TypeNodes.inc"
957
958 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
959
960 // Implicit special member functions.
961 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
962 << NumImplicitDefaultConstructors
963 << " implicit default constructors created\n";
964 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
965 << NumImplicitCopyConstructors
966 << " implicit copy constructors created\n";
967 if (getLangOpts().CPlusPlus)
968 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
969 << NumImplicitMoveConstructors
970 << " implicit move constructors created\n";
971 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
972 << NumImplicitCopyAssignmentOperators
973 << " implicit copy assignment operators created\n";
974 if (getLangOpts().CPlusPlus)
975 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
976 << NumImplicitMoveAssignmentOperators
977 << " implicit move assignment operators created\n";
978 llvm::errs() << NumImplicitDestructorsDeclared << "/"
979 << NumImplicitDestructors
980 << " implicit destructors created\n";
981
982 if (ExternalSource) {
983 llvm::errs() << "\n";
984 ExternalSource->PrintStats();
985 }
986
987 BumpAlloc.PrintStats();
988 }
989
990 void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
991 bool NotifyListeners) {
992 if (NotifyListeners)
993 if (auto *Listener = getASTMutationListener();
994 Listener && !ND->isUnconditionallyVisible())
995 Listener->RedefinedHiddenDefinition(ND, M);
996
997 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
998 }
999
1000 void ASTContext::deduplicateMergedDefinitionsFor(NamedDecl *ND) {
1001 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1002 if (It == MergedDefModules.end())
1003 return;
1004
1005 auto &Merged = It->second;
1006 llvm::DenseSet<Module*> Found;
1007 for (Module *&M : Merged)
1008 if (!Found.insert(M).second)
1009 M = nullptr;
1010 llvm::erase(Merged, nullptr);
1011 }
1012
1013 ArrayRef<Module *>
1014 ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) {
1015 auto MergedIt =
1016 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1017 if (MergedIt == MergedDefModules.end())
1018 return {};
1019 return MergedIt->second;
1020 }
1021
1022 void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1023 if (LazyInitializers.empty())
1024 return;
1025
1026 auto *Source = Ctx.getExternalSource();
1027 assert(Source && "lazy initializers but no external source");
1028
1029 auto LazyInits = std::move(LazyInitializers);
1030 LazyInitializers.clear();
1031
1032 for (auto ID : LazyInits)
1033 Initializers.push_back(Source->GetExternalDecl(ID));
1034
1035 assert(LazyInitializers.empty() &&
1036 "GetExternalDecl for lazy module initializer added more inits");
1037 }
1038
1039 void ASTContext::addModuleInitializer(Module *M, Decl *D) {
1040 // One special case: if we add a module initializer that imports another
1041 // module, and that module's only initializer is an ImportDecl, simplify.
1042 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1043 auto It = ModuleInitializers.find(ID->getImportedModule());
1044
1045 // Maybe the ImportDecl does nothing at all. (Common case.)
1046 if (It == ModuleInitializers.end())
1047 return;
1048
1049 // Maybe the ImportDecl only imports another ImportDecl.
1050 auto &Imported = *It->second;
1051 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1052 Imported.resolve(*this);
1053 auto *OnlyDecl = Imported.Initializers.front();
1054 if (isa<ImportDecl>(OnlyDecl))
1055 D = OnlyDecl;
1056 }
1057 }
1058
1059 auto *&Inits = ModuleInitializers[M];
1060 if (!Inits)
1061 Inits = new (*this) PerModuleInitializers;
1062 Inits->Initializers.push_back(D);
1063 }
1064
1065 void ASTContext::addLazyModuleInitializers(Module *M,
1066 ArrayRef<GlobalDeclID> IDs) {
1067 auto *&Inits = ModuleInitializers[M];
1068 if (!Inits)
1069 Inits = new (*this) PerModuleInitializers;
1070 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1071 IDs.begin(), IDs.end());
1072 }
1073
1074 ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
1075 auto It = ModuleInitializers.find(M);
1076 if (It == ModuleInitializers.end())
1077 return {};
1078
1079 auto *Inits = It->second;
1080 Inits->resolve(*this);
1081 return Inits->Initializers;
1082 }
1083
1084 void ASTContext::setCurrentNamedModule(Module *M) {
1085 assert(M->isNamedModule());
1086 assert(!CurrentCXXNamedModule &&
1087 "We should set named module for ASTContext for only once");
1088 CurrentCXXNamedModule = M;
1089 }
1090
1091 bool ASTContext::isInSameModule(const Module *M1, const Module *M2) const {
1092 if (!M1 != !M2)
1093 return false;
1094
1095 /// Get the representative module for M. The representative module is the
1096 /// first module unit for a specific primary module name. So that the module
1097 /// units have the same representative module belongs to the same module.
1098 ///
1099 /// The process is helpful to reduce the expensive string operations.
1100 auto GetRepresentativeModule = [this](const Module *M) {
1101 auto Iter = SameModuleLookupSet.find(M);
1102 if (Iter != SameModuleLookupSet.end())
1103 return Iter->second;
1104
1105 const Module *RepresentativeModule =
1106 PrimaryModuleNameMap.try_emplace(M->getPrimaryModuleInterfaceName(), M)
1107 .first->second;
1108 SameModuleLookupSet[M] = RepresentativeModule;
1109 return RepresentativeModule;
1110 };
1111
1112 assert(M1 && "Shouldn't call `isInSameModule` if both M1 and M2 are none.");
1113 return GetRepresentativeModule(M1) == GetRepresentativeModule(M2);
1114 }
1115
1116 ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1117 if (!ExternCContext)
1118 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1119
1120 return ExternCContext;
1121 }
1122
1123 BuiltinTemplateDecl *
1124 ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1125 const IdentifierInfo *II) const {
1126 auto *BuiltinTemplate =
1127 BuiltinTemplateDecl::Create(*this, getTranslationUnitDecl(), II, BTK);
1128 BuiltinTemplate->setImplicit();
1129 getTranslationUnitDecl()->addDecl(BuiltinTemplate);
1130
1131 return BuiltinTemplate;
1132 }
1133
1134 #define BuiltinTemplate(BTName) \
1135 BuiltinTemplateDecl *ASTContext::get##BTName##Decl() const { \
1136 if (!Decl##BTName) \
1137 Decl##BTName = \
1138 buildBuiltinTemplateDecl(BTK##BTName, get##BTName##Name()); \
1139 return Decl##BTName; \
1140 }
1141 #include "clang/Basic/BuiltinTemplates.inc"
1142
1143 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1144 RecordDecl::TagKind TK) const {
1145 SourceLocation Loc;
1146 RecordDecl *NewDecl;
1147 if (getLangOpts().CPlusPlus)
1148 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1149 Loc, &Idents.get(Name));
1150 else
1151 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1152 &Idents.get(Name));
1153 NewDecl->setImplicit();
1154 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1155 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1156 return NewDecl;
1157 }
1158
1159 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1160 StringRef Name) const {
1161 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1162 TypedefDecl *NewDecl = TypedefDecl::Create(
1163 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1164 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1165 NewDecl->setImplicit();
1166 return NewDecl;
1167 }
1168
1169 TypedefDecl *ASTContext::getInt128Decl() const {
1170 if (!Int128Decl)
1171 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1172 return Int128Decl;
1173 }
1174
1175 TypedefDecl *ASTContext::getUInt128Decl() const {
1176 if (!UInt128Decl)
1177 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1178 return UInt128Decl;
1179 }
1180
1181 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1182 auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K);
1183 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
1184 Types.push_back(Ty);
1185 }
1186
1187 void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1188 const TargetInfo *AuxTarget) {
1189 assert((!this->Target || this->Target == &Target) &&
1190 "Incorrect target reinitialization");
1191 assert(VoidTy.isNull() && "Context reinitialized?");
1192
1193 this->Target = &Target;
1194 this->AuxTarget = AuxTarget;
1195
1196 ABI.reset(createCXXABI(Target));
1197 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1198
1199 // C99 6.2.5p19.
1200 InitBuiltinType(VoidTy, BuiltinType::Void);
1201
1202 // C99 6.2.5p2.
1203 InitBuiltinType(BoolTy, BuiltinType::Bool);
1204 // C99 6.2.5p3.
1205 if (LangOpts.CharIsSigned)
1206 InitBuiltinType(CharTy, BuiltinType::Char_S);
1207 else
1208 InitBuiltinType(CharTy, BuiltinType::Char_U);
1209 // C99 6.2.5p4.
1210 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1211 InitBuiltinType(ShortTy, BuiltinType::Short);
1212 InitBuiltinType(IntTy, BuiltinType::Int);
1213 InitBuiltinType(LongTy, BuiltinType::Long);
1214 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1215
1216 // C99 6.2.5p6.
1217 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1218 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1219 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1220 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1221 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1222
1223 // C99 6.2.5p10.
1224 InitBuiltinType(FloatTy, BuiltinType::Float);
1225 InitBuiltinType(DoubleTy, BuiltinType::Double);
1226 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1227
1228 // GNU extension, __float128 for IEEE quadruple precision
1229 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1230
1231 // __ibm128 for IBM extended precision
1232 InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128);
1233
1234 // C11 extension ISO/IEC TS 18661-3
1235 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1236
1237 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1238 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1239 InitBuiltinType(AccumTy, BuiltinType::Accum);
1240 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1241 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1242 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1243 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1244 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1245 InitBuiltinType(FractTy, BuiltinType::Fract);
1246 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1247 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1248 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1249 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1250 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1251 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1252 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1253 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1254 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1255 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1256 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1257 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1258 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1259 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1260 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1261 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
1262
1263 // GNU extension, 128-bit integers.
1264 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1265 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1266
1267 // C++ 3.9.1p5
1268 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1269 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1270 else // -fshort-wchar makes wchar_t be unsigned.
1271 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1272 if (LangOpts.CPlusPlus && LangOpts.WChar)
1273 WideCharTy = WCharTy;
1274 else {
1275 // C99 (or C++ using -fno-wchar).
1276 WideCharTy = getFromTargetType(Target.getWCharType());
1277 }
1278
1279 WIntTy = getFromTargetType(Target.getWIntType());
1280
1281 // C++20 (proposed)
1282 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1283
1284 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1285 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1286 else // C99
1287 Char16Ty = getFromTargetType(Target.getChar16Type());
1288
1289 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1290 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1291 else // C99
1292 Char32Ty = getFromTargetType(Target.getChar32Type());
1293
1294 // Placeholder type for type-dependent expressions whose type is
1295 // completely unknown. No code should ever check a type against
1296 // DependentTy and users should never see it; however, it is here to
1297 // help diagnose failures to properly check for type-dependent
1298 // expressions.
1299 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1300
1301 // Placeholder type for functions.
1302 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1303
1304 // Placeholder type for bound members.
1305 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1306
1307 // Placeholder type for unresolved templates.
1308 InitBuiltinType(UnresolvedTemplateTy, BuiltinType::UnresolvedTemplate);
1309
1310 // Placeholder type for pseudo-objects.
1311 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1312
1313 // "any" type; useful for debugger-like clients.
1314 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1315
1316 // Placeholder type for unbridged ARC casts.
1317 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1318
1319 // Placeholder type for builtin functions.
1320 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1321
1322 // Placeholder type for OMP array sections.
1323 if (LangOpts.OpenMP) {
1324 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1325 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1326 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1327 }
1328 // Placeholder type for OpenACC array sections, if we are ALSO in OMP mode,
1329 // don't bother, as we're just using the same type as OMP.
1330 if (LangOpts.OpenACC && !LangOpts.OpenMP) {
1331 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1332 }
1333 if (LangOpts.MatrixTypes)
1334 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1335
1336 // Builtin types for 'id', 'Class', and 'SEL'.
1337 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1338 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1339 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1340
1341 if (LangOpts.OpenCL) {
1342 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1343 InitBuiltinType(SingletonId, BuiltinType::Id);
1344 #include "clang/Basic/OpenCLImageTypes.def"
1345
1346 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1347 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1348 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1349 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1350 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1351
1352 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1353 InitBuiltinType(Id##Ty, BuiltinType::Id);
1354 #include "clang/Basic/OpenCLExtensionTypes.def"
1355 }
1356
1357 if (LangOpts.HLSL) {
1358 #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1359 InitBuiltinType(SingletonId, BuiltinType::Id);
1360 #include "clang/Basic/HLSLIntangibleTypes.def"
1361 }
1362
1363 if (Target.hasAArch64ACLETypes() ||
1364 (AuxTarget && AuxTarget->hasAArch64ACLETypes())) {
1365 #define SVE_TYPE(Name, Id, SingletonId) \
1366 InitBuiltinType(SingletonId, BuiltinType::Id);
1367 #include "clang/Basic/AArch64ACLETypes.def"
1368 }
1369
1370 if (Target.getTriple().isPPC64()) {
1371 #define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1372 InitBuiltinType(Id##Ty, BuiltinType::Id);
1373 #include "clang/Basic/PPCTypes.def"
1374 #define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1375 InitBuiltinType(Id##Ty, BuiltinType::Id);
1376 #include "clang/Basic/PPCTypes.def"
1377 }
1378
1379 if (Target.hasRISCVVTypes()) {
1380 #define RVV_TYPE(Name, Id, SingletonId) \
1381 InitBuiltinType(SingletonId, BuiltinType::Id);
1382 #include "clang/Basic/RISCVVTypes.def"
1383 }
1384
1385 if (Target.getTriple().isWasm() && Target.hasFeature("reference-types")) {
1386 #define WASM_TYPE(Name, Id, SingletonId) \
1387 InitBuiltinType(SingletonId, BuiltinType::Id);
1388 #include "clang/Basic/WebAssemblyReferenceTypes.def"
1389 }
1390
1391 if (Target.getTriple().isAMDGPU() ||
1392 (AuxTarget && AuxTarget->getTriple().isAMDGPU())) {
1393 #define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
1394 InitBuiltinType(SingletonId, BuiltinType::Id);
1395 #include "clang/Basic/AMDGPUTypes.def"
1396 }
1397
1398 // Builtin type for __objc_yes and __objc_no
1399 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1400 SignedCharTy : BoolTy);
1401
1402 ObjCConstantStringType = QualType();
1403
1404 ObjCSuperType = QualType();
1405
1406 // void * type
1407 if (LangOpts.OpenCLGenericAddressSpace) {
1408 auto Q = VoidTy.getQualifiers();
1409 Q.setAddressSpace(LangAS::opencl_generic);
1410 VoidPtrTy = getPointerType(getCanonicalType(
1411 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1412 } else {
1413 VoidPtrTy = getPointerType(VoidTy);
1414 }
1415
1416 // nullptr type (C++0x 2.14.7)
1417 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1418
1419 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1420 InitBuiltinType(HalfTy, BuiltinType::Half);
1421
1422 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1423
1424 // Builtin type used to help define __builtin_va_list.
1425 VaListTagDecl = nullptr;
1426
1427 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1428 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1429 MSGuidTagDecl = buildImplicitRecord("_GUID");
1430 getTranslationUnitDecl()->addDecl(MSGuidTagDecl);
1431 }
1432 }
1433
1434 DiagnosticsEngine &ASTContext::getDiagnostics() const {
1435 return SourceMgr.getDiagnostics();
1436 }
1437
1438 AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1439 AttrVec *&Result = DeclAttrs[D];
1440 if (!Result) {
1441 void *Mem = Allocate(sizeof(AttrVec));
1442 Result = new (Mem) AttrVec;
1443 }
1444
1445 return *Result;
1446 }
1447
1448 /// Erase the attributes corresponding to the given declaration.
1449 void ASTContext::eraseDeclAttrs(const Decl *D) {
1450 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1451 if (Pos != DeclAttrs.end()) {
1452 Pos->second->~AttrVec();
1453 DeclAttrs.erase(Pos);
1454 }
1455 }
1456
1457 // FIXME: Remove ?
1458 MemberSpecializationInfo *
1459 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1460 assert(Var->isStaticDataMember() && "Not a static data member");
1461 return getTemplateOrSpecializationInfo(Var)
1462 .dyn_cast<MemberSpecializationInfo *>();
1463 }
1464
1465 ASTContext::TemplateOrSpecializationInfo
1466 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1467 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1468 TemplateOrInstantiation.find(Var);
1469 if (Pos == TemplateOrInstantiation.end())
1470 return {};
1471
1472 return Pos->second;
1473 }
1474
1475 void
1476 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1477 TemplateSpecializationKind TSK,
1478 SourceLocation PointOfInstantiation) {
1479 assert(Inst->isStaticDataMember() && "Not a static data member");
1480 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1481 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1482 Tmpl, TSK, PointOfInstantiation));
1483 }
1484
1485 void
1486 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1487 TemplateOrSpecializationInfo TSI) {
1488 assert(!TemplateOrInstantiation[Inst] &&
1489 "Already noted what the variable was instantiated from");
1490 TemplateOrInstantiation[Inst] = TSI;
1491 }
1492
1493 NamedDecl *
1494 ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1495 return InstantiatedFromUsingDecl.lookup(UUD);
1496 }
1497
1498 void
1499 ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
1500 assert((isa<UsingDecl>(Pattern) ||
1501 isa<UnresolvedUsingValueDecl>(Pattern) ||
1502 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1503 "pattern decl is not a using decl");
1504 assert((isa<UsingDecl>(Inst) ||
1505 isa<UnresolvedUsingValueDecl>(Inst) ||
1506 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1507 "instantiation did not produce a using decl");
1508 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1509 InstantiatedFromUsingDecl[Inst] = Pattern;
1510 }
1511
1512 UsingEnumDecl *
1513 ASTContext::getInstantiatedFromUsingEnumDecl(UsingEnumDecl *UUD) {
1514 return InstantiatedFromUsingEnumDecl.lookup(UUD);
1515 }
1516
1517 void ASTContext::setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst,
1518 UsingEnumDecl *Pattern) {
1519 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1520 InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1521 }
1522
1523 UsingShadowDecl *
1524 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1525 return InstantiatedFromUsingShadowDecl.lookup(Inst);
1526 }
1527
1528 void
1529 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1530 UsingShadowDecl *Pattern) {
1531 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1532 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1533 }
1534
1535 FieldDecl *
1536 ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const {
1537 return InstantiatedFromUnnamedFieldDecl.lookup(Field);
1538 }
1539
1540 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1541 FieldDecl *Tmpl) {
1542 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1543 "Instantiated field decl is not unnamed");
1544 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1545 "Template field decl is not unnamed");
1546 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1547 "Already noted what unnamed field was instantiated from");
1548
1549 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1550 }
1551
1552 ASTContext::overridden_cxx_method_iterator
1553 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1554 return overridden_methods(Method).begin();
1555 }
1556
1557 ASTContext::overridden_cxx_method_iterator
1558 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1559 return overridden_methods(Method).end();
1560 }
1561
1562 unsigned
1563 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1564 auto Range = overridden_methods(Method);
1565 return Range.end() - Range.begin();
1566 }
1567
1568 ASTContext::overridden_method_range
1569 ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1570 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1571 OverriddenMethods.find(Method->getCanonicalDecl());
1572 if (Pos == OverriddenMethods.end())
1573 return overridden_method_range(nullptr, nullptr);
1574 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1575 }
1576
1577 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1578 const CXXMethodDecl *Overridden) {
1579 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1580 OverriddenMethods[Method].push_back(Overridden);
1581 }
1582
1583 void ASTContext::getOverriddenMethods(
1584 const NamedDecl *D,
1585 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1586 assert(D);
1587
1588 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1589 Overridden.append(overridden_methods_begin(CXXMethod),
1590 overridden_methods_end(CXXMethod));
1591 return;
1592 }
1593
1594 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1595 if (!Method)
1596 return;
1597
1598 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1599 Method->getOverriddenMethods(OverDecls);
1600 Overridden.append(OverDecls.begin(), OverDecls.end());
1601 }
1602
1603 std::optional<ASTContext::CXXRecordDeclRelocationInfo>
1604 ASTContext::getRelocationInfoForCXXRecord(const CXXRecordDecl *RD) const {
1605 assert(RD);
1606 CXXRecordDecl *D = RD->getDefinition();
1607 auto it = RelocatableClasses.find(D);
1608 if (it != RelocatableClasses.end())
1609 return it->getSecond();
1610 return std::nullopt;
1611 }
1612
1613 void ASTContext::setRelocationInfoForCXXRecord(
1614 const CXXRecordDecl *RD, CXXRecordDeclRelocationInfo Info) {
1615 assert(RD);
1616 CXXRecordDecl *D = RD->getDefinition();
1617 assert(RelocatableClasses.find(D) == RelocatableClasses.end());
1618 RelocatableClasses.insert({D, Info});
1619 }
1620
1621 static bool primaryBaseHaseAddressDiscriminatedVTableAuthentication(
1622 const ASTContext &Context, const CXXRecordDecl *Class) {
1623 if (!Class->isPolymorphic())
1624 return false;
1625 const CXXRecordDecl *BaseType = Context.baseForVTableAuthentication(Class);
1626 using AuthAttr = VTablePointerAuthenticationAttr;
1627 const AuthAttr *ExplicitAuth = BaseType->getAttr<AuthAttr>();
1628 if (!ExplicitAuth)
1629 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1630 AuthAttr::AddressDiscriminationMode AddressDiscrimination =
1631 ExplicitAuth->getAddressDiscrimination();
1632 if (AddressDiscrimination == AuthAttr::DefaultAddressDiscrimination)
1633 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1634 return AddressDiscrimination == AuthAttr::AddressDiscrimination;
1635 }
1636
1637 ASTContext::PointerAuthContent
1638 ASTContext::findPointerAuthContent(QualType T) const {
1639 assert(isPointerAuthenticationAvailable());
1640
1641 T = T.getCanonicalType();
1642 if (T->isDependentType())
1643 return PointerAuthContent::None;
1644
1645 if (T.hasAddressDiscriminatedPointerAuth())
1646 return PointerAuthContent::AddressDiscriminatedData;
1647 const RecordDecl *RD = T->getAsRecordDecl();
1648 if (!RD)
1649 return PointerAuthContent::None;
1650
1651 if (RD->isInvalidDecl())
1652 return PointerAuthContent::None;
1653
1654 if (auto Existing = RecordContainsAddressDiscriminatedPointerAuth.find(RD);
1655 Existing != RecordContainsAddressDiscriminatedPointerAuth.end())
1656 return Existing->second;
1657
1658 PointerAuthContent Result = PointerAuthContent::None;
1659
1660 auto SaveResultAndReturn = [&]() -> PointerAuthContent {
1661 auto [ResultIter, DidAdd] =
1662 RecordContainsAddressDiscriminatedPointerAuth.try_emplace(RD, Result);
1663 (void)ResultIter;
1664 (void)DidAdd;
1665 assert(DidAdd);
1666 return Result;
1667 };
1668 auto ShouldContinueAfterUpdate = [&](PointerAuthContent NewResult) {
1669 static_assert(PointerAuthContent::None <
1670 PointerAuthContent::AddressDiscriminatedVTable);
1671 static_assert(PointerAuthContent::AddressDiscriminatedVTable <
1672 PointerAuthContent::AddressDiscriminatedData);
1673 if (NewResult > Result)
1674 Result = NewResult;
1675 return Result != PointerAuthContent::AddressDiscriminatedData;
1676 };
1677 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1678 if (primaryBaseHaseAddressDiscriminatedVTableAuthentication(*this, CXXRD) &&
1679 !ShouldContinueAfterUpdate(
1680 PointerAuthContent::AddressDiscriminatedVTable))
1681 return SaveResultAndReturn();
1682 for (auto Base : CXXRD->bases()) {
1683 if (!ShouldContinueAfterUpdate(findPointerAuthContent(Base.getType())))
1684 return SaveResultAndReturn();
1685 }
1686 }
1687 for (auto *FieldDecl : RD->fields()) {
1688 if (!ShouldContinueAfterUpdate(
1689 findPointerAuthContent(FieldDecl->getType())))
1690 return SaveResultAndReturn();
1691 }
1692 return SaveResultAndReturn();
1693 }
1694
1695 void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1696 assert(!Import->getNextLocalImport() &&
1697 "Import declaration already in the chain");
1698 assert(!Import->isFromASTFile() && "Non-local import declaration");
1699 if (!FirstLocalImport) {
1700 FirstLocalImport = Import;
1701 LastLocalImport = Import;
1702 return;
1703 }
1704
1705 LastLocalImport->setNextLocalImport(Import);
1706 LastLocalImport = Import;
1707 }
1708
1709 //===----------------------------------------------------------------------===//
1710 // Type Sizing and Analysis
1711 //===----------------------------------------------------------------------===//
1712
1713 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1714 /// scalar floating point type.
1715 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1716 switch (T->castAs<BuiltinType>()->getKind()) {
1717 default:
1718 llvm_unreachable("Not a floating point type!");
1719 case BuiltinType::BFloat16:
1720 return Target->getBFloat16Format();
1721 case BuiltinType::Float16:
1722 return Target->getHalfFormat();
1723 case BuiltinType::Half:
1724 return Target->getHalfFormat();
1725 case BuiltinType::Float: return Target->getFloatFormat();
1726 case BuiltinType::Double: return Target->getDoubleFormat();
1727 case BuiltinType::Ibm128:
1728 return Target->getIbm128Format();
1729 case BuiltinType::LongDouble:
1730 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1731 return AuxTarget->getLongDoubleFormat();
1732 return Target->getLongDoubleFormat();
1733 case BuiltinType::Float128:
1734 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1735 return AuxTarget->getFloat128Format();
1736 return Target->getFloat128Format();
1737 }
1738 }
1739
1740 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1741 unsigned Align = Target->getCharWidth();
1742
1743 const unsigned AlignFromAttr = D->getMaxAlignment();
1744 if (AlignFromAttr)
1745 Align = AlignFromAttr;
1746
1747 // __attribute__((aligned)) can increase or decrease alignment
1748 // *except* on a struct or struct member, where it only increases
1749 // alignment unless 'packed' is also specified.
1750 //
1751 // It is an error for alignas to decrease alignment, so we can
1752 // ignore that possibility; Sema should diagnose it.
1753 bool UseAlignAttrOnly;
1754 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D))
1755 UseAlignAttrOnly =
1756 FD->hasAttr<PackedAttr>() || FD->getParent()->hasAttr<PackedAttr>();
1757 else
1758 UseAlignAttrOnly = AlignFromAttr != 0;
1759 // If we're using the align attribute only, just ignore everything
1760 // else about the declaration and its type.
1761 if (UseAlignAttrOnly) {
1762 // do nothing
1763 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1764 QualType T = VD->getType();
1765 if (const auto *RT = T->getAs<ReferenceType>()) {
1766 if (ForAlignof)
1767 T = RT->getPointeeType();
1768 else
1769 T = getPointerType(RT->getPointeeType());
1770 }
1771 QualType BaseT = getBaseElementType(T);
1772 if (T->isFunctionType())
1773 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1774 else if (!BaseT->isIncompleteType()) {
1775 // Adjust alignments of declarations with array type by the
1776 // large-array alignment on the target.
1777 if (const ArrayType *arrayType = getAsArrayType(T)) {
1778 unsigned MinWidth = Target->getLargeArrayMinWidth();
1779 if (!ForAlignof && MinWidth) {
1780 if (isa<VariableArrayType>(arrayType))
1781 Align = std::max(Align, Target->getLargeArrayAlign());
1782 else if (isa<ConstantArrayType>(arrayType) &&
1783 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1784 Align = std::max(Align, Target->getLargeArrayAlign());
1785 }
1786 }
1787 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1788 if (BaseT.getQualifiers().hasUnaligned())
1789 Align = Target->getCharWidth();
1790 }
1791
1792 // Ensure minimum alignment for global variables.
1793 if (const auto *VD = dyn_cast<VarDecl>(D))
1794 if (VD->hasGlobalStorage() && !ForAlignof) {
1795 uint64_t TypeSize =
1796 !BaseT->isIncompleteType() ? getTypeSize(T.getTypePtr()) : 0;
1797 Align = std::max(Align, getMinGlobalAlignOfVar(TypeSize, VD));
1798 }
1799
1800 // Fields can be subject to extra alignment constraints, like if
1801 // the field is packed, the struct is packed, or the struct has a
1802 // a max-field-alignment constraint (#pragma pack). So calculate
1803 // the actual alignment of the field within the struct, and then
1804 // (as we're expected to) constrain that by the alignment of the type.
1805 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1806 const RecordDecl *Parent = Field->getParent();
1807 // We can only produce a sensible answer if the record is valid.
1808 if (!Parent->isInvalidDecl()) {
1809 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1810
1811 // Start with the record's overall alignment.
1812 unsigned FieldAlign = toBits(Layout.getAlignment());
1813
1814 // Use the GCD of that and the offset within the record.
1815 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1816 if (Offset > 0) {
1817 // Alignment is always a power of 2, so the GCD will be a power of 2,
1818 // which means we get to do this crazy thing instead of Euclid's.
1819 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1820 if (LowBitOfOffset < FieldAlign)
1821 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1822 }
1823
1824 Align = std::min(Align, FieldAlign);
1825 }
1826 }
1827 }
1828
1829 // Some targets have hard limitation on the maximum requestable alignment in
1830 // aligned attribute for static variables.
1831 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1832 const auto *VD = dyn_cast<VarDecl>(D);
1833 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1834 Align = std::min(Align, MaxAlignedAttr);
1835
1836 return toCharUnitsFromBits(Align);
1837 }
1838
1839 CharUnits ASTContext::getExnObjectAlignment() const {
1840 return toCharUnitsFromBits(Target->getExnObjectAlignment());
1841 }
1842
1843 // getTypeInfoDataSizeInChars - Return the size of a type, in
1844 // chars. If the type is a record, its data size is returned. This is
1845 // the size of the memcpy that's performed when assigning this type
1846 // using a trivial copy/move assignment operator.
1847 TypeInfoChars ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1848 TypeInfoChars Info = getTypeInfoInChars(T);
1849
1850 // In C++, objects can sometimes be allocated into the tail padding
1851 // of a base-class subobject. We decide whether that's possible
1852 // during class layout, so here we can just trust the layout results.
1853 if (getLangOpts().CPlusPlus) {
1854 if (const auto *RD = T->getAsCXXRecordDecl(); RD && !RD->isInvalidDecl()) {
1855 const ASTRecordLayout &layout = getASTRecordLayout(RD);
1856 Info.Width = layout.getDataSize();
1857 }
1858 }
1859
1860 return Info;
1861 }
1862
1863 /// getConstantArrayInfoInChars - Performing the computation in CharUnits
1864 /// instead of in bits prevents overflowing the uint64_t for some large arrays.
1865 TypeInfoChars
1866 static getConstantArrayInfoInChars(const ASTContext &Context,
1867 const ConstantArrayType *CAT) {
1868 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1869 uint64_t Size = CAT->getZExtSize();
1870 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1871 (uint64_t)(-1)/Size) &&
1872 "Overflow in array type char size evaluation");
1873 uint64_t Width = EltInfo.Width.getQuantity() * Size;
1874 unsigned Align = EltInfo.Align.getQuantity();
1875 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1876 Context.getTargetInfo().getPointerWidth(LangAS::Default) == 64)
1877 Width = llvm::alignTo(Width, Align);
1878 return TypeInfoChars(CharUnits::fromQuantity(Width),
1879 CharUnits::fromQuantity(Align),
1880 EltInfo.AlignRequirement);
1881 }
1882
1883 TypeInfoChars ASTContext::getTypeInfoInChars(const Type *T) const {
1884 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1885 return getConstantArrayInfoInChars(*this, CAT);
1886 TypeInfo Info = getTypeInfo(T);
1887 return TypeInfoChars(toCharUnitsFromBits(Info.Width),
1888 toCharUnitsFromBits(Info.Align), Info.AlignRequirement);
1889 }
1890
1891 TypeInfoChars ASTContext::getTypeInfoInChars(QualType T) const {
1892 return getTypeInfoInChars(T.getTypePtr());
1893 }
1894
1895 bool ASTContext::isPromotableIntegerType(QualType T) const {
1896 // HLSL doesn't promote all small integer types to int, it
1897 // just uses the rank-based promotion rules for all types.
1898 if (getLangOpts().HLSL)
1899 return false;
1900
1901 if (const auto *BT = T->getAs<BuiltinType>())
1902 switch (BT->getKind()) {
1903 case BuiltinType::Bool:
1904 case BuiltinType::Char_S:
1905 case BuiltinType::Char_U:
1906 case BuiltinType::SChar:
1907 case BuiltinType::UChar:
1908 case BuiltinType::Short:
1909 case BuiltinType::UShort:
1910 case BuiltinType::WChar_S:
1911 case BuiltinType::WChar_U:
1912 case BuiltinType::Char8:
1913 case BuiltinType::Char16:
1914 case BuiltinType::Char32:
1915 return true;
1916 default:
1917 return false;
1918 }
1919
1920 // Enumerated types are promotable to their compatible integer types
1921 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
1922 if (const auto *ED = T->getAsEnumDecl()) {
1923 if (T->isDependentType() || ED->getPromotionType().isNull() ||
1924 ED->isScoped())
1925 return false;
1926
1927 return true;
1928 }
1929
1930 return false;
1931 }
1932
1933 bool ASTContext::isAlignmentRequired(const Type *T) const {
1934 return getTypeInfo(T).AlignRequirement != AlignRequirementKind::None;
1935 }
1936
1937 bool ASTContext::isAlignmentRequired(QualType T) const {
1938 return isAlignmentRequired(T.getTypePtr());
1939 }
1940
1941 unsigned ASTContext::getTypeAlignIfKnown(QualType T,
1942 bool NeedsPreferredAlignment) const {
1943 // An alignment on a typedef overrides anything else.
1944 if (const auto *TT = T->getAs<TypedefType>())
1945 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1946 return Align;
1947
1948 // If we have an (array of) complete type, we're done.
1949 T = getBaseElementType(T);
1950 if (!T->isIncompleteType())
1951 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
1952
1953 // If we had an array type, its element type might be a typedef
1954 // type with an alignment attribute.
1955 if (const auto *TT = T->getAs<TypedefType>())
1956 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1957 return Align;
1958
1959 // Otherwise, see if the declaration of the type had an attribute.
1960 if (const auto *TD = T->getAsTagDecl())
1961 return TD->getMaxAlignment();
1962
1963 return 0;
1964 }
1965
1966 TypeInfo ASTContext::getTypeInfo(const Type *T) const {
1967 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1968 if (I != MemoizedTypeInfo.end())
1969 return I->second;
1970
1971 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1972 TypeInfo TI = getTypeInfoImpl(T);
1973 MemoizedTypeInfo[T] = TI;
1974 return TI;
1975 }
1976
1977 /// getTypeInfoImpl - Return the size of the specified type, in bits. This
1978 /// method does not work on incomplete types.
1979 ///
1980 /// FIXME: Pointers into different addr spaces could have different sizes and
1981 /// alignment requirements: getPointerInfo should take an AddrSpace, this
1982 /// should take a QualType, &c.
1983 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1984 uint64_t Width = 0;
1985 unsigned Align = 8;
1986 AlignRequirementKind AlignRequirement = AlignRequirementKind::None;
1987 LangAS AS = LangAS::Default;
1988 switch (T->getTypeClass()) {
1989 #define TYPE(Class, Base)
1990 #define ABSTRACT_TYPE(Class, Base)
1991 #define NON_CANONICAL_TYPE(Class, Base)
1992 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1993 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1994 case Type::Class: \
1995 assert(!T->isDependentType() && "should not see dependent types here"); \
1996 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1997 #include "clang/AST/TypeNodes.inc"
1998 llvm_unreachable("Should not see dependent types");
1999
2000 case Type::FunctionNoProto:
2001 case Type::FunctionProto:
2002 // GCC extension: alignof(function) = 32 bits
2003 Width = 0;
2004 Align = 32;
2005 break;
2006
2007 case Type::IncompleteArray:
2008 case Type::VariableArray:
2009 case Type::ConstantArray:
2010 case Type::ArrayParameter: {
2011 // Model non-constant sized arrays as size zero, but track the alignment.
2012 uint64_t Size = 0;
2013 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
2014 Size = CAT->getZExtSize();
2015
2016 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
2017 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
2018 "Overflow in array type bit size evaluation");
2019 Width = EltInfo.Width * Size;
2020 Align = EltInfo.Align;
2021 AlignRequirement = EltInfo.AlignRequirement;
2022 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
2023 getTargetInfo().getPointerWidth(LangAS::Default) == 64)
2024 Width = llvm::alignTo(Width, Align);
2025 break;
2026 }
2027
2028 case Type::ExtVector:
2029 case Type::Vector: {
2030 const auto *VT = cast<VectorType>(T);
2031 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
2032 Width = VT->isPackedVectorBoolType(*this)
2033 ? VT->getNumElements()
2034 : EltInfo.Width * VT->getNumElements();
2035 // Enforce at least byte size and alignment.
2036 Width = std::max<unsigned>(8, Width);
2037 Align = std::max<unsigned>(8, Width);
2038
2039 // If the alignment is not a power of 2, round up to the next power of 2.
2040 // This happens for non-power-of-2 length vectors.
2041 if (Align & (Align-1)) {
2042 Align = llvm::bit_ceil(Align);
2043 Width = llvm::alignTo(Width, Align);
2044 }
2045 // Adjust the alignment based on the target max.
2046 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
2047 if (TargetVectorAlign && TargetVectorAlign < Align)
2048 Align = TargetVectorAlign;
2049 if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
2050 // Adjust the alignment for fixed-length SVE vectors. This is important
2051 // for non-power-of-2 vector lengths.
2052 Align = 128;
2053 else if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
2054 // Adjust the alignment for fixed-length SVE predicates.
2055 Align = 16;
2056 else if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
2057 VT->getVectorKind() == VectorKind::RVVFixedLengthMask ||
2058 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
2059 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
2060 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4)
2061 // Adjust the alignment for fixed-length RVV vectors.
2062 Align = std::min<unsigned>(64, Width);
2063 break;
2064 }
2065
2066 case Type::ConstantMatrix: {
2067 const auto *MT = cast<ConstantMatrixType>(T);
2068 TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
2069 // The internal layout of a matrix value is implementation defined.
2070 // Initially be ABI compatible with arrays with respect to alignment and
2071 // size.
2072 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
2073 Align = ElementInfo.Align;
2074 break;
2075 }
2076
2077 case Type::Builtin:
2078 switch (cast<BuiltinType>(T)->getKind()) {
2079 default: llvm_unreachable("Unknown builtin type!");
2080 case BuiltinType::Void:
2081 // GCC extension: alignof(void) = 8 bits.
2082 Width = 0;
2083 Align = 8;
2084 break;
2085 case BuiltinType::Bool:
2086 Width = Target->getBoolWidth();
2087 Align = Target->getBoolAlign();
2088 break;
2089 case BuiltinType::Char_S:
2090 case BuiltinType::Char_U:
2091 case BuiltinType::UChar:
2092 case BuiltinType::SChar:
2093 case BuiltinType::Char8:
2094 Width = Target->getCharWidth();
2095 Align = Target->getCharAlign();
2096 break;
2097 case BuiltinType::WChar_S:
2098 case BuiltinType::WChar_U:
2099 Width = Target->getWCharWidth();
2100 Align = Target->getWCharAlign();
2101 break;
2102 case BuiltinType::Char16:
2103 Width = Target->getChar16Width();
2104 Align = Target->getChar16Align();
2105 break;
2106 case BuiltinType::Char32:
2107 Width = Target->getChar32Width();
2108 Align = Target->getChar32Align();
2109 break;
2110 case BuiltinType::UShort:
2111 case BuiltinType::Short:
2112 Width = Target->getShortWidth();
2113 Align = Target->getShortAlign();
2114 break;
2115 case BuiltinType::UInt:
2116 case BuiltinType::Int:
2117 Width = Target->getIntWidth();
2118 Align = Target->getIntAlign();
2119 break;
2120 case BuiltinType::ULong:
2121 case BuiltinType::Long:
2122 Width = Target->getLongWidth();
2123 Align = Target->getLongAlign();
2124 break;
2125 case BuiltinType::ULongLong:
2126 case BuiltinType::LongLong:
2127 Width = Target->getLongLongWidth();
2128 Align = Target->getLongLongAlign();
2129 break;
2130 case BuiltinType::Int128:
2131 case BuiltinType::UInt128:
2132 Width = 128;
2133 Align = Target->getInt128Align();
2134 break;
2135 case BuiltinType::ShortAccum:
2136 case BuiltinType::UShortAccum:
2137 case BuiltinType::SatShortAccum:
2138 case BuiltinType::SatUShortAccum:
2139 Width = Target->getShortAccumWidth();
2140 Align = Target->getShortAccumAlign();
2141 break;
2142 case BuiltinType::Accum:
2143 case BuiltinType::UAccum:
2144 case BuiltinType::SatAccum:
2145 case BuiltinType::SatUAccum:
2146 Width = Target->getAccumWidth();
2147 Align = Target->getAccumAlign();
2148 break;
2149 case BuiltinType::LongAccum:
2150 case BuiltinType::ULongAccum:
2151 case BuiltinType::SatLongAccum:
2152 case BuiltinType::SatULongAccum:
2153 Width = Target->getLongAccumWidth();
2154 Align = Target->getLongAccumAlign();
2155 break;
2156 case BuiltinType::ShortFract:
2157 case BuiltinType::UShortFract:
2158 case BuiltinType::SatShortFract:
2159 case BuiltinType::SatUShortFract:
2160 Width = Target->getShortFractWidth();
2161 Align = Target->getShortFractAlign();
2162 break;
2163 case BuiltinType::Fract:
2164 case BuiltinType::UFract:
2165 case BuiltinType::SatFract:
2166 case BuiltinType::SatUFract:
2167 Width = Target->getFractWidth();
2168 Align = Target->getFractAlign();
2169 break;
2170 case BuiltinType::LongFract:
2171 case BuiltinType::ULongFract:
2172 case BuiltinType::SatLongFract:
2173 case BuiltinType::SatULongFract:
2174 Width = Target->getLongFractWidth();
2175 Align = Target->getLongFractAlign();
2176 break;
2177 case BuiltinType::BFloat16:
2178 if (Target->hasBFloat16Type()) {
2179 Width = Target->getBFloat16Width();
2180 Align = Target->getBFloat16Align();
2181 } else if ((getLangOpts().SYCLIsDevice ||
2182 (getLangOpts().OpenMP &&
2183 getLangOpts().OpenMPIsTargetDevice)) &&
2184 AuxTarget->hasBFloat16Type()) {
2185 Width = AuxTarget->getBFloat16Width();
2186 Align = AuxTarget->getBFloat16Align();
2187 }
2188 break;
2189 case BuiltinType::Float16:
2190 case BuiltinType::Half:
2191 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2192 !getLangOpts().OpenMPIsTargetDevice) {
2193 Width = Target->getHalfWidth();
2194 Align = Target->getHalfAlign();
2195 } else {
2196 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2197 "Expected OpenMP device compilation.");
2198 Width = AuxTarget->getHalfWidth();
2199 Align = AuxTarget->getHalfAlign();
2200 }
2201 break;
2202 case BuiltinType::Float:
2203 Width = Target->getFloatWidth();
2204 Align = Target->getFloatAlign();
2205 break;
2206 case BuiltinType::Double:
2207 Width = Target->getDoubleWidth();
2208 Align = Target->getDoubleAlign();
2209 break;
2210 case BuiltinType::Ibm128:
2211 Width = Target->getIbm128Width();
2212 Align = Target->getIbm128Align();
2213 break;
2214 case BuiltinType::LongDouble:
2215 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2216 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2217 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2218 Width = AuxTarget->getLongDoubleWidth();
2219 Align = AuxTarget->getLongDoubleAlign();
2220 } else {
2221 Width = Target->getLongDoubleWidth();
2222 Align = Target->getLongDoubleAlign();
2223 }
2224 break;
2225 case BuiltinType::Float128:
2226 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2227 !getLangOpts().OpenMPIsTargetDevice) {
2228 Width = Target->getFloat128Width();
2229 Align = Target->getFloat128Align();
2230 } else {
2231 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2232 "Expected OpenMP device compilation.");
2233 Width = AuxTarget->getFloat128Width();
2234 Align = AuxTarget->getFloat128Align();
2235 }
2236 break;
2237 case BuiltinType::NullPtr:
2238 // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
2239 Width = Target->getPointerWidth(LangAS::Default);
2240 Align = Target->getPointerAlign(LangAS::Default);
2241 break;
2242 case BuiltinType::ObjCId:
2243 case BuiltinType::ObjCClass:
2244 case BuiltinType::ObjCSel:
2245 Width = Target->getPointerWidth(LangAS::Default);
2246 Align = Target->getPointerAlign(LangAS::Default);
2247 break;
2248 case BuiltinType::OCLSampler:
2249 case BuiltinType::OCLEvent:
2250 case BuiltinType::OCLClkEvent:
2251 case BuiltinType::OCLQueue:
2252 case BuiltinType::OCLReserveID:
2253 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2254 case BuiltinType::Id:
2255 #include "clang/Basic/OpenCLImageTypes.def"
2256 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2257 case BuiltinType::Id:
2258 #include "clang/Basic/OpenCLExtensionTypes.def"
2259 AS = Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
2260 Width = Target->getPointerWidth(AS);
2261 Align = Target->getPointerAlign(AS);
2262 break;
2263 // The SVE types are effectively target-specific. The length of an
2264 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2265 // of 128 bits. There is one predicate bit for each vector byte, so the
2266 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2267 //
2268 // Because the length is only known at runtime, we use a dummy value
2269 // of 0 for the static length. The alignment values are those defined
2270 // by the Procedure Call Standard for the Arm Architecture.
2271 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
2272 case BuiltinType::Id: \
2273 Width = 0; \
2274 Align = 128; \
2275 break;
2276 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
2277 case BuiltinType::Id: \
2278 Width = 0; \
2279 Align = 16; \
2280 break;
2281 #define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
2282 case BuiltinType::Id: \
2283 Width = 0; \
2284 Align = 16; \
2285 break;
2286 #define SVE_SCALAR_TYPE(Name, MangledName, Id, SingletonId, Bits) \
2287 case BuiltinType::Id: \
2288 Width = Bits; \
2289 Align = Bits; \
2290 break;
2291 #include "clang/Basic/AArch64ACLETypes.def"
2292 #define PPC_VECTOR_TYPE(Name, Id, Size) \
2293 case BuiltinType::Id: \
2294 Width = Size; \
2295 Align = Size; \
2296 break;
2297 #include "clang/Basic/PPCTypes.def"
2298 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
2299 IsFP, IsBF) \
2300 case BuiltinType::Id: \
2301 Width = 0; \
2302 Align = ElBits; \
2303 break;
2304 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2305 case BuiltinType::Id: \
2306 Width = 0; \
2307 Align = 8; \
2308 break;
2309 #include "clang/Basic/RISCVVTypes.def"
2310 #define WASM_TYPE(Name, Id, SingletonId) \
2311 case BuiltinType::Id: \
2312 Width = 0; \
2313 Align = 8; \
2314 break;
2315 #include "clang/Basic/WebAssemblyReferenceTypes.def"
2316 #define AMDGPU_TYPE(NAME, ID, SINGLETONID, WIDTH, ALIGN) \
2317 case BuiltinType::ID: \
2318 Width = WIDTH; \
2319 Align = ALIGN; \
2320 break;
2321 #include "clang/Basic/AMDGPUTypes.def"
2322 #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2323 #include "clang/Basic/HLSLIntangibleTypes.def"
2324 Width = Target->getPointerWidth(LangAS::Default);
2325 Align = Target->getPointerAlign(LangAS::Default);
2326 break;
2327 }
2328 break;
2329 case Type::ObjCObjectPointer:
2330 Width = Target->getPointerWidth(LangAS::Default);
2331 Align = Target->getPointerAlign(LangAS::Default);
2332 break;
2333 case Type::BlockPointer:
2334 AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
2335 Width = Target->getPointerWidth(AS);
2336 Align = Target->getPointerAlign(AS);
2337 break;
2338 case Type::LValueReference:
2339 case Type::RValueReference:
2340 // alignof and sizeof should never enter this code path here, so we go
2341 // the pointer route.
2342 AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
2343 Width = Target->getPointerWidth(AS);
2344 Align = Target->getPointerAlign(AS);
2345 break;
2346 case Type::Pointer:
2347 AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
2348 Width = Target->getPointerWidth(AS);
2349 Align = Target->getPointerAlign(AS);
2350 break;
2351 case Type::MemberPointer: {
2352 const auto *MPT = cast<MemberPointerType>(T);
2353 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2354 Width = MPI.Width;
2355 Align = MPI.Align;
2356 break;
2357 }
2358 case Type::Complex: {
2359 // Complex types have the same alignment as their elements, but twice the
2360 // size.
2361 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2362 Width = EltInfo.Width * 2;
2363 Align = EltInfo.Align;
2364 break;
2365 }
2366 case Type::ObjCObject:
2367 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2368 case Type::Adjusted:
2369 case Type::Decayed:
2370 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2371 case Type::ObjCInterface: {
2372 const auto *ObjCI = cast<ObjCInterfaceType>(T);
2373 if (ObjCI->getDecl()->isInvalidDecl()) {
2374 Width = 8;
2375 Align = 8;
2376 break;
2377 }
2378 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2379 Width = toBits(Layout.getSize());
2380 Align = toBits(Layout.getAlignment());
2381 break;
2382 }
2383 case Type::BitInt: {
2384 const auto *EIT = cast<BitIntType>(T);
2385 Align = Target->getBitIntAlign(EIT->getNumBits());
2386 Width = Target->getBitIntWidth(EIT->getNumBits());
2387 break;
2388 }
2389 case Type::Record:
2390 case Type::Enum: {
2391 const auto *TT = cast<TagType>(T);
2392 const TagDecl *TD = TT->getDecl()->getDefinitionOrSelf();
2393
2394 if (TD->isInvalidDecl()) {
2395 Width = 8;
2396 Align = 8;
2397 break;
2398 }
2399
2400 if (isa<EnumType>(TT)) {
2401 const EnumDecl *ED = cast<EnumDecl>(TD);
2402 TypeInfo Info =
2403 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
2404 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2405 Info.Align = AttrAlign;
2406 Info.AlignRequirement = AlignRequirementKind::RequiredByEnum;
2407 }
2408 return Info;
2409 }
2410
2411 const auto *RD = cast<RecordDecl>(TD);
2412 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2413 Width = toBits(Layout.getSize());
2414 Align = toBits(Layout.getAlignment());
2415 AlignRequirement = RD->hasAttr<AlignedAttr>()
2416 ? AlignRequirementKind::RequiredByRecord
2417 : AlignRequirementKind::None;
2418 break;
2419 }
2420
2421 case Type::SubstTemplateTypeParm:
2422 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2423 getReplacementType().getTypePtr());
2424
2425 case Type::Auto:
2426 case Type::DeducedTemplateSpecialization: {
2427 const auto *A = cast<DeducedType>(T);
2428 assert(!A->getDeducedType().isNull() &&
2429 "cannot request the size of an undeduced or dependent auto type");
2430 return getTypeInfo(A->getDeducedType().getTypePtr());
2431 }
2432
2433 case Type::Paren:
2434 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2435
2436 case Type::MacroQualified:
2437 return getTypeInfo(
2438 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2439
2440 case Type::ObjCTypeParam:
2441 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2442
2443 case Type::Using:
2444 return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr());
2445
2446 case Type::Typedef: {
2447 const auto *TT = cast<TypedefType>(T);
2448 TypeInfo Info = getTypeInfo(TT->desugar().getTypePtr());
2449 // If the typedef has an aligned attribute on it, it overrides any computed
2450 // alignment we have. This violates the GCC documentation (which says that
2451 // attribute(aligned) can only round up) but matches its implementation.
2452 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2453 Align = AttrAlign;
2454 AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2455 } else {
2456 Align = Info.Align;
2457 AlignRequirement = Info.AlignRequirement;
2458 }
2459 Width = Info.Width;
2460 break;
2461 }
2462
2463 case Type::Attributed:
2464 return getTypeInfo(
2465 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2466
2467 case Type::CountAttributed:
2468 return getTypeInfo(cast<CountAttributedType>(T)->desugar().getTypePtr());
2469
2470 case Type::BTFTagAttributed:
2471 return getTypeInfo(
2472 cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr());
2473
2474 case Type::HLSLAttributedResource:
2475 return getTypeInfo(
2476 cast<HLSLAttributedResourceType>(T)->getWrappedType().getTypePtr());
2477
2478 case Type::HLSLInlineSpirv: {
2479 const auto *ST = cast<HLSLInlineSpirvType>(T);
2480 // Size is specified in bytes, convert to bits
2481 Width = ST->getSize() * 8;
2482 Align = ST->getAlignment();
2483 if (Width == 0 && Align == 0) {
2484 // We are defaulting to laying out opaque SPIR-V types as 32-bit ints.
2485 Width = 32;
2486 Align = 32;
2487 }
2488 break;
2489 }
2490
2491 case Type::Atomic: {
2492 // Start with the base type information.
2493 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2494 Width = Info.Width;
2495 Align = Info.Align;
2496
2497 if (!Width) {
2498 // An otherwise zero-sized type should still generate an
2499 // atomic operation.
2500 Width = Target->getCharWidth();
2501 assert(Align);
2502 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2503 // If the size of the type doesn't exceed the platform's max
2504 // atomic promotion width, make the size and alignment more
2505 // favorable to atomic operations:
2506
2507 // Round the size up to a power of 2.
2508 Width = llvm::bit_ceil(Width);
2509
2510 // Set the alignment equal to the size.
2511 Align = static_cast<unsigned>(Width);
2512 }
2513 }
2514 break;
2515
2516 case Type::PredefinedSugar:
2517 return getTypeInfo(cast<PredefinedSugarType>(T)->desugar().getTypePtr());
2518
2519 case Type::Pipe:
2520 Width = Target->getPointerWidth(LangAS::opencl_global);
2521 Align = Target->getPointerAlign(LangAS::opencl_global);
2522 break;
2523 }
2524
2525 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2526 return TypeInfo(Width, Align, AlignRequirement);
2527 }
2528
2529 unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2530 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2531 if (I != MemoizedUnadjustedAlign.end())
2532 return I->second;
2533
2534 unsigned UnadjustedAlign;
2535 if (const auto *RT = T->getAsCanonical<RecordType>()) {
2536 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
2537 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2538 } else if (const auto *ObjCI = T->getAsCanonical<ObjCInterfaceType>()) {
2539 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2540 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2541 } else {
2542 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2543 }
2544
2545 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2546 return UnadjustedAlign;
2547 }
2548
2549 unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2550 unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign(
2551 getTargetInfo().getTriple(), Target->getTargetOpts().FeatureMap);
2552 return SimdAlign;
2553 }
2554
2555 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2556 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2557 return CharUnits::fromQuantity(BitSize / getCharWidth());
2558 }
2559
2560 /// toBits - Convert a size in characters to a size in characters.
2561 int64_t ASTContext::toBits(CharUnits CharSize) const {
2562 return CharSize.getQuantity() * getCharWidth();
2563 }
2564
2565 /// getTypeSizeInChars - Return the size of the specified type, in characters.
2566 /// This method does not work on incomplete types.
2567 CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
2568 return getTypeInfoInChars(T).Width;
2569 }
2570 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
2571 return getTypeInfoInChars(T).Width;
2572 }
2573
2574 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2575 /// characters. This method does not work on incomplete types.
2576 CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
2577 return toCharUnitsFromBits(getTypeAlign(T));
2578 }
2579 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
2580 return toCharUnitsFromBits(getTypeAlign(T));
2581 }
2582
2583 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2584 /// type, in characters, before alignment adjustments. This method does
2585 /// not work on incomplete types.
2586 CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2587 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2588 }
2589 CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2590 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2591 }
2592
2593 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2594 /// type for the current target in bits. This can be different than the ABI
2595 /// alignment in cases where it is beneficial for performance or backwards
2596 /// compatibility preserving to overalign a data type. (Note: despite the name,
2597 /// the preferred alignment is ABI-impacting, and not an optimization.)
2598 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
2599 TypeInfo TI = getTypeInfo(T);
2600 unsigned ABIAlign = TI.Align;
2601
2602 T = T->getBaseElementTypeUnsafe();
2603
2604 // The preferred alignment of member pointers is that of a pointer.
2605 if (T->isMemberPointerType())
2606 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2607
2608 if (!Target->allowsLargerPreferedTypeAlignment())
2609 return ABIAlign;
2610
2611 if (const auto *RD = T->getAsRecordDecl()) {
2612 // When used as part of a typedef, or together with a 'packed' attribute,
2613 // the 'aligned' attribute can be used to decrease alignment. Note that the
2614 // 'packed' case is already taken into consideration when computing the
2615 // alignment, we only need to handle the typedef case here.
2616 if (TI.AlignRequirement == AlignRequirementKind::RequiredByTypedef ||
2617 RD->isInvalidDecl())
2618 return ABIAlign;
2619
2620 unsigned PreferredAlign = static_cast<unsigned>(
2621 toBits(getASTRecordLayout(RD).PreferredAlignment));
2622 assert(PreferredAlign >= ABIAlign &&
2623 "PreferredAlign should be at least as large as ABIAlign.");
2624 return PreferredAlign;
2625 }
2626
2627 // Double (and, for targets supporting AIX `power` alignment, long double) and
2628 // long long should be naturally aligned (despite requiring less alignment) if
2629 // possible.
2630 if (const auto *CT = T->getAs<ComplexType>())
2631 T = CT->getElementType().getTypePtr();
2632 if (const auto *ED = T->getAsEnumDecl())
2633 T = ED->getIntegerType().getTypePtr();
2634 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2635 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2636 T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2637 (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2638 Target->defaultsToAIXPowerAlignment()))
2639 // Don't increase the alignment if an alignment attribute was specified on a
2640 // typedef declaration.
2641 if (!TI.isAlignRequired())
2642 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2643
2644 return ABIAlign;
2645 }
2646
2647 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2648 /// for __attribute__((aligned)) on this target, to be used if no alignment
2649 /// value is specified.
2650 unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
2651 return getTargetInfo().getDefaultAlignForAttributeAligned();
2652 }
2653
2654 /// getAlignOfGlobalVar - Return the alignment in bits that should be given
2655 /// to a global variable of the specified type.
2656 unsigned ASTContext::getAlignOfGlobalVar(QualType T, const VarDecl *VD) const {
2657 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2658 return std::max(getPreferredTypeAlign(T),
2659 getMinGlobalAlignOfVar(TypeSize, VD));
2660 }
2661
2662 /// getAlignOfGlobalVarInChars - Return the alignment in characters that
2663 /// should be given to a global variable of the specified type.
2664 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T,
2665 const VarDecl *VD) const {
2666 return toCharUnitsFromBits(getAlignOfGlobalVar(T, VD));
2667 }
2668
2669 unsigned ASTContext::getMinGlobalAlignOfVar(uint64_t Size,
2670 const VarDecl *VD) const {
2671 // Make the default handling as that of a non-weak definition in the
2672 // current translation unit.
2673 bool HasNonWeakDef = !VD || (VD->hasDefinition() && !VD->isWeak());
2674 return getTargetInfo().getMinGlobalAlign(Size, HasNonWeakDef);
2675 }
2676
2677 CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2678 CharUnits Offset = CharUnits::Zero();
2679 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2680 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2681 Offset += Layout->getBaseClassOffset(Base);
2682 Layout = &getASTRecordLayout(Base);
2683 }
2684 return Offset;
2685 }
2686
2687 CharUnits ASTContext::getMemberPointerPathAdjustment(const APValue &MP) const {
2688 const ValueDecl *MPD = MP.getMemberPointerDecl();
2689 CharUnits ThisAdjustment = CharUnits::Zero();
2690 ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath();
2691 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2692 const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext());
2693 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2694 const CXXRecordDecl *Base = RD;
2695 const CXXRecordDecl *Derived = Path[I];
2696 if (DerivedMember)
2697 std::swap(Base, Derived);
2698 ThisAdjustment += getASTRecordLayout(Derived).getBaseClassOffset(Base);
2699 RD = Path[I];
2700 }
2701 if (DerivedMember)
2702 ThisAdjustment = -ThisAdjustment;
2703 return ThisAdjustment;
2704 }
2705
2706 /// DeepCollectObjCIvars -
2707 /// This routine first collects all declared, but not synthesized, ivars in
2708 /// super class and then collects all ivars, including those synthesized for
2709 /// current class. This routine is used for implementation of current class
2710 /// when all ivars, declared and synthesized are known.
2711 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2712 bool leafClass,
2713 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
2714 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2715 DeepCollectObjCIvars(SuperClass, false, Ivars);
2716 if (!leafClass) {
2717 llvm::append_range(Ivars, OI->ivars());
2718 } else {
2719 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2720 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2721 Iv= Iv->getNextIvar())
2722 Ivars.push_back(Iv);
2723 }
2724 }
2725
2726 /// CollectInheritedProtocols - Collect all protocols in current class and
2727 /// those inherited by it.
2728 void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
2729 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
2730 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2731 // We can use protocol_iterator here instead of
2732 // all_referenced_protocol_iterator since we are walking all categories.
2733 for (auto *Proto : OI->all_referenced_protocols()) {
2734 CollectInheritedProtocols(Proto, Protocols);
2735 }
2736
2737 // Categories of this Interface.
2738 for (const auto *Cat : OI->visible_categories())
2739 CollectInheritedProtocols(Cat, Protocols);
2740
2741 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2742 while (SD) {
2743 CollectInheritedProtocols(SD, Protocols);
2744 SD = SD->getSuperClass();
2745 }
2746 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2747 for (auto *Proto : OC->protocols()) {
2748 CollectInheritedProtocols(Proto, Protocols);
2749 }
2750 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2751 // Insert the protocol.
2752 if (!Protocols.insert(
2753 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2754 return;
2755
2756 for (auto *Proto : OP->protocols())
2757 CollectInheritedProtocols(Proto, Protocols);
2758 }
2759 }
2760
2761 static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2762 const RecordDecl *RD,
2763 bool CheckIfTriviallyCopyable) {
2764 assert(RD->isUnion() && "Must be union type");
2765 CharUnits UnionSize =
2766 Context.getTypeSizeInChars(Context.getCanonicalTagType(RD));
2767
2768 for (const auto *Field : RD->fields()) {
2769 if (!Context.hasUniqueObjectRepresentations(Field->getType(),
2770 CheckIfTriviallyCopyable))
2771 return false;
2772 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2773 if (FieldSize != UnionSize)
2774 return false;
2775 }
2776 return !RD->field_empty();
2777 }
2778
2779 static int64_t getSubobjectOffset(const FieldDecl *Field,
2780 const ASTContext &Context,
2781 const clang::ASTRecordLayout & /*Layout*/) {
2782 return Context.getFieldOffset(Field);
2783 }
2784
2785 static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2786 const ASTContext &Context,
2787 const clang::ASTRecordLayout &Layout) {
2788 return Context.toBits(Layout.getBaseClassOffset(RD));
2789 }
2790
2791 static std::optional<int64_t>
2792 structHasUniqueObjectRepresentations(const ASTContext &Context,
2793 const RecordDecl *RD,
2794 bool CheckIfTriviallyCopyable);
2795
2796 static std::optional<int64_t>
2797 getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context,
2798 bool CheckIfTriviallyCopyable) {
2799 if (const auto *RD = Field->getType()->getAsRecordDecl();
2800 RD && !RD->isUnion())
2801 return structHasUniqueObjectRepresentations(Context, RD,
2802 CheckIfTriviallyCopyable);
2803
2804 // A _BitInt type may not be unique if it has padding bits
2805 // but if it is a bitfield the padding bits are not used.
2806 bool IsBitIntType = Field->getType()->isBitIntType();
2807 if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2808 !Context.hasUniqueObjectRepresentations(Field->getType(),
2809 CheckIfTriviallyCopyable))
2810 return std::nullopt;
2811
2812 int64_t FieldSizeInBits =
2813 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2814 if (Field->isBitField()) {
2815 // If we have explicit padding bits, they don't contribute bits
2816 // to the actual object representation, so return 0.
2817 if (Field->isUnnamedBitField())
2818 return 0;
2819
2820 int64_t BitfieldSize = Field->getBitWidthValue();
2821 if (IsBitIntType) {
2822 if ((unsigned)BitfieldSize >
2823 cast<BitIntType>(Field->getType())->getNumBits())
2824 return std::nullopt;
2825 } else if (BitfieldSize > FieldSizeInBits) {
2826 return std::nullopt;
2827 }
2828 FieldSizeInBits = BitfieldSize;
2829 } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations(
2830 Field->getType(), CheckIfTriviallyCopyable)) {
2831 return std::nullopt;
2832 }
2833 return FieldSizeInBits;
2834 }
2835
2836 static std::optional<int64_t>
2837 getSubobjectSizeInBits(const CXXRecordDecl *RD, const ASTContext &Context,
2838 bool CheckIfTriviallyCopyable) {
2839 return structHasUniqueObjectRepresentations(Context, RD,
2840 CheckIfTriviallyCopyable);
2841 }
2842
2843 template <typename RangeT>
2844 static std::optional<int64_t> structSubobjectsHaveUniqueObjectRepresentations(
2845 const RangeT &Subobjects, int64_t CurOffsetInBits,
2846 const ASTContext &Context, const clang::ASTRecordLayout &Layout,
2847 bool CheckIfTriviallyCopyable) {
2848 for (const auto *Subobject : Subobjects) {
2849 std::optional<int64_t> SizeInBits =
2850 getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable);
2851 if (!SizeInBits)
2852 return std::nullopt;
2853 if (*SizeInBits != 0) {
2854 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2855 if (Offset != CurOffsetInBits)
2856 return std::nullopt;
2857 CurOffsetInBits += *SizeInBits;
2858 }
2859 }
2860 return CurOffsetInBits;
2861 }
2862
2863 static std::optional<int64_t>
2864 structHasUniqueObjectRepresentations(const ASTContext &Context,
2865 const RecordDecl *RD,
2866 bool CheckIfTriviallyCopyable) {
2867 assert(!RD->isUnion() && "Must be struct/class type");
2868 const auto &Layout = Context.getASTRecordLayout(RD);
2869
2870 int64_t CurOffsetInBits = 0;
2871 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2872 if (ClassDecl->isDynamicClass())
2873 return std::nullopt;
2874
2875 SmallVector<CXXRecordDecl *, 4> Bases;
2876 for (const auto &Base : ClassDecl->bases()) {
2877 // Empty types can be inherited from, and non-empty types can potentially
2878 // have tail padding, so just make sure there isn't an error.
2879 Bases.emplace_back(Base.getType()->getAsCXXRecordDecl());
2880 }
2881
2882 llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
2883 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
2884 });
2885
2886 std::optional<int64_t> OffsetAfterBases =
2887 structSubobjectsHaveUniqueObjectRepresentations(
2888 Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable);
2889 if (!OffsetAfterBases)
2890 return std::nullopt;
2891 CurOffsetInBits = *OffsetAfterBases;
2892 }
2893
2894 std::optional<int64_t> OffsetAfterFields =
2895 structSubobjectsHaveUniqueObjectRepresentations(
2896 RD->fields(), CurOffsetInBits, Context, Layout,
2897 CheckIfTriviallyCopyable);
2898 if (!OffsetAfterFields)
2899 return std::nullopt;
2900 CurOffsetInBits = *OffsetAfterFields;
2901
2902 return CurOffsetInBits;
2903 }
2904
2905 bool ASTContext::hasUniqueObjectRepresentations(
2906 QualType Ty, bool CheckIfTriviallyCopyable) const {
2907 // C++17 [meta.unary.prop]:
2908 // The predicate condition for a template specialization
2909 // has_unique_object_representations<T> shall be satisfied if and only if:
2910 // (9.1) - T is trivially copyable, and
2911 // (9.2) - any two objects of type T with the same value have the same
2912 // object representation, where:
2913 // - two objects of array or non-union class type are considered to have
2914 // the same value if their respective sequences of direct subobjects
2915 // have the same values, and
2916 // - two objects of union type are considered to have the same value if
2917 // they have the same active member and the corresponding members have
2918 // the same value.
2919 // The set of scalar types for which this condition holds is
2920 // implementation-defined. [ Note: If a type has padding bits, the condition
2921 // does not hold; otherwise, the condition holds true for unsigned integral
2922 // types. -- end note ]
2923 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2924
2925 // Arrays are unique only if their element type is unique.
2926 if (Ty->isArrayType())
2927 return hasUniqueObjectRepresentations(getBaseElementType(Ty),
2928 CheckIfTriviallyCopyable);
2929
2930 assert((Ty->isVoidType() || !Ty->isIncompleteType()) &&
2931 "hasUniqueObjectRepresentations should not be called with an "
2932 "incomplete type");
2933
2934 // (9.1) - T is trivially copyable...
2935 if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(*this))
2936 return false;
2937
2938 // All integrals and enums are unique.
2939 if (Ty->isIntegralOrEnumerationType()) {
2940 // Address discriminated integer types are not unique.
2941 if (Ty.hasAddressDiscriminatedPointerAuth())
2942 return false;
2943 // Except _BitInt types that have padding bits.
2944 if (const auto *BIT = Ty->getAs<BitIntType>())
2945 return getTypeSize(BIT) == BIT->getNumBits();
2946
2947 return true;
2948 }
2949
2950 // All other pointers are unique.
2951 if (Ty->isPointerType())
2952 return !Ty.hasAddressDiscriminatedPointerAuth();
2953
2954 if (const auto *MPT = Ty->getAs<MemberPointerType>())
2955 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2956
2957 if (const auto *Record = Ty->getAsRecordDecl()) {
2958 if (Record->isInvalidDecl())
2959 return false;
2960
2961 if (Record->isUnion())
2962 return unionHasUniqueObjectRepresentations(*this, Record,
2963 CheckIfTriviallyCopyable);
2964
2965 std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(
2966 *this, Record, CheckIfTriviallyCopyable);
2967
2968 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(Ty));
2969 }
2970
2971 // FIXME: More cases to handle here (list by rsmith):
2972 // vectors (careful about, eg, vector of 3 foo)
2973 // _Complex int and friends
2974 // _Atomic T
2975 // Obj-C block pointers
2976 // Obj-C object pointers
2977 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2978 // clk_event_t, queue_t, reserve_id_t)
2979 // There're also Obj-C class types and the Obj-C selector type, but I think it
2980 // makes sense for those to return false here.
2981
2982 return false;
2983 }
2984
2985 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
2986 unsigned count = 0;
2987 // Count ivars declared in class extension.
2988 for (const auto *Ext : OI->known_extensions())
2989 count += Ext->ivar_size();
2990
2991 // Count ivar defined in this class's implementation. This
2992 // includes synthesized ivars.
2993 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2994 count += ImplDecl->ivar_size();
2995
2996 return count;
2997 }
2998
2999 bool ASTContext::isSentinelNullExpr(const Expr *E) {
3000 if (!E)
3001 return false;
3002
3003 // nullptr_t is always treated as null.
3004 if (E->getType()->isNullPtrType()) return true;
3005
3006 if (E->getType()->isAnyPointerType() &&
3007 E->IgnoreParenCasts()->isNullPointerConstant(*this,
3008 Expr::NPC_ValueDependentIsNull))
3009 return true;
3010
3011 // Unfortunately, __null has type 'int'.
3012 if (isa<GNUNullExpr>(E)) return true;
3013
3014 return false;
3015 }
3016
3017 /// Get the implementation of ObjCInterfaceDecl, or nullptr if none
3018 /// exists.
3019 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
3020 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3021 I = ObjCImpls.find(D);
3022 if (I != ObjCImpls.end())
3023 return cast<ObjCImplementationDecl>(I->second);
3024 return nullptr;
3025 }
3026
3027 /// Get the implementation of ObjCCategoryDecl, or nullptr if none
3028 /// exists.
3029 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
3030 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3031 I = ObjCImpls.find(D);
3032 if (I != ObjCImpls.end())
3033 return cast<ObjCCategoryImplDecl>(I->second);
3034 return nullptr;
3035 }
3036
3037 /// Set the implementation of ObjCInterfaceDecl.
3038 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
3039 ObjCImplementationDecl *ImplD) {
3040 assert(IFaceD && ImplD && "Passed null params");
3041 ObjCImpls[IFaceD] = ImplD;
3042 }
3043
3044 /// Set the implementation of ObjCCategoryDecl.
3045 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
3046 ObjCCategoryImplDecl *ImplD) {
3047 assert(CatD && ImplD && "Passed null params");
3048 ObjCImpls[CatD] = ImplD;
3049 }
3050
3051 const ObjCMethodDecl *
3052 ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
3053 return ObjCMethodRedecls.lookup(MD);
3054 }
3055
3056 void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
3057 const ObjCMethodDecl *Redecl) {
3058 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
3059 ObjCMethodRedecls[MD] = Redecl;
3060 }
3061
3062 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
3063 const NamedDecl *ND) const {
3064 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
3065 return ID;
3066 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
3067 return CD->getClassInterface();
3068 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
3069 return IMD->getClassInterface();
3070
3071 return nullptr;
3072 }
3073
3074 /// Get the copy initialization expression of VarDecl, or nullptr if
3075 /// none exists.
3076 BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const {
3077 assert(VD && "Passed null params");
3078 assert(VD->hasAttr<BlocksAttr>() &&
3079 "getBlockVarCopyInits - not __block var");
3080 auto I = BlockVarCopyInits.find(VD);
3081 if (I != BlockVarCopyInits.end())
3082 return I->second;
3083 return {nullptr, false};
3084 }
3085
3086 /// Set the copy initialization expression of a block var decl.
3087 void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
3088 bool CanThrow) {
3089 assert(VD && CopyExpr && "Passed null params");
3090 assert(VD->hasAttr<BlocksAttr>() &&
3091 "setBlockVarCopyInits - not __block var");
3092 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
3093 }
3094
3095 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
3096 unsigned DataSize) const {
3097 if (!DataSize)
3098 DataSize = TypeLoc::getFullDataSizeForType(T);
3099 else
3100 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
3101 "incorrect data size provided to CreateTypeSourceInfo!");
3102
3103 auto *TInfo =
3104 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
3105 new (TInfo) TypeSourceInfo(T, DataSize);
3106 return TInfo;
3107 }
3108
3109 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
3110 SourceLocation L) const {
3111 TypeSourceInfo *TSI = CreateTypeSourceInfo(T);
3112 TSI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
3113 return TSI;
3114 }
3115
3116 const ASTRecordLayout &
3117 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
3118 return getObjCLayout(D);
3119 }
3120
3121 static auto getCanonicalTemplateArguments(const ASTContext &C,
3122 ArrayRef<TemplateArgument> Args,
3123 bool &AnyNonCanonArgs) {
3124 SmallVector<TemplateArgument, 16> CanonArgs(Args);
3125 AnyNonCanonArgs |= C.canonicalizeTemplateArguments(CanonArgs);
3126 return CanonArgs;
3127 }
3128
3129 bool ASTContext::canonicalizeTemplateArguments(
3130 MutableArrayRef<TemplateArgument> Args) const {
3131 bool AnyNonCanonArgs = false;
3132 for (auto &Arg : Args) {
3133 TemplateArgument OrigArg = Arg;
3134 Arg = getCanonicalTemplateArgument(Arg);
3135 AnyNonCanonArgs |= !Arg.structurallyEquals(OrigArg);
3136 }
3137 return AnyNonCanonArgs;
3138 }
3139
3140 //===----------------------------------------------------------------------===//
3141 // Type creation/memoization methods
3142 //===----------------------------------------------------------------------===//
3143
3144 QualType
3145 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3146 unsigned fastQuals = quals.getFastQualifiers();
3147 quals.removeFastQualifiers();
3148
3149 // Check if we've already instantiated this type.
3150 llvm::FoldingSetNodeID ID;
3151 ExtQuals::Profile(ID, baseType, quals);
3152 void *insertPos = nullptr;
3153 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
3154 assert(eq->getQualifiers() == quals);
3155 return QualType(eq, fastQuals);
3156 }
3157
3158 // If the base type is not canonical, make the appropriate canonical type.
3159 QualType canon;
3160 if (!baseType->isCanonicalUnqualified()) {
3161 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3162 canonSplit.Quals.addConsistentQualifiers(quals);
3163 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
3164
3165 // Re-find the insert position.
3166 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
3167 }
3168
3169 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3170 ExtQualNodes.InsertNode(eq, insertPos);
3171 return QualType(eq, fastQuals);
3172 }
3173
3174 QualType ASTContext::getAddrSpaceQualType(QualType T,
3175 LangAS AddressSpace) const {
3176 QualType CanT = getCanonicalType(T);
3177 if (CanT.getAddressSpace() == AddressSpace)
3178 return T;
3179
3180 // If we are composing extended qualifiers together, merge together
3181 // into one ExtQuals node.
3182 QualifierCollector Quals;
3183 const Type *TypeNode = Quals.strip(T);
3184
3185 // If this type already has an address space specified, it cannot get
3186 // another one.
3187 assert(!Quals.hasAddressSpace() &&
3188 "Type cannot be in multiple addr spaces!");
3189 Quals.addAddressSpace(AddressSpace);
3190
3191 return getExtQualType(TypeNode, Quals);
3192 }
3193
3194 QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
3195 // If the type is not qualified with an address space, just return it
3196 // immediately.
3197 if (!T.hasAddressSpace())
3198 return T;
3199
3200 QualifierCollector Quals;
3201 const Type *TypeNode;
3202 // For arrays, strip the qualifier off the element type, then reconstruct the
3203 // array type
3204 if (T.getTypePtr()->isArrayType()) {
3205 T = getUnqualifiedArrayType(T, Quals);
3206 TypeNode = T.getTypePtr();
3207 } else {
3208 // If we are composing extended qualifiers together, merge together
3209 // into one ExtQuals node.
3210 while (T.hasAddressSpace()) {
3211 TypeNode = Quals.strip(T);
3212
3213 // If the type no longer has an address space after stripping qualifiers,
3214 // jump out.
3215 if (!QualType(TypeNode, 0).hasAddressSpace())
3216 break;
3217
3218 // There might be sugar in the way. Strip it and try again.
3219 T = T.getSingleStepDesugaredType(*this);
3220 }
3221 }
3222
3223 Quals.removeAddressSpace();
3224
3225 // Removal of the address space can mean there are no longer any
3226 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3227 // or required.
3228 if (Quals.hasNonFastQualifiers())
3229 return getExtQualType(TypeNode, Quals);
3230 else
3231 return QualType(TypeNode, Quals.getFastQualifiers());
3232 }
3233
3234 uint16_t
3235 ASTContext::getPointerAuthVTablePointerDiscriminator(const CXXRecordDecl *RD) {
3236 assert(RD->isPolymorphic() &&
3237 "Attempted to get vtable pointer discriminator on a monomorphic type");
3238 std::unique_ptr<MangleContext> MC(createMangleContext());
3239 SmallString<256> Str;
3240 llvm::raw_svector_ostream Out(Str);
3241 MC->mangleCXXVTable(RD, Out);
3242 return llvm::getPointerAuthStableSipHash(Str);
3243 }
3244
3245 /// Encode a function type for use in the discriminator of a function pointer
3246 /// type. We can't use the itanium scheme for this since C has quite permissive
3247 /// rules for type compatibility that we need to be compatible with.
3248 ///
3249 /// Formally, this function associates every function pointer type T with an
3250 /// encoded string E(T). Let the equivalence relation T1 ~ T2 be defined as
3251 /// E(T1) == E(T2). E(T) is part of the ABI of values of type T. C type
3252 /// compatibility requires equivalent treatment under the ABI, so
3253 /// CCompatible(T1, T2) must imply E(T1) == E(T2), that is, CCompatible must be
3254 /// a subset of ~. Crucially, however, it must be a proper subset because
3255 /// CCompatible is not an equivalence relation: for example, int[] is compatible
3256 /// with both int[1] and int[2], but the latter are not compatible with each
3257 /// other. Therefore this encoding function must be careful to only distinguish
3258 /// types if there is no third type with which they are both required to be
3259 /// compatible.
3260 static void encodeTypeForFunctionPointerAuth(const ASTContext &Ctx,
3261 raw_ostream &OS, QualType QT) {
3262 // FIXME: Consider address space qualifiers.
3263 const Type *T = QT.getCanonicalType().getTypePtr();
3264
3265 // FIXME: Consider using the C++ type mangling when we encounter a construct
3266 // that is incompatible with C.
3267
3268 switch (T->getTypeClass()) {
3269 case Type::Atomic:
3270 return encodeTypeForFunctionPointerAuth(
3271 Ctx, OS, cast<AtomicType>(T)->getValueType());
3272
3273 case Type::LValueReference:
3274 OS << "R";
3275 encodeTypeForFunctionPointerAuth(Ctx, OS,
3276 cast<ReferenceType>(T)->getPointeeType());
3277 return;
3278 case Type::RValueReference:
3279 OS << "O";
3280 encodeTypeForFunctionPointerAuth(Ctx, OS,
3281 cast<ReferenceType>(T)->getPointeeType());
3282 return;
3283
3284 case Type::Pointer:
3285 // C11 6.7.6.1p2:
3286 // For two pointer types to be compatible, both shall be identically
3287 // qualified and both shall be pointers to compatible types.
3288 // FIXME: we should also consider pointee types.
3289 OS << "P";
3290 return;
3291
3292 case Type::ObjCObjectPointer:
3293 case Type::BlockPointer:
3294 OS << "P";
3295 return;
3296
3297 case Type::Complex:
3298 OS << "C";
3299 return encodeTypeForFunctionPointerAuth(
3300 Ctx, OS, cast<ComplexType>(T)->getElementType());
3301
3302 case Type::VariableArray:
3303 case Type::ConstantArray:
3304 case Type::IncompleteArray:
3305 case Type::ArrayParameter:
3306 // C11 6.7.6.2p6:
3307 // For two array types to be compatible, both shall have compatible
3308 // element types, and if both size specifiers are present, and are integer
3309 // constant expressions, then both size specifiers shall have the same
3310 // constant value [...]
3311 //
3312 // So since ElemType[N] has to be compatible ElemType[], we can't encode the
3313 // width of the array.
3314 OS << "A";
3315 return encodeTypeForFunctionPointerAuth(
3316 Ctx, OS, cast<ArrayType>(T)->getElementType());
3317
3318 case Type::ObjCInterface:
3319 case Type::ObjCObject:
3320 OS << "<objc_object>";
3321 return;
3322
3323 case Type::Enum: {
3324 // C11 6.7.2.2p4:
3325 // Each enumerated type shall be compatible with char, a signed integer
3326 // type, or an unsigned integer type.
3327 //
3328 // So we have to treat enum types as integers.
3329 QualType UnderlyingType = T->castAsEnumDecl()->getIntegerType();
3330 return encodeTypeForFunctionPointerAuth(
3331 Ctx, OS, UnderlyingType.isNull() ? Ctx.IntTy : UnderlyingType);
3332 }
3333
3334 case Type::FunctionNoProto:
3335 case Type::FunctionProto: {
3336 // C11 6.7.6.3p15:
3337 // For two function types to be compatible, both shall specify compatible
3338 // return types. Moreover, the parameter type lists, if both are present,
3339 // shall agree in the number of parameters and in the use of the ellipsis
3340 // terminator; corresponding parameters shall have compatible types.
3341 //
3342 // That paragraph goes on to describe how unprototyped functions are to be
3343 // handled, which we ignore here. Unprototyped function pointers are hashed
3344 // as though they were prototyped nullary functions since thats probably
3345 // what the user meant. This behavior is non-conforming.
3346 // FIXME: If we add a "custom discriminator" function type attribute we
3347 // should encode functions as their discriminators.
3348 OS << "F";
3349 const auto *FuncType = cast<FunctionType>(T);
3350 encodeTypeForFunctionPointerAuth(Ctx, OS, FuncType->getReturnType());
3351 if (const auto *FPT = dyn_cast<FunctionProtoType>(FuncType)) {
3352 for (QualType Param : FPT->param_types()) {
3353 Param = Ctx.getSignatureParameterType(Param);
3354 encodeTypeForFunctionPointerAuth(Ctx, OS, Param);
3355 }
3356 if (FPT->isVariadic())
3357 OS << "z";
3358 }
3359 OS << "E";
3360 return;
3361 }
3362
3363 case Type::MemberPointer: {
3364 OS << "M";
3365 const auto *MPT = T->castAs<MemberPointerType>();
3366 encodeTypeForFunctionPointerAuth(
3367 Ctx, OS, QualType(MPT->getQualifier().getAsType(), 0));
3368 encodeTypeForFunctionPointerAuth(Ctx, OS, MPT->getPointeeType());
3369 return;
3370 }
3371 case Type::ExtVector:
3372 case Type::Vector:
3373 OS << "Dv" << Ctx.getTypeSizeInChars(T).getQuantity();
3374 break;
3375
3376 // Don't bother discriminating based on these types.
3377 case Type::Pipe:
3378 case Type::BitInt:
3379 case Type::ConstantMatrix:
3380 OS << "?";
3381 return;
3382
3383 case Type::Builtin: {
3384 const auto *BTy = T->castAs<BuiltinType>();
3385 switch (BTy->getKind()) {
3386 #define SIGNED_TYPE(Id, SingletonId) \
3387 case BuiltinType::Id: \
3388 OS << "i"; \
3389 return;
3390 #define UNSIGNED_TYPE(Id, SingletonId) \
3391 case BuiltinType::Id: \
3392 OS << "i"; \
3393 return;
3394 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
3395 #define BUILTIN_TYPE(Id, SingletonId)
3396 #include "clang/AST/BuiltinTypes.def"
3397 llvm_unreachable("placeholder types should not appear here.");
3398
3399 case BuiltinType::Half:
3400 OS << "Dh";
3401 return;
3402 case BuiltinType::Float:
3403 OS << "f";
3404 return;
3405 case BuiltinType::Double:
3406 OS << "d";
3407 return;
3408 case BuiltinType::LongDouble:
3409 OS << "e";
3410 return;
3411 case BuiltinType::Float16:
3412 OS << "DF16_";
3413 return;
3414 case BuiltinType::Float128:
3415 OS << "g";
3416 return;
3417
3418 case BuiltinType::Void:
3419 OS << "v";
3420 return;
3421
3422 case BuiltinType::ObjCId:
3423 case BuiltinType::ObjCClass:
3424 case BuiltinType::ObjCSel:
3425 case BuiltinType::NullPtr:
3426 OS << "P";
3427 return;
3428
3429 // Don't bother discriminating based on OpenCL types.
3430 case BuiltinType::OCLSampler:
3431 case BuiltinType::OCLEvent:
3432 case BuiltinType::OCLClkEvent:
3433 case BuiltinType::OCLQueue:
3434 case BuiltinType::OCLReserveID:
3435 case BuiltinType::BFloat16:
3436 case BuiltinType::VectorQuad:
3437 case BuiltinType::VectorPair:
3438 case BuiltinType::DMR1024:
3439 case BuiltinType::DMR2048:
3440 OS << "?";
3441 return;
3442
3443 // Don't bother discriminating based on these seldom-used types.
3444 case BuiltinType::Ibm128:
3445 return;
3446 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3447 case BuiltinType::Id: \
3448 return;
3449 #include "clang/Basic/OpenCLImageTypes.def"
3450 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3451 case BuiltinType::Id: \
3452 return;
3453 #include "clang/Basic/OpenCLExtensionTypes.def"
3454 #define SVE_TYPE(Name, Id, SingletonId) \
3455 case BuiltinType::Id: \
3456 return;
3457 #include "clang/Basic/AArch64ACLETypes.def"
3458 #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3459 case BuiltinType::Id: \
3460 return;
3461 #include "clang/Basic/HLSLIntangibleTypes.def"
3462 case BuiltinType::Dependent:
3463 llvm_unreachable("should never get here");
3464 #define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
3465 #include "clang/Basic/AMDGPUTypes.def"
3466 case BuiltinType::WasmExternRef:
3467 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3468 #include "clang/Basic/RISCVVTypes.def"
3469 llvm_unreachable("not yet implemented");
3470 }
3471 llvm_unreachable("should never get here");
3472 }
3473 case Type::Record: {
3474 const RecordDecl *RD = T->castAsCanonical<RecordType>()->getDecl();
3475 const IdentifierInfo *II = RD->getIdentifier();
3476
3477 // In C++, an immediate typedef of an anonymous struct or union
3478 // is considered to name it for ODR purposes, but C's specification
3479 // of type compatibility does not have a similar rule. Using the typedef
3480 // name in function type discriminators anyway, as we do here,
3481 // therefore technically violates the C standard: two function pointer
3482 // types defined in terms of two typedef'd anonymous structs with
3483 // different names are formally still compatible, but we are assigning
3484 // them different discriminators and therefore incompatible ABIs.
3485 //
3486 // This is a relatively minor violation that significantly improves
3487 // discrimination in some cases and has not caused problems in
3488 // practice. Regardless, it is now part of the ABI in places where
3489 // function type discrimination is used, and it can no longer be
3490 // changed except on new platforms.
3491
3492 if (!II)
3493 if (const TypedefNameDecl *Typedef = RD->getTypedefNameForAnonDecl())
3494 II = Typedef->getDeclName().getAsIdentifierInfo();
3495
3496 if (!II) {
3497 OS << "<anonymous_record>";
3498 return;
3499 }
3500 OS << II->getLength() << II->getName();
3501 return;
3502 }
3503 case Type::HLSLAttributedResource:
3504 case Type::HLSLInlineSpirv:
3505 llvm_unreachable("should never get here");
3506 break;
3507 case Type::DeducedTemplateSpecialization:
3508 case Type::Auto:
3509 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3510 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3511 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3512 #define ABSTRACT_TYPE(Class, Base)
3513 #define TYPE(Class, Base)
3514 #include "clang/AST/TypeNodes.inc"
3515 llvm_unreachable("unexpected non-canonical or dependent type!");
3516 return;
3517 }
3518 }
3519
3520 uint16_t ASTContext::getPointerAuthTypeDiscriminator(QualType T) {
3521 assert(!T->isDependentType() &&
3522 "cannot compute type discriminator of a dependent type");
3523 SmallString<256> Str;
3524 llvm::raw_svector_ostream Out(Str);
3525
3526 if (T->isFunctionPointerType() || T->isFunctionReferenceType())
3527 T = T->getPointeeType();
3528
3529 if (T->isFunctionType()) {
3530 encodeTypeForFunctionPointerAuth(*this, Out, T);
3531 } else {
3532 T = T.getUnqualifiedType();
3533 // Calls to member function pointers don't need to worry about
3534 // language interop or the laxness of the C type compatibility rules.
3535 // We just mangle the member pointer type directly, which is
3536 // implicitly much stricter about type matching. However, we do
3537 // strip any top-level exception specification before this mangling.
3538 // C++23 requires calls to work when the function type is convertible
3539 // to the pointer type by a function pointer conversion, which can
3540 // change the exception specification. This does not technically
3541 // require the exception specification to not affect representation,
3542 // because the function pointer conversion is still always a direct
3543 // value conversion and therefore an opportunity to resign the
3544 // pointer. (This is in contrast to e.g. qualification conversions,
3545 // which can be applied in nested pointer positions, effectively
3546 // requiring qualified and unqualified representations to match.)
3547 // However, it is pragmatic to ignore exception specifications
3548 // because it allows a certain amount of `noexcept` mismatching
3549 // to not become a visible ODR problem. This also leaves some
3550 // room for the committee to add laxness to function pointer
3551 // conversions in future standards.
3552 if (auto *MPT = T->getAs<MemberPointerType>())
3553 if (MPT->isMemberFunctionPointer()) {
3554 QualType PointeeType = MPT->getPointeeType();
3555 if (PointeeType->castAs<FunctionProtoType>()->getExceptionSpecType() !=
3556 EST_None) {
3557 QualType FT = getFunctionTypeWithExceptionSpec(PointeeType, EST_None);
3558 T = getMemberPointerType(FT, MPT->getQualifier(),
3559 MPT->getMostRecentCXXRecordDecl());
3560 }
3561 }
3562 std::unique_ptr<MangleContext> MC(createMangleContext());
3563 MC->mangleCanonicalTypeName(T, Out);
3564 }
3565
3566 return llvm::getPointerAuthStableSipHash(Str);
3567 }
3568
3569 QualType ASTContext::getObjCGCQualType(QualType T,
3570 Qualifiers::GC GCAttr) const {
3571 QualType CanT = getCanonicalType(T);
3572 if (CanT.getObjCGCAttr() == GCAttr)
3573 return T;
3574
3575 if (const auto *ptr = T->getAs<PointerType>()) {
3576 QualType Pointee = ptr->getPointeeType();
3577 if (Pointee->isAnyPointerType()) {
3578 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
3579 return getPointerType(ResultType);
3580 }
3581 }
3582
3583 // If we are composing extended qualifiers together, merge together
3584 // into one ExtQuals node.
3585 QualifierCollector Quals;
3586 const Type *TypeNode = Quals.strip(T);
3587
3588 // If this type already has an ObjCGC specified, it cannot get
3589 // another one.
3590 assert(!Quals.hasObjCGCAttr() &&
3591 "Type cannot have multiple ObjCGCs!");
3592 Quals.addObjCGCAttr(GCAttr);
3593
3594 return getExtQualType(TypeNode, Quals);
3595 }
3596
3597 QualType ASTContext::removePtrSizeAddrSpace(QualType T) const {
3598 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3599 QualType Pointee = Ptr->getPointeeType();
3600 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3601 return getPointerType(removeAddrSpaceQualType(Pointee));
3602 }
3603 }
3604 return T;
3605 }
3606
3607 QualType ASTContext::getCountAttributedType(
3608 QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull,
3609 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3610 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3611
3612 llvm::FoldingSetNodeID ID;
3613 CountAttributedType::Profile(ID, WrappedTy, CountExpr, CountInBytes, OrNull);
3614
3615 void *InsertPos = nullptr;
3616 CountAttributedType *CATy =
3617 CountAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
3618 if (CATy)
3619 return QualType(CATy, 0);
3620
3621 QualType CanonTy = getCanonicalType(WrappedTy);
3622 size_t Size = CountAttributedType::totalSizeToAlloc<TypeCoupledDeclRefInfo>(
3623 DependentDecls.size());
3624 CATy = (CountAttributedType *)Allocate(Size, TypeAlignment);
3625 new (CATy) CountAttributedType(WrappedTy, CanonTy, CountExpr, CountInBytes,
3626 OrNull, DependentDecls);
3627 Types.push_back(CATy);
3628 CountAttributedTypes.InsertNode(CATy, InsertPos);
3629
3630 return QualType(CATy, 0);
3631 }
3632
3633 QualType
3634 ASTContext::adjustType(QualType Orig,
3635 llvm::function_ref<QualType(QualType)> Adjust) const {
3636 switch (Orig->getTypeClass()) {
3637 case Type::Attributed: {
3638 const auto *AT = cast<AttributedType>(Orig);
3639 return getAttributedType(AT->getAttrKind(),
3640 adjustType(AT->getModifiedType(), Adjust),
3641 adjustType(AT->getEquivalentType(), Adjust),
3642 AT->getAttr());
3643 }
3644
3645 case Type::BTFTagAttributed: {
3646 const auto *BTFT = dyn_cast<BTFTagAttributedType>(Orig);
3647 return getBTFTagAttributedType(BTFT->getAttr(),
3648 adjustType(BTFT->getWrappedType(), Adjust));
3649 }
3650
3651 case Type::Paren:
3652 return getParenType(
3653 adjustType(cast<ParenType>(Orig)->getInnerType(), Adjust));
3654
3655 case Type::Adjusted: {
3656 const auto *AT = cast<AdjustedType>(Orig);
3657 return getAdjustedType(AT->getOriginalType(),
3658 adjustType(AT->getAdjustedType(), Adjust));
3659 }
3660
3661 case Type::MacroQualified: {
3662 const auto *MQT = cast<MacroQualifiedType>(Orig);
3663 return getMacroQualifiedType(adjustType(MQT->getUnderlyingType(), Adjust),
3664 MQT->getMacroIdentifier());
3665 }
3666
3667 default:
3668 return Adjust(Orig);
3669 }
3670 }
3671
3672 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
3673 FunctionType::ExtInfo Info) {
3674 if (T->getExtInfo() == Info)
3675 return T;
3676
3677 QualType Result;
3678 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3679 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3680 } else {
3681 const auto *FPT = cast<FunctionProtoType>(T);
3682 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3683 EPI.ExtInfo = Info;
3684 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3685 }
3686
3687 return cast<FunctionType>(Result.getTypePtr());
3688 }
3689
3690 QualType ASTContext::adjustFunctionResultType(QualType FunctionType,
3691 QualType ResultType) {
3692 return adjustType(FunctionType, [&](QualType Orig) {
3693 if (const auto *FNPT = Orig->getAs<FunctionNoProtoType>())
3694 return getFunctionNoProtoType(ResultType, FNPT->getExtInfo());
3695
3696 const auto *FPT = Orig->castAs<FunctionProtoType>();
3697 return getFunctionType(ResultType, FPT->getParamTypes(),
3698 FPT->getExtProtoInfo());
3699 });
3700 }
3701
3702 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
3703 QualType ResultType) {
3704 FD = FD->getMostRecentDecl();
3705 while (true) {
3706 FD->setType(adjustFunctionResultType(FD->getType(), ResultType));
3707 if (FunctionDecl *Next = FD->getPreviousDecl())
3708 FD = Next;
3709 else
3710 break;
3711 }
3712 if (ASTMutationListener *L = getASTMutationListener())
3713 L->DeducedReturnType(FD, ResultType);
3714 }
3715
3716 /// Get a function type and produce the equivalent function type with the
3717 /// specified exception specification. Type sugar that can be present on a
3718 /// declaration of a function with an exception specification is permitted
3719 /// and preserved. Other type sugar (for instance, typedefs) is not.
3720 QualType ASTContext::getFunctionTypeWithExceptionSpec(
3721 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3722 return adjustType(Orig, [&](QualType Ty) {
3723 const auto *Proto = Ty->castAs<FunctionProtoType>();
3724 return getFunctionType(Proto->getReturnType(), Proto->getParamTypes(),
3725 Proto->getExtProtoInfo().withExceptionSpec(ESI));
3726 });
3727 }
3728
3729 bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
3730 QualType U) const {
3731 return hasSameType(T, U) ||
3732 (getLangOpts().CPlusPlus17 &&
3733 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
3734 getFunctionTypeWithExceptionSpec(U, EST_None)));
3735 }
3736
3737 QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) {
3738 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3739 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3740 SmallVector<QualType, 16> Args(Proto->param_types().size());
3741 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3742 Args[i] = removePtrSizeAddrSpace(Proto->param_types()[i]);
3743 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3744 }
3745
3746 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3747 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3748 return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3749 }
3750
3751 return T;
3752 }
3753
3754 bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) {
3755 return hasSameType(T, U) ||
3756 hasSameType(getFunctionTypeWithoutPtrSizes(T),
3757 getFunctionTypeWithoutPtrSizes(U));
3758 }
3759
3760 QualType ASTContext::getFunctionTypeWithoutParamABIs(QualType T) const {
3761 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3762 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3763 EPI.ExtParameterInfos = nullptr;
3764 return getFunctionType(Proto->getReturnType(), Proto->param_types(), EPI);
3765 }
3766 return T;
3767 }
3768
3769 bool ASTContext::hasSameFunctionTypeIgnoringParamABI(QualType T,
3770 QualType U) const {
3771 return hasSameType(T, U) || hasSameType(getFunctionTypeWithoutParamABIs(T),
3772 getFunctionTypeWithoutParamABIs(U));
3773 }
3774
3775 void ASTContext::adjustExceptionSpec(
3776 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
3777 bool AsWritten) {
3778 // Update the type.
3779 QualType Updated =
3780 getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
3781 FD->setType(Updated);
3782
3783 if (!AsWritten)
3784 return;
3785
3786 // Update the type in the type source information too.
3787 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3788 // If the type and the type-as-written differ, we may need to update
3789 // the type-as-written too.
3790 if (TSInfo->getType() != FD->getType())
3791 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3792
3793 // FIXME: When we get proper type location information for exceptions,
3794 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3795 // up the TypeSourceInfo;
3796 assert(TypeLoc::getFullDataSizeForType(Updated) ==
3797 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3798 "TypeLoc size mismatch from updating exception specification");
3799 TSInfo->overrideType(Updated);
3800 }
3801 }
3802
3803 /// getComplexType - Return the uniqued reference to the type for a complex
3804 /// number with the specified element type.
3805 QualType ASTContext::getComplexType(QualType T) const {
3806 // Unique pointers, to guarantee there is only one pointer of a particular
3807 // structure.
3808 llvm::FoldingSetNodeID ID;
3809 ComplexType::Profile(ID, T);
3810
3811 void *InsertPos = nullptr;
3812 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3813 return QualType(CT, 0);
3814
3815 // If the pointee type isn't canonical, this won't be a canonical type either,
3816 // so fill in the canonical type field.
3817 QualType Canonical;
3818 if (!T.isCanonical()) {
3819 Canonical = getComplexType(getCanonicalType(T));
3820
3821 // Get the new insert position for the node we care about.
3822 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3823 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3824 }
3825 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
3826 Types.push_back(New);
3827 ComplexTypes.InsertNode(New, InsertPos);
3828 return QualType(New, 0);
3829 }
3830
3831 /// getPointerType - Return the uniqued reference to the type for a pointer to
3832 /// the specified type.
3833 QualType ASTContext::getPointerType(QualType T) const {
3834 // Unique pointers, to guarantee there is only one pointer of a particular
3835 // structure.
3836 llvm::FoldingSetNodeID ID;
3837 PointerType::Profile(ID, T);
3838
3839 void *InsertPos = nullptr;
3840 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3841 return QualType(PT, 0);
3842
3843 // If the pointee type isn't canonical, this won't be a canonical type either,
3844 // so fill in the canonical type field.
3845 QualType Canonical;
3846 if (!T.isCanonical()) {
3847 Canonical = getPointerType(getCanonicalType(T));
3848
3849 // Get the new insert position for the node we care about.
3850 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3851 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3852 }
3853 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
3854 Types.push_back(New);
3855 PointerTypes.InsertNode(New, InsertPos);
3856 return QualType(New, 0);
3857 }
3858
3859 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
3860 llvm::FoldingSetNodeID ID;
3861 AdjustedType::Profile(ID, Orig, New);
3862 void *InsertPos = nullptr;
3863 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3864 if (AT)
3865 return QualType(AT, 0);
3866
3867 QualType Canonical = getCanonicalType(New);
3868
3869 // Get the new insert position for the node we care about.
3870 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3871 assert(!AT && "Shouldn't be in the map!");
3872
3873 AT = new (*this, alignof(AdjustedType))
3874 AdjustedType(Type::Adjusted, Orig, New, Canonical);
3875 Types.push_back(AT);
3876 AdjustedTypes.InsertNode(AT, InsertPos);
3877 return QualType(AT, 0);
3878 }
3879
3880 QualType ASTContext::getDecayedType(QualType Orig, QualType Decayed) const {
3881 llvm::FoldingSetNodeID ID;
3882 AdjustedType::Profile(ID, Orig, Decayed);
3883 void *InsertPos = nullptr;
3884 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3885 if (AT)
3886 return QualType(AT, 0);
3887
3888 QualType Canonical = getCanonicalType(Decayed);
3889
3890 // Get the new insert position for the node we care about.
3891 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3892 assert(!AT && "Shouldn't be in the map!");
3893
3894 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
3895 Types.push_back(AT);
3896 AdjustedTypes.InsertNode(AT, InsertPos);
3897 return QualType(AT, 0);
3898 }
3899
3900 QualType ASTContext::getDecayedType(QualType T) const {
3901 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
3902
3903 QualType Decayed;
3904
3905 // C99 6.7.5.3p7:
3906 // A declaration of a parameter as "array of type" shall be
3907 // adjusted to "qualified pointer to type", where the type
3908 // qualifiers (if any) are those specified within the [ and ] of
3909 // the array type derivation.
3910 if (T->isArrayType())
3911 Decayed = getArrayDecayedType(T);
3912
3913 // C99 6.7.5.3p8:
3914 // A declaration of a parameter as "function returning type"
3915 // shall be adjusted to "pointer to function returning type", as
3916 // in 6.3.2.1.
3917 if (T->isFunctionType())
3918 Decayed = getPointerType(T);
3919
3920 return getDecayedType(T, Decayed);
3921 }
3922
3923 QualType ASTContext::getArrayParameterType(QualType Ty) const {
3924 if (Ty->isArrayParameterType())
3925 return Ty;
3926 assert(Ty->isConstantArrayType() && "Ty must be an array type.");
3927 QualType DTy = Ty.getDesugaredType(*this);
3928 const auto *ATy = cast<ConstantArrayType>(DTy);
3929 llvm::FoldingSetNodeID ID;
3930 ATy->Profile(ID, *this, ATy->getElementType(), ATy->getZExtSize(),
3931 ATy->getSizeExpr(), ATy->getSizeModifier(),
3932 ATy->getIndexTypeQualifiers().getAsOpaqueValue());
3933 void *InsertPos = nullptr;
3934 ArrayParameterType *AT =
3935 ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
3936 if (AT)
3937 return QualType(AT, 0);
3938
3939 QualType Canonical;
3940 if (!DTy.isCanonical()) {
3941 Canonical = getArrayParameterType(getCanonicalType(Ty));
3942
3943 // Get the new insert position for the node we care about.
3944 AT = ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
3945 assert(!AT && "Shouldn't be in the map!");
3946 }
3947
3948 AT = new (*this, alignof(ArrayParameterType))
3949 ArrayParameterType(ATy, Canonical);
3950 Types.push_back(AT);
3951 ArrayParameterTypes.InsertNode(AT, InsertPos);
3952 return QualType(AT, 0);
3953 }
3954
3955 /// getBlockPointerType - Return the uniqued reference to the type for
3956 /// a pointer to the specified block.
3957 QualType ASTContext::getBlockPointerType(QualType T) const {
3958 assert(T->isFunctionType() && "block of function types only");
3959 // Unique pointers, to guarantee there is only one block of a particular
3960 // structure.
3961 llvm::FoldingSetNodeID ID;
3962 BlockPointerType::Profile(ID, T);
3963
3964 void *InsertPos = nullptr;
3965 if (BlockPointerType *PT =
3966 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3967 return QualType(PT, 0);
3968
3969 // If the block pointee type isn't canonical, this won't be a canonical
3970 // type either so fill in the canonical type field.
3971 QualType Canonical;
3972 if (!T.isCanonical()) {
3973 Canonical = getBlockPointerType(getCanonicalType(T));
3974
3975 // Get the new insert position for the node we care about.
3976 BlockPointerType *NewIP =
3977 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3978 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3979 }
3980 auto *New =
3981 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
3982 Types.push_back(New);
3983 BlockPointerTypes.InsertNode(New, InsertPos);
3984 return QualType(New, 0);
3985 }
3986
3987 /// getLValueReferenceType - Return the uniqued reference to the type for an
3988 /// lvalue reference to the specified type.
3989 QualType
3990 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
3991 assert((!T->isPlaceholderType() ||
3992 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
3993 "Unresolved placeholder type");
3994
3995 // Unique pointers, to guarantee there is only one pointer of a particular
3996 // structure.
3997 llvm::FoldingSetNodeID ID;
3998 ReferenceType::Profile(ID, T, SpelledAsLValue);
3999
4000 void *InsertPos = nullptr;
4001 if (LValueReferenceType *RT =
4002 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4003 return QualType(RT, 0);
4004
4005 const auto *InnerRef = T->getAs<ReferenceType>();
4006
4007 // If the referencee type isn't canonical, this won't be a canonical type
4008 // either, so fill in the canonical type field.
4009 QualType Canonical;
4010 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
4011 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4012 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
4013
4014 // Get the new insert position for the node we care about.
4015 LValueReferenceType *NewIP =
4016 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4017 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4018 }
4019
4020 auto *New = new (*this, alignof(LValueReferenceType))
4021 LValueReferenceType(T, Canonical, SpelledAsLValue);
4022 Types.push_back(New);
4023 LValueReferenceTypes.InsertNode(New, InsertPos);
4024
4025 return QualType(New, 0);
4026 }
4027
4028 /// getRValueReferenceType - Return the uniqued reference to the type for an
4029 /// rvalue reference to the specified type.
4030 QualType ASTContext::getRValueReferenceType(QualType T) const {
4031 assert((!T->isPlaceholderType() ||
4032 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4033 "Unresolved placeholder type");
4034
4035 // Unique pointers, to guarantee there is only one pointer of a particular
4036 // structure.
4037 llvm::FoldingSetNodeID ID;
4038 ReferenceType::Profile(ID, T, false);
4039
4040 void *InsertPos = nullptr;
4041 if (RValueReferenceType *RT =
4042 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4043 return QualType(RT, 0);
4044
4045 const auto *InnerRef = T->getAs<ReferenceType>();
4046
4047 // If the referencee type isn't canonical, this won't be a canonical type
4048 // either, so fill in the canonical type field.
4049 QualType Canonical;
4050 if (InnerRef || !T.isCanonical()) {
4051 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4052 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
4053
4054 // Get the new insert position for the node we care about.
4055 RValueReferenceType *NewIP =
4056 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4057 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4058 }
4059
4060 auto *New = new (*this, alignof(RValueReferenceType))
4061 RValueReferenceType(T, Canonical);
4062 Types.push_back(New);
4063 RValueReferenceTypes.InsertNode(New, InsertPos);
4064 return QualType(New, 0);
4065 }
4066
4067 QualType ASTContext::getMemberPointerType(QualType T,
4068 NestedNameSpecifier Qualifier,
4069 const CXXRecordDecl *Cls) const {
4070 if (!Qualifier) {
4071 assert(Cls && "At least one of Qualifier or Cls must be provided");
4072 Qualifier = NestedNameSpecifier(getCanonicalTagType(Cls).getTypePtr());
4073 } else if (!Cls) {
4074 Cls = Qualifier.getAsRecordDecl();
4075 }
4076 // Unique pointers, to guarantee there is only one pointer of a particular
4077 // structure.
4078 llvm::FoldingSetNodeID ID;
4079 MemberPointerType::Profile(ID, T, Qualifier, Cls);
4080
4081 void *InsertPos = nullptr;
4082 if (MemberPointerType *PT =
4083 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4084 return QualType(PT, 0);
4085
4086 NestedNameSpecifier CanonicalQualifier = [&] {
4087 if (!Cls)
4088 return Qualifier.getCanonical();
4089 NestedNameSpecifier R(getCanonicalTagType(Cls).getTypePtr());
4090 assert(R.isCanonical());
4091 return R;
4092 }();
4093 // If the pointee or class type isn't canonical, this won't be a canonical
4094 // type either, so fill in the canonical type field.
4095 QualType Canonical;
4096 if (!T.isCanonical() || Qualifier != CanonicalQualifier) {
4097 Canonical =
4098 getMemberPointerType(getCanonicalType(T), CanonicalQualifier, Cls);
4099 assert(!cast<MemberPointerType>(Canonical)->isSugared());
4100 // Get the new insert position for the node we care about.
4101 [[maybe_unused]] MemberPointerType *NewIP =
4102 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4103 assert(!NewIP && "Shouldn't be in the map!");
4104 }
4105 auto *New = new (*this, alignof(MemberPointerType))
4106 MemberPointerType(T, Qualifier, Canonical);
4107 Types.push_back(New);
4108 MemberPointerTypes.InsertNode(New, InsertPos);
4109 return QualType(New, 0);
4110 }
4111
4112 /// getConstantArrayType - Return the unique reference to the type for an
4113 /// array of the specified element type.
4114 QualType ASTContext::getConstantArrayType(QualType EltTy,
4115 const llvm::APInt &ArySizeIn,
4116 const Expr *SizeExpr,
4117 ArraySizeModifier ASM,
4118 unsigned IndexTypeQuals) const {
4119 assert((EltTy->isDependentType() ||
4120 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
4121 "Constant array of VLAs is illegal!");
4122
4123 // We only need the size as part of the type if it's instantiation-dependent.
4124 if (SizeExpr && !SizeExpr->isInstantiationDependent())
4125 SizeExpr = nullptr;
4126
4127 // Convert the array size into a canonical width matching the pointer size for
4128 // the target.
4129 llvm::APInt ArySize(ArySizeIn);
4130 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
4131
4132 llvm::FoldingSetNodeID ID;
4133 ConstantArrayType::Profile(ID, *this, EltTy, ArySize.getZExtValue(), SizeExpr,
4134 ASM, IndexTypeQuals);
4135
4136 void *InsertPos = nullptr;
4137 if (ConstantArrayType *ATP =
4138 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
4139 return QualType(ATP, 0);
4140
4141 // If the element type isn't canonical or has qualifiers, or the array bound
4142 // is instantiation-dependent, this won't be a canonical type either, so fill
4143 // in the canonical type field.
4144 QualType Canon;
4145 // FIXME: Check below should look for qualifiers behind sugar.
4146 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
4147 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4148 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
4149 ASM, IndexTypeQuals);
4150 Canon = getQualifiedType(Canon, canonSplit.Quals);
4151
4152 // Get the new insert position for the node we care about.
4153 ConstantArrayType *NewIP =
4154 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
4155 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4156 }
4157
4158 auto *New = ConstantArrayType::Create(*this, EltTy, Canon, ArySize, SizeExpr,
4159 ASM, IndexTypeQuals);
4160 ConstantArrayTypes.InsertNode(New, InsertPos);
4161 Types.push_back(New);
4162 return QualType(New, 0);
4163 }
4164
4165 /// getVariableArrayDecayedType - Turns the given type, which may be
4166 /// variably-modified, into the corresponding type with all the known
4167 /// sizes replaced with [*].
4168 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
4169 // Vastly most common case.
4170 if (!type->isVariablyModifiedType()) return type;
4171
4172 QualType result;
4173
4174 SplitQualType split = type.getSplitDesugaredType();
4175 const Type *ty = split.Ty;
4176 switch (ty->getTypeClass()) {
4177 #define TYPE(Class, Base)
4178 #define ABSTRACT_TYPE(Class, Base)
4179 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4180 #include "clang/AST/TypeNodes.inc"
4181 llvm_unreachable("didn't desugar past all non-canonical types?");
4182
4183 // These types should never be variably-modified.
4184 case Type::Builtin:
4185 case Type::Complex:
4186 case Type::Vector:
4187 case Type::DependentVector:
4188 case Type::ExtVector:
4189 case Type::DependentSizedExtVector:
4190 case Type::ConstantMatrix:
4191 case Type::DependentSizedMatrix:
4192 case Type::DependentAddressSpace:
4193 case Type::ObjCObject:
4194 case Type::ObjCInterface:
4195 case Type::ObjCObjectPointer:
4196 case Type::Record:
4197 case Type::Enum:
4198 case Type::UnresolvedUsing:
4199 case Type::TypeOfExpr:
4200 case Type::TypeOf:
4201 case Type::Decltype:
4202 case Type::UnaryTransform:
4203 case Type::DependentName:
4204 case Type::InjectedClassName:
4205 case Type::TemplateSpecialization:
4206 case Type::TemplateTypeParm:
4207 case Type::SubstTemplateTypeParmPack:
4208 case Type::SubstBuiltinTemplatePack:
4209 case Type::Auto:
4210 case Type::DeducedTemplateSpecialization:
4211 case Type::PackExpansion:
4212 case Type::PackIndexing:
4213 case Type::BitInt:
4214 case Type::DependentBitInt:
4215 case Type::ArrayParameter:
4216 case Type::HLSLAttributedResource:
4217 case Type::HLSLInlineSpirv:
4218 llvm_unreachable("type should never be variably-modified");
4219
4220 // These types can be variably-modified but should never need to
4221 // further decay.
4222 case Type::FunctionNoProto:
4223 case Type::FunctionProto:
4224 case Type::BlockPointer:
4225 case Type::MemberPointer:
4226 case Type::Pipe:
4227 return type;
4228
4229 // These types can be variably-modified. All these modifications
4230 // preserve structure except as noted by comments.
4231 // TODO: if we ever care about optimizing VLAs, there are no-op
4232 // optimizations available here.
4233 case Type::Pointer:
4234 result = getPointerType(getVariableArrayDecayedType(
4235 cast<PointerType>(ty)->getPointeeType()));
4236 break;
4237
4238 case Type::LValueReference: {
4239 const auto *lv = cast<LValueReferenceType>(ty);
4240 result = getLValueReferenceType(
4241 getVariableArrayDecayedType(lv->getPointeeType()),
4242 lv->isSpelledAsLValue());
4243 break;
4244 }
4245
4246 case Type::RValueReference: {
4247 const auto *lv = cast<RValueReferenceType>(ty);
4248 result = getRValueReferenceType(
4249 getVariableArrayDecayedType(lv->getPointeeType()));
4250 break;
4251 }
4252
4253 case Type::Atomic: {
4254 const auto *at = cast<AtomicType>(ty);
4255 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
4256 break;
4257 }
4258
4259 case Type::ConstantArray: {
4260 const auto *cat = cast<ConstantArrayType>(ty);
4261 result = getConstantArrayType(
4262 getVariableArrayDecayedType(cat->getElementType()),
4263 cat->getSize(),
4264 cat->getSizeExpr(),
4265 cat->getSizeModifier(),
4266 cat->getIndexTypeCVRQualifiers());
4267 break;
4268 }
4269
4270 case Type::DependentSizedArray: {
4271 const auto *dat = cast<DependentSizedArrayType>(ty);
4272 result = getDependentSizedArrayType(
4273 getVariableArrayDecayedType(dat->getElementType()), dat->getSizeExpr(),
4274 dat->getSizeModifier(), dat->getIndexTypeCVRQualifiers());
4275 break;
4276 }
4277
4278 // Turn incomplete types into [*] types.
4279 case Type::IncompleteArray: {
4280 const auto *iat = cast<IncompleteArrayType>(ty);
4281 result =
4282 getVariableArrayType(getVariableArrayDecayedType(iat->getElementType()),
4283 /*size*/ nullptr, ArraySizeModifier::Normal,
4284 iat->getIndexTypeCVRQualifiers());
4285 break;
4286 }
4287
4288 // Turn VLA types into [*] types.
4289 case Type::VariableArray: {
4290 const auto *vat = cast<VariableArrayType>(ty);
4291 result =
4292 getVariableArrayType(getVariableArrayDecayedType(vat->getElementType()),
4293 /*size*/ nullptr, ArraySizeModifier::Star,
4294 vat->getIndexTypeCVRQualifiers());
4295 break;
4296 }
4297 }
4298
4299 // Apply the top-level qualifiers from the original.
4300 return getQualifiedType(result, split.Quals);
4301 }
4302
4303 /// getVariableArrayType - Returns a non-unique reference to the type for a
4304 /// variable array of the specified element type.
4305 QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts,
4306 ArraySizeModifier ASM,
4307 unsigned IndexTypeQuals) const {
4308 // Since we don't unique expressions, it isn't possible to unique VLA's
4309 // that have an expression provided for their size.
4310 QualType Canon;
4311
4312 // Be sure to pull qualifiers off the element type.
4313 // FIXME: Check below should look for qualifiers behind sugar.
4314 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
4315 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4316 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
4317 IndexTypeQuals);
4318 Canon = getQualifiedType(Canon, canonSplit.Quals);
4319 }
4320
4321 auto *New = new (*this, alignof(VariableArrayType))
4322 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals);
4323
4324 VariableArrayTypes.push_back(New);
4325 Types.push_back(New);
4326 return QualType(New, 0);
4327 }
4328
4329 /// getDependentSizedArrayType - Returns a non-unique reference to
4330 /// the type for a dependently-sized array of the specified element
4331 /// type.
4332 QualType
4333 ASTContext::getDependentSizedArrayType(QualType elementType, Expr *numElements,
4334 ArraySizeModifier ASM,
4335 unsigned elementTypeQuals) const {
4336 assert((!numElements || numElements->isTypeDependent() ||
4337 numElements->isValueDependent()) &&
4338 "Size must be type- or value-dependent!");
4339
4340 SplitQualType canonElementType = getCanonicalType(elementType).split();
4341
4342 void *insertPos = nullptr;
4343 llvm::FoldingSetNodeID ID;
4344 DependentSizedArrayType::Profile(
4345 ID, *this, numElements ? QualType(canonElementType.Ty, 0) : elementType,
4346 ASM, elementTypeQuals, numElements);
4347
4348 // Look for an existing type with these properties.
4349 DependentSizedArrayType *canonTy =
4350 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4351
4352 // Dependently-sized array types that do not have a specified number
4353 // of elements will have their sizes deduced from a dependent
4354 // initializer.
4355 if (!numElements) {
4356 if (canonTy)
4357 return QualType(canonTy, 0);
4358
4359 auto *newType = new (*this, alignof(DependentSizedArrayType))
4360 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
4361 elementTypeQuals);
4362 DependentSizedArrayTypes.InsertNode(newType, insertPos);
4363 Types.push_back(newType);
4364 return QualType(newType, 0);
4365 }
4366
4367 // If we don't have one, build one.
4368 if (!canonTy) {
4369 canonTy = new (*this, alignof(DependentSizedArrayType))
4370 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
4371 numElements, ASM, elementTypeQuals);
4372 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
4373 Types.push_back(canonTy);
4374 }
4375
4376 // Apply qualifiers from the element type to the array.
4377 QualType canon = getQualifiedType(QualType(canonTy,0),
4378 canonElementType.Quals);
4379
4380 // If we didn't need extra canonicalization for the element type or the size
4381 // expression, then just use that as our result.
4382 if (QualType(canonElementType.Ty, 0) == elementType &&
4383 canonTy->getSizeExpr() == numElements)
4384 return canon;
4385
4386 // Otherwise, we need to build a type which follows the spelling
4387 // of the element type.
4388 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
4389 DependentSizedArrayType(elementType, canon, numElements, ASM,
4390 elementTypeQuals);
4391 Types.push_back(sugaredType);
4392 return QualType(sugaredType, 0);
4393 }
4394
4395 QualType ASTContext::getIncompleteArrayType(QualType elementType,
4396 ArraySizeModifier ASM,
4397 unsigned elementTypeQuals) const {
4398 llvm::FoldingSetNodeID ID;
4399 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
4400
4401 void *insertPos = nullptr;
4402 if (IncompleteArrayType *iat =
4403 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
4404 return QualType(iat, 0);
4405
4406 // If the element type isn't canonical, this won't be a canonical type
4407 // either, so fill in the canonical type field. We also have to pull
4408 // qualifiers off the element type.
4409 QualType canon;
4410
4411 // FIXME: Check below should look for qualifiers behind sugar.
4412 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
4413 SplitQualType canonSplit = getCanonicalType(elementType).split();
4414 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
4415 ASM, elementTypeQuals);
4416 canon = getQualifiedType(canon, canonSplit.Quals);
4417
4418 // Get the new insert position for the node we care about.
4419 IncompleteArrayType *existing =
4420 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4421 assert(!existing && "Shouldn't be in the map!"); (void) existing;
4422 }
4423
4424 auto *newType = new (*this, alignof(IncompleteArrayType))
4425 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
4426
4427 IncompleteArrayTypes.InsertNode(newType, insertPos);
4428 Types.push_back(newType);
4429 return QualType(newType, 0);
4430 }
4431
4432 ASTContext::BuiltinVectorTypeInfo
4433 ASTContext::getBuiltinVectorTypeInfo(const BuiltinType *Ty) const {
4434 #define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
4435 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
4436 NUMVECTORS};
4437
4438 #define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
4439 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
4440
4441 switch (Ty->getKind()) {
4442 default:
4443 llvm_unreachable("Unsupported builtin vector type");
4444
4445 #define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4446 ElBits, NF, IsSigned) \
4447 case BuiltinType::Id: \
4448 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4449 llvm::ElementCount::getScalable(NumEls), NF};
4450 #define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4451 ElBits, NF) \
4452 case BuiltinType::Id: \
4453 return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy), \
4454 llvm::ElementCount::getScalable(NumEls), NF};
4455 #define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4456 ElBits, NF) \
4457 case BuiltinType::Id: \
4458 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4459 #define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4460 ElBits, NF) \
4461 case BuiltinType::Id: \
4462 return {MFloat8Ty, llvm::ElementCount::getScalable(NumEls), NF};
4463 #define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4464 case BuiltinType::Id: \
4465 return {BoolTy, llvm::ElementCount::getScalable(NumEls), NF};
4466 #include "clang/Basic/AArch64ACLETypes.def"
4467
4468 #define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4469 IsSigned) \
4470 case BuiltinType::Id: \
4471 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4472 llvm::ElementCount::getScalable(NumEls), NF};
4473 #define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4474 case BuiltinType::Id: \
4475 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4476 llvm::ElementCount::getScalable(NumEls), NF};
4477 #define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4478 case BuiltinType::Id: \
4479 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4480 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4481 case BuiltinType::Id: \
4482 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4483 #include "clang/Basic/RISCVVTypes.def"
4484 }
4485 }
4486
4487 /// getExternrefType - Return a WebAssembly externref type, which represents an
4488 /// opaque reference to a host value.
4489 QualType ASTContext::getWebAssemblyExternrefType() const {
4490 if (Target->getTriple().isWasm() && Target->hasFeature("reference-types")) {
4491 #define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4492 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4493 return SingletonId;
4494 #include "clang/Basic/WebAssemblyReferenceTypes.def"
4495 }
4496 llvm_unreachable(
4497 "shouldn't try to generate type externref outside WebAssembly target");
4498 }
4499
4500 /// getScalableVectorType - Return the unique reference to a scalable vector
4501 /// type of the specified element type and size. VectorType must be a built-in
4502 /// type.
4503 QualType ASTContext::getScalableVectorType(QualType EltTy, unsigned NumElts,
4504 unsigned NumFields) const {
4505 auto K = llvm::ScalableVecTyKey{EltTy, NumElts, NumFields};
4506 if (auto It = ScalableVecTyMap.find(K); It != ScalableVecTyMap.end())
4507 return It->second;
4508
4509 if (Target->hasAArch64ACLETypes()) {
4510 uint64_t EltTySize = getTypeSize(EltTy);
4511
4512 #define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4513 ElBits, NF, IsSigned) \
4514 if (EltTy->hasIntegerRepresentation() && !EltTy->isBooleanType() && \
4515 EltTy->hasSignedIntegerRepresentation() == IsSigned && \
4516 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4517 return ScalableVecTyMap[K] = SingletonId; \
4518 }
4519 #define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4520 ElBits, NF) \
4521 if (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4522 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4523 return ScalableVecTyMap[K] = SingletonId; \
4524 }
4525 #define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4526 ElBits, NF) \
4527 if (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4528 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4529 return ScalableVecTyMap[K] = SingletonId; \
4530 }
4531 #define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4532 ElBits, NF) \
4533 if (EltTy->isMFloat8Type() && EltTySize == ElBits && \
4534 NumElts == (NumEls * NF) && NumFields == 1) { \
4535 return ScalableVecTyMap[K] = SingletonId; \
4536 }
4537 #define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4538 if (EltTy->isBooleanType() && NumElts == (NumEls * NF) && NumFields == 1) \
4539 return ScalableVecTyMap[K] = SingletonId;
4540 #include "clang/Basic/AArch64ACLETypes.def"
4541 } else if (Target->hasRISCVVTypes()) {
4542 uint64_t EltTySize = getTypeSize(EltTy);
4543 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4544 IsFP, IsBF) \
4545 if (!EltTy->isBooleanType() && \
4546 ((EltTy->hasIntegerRepresentation() && \
4547 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4548 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4549 IsFP && !IsBF) || \
4550 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4551 IsBF && !IsFP)) && \
4552 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4553 return ScalableVecTyMap[K] = SingletonId;
4554 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4555 if (EltTy->isBooleanType() && NumElts == NumEls) \
4556 return ScalableVecTyMap[K] = SingletonId;
4557 #include "clang/Basic/RISCVVTypes.def"
4558 }
4559 return QualType();
4560 }
4561
4562 /// getVectorType - Return the unique reference to a vector type of
4563 /// the specified element type and size. VectorType must be a built-in type.
4564 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
4565 VectorKind VecKind) const {
4566 assert(vecType->isBuiltinType() ||
4567 (vecType->isBitIntType() &&
4568 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4569 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4570
4571 // Check if we've already instantiated a vector of this type.
4572 llvm::FoldingSetNodeID ID;
4573 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
4574
4575 void *InsertPos = nullptr;
4576 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4577 return QualType(VTP, 0);
4578
4579 // If the element type isn't canonical, this won't be a canonical type either,
4580 // so fill in the canonical type field.
4581 QualType Canonical;
4582 if (!vecType.isCanonical()) {
4583 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4584
4585 // Get the new insert position for the node we care about.
4586 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4587 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4588 }
4589 auto *New = new (*this, alignof(VectorType))
4590 VectorType(vecType, NumElts, Canonical, VecKind);
4591 VectorTypes.InsertNode(New, InsertPos);
4592 Types.push_back(New);
4593 return QualType(New, 0);
4594 }
4595
4596 QualType ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
4597 SourceLocation AttrLoc,
4598 VectorKind VecKind) const {
4599 llvm::FoldingSetNodeID ID;
4600 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4601 VecKind);
4602 void *InsertPos = nullptr;
4603 DependentVectorType *Canon =
4604 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4605 DependentVectorType *New;
4606
4607 if (Canon) {
4608 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4609 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4610 } else {
4611 QualType CanonVecTy = getCanonicalType(VecType);
4612 if (CanonVecTy == VecType) {
4613 New = new (*this, alignof(DependentVectorType))
4614 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4615
4616 DependentVectorType *CanonCheck =
4617 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4618 assert(!CanonCheck &&
4619 "Dependent-sized vector_size canonical type broken");
4620 (void)CanonCheck;
4621 DependentVectorTypes.InsertNode(New, InsertPos);
4622 } else {
4623 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4624 SourceLocation(), VecKind);
4625 New = new (*this, alignof(DependentVectorType))
4626 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4627 }
4628 }
4629
4630 Types.push_back(New);
4631 return QualType(New, 0);
4632 }
4633
4634 /// getExtVectorType - Return the unique reference to an extended vector type of
4635 /// the specified element type and size. VectorType must be a built-in type.
4636 QualType ASTContext::getExtVectorType(QualType vecType,
4637 unsigned NumElts) const {
4638 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4639 (vecType->isBitIntType() &&
4640 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4641 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4642
4643 // Check if we've already instantiated a vector of this type.
4644 llvm::FoldingSetNodeID ID;
4645 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4646 VectorKind::Generic);
4647 void *InsertPos = nullptr;
4648 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4649 return QualType(VTP, 0);
4650
4651 // If the element type isn't canonical, this won't be a canonical type either,
4652 // so fill in the canonical type field.
4653 QualType Canonical;
4654 if (!vecType.isCanonical()) {
4655 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4656
4657 // Get the new insert position for the node we care about.
4658 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4659 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4660 }
4661 auto *New = new (*this, alignof(ExtVectorType))
4662 ExtVectorType(vecType, NumElts, Canonical);
4663 VectorTypes.InsertNode(New, InsertPos);
4664 Types.push_back(New);
4665 return QualType(New, 0);
4666 }
4667
4668 QualType
4669 ASTContext::getDependentSizedExtVectorType(QualType vecType,
4670 Expr *SizeExpr,
4671 SourceLocation AttrLoc) const {
4672 llvm::FoldingSetNodeID ID;
4673 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
4674 SizeExpr);
4675
4676 void *InsertPos = nullptr;
4677 DependentSizedExtVectorType *Canon
4678 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4679 DependentSizedExtVectorType *New;
4680 if (Canon) {
4681 // We already have a canonical version of this array type; use it as
4682 // the canonical type for a newly-built type.
4683 New = new (*this, alignof(DependentSizedExtVectorType))
4684 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4685 AttrLoc);
4686 } else {
4687 QualType CanonVecTy = getCanonicalType(vecType);
4688 if (CanonVecTy == vecType) {
4689 New = new (*this, alignof(DependentSizedExtVectorType))
4690 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4691
4692 DependentSizedExtVectorType *CanonCheck
4693 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4694 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4695 (void)CanonCheck;
4696 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4697 } else {
4698 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4699 SourceLocation());
4700 New = new (*this, alignof(DependentSizedExtVectorType))
4701 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4702 }
4703 }
4704
4705 Types.push_back(New);
4706 return QualType(New, 0);
4707 }
4708
4709 QualType ASTContext::getConstantMatrixType(QualType ElementTy, unsigned NumRows,
4710 unsigned NumColumns) const {
4711 llvm::FoldingSetNodeID ID;
4712 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4713 Type::ConstantMatrix);
4714
4715 assert(MatrixType::isValidElementType(ElementTy, getLangOpts()) &&
4716 "need a valid element type");
4717 assert(NumRows > 0 && NumRows <= LangOpts.MaxMatrixDimension &&
4718 NumColumns > 0 && NumColumns <= LangOpts.MaxMatrixDimension &&
4719 "need valid matrix dimensions");
4720 void *InsertPos = nullptr;
4721 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4722 return QualType(MTP, 0);
4723
4724 QualType Canonical;
4725 if (!ElementTy.isCanonical()) {
4726 Canonical =
4727 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4728
4729 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4730 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4731 (void)NewIP;
4732 }
4733
4734 auto *New = new (*this, alignof(ConstantMatrixType))
4735 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4736 MatrixTypes.InsertNode(New, InsertPos);
4737 Types.push_back(New);
4738 return QualType(New, 0);
4739 }
4740
4741 QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy,
4742 Expr *RowExpr,
4743 Expr *ColumnExpr,
4744 SourceLocation AttrLoc) const {
4745 QualType CanonElementTy = getCanonicalType(ElementTy);
4746 llvm::FoldingSetNodeID ID;
4747 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4748 ColumnExpr);
4749
4750 void *InsertPos = nullptr;
4751 DependentSizedMatrixType *Canon =
4752 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4753
4754 if (!Canon) {
4755 Canon = new (*this, alignof(DependentSizedMatrixType))
4756 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4757 ColumnExpr, AttrLoc);
4758 #ifndef NDEBUG
4759 DependentSizedMatrixType *CanonCheck =
4760 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4761 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4762 #endif
4763 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4764 Types.push_back(Canon);
4765 }
4766
4767 // Already have a canonical version of the matrix type
4768 //
4769 // If it exactly matches the requested type, use it directly.
4770 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4771 Canon->getRowExpr() == ColumnExpr)
4772 return QualType(Canon, 0);
4773
4774 // Use Canon as the canonical type for newly-built type.
4775 DependentSizedMatrixType *New = new (*this, alignof(DependentSizedMatrixType))
4776 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4777 ColumnExpr, AttrLoc);
4778 Types.push_back(New);
4779 return QualType(New, 0);
4780 }
4781
4782 QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
4783 Expr *AddrSpaceExpr,
4784 SourceLocation AttrLoc) const {
4785 assert(AddrSpaceExpr->isInstantiationDependent());
4786
4787 QualType canonPointeeType = getCanonicalType(PointeeType);
4788
4789 void *insertPos = nullptr;
4790 llvm::FoldingSetNodeID ID;
4791 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4792 AddrSpaceExpr);
4793
4794 DependentAddressSpaceType *canonTy =
4795 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4796
4797 if (!canonTy) {
4798 canonTy = new (*this, alignof(DependentAddressSpaceType))
4799 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
4800 AttrLoc);
4801 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4802 Types.push_back(canonTy);
4803 }
4804
4805 if (canonPointeeType == PointeeType &&
4806 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4807 return QualType(canonTy, 0);
4808
4809 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
4810 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
4811 AddrSpaceExpr, AttrLoc);
4812 Types.push_back(sugaredType);
4813 return QualType(sugaredType, 0);
4814 }
4815
4816 /// Determine whether \p T is canonical as the result type of a function.
4817 static bool isCanonicalResultType(QualType T) {
4818 return T.isCanonical() &&
4819 (T.getObjCLifetime() == Qualifiers::OCL_None ||
4820 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4821 }
4822
4823 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4824 QualType
4825 ASTContext::getFunctionNoProtoType(QualType ResultTy,
4826 const FunctionType::ExtInfo &Info) const {
4827 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
4828 // functionality creates a function without a prototype regardless of
4829 // language mode (so it makes them even in C++). Once the rewriter has been
4830 // fixed, this assertion can be enabled again.
4831 //assert(!LangOpts.requiresStrictPrototypes() &&
4832 // "strict prototypes are disabled");
4833
4834 // Unique functions, to guarantee there is only one function of a particular
4835 // structure.
4836 llvm::FoldingSetNodeID ID;
4837 FunctionNoProtoType::Profile(ID, ResultTy, Info);
4838
4839 void *InsertPos = nullptr;
4840 if (FunctionNoProtoType *FT =
4841 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4842 return QualType(FT, 0);
4843
4844 QualType Canonical;
4845 if (!isCanonicalResultType(ResultTy)) {
4846 Canonical =
4847 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
4848
4849 // Get the new insert position for the node we care about.
4850 FunctionNoProtoType *NewIP =
4851 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4852 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4853 }
4854
4855 auto *New = new (*this, alignof(FunctionNoProtoType))
4856 FunctionNoProtoType(ResultTy, Canonical, Info);
4857 Types.push_back(New);
4858 FunctionNoProtoTypes.InsertNode(New, InsertPos);
4859 return QualType(New, 0);
4860 }
4861
4862 CanQualType
4863 ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
4864 CanQualType CanResultType = getCanonicalType(ResultType);
4865
4866 // Canonical result types do not have ARC lifetime qualifiers.
4867 if (CanResultType.getQualifiers().hasObjCLifetime()) {
4868 Qualifiers Qs = CanResultType.getQualifiers();
4869 Qs.removeObjCLifetime();
4870 return CanQualType::CreateUnsafe(
4871 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
4872 }
4873
4874 return CanResultType;
4875 }
4876
4877 static bool isCanonicalExceptionSpecification(
4878 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
4879 if (ESI.Type == EST_None)
4880 return true;
4881 if (!NoexceptInType)
4882 return false;
4883
4884 // C++17 onwards: exception specification is part of the type, as a simple
4885 // boolean "can this function type throw".
4886 if (ESI.Type == EST_BasicNoexcept)
4887 return true;
4888
4889 // A noexcept(expr) specification is (possibly) canonical if expr is
4890 // value-dependent.
4891 if (ESI.Type == EST_DependentNoexcept)
4892 return true;
4893
4894 // A dynamic exception specification is canonical if it only contains pack
4895 // expansions (so we can't tell whether it's non-throwing) and all its
4896 // contained types are canonical.
4897 if (ESI.Type == EST_Dynamic) {
4898 bool AnyPackExpansions = false;
4899 for (QualType ET : ESI.Exceptions) {
4900 if (!ET.isCanonical())
4901 return false;
4902 if (ET->getAs<PackExpansionType>())
4903 AnyPackExpansions = true;
4904 }
4905 return AnyPackExpansions;
4906 }
4907
4908 return false;
4909 }
4910
4911 QualType ASTContext::getFunctionTypeInternal(
4912 QualType ResultTy, ArrayRef<QualType> ArgArray,
4913 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
4914 size_t NumArgs = ArgArray.size();
4915
4916 // Unique functions, to guarantee there is only one function of a particular
4917 // structure.
4918 llvm::FoldingSetNodeID ID;
4919 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
4920 *this, true);
4921
4922 QualType Canonical;
4923 bool Unique = false;
4924
4925 void *InsertPos = nullptr;
4926 if (FunctionProtoType *FPT =
4927 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4928 QualType Existing = QualType(FPT, 0);
4929
4930 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
4931 // it so long as our exception specification doesn't contain a dependent
4932 // noexcept expression, or we're just looking for a canonical type.
4933 // Otherwise, we're going to need to create a type
4934 // sugar node to hold the concrete expression.
4935 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
4936 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
4937 return Existing;
4938
4939 // We need a new type sugar node for this one, to hold the new noexcept
4940 // expression. We do no canonicalization here, but that's OK since we don't
4941 // expect to see the same noexcept expression much more than once.
4942 Canonical = getCanonicalType(Existing);
4943 Unique = true;
4944 }
4945
4946 bool NoexceptInType = getLangOpts().CPlusPlus17;
4947 bool IsCanonicalExceptionSpec =
4948 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
4949
4950 // Determine whether the type being created is already canonical or not.
4951 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
4952 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
4953 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
4954 if (!ArgArray[i].isCanonicalAsParam())
4955 isCanonical = false;
4956
4957 if (OnlyWantCanonical)
4958 assert(isCanonical &&
4959 "given non-canonical parameters constructing canonical type");
4960
4961 // If this type isn't canonical, get the canonical version of it if we don't
4962 // already have it. The exception spec is only partially part of the
4963 // canonical type, and only in C++17 onwards.
4964 if (!isCanonical && Canonical.isNull()) {
4965 SmallVector<QualType, 16> CanonicalArgs;
4966 CanonicalArgs.reserve(NumArgs);
4967 for (unsigned i = 0; i != NumArgs; ++i)
4968 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
4969
4970 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
4971 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
4972 CanonicalEPI.HasTrailingReturn = false;
4973
4974 if (IsCanonicalExceptionSpec) {
4975 // Exception spec is already OK.
4976 } else if (NoexceptInType) {
4977 switch (EPI.ExceptionSpec.Type) {
4978 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
4979 // We don't know yet. It shouldn't matter what we pick here; no-one
4980 // should ever look at this.
4981 [[fallthrough]];
4982 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
4983 CanonicalEPI.ExceptionSpec.Type = EST_None;
4984 break;
4985
4986 // A dynamic exception specification is almost always "not noexcept",
4987 // with the exception that a pack expansion might expand to no types.
4988 case EST_Dynamic: {
4989 bool AnyPacks = false;
4990 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
4991 if (ET->getAs<PackExpansionType>())
4992 AnyPacks = true;
4993 ExceptionTypeStorage.push_back(getCanonicalType(ET));
4994 }
4995 if (!AnyPacks)
4996 CanonicalEPI.ExceptionSpec.Type = EST_None;
4997 else {
4998 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
4999 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
5000 }
5001 break;
5002 }
5003
5004 case EST_DynamicNone:
5005 case EST_BasicNoexcept:
5006 case EST_NoexceptTrue:
5007 case EST_NoThrow:
5008 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
5009 break;
5010
5011 case EST_DependentNoexcept:
5012 llvm_unreachable("dependent noexcept is already canonical");
5013 }
5014 } else {
5015 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
5016 }
5017
5018 // Adjust the canonical function result type.
5019 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
5020 Canonical =
5021 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
5022
5023 // Get the new insert position for the node we care about.
5024 FunctionProtoType *NewIP =
5025 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
5026 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5027 }
5028
5029 // Compute the needed size to hold this FunctionProtoType and the
5030 // various trailing objects.
5031 auto ESH = FunctionProtoType::getExceptionSpecSize(
5032 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
5033 size_t Size = FunctionProtoType::totalSizeToAlloc<
5034 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
5035 FunctionType::FunctionTypeExtraAttributeInfo,
5036 FunctionType::FunctionTypeArmAttributes, FunctionType::ExceptionType,
5037 Expr *, FunctionDecl *, FunctionProtoType::ExtParameterInfo, Qualifiers,
5038 FunctionEffect, EffectConditionExpr>(
5039 NumArgs, EPI.Variadic, EPI.requiresFunctionProtoTypeExtraBitfields(),
5040 EPI.requiresFunctionProtoTypeExtraAttributeInfo(),
5041 EPI.requiresFunctionProtoTypeArmAttributes(), ESH.NumExceptionType,
5042 ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
5043 EPI.ExtParameterInfos ? NumArgs : 0,
5044 EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0, EPI.FunctionEffects.size(),
5045 EPI.FunctionEffects.conditions().size());
5046
5047 auto *FTP = (FunctionProtoType *)Allocate(Size, alignof(FunctionProtoType));
5048 FunctionProtoType::ExtProtoInfo newEPI = EPI;
5049 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
5050 Types.push_back(FTP);
5051 if (!Unique)
5052 FunctionProtoTypes.InsertNode(FTP, InsertPos);
5053 if (!EPI.FunctionEffects.empty())
5054 AnyFunctionEffects = true;
5055 return QualType(FTP, 0);
5056 }
5057
5058 QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
5059 llvm::FoldingSetNodeID ID;
5060 PipeType::Profile(ID, T, ReadOnly);
5061
5062 void *InsertPos = nullptr;
5063 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
5064 return QualType(PT, 0);
5065
5066 // If the pipe element type isn't canonical, this won't be a canonical type
5067 // either, so fill in the canonical type field.
5068 QualType Canonical;
5069 if (!T.isCanonical()) {
5070 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
5071
5072 // Get the new insert position for the node we care about.
5073 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
5074 assert(!NewIP && "Shouldn't be in the map!");
5075 (void)NewIP;
5076 }
5077 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
5078 Types.push_back(New);
5079 PipeTypes.InsertNode(New, InsertPos);
5080 return QualType(New, 0);
5081 }
5082
5083 QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
5084 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
5085 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
5086 : Ty;
5087 }
5088
5089 QualType ASTContext::getReadPipeType(QualType T) const {
5090 return getPipeType(T, true);
5091 }
5092
5093 QualType ASTContext::getWritePipeType(QualType T) const {
5094 return getPipeType(T, false);
5095 }
5096
5097 QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
5098 llvm::FoldingSetNodeID ID;
5099 BitIntType::Profile(ID, IsUnsigned, NumBits);
5100
5101 void *InsertPos = nullptr;
5102 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5103 return QualType(EIT, 0);
5104
5105 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
5106 BitIntTypes.InsertNode(New, InsertPos);
5107 Types.push_back(New);
5108 return QualType(New, 0);
5109 }
5110
5111 QualType ASTContext::getDependentBitIntType(bool IsUnsigned,
5112 Expr *NumBitsExpr) const {
5113 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
5114 llvm::FoldingSetNodeID ID;
5115 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
5116
5117 void *InsertPos = nullptr;
5118 if (DependentBitIntType *Existing =
5119 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5120 return QualType(Existing, 0);
5121
5122 auto *New = new (*this, alignof(DependentBitIntType))
5123 DependentBitIntType(IsUnsigned, NumBitsExpr);
5124 DependentBitIntTypes.InsertNode(New, InsertPos);
5125
5126 Types.push_back(New);
5127 return QualType(New, 0);
5128 }
5129
5130 QualType
5131 ASTContext::getPredefinedSugarType(PredefinedSugarType::Kind KD) const {
5132 using Kind = PredefinedSugarType::Kind;
5133
5134 if (auto *Target = PredefinedSugarTypes[llvm::to_underlying(KD)];
5135 Target != nullptr)
5136 return QualType(Target, 0);
5137
5138 auto getCanonicalType = [](const ASTContext &Ctx, Kind KDI) -> QualType {
5139 switch (KDI) {
5140 // size_t (C99TC3 6.5.3.4), signed size_t (C++23 5.13.2) and
5141 // ptrdiff_t (C99TC3 6.5.6) Although these types are not built-in, they
5142 // are part of the core language and are widely used. Using
5143 // PredefinedSugarType makes these types as named sugar types rather than
5144 // standard integer types, enabling better hints and diagnostics.
5145 case Kind::SizeT:
5146 return Ctx.getFromTargetType(Ctx.Target->getSizeType());
5147 case Kind::SignedSizeT:
5148 return Ctx.getFromTargetType(Ctx.Target->getSignedSizeType());
5149 case Kind::PtrdiffT:
5150 return Ctx.getFromTargetType(Ctx.Target->getPtrDiffType(LangAS::Default));
5151 }
5152 llvm_unreachable("unexpected kind");
5153 };
5154 auto *New = new (*this, alignof(PredefinedSugarType))
5155 PredefinedSugarType(KD, &Idents.get(PredefinedSugarType::getName(KD)),
5156 getCanonicalType(*this, static_cast<Kind>(KD)));
5157 Types.push_back(New);
5158 PredefinedSugarTypes[llvm::to_underlying(KD)] = New;
5159 return QualType(New, 0);
5160 }
5161
5162 QualType ASTContext::getTypeDeclType(ElaboratedTypeKeyword Keyword,
5163 NestedNameSpecifier Qualifier,
5164 const TypeDecl *Decl) const {
5165 if (auto *Tag = dyn_cast<TagDecl>(Decl))
5166 return getTagType(Keyword, Qualifier, Tag,
5167 /*OwnsTag=*/false);
5168 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
5169 return getTypedefType(Keyword, Qualifier, Typedef);
5170 if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5171 return getUnresolvedUsingType(Keyword, Qualifier, UD);
5172
5173 assert(Keyword == ElaboratedTypeKeyword::None);
5174 assert(!Qualifier);
5175 return QualType(Decl->TypeForDecl, 0);
5176 }
5177
5178 CanQualType ASTContext::getCanonicalTypeDeclType(const TypeDecl *TD) const {
5179 if (auto *Tag = dyn_cast<TagDecl>(TD))
5180 return getCanonicalTagType(Tag);
5181 if (auto *TN = dyn_cast<TypedefNameDecl>(TD))
5182 return getCanonicalType(TN->getUnderlyingType());
5183 if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD))
5184 return getCanonicalUnresolvedUsingType(UD);
5185 assert(TD->TypeForDecl);
5186 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5187 }
5188
5189 QualType ASTContext::getTypeDeclType(const TypeDecl *Decl) const {
5190 if (const auto *TD = dyn_cast<TagDecl>(Decl))
5191 return getCanonicalTagType(TD);
5192 if (const auto *TD = dyn_cast<TypedefNameDecl>(Decl);
5193 isa_and_nonnull<TypedefDecl, TypeAliasDecl>(TD))
5194 return getTypedefType(ElaboratedTypeKeyword::None,
5195 /*Qualifier=*/std::nullopt, TD);
5196 if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5197 return getCanonicalUnresolvedUsingType(Using);
5198
5199 assert(Decl->TypeForDecl);
5200 return QualType(Decl->TypeForDecl, 0);
5201 }
5202
5203 /// getTypedefType - Return the unique reference to the type for the
5204 /// specified typedef name decl.
5205 QualType
5206 ASTContext::getTypedefType(ElaboratedTypeKeyword Keyword,
5207 NestedNameSpecifier Qualifier,
5208 const TypedefNameDecl *Decl, QualType UnderlyingType,
5209 std::optional<bool> TypeMatchesDeclOrNone) const {
5210 if (!TypeMatchesDeclOrNone) {
5211 QualType DeclUnderlyingType = Decl->getUnderlyingType();
5212 assert(!DeclUnderlyingType.isNull());
5213 if (UnderlyingType.isNull())
5214 UnderlyingType = DeclUnderlyingType;
5215 else
5216 assert(hasSameType(UnderlyingType, DeclUnderlyingType));
5217 TypeMatchesDeclOrNone = UnderlyingType == DeclUnderlyingType;
5218 } else {
5219 // FIXME: This is a workaround for a serialization cycle: assume the decl
5220 // underlying type is not available; don't touch it.
5221 assert(!UnderlyingType.isNull());
5222 }
5223
5224 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier &&
5225 *TypeMatchesDeclOrNone) {
5226 if (Decl->TypeForDecl)
5227 return QualType(Decl->TypeForDecl, 0);
5228
5229 auto *NewType = new (*this, alignof(TypedefType))
5230 TypedefType(Type::Typedef, Keyword, Qualifier, Decl, UnderlyingType,
5231 !*TypeMatchesDeclOrNone);
5232
5233 Types.push_back(NewType);
5234 Decl->TypeForDecl = NewType;
5235 return QualType(NewType, 0);
5236 }
5237
5238 llvm::FoldingSetNodeID ID;
5239 TypedefType::Profile(ID, Keyword, Qualifier, Decl,
5240 *TypeMatchesDeclOrNone ? QualType() : UnderlyingType);
5241
5242 void *InsertPos = nullptr;
5243 if (FoldingSetPlaceholder<TypedefType> *Placeholder =
5244 TypedefTypes.FindNodeOrInsertPos(ID, InsertPos))
5245 return QualType(Placeholder->getType(), 0);
5246
5247 void *Mem =
5248 Allocate(TypedefType::totalSizeToAlloc<FoldingSetPlaceholder<TypedefType>,
5249 NestedNameSpecifier, QualType>(
5250 1, !!Qualifier, !*TypeMatchesDeclOrNone),
5251 alignof(TypedefType));
5252 auto *NewType =
5253 new (Mem) TypedefType(Type::Typedef, Keyword, Qualifier, Decl,
5254 UnderlyingType, !*TypeMatchesDeclOrNone);
5255 auto *Placeholder = new (NewType->getFoldingSetPlaceholder())
5256 FoldingSetPlaceholder<TypedefType>();
5257 TypedefTypes.InsertNode(Placeholder, InsertPos);
5258 Types.push_back(NewType);
5259 return QualType(NewType, 0);
5260 }
5261
5262 QualType ASTContext::getUsingType(ElaboratedTypeKeyword Keyword,
5263 NestedNameSpecifier Qualifier,
5264 const UsingShadowDecl *D,
5265 QualType UnderlyingType) const {
5266 // FIXME: This is expensive to compute every time!
5267 if (UnderlyingType.isNull()) {
5268 const auto *UD = cast<UsingDecl>(D->getIntroducer());
5269 UnderlyingType =
5270 getTypeDeclType(UD->hasTypename() ? ElaboratedTypeKeyword::Typename
5271 : ElaboratedTypeKeyword::None,
5272 UD->getQualifier(), cast<TypeDecl>(D->getTargetDecl()));
5273 }
5274
5275 llvm::FoldingSetNodeID ID;
5276 UsingType::Profile(ID, Keyword, Qualifier, D, UnderlyingType);
5277
5278 void *InsertPos = nullptr;
5279 if (const UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5280 return QualType(T, 0);
5281
5282 assert(!UnderlyingType.hasLocalQualifiers());
5283
5284 assert(
5285 hasSameType(getCanonicalTypeDeclType(cast<TypeDecl>(D->getTargetDecl())),
5286 UnderlyingType));
5287
5288 void *Mem =
5289 Allocate(UsingType::totalSizeToAlloc<NestedNameSpecifier>(!!Qualifier),
5290 alignof(UsingType));
5291 UsingType *T = new (Mem) UsingType(Keyword, Qualifier, D, UnderlyingType);
5292 Types.push_back(T);
5293 UsingTypes.InsertNode(T, InsertPos);
5294 return QualType(T, 0);
5295 }
5296
5297 TagType *ASTContext::getTagTypeInternal(ElaboratedTypeKeyword Keyword,
5298 NestedNameSpecifier Qualifier,
5299 const TagDecl *TD, bool OwnsTag,
5300 bool IsInjected,
5301 const Type *CanonicalType,
5302 bool WithFoldingSetNode) const {
5303 auto [TC, Size] = [&] {
5304 switch (TD->getDeclKind()) {
5305 case Decl::Enum:
5306 static_assert(alignof(EnumType) == alignof(TagType));
5307 return std::make_tuple(Type::Enum, sizeof(EnumType));
5308 case Decl::ClassTemplatePartialSpecialization:
5309 case Decl::ClassTemplateSpecialization:
5310 case Decl::CXXRecord:
5311 static_assert(alignof(RecordType) == alignof(TagType));
5312 static_assert(alignof(InjectedClassNameType) == alignof(TagType));
5313 if (cast<CXXRecordDecl>(TD)->hasInjectedClassType())
5314 return std::make_tuple(Type::InjectedClassName,
5315 sizeof(InjectedClassNameType));
5316 [[fallthrough]];
5317 case Decl::Record:
5318 return std::make_tuple(Type::Record, sizeof(RecordType));
5319 default:
5320 llvm_unreachable("unexpected decl kind");
5321 }
5322 }();
5323
5324 if (Qualifier) {
5325 static_assert(alignof(NestedNameSpecifier) <= alignof(TagType));
5326 Size = llvm::alignTo(Size, alignof(NestedNameSpecifier)) +
5327 sizeof(NestedNameSpecifier);
5328 }
5329 void *Mem;
5330 if (WithFoldingSetNode) {
5331 // FIXME: It would be more profitable to tail allocate the folding set node
5332 // from the type, instead of the other way around, due to the greater
5333 // alignment requirements of the type. But this makes it harder to deal with
5334 // the different type node sizes. This would require either uniquing from
5335 // different folding sets, or having the folding setaccept a
5336 // contextual parameter which is not fixed at construction.
5337 Mem = Allocate(
5338 sizeof(TagTypeFoldingSetPlaceholder) +
5339 TagTypeFoldingSetPlaceholder::getOffset() + Size,
5340 std::max(alignof(TagTypeFoldingSetPlaceholder), alignof(TagType)));
5341 auto *T = new (Mem) TagTypeFoldingSetPlaceholder();
5342 Mem = T->getTagType();
5343 } else {
5344 Mem = Allocate(Size, alignof(TagType));
5345 }
5346
5347 auto *T = [&, TC = TC]() -> TagType * {
5348 switch (TC) {
5349 case Type::Enum: {
5350 assert(isa<EnumDecl>(TD));
5351 auto *T = new (Mem) EnumType(TC, Keyword, Qualifier, TD, OwnsTag,
5352 IsInjected, CanonicalType);
5353 assert(reinterpret_cast<void *>(T) ==
5354 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5355 "TagType must be the first base of EnumType");
5356 return T;
5357 }
5358 case Type::Record: {
5359 assert(isa<RecordDecl>(TD));
5360 auto *T = new (Mem) RecordType(TC, Keyword, Qualifier, TD, OwnsTag,
5361 IsInjected, CanonicalType);
5362 assert(reinterpret_cast<void *>(T) ==
5363 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5364 "TagType must be the first base of RecordType");
5365 return T;
5366 }
5367 case Type::InjectedClassName: {
5368 auto *T = new (Mem) InjectedClassNameType(Keyword, Qualifier, TD,
5369 IsInjected, CanonicalType);
5370 assert(reinterpret_cast<void *>(T) ==
5371 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5372 "TagType must be the first base of InjectedClassNameType");
5373 return T;
5374 }
5375 default:
5376 llvm_unreachable("unexpected type class");
5377 }
5378 }();
5379 assert(T->getKeyword() == Keyword);
5380 assert(T->getQualifier() == Qualifier);
5381 assert(T->getDecl() == TD);
5382 assert(T->isInjected() == IsInjected);
5383 assert(T->isTagOwned() == OwnsTag);
5384 assert((T->isCanonicalUnqualified()
5385 ? QualType()
5386 : T->getCanonicalTypeInternal()) == QualType(CanonicalType, 0));
5387 Types.push_back(T);
5388 return T;
5389 }
5390
5391 static const TagDecl *getNonInjectedClassName(const TagDecl *TD) {
5392 if (const auto *RD = dyn_cast<CXXRecordDecl>(TD);
5393 RD && RD->isInjectedClassName())
5394 return cast<TagDecl>(RD->getDeclContext());
5395 return TD;
5396 }
5397
5398 CanQualType ASTContext::getCanonicalTagType(const TagDecl *TD) const {
5399 TD = ::getNonInjectedClassName(TD)->getCanonicalDecl();
5400 if (TD->TypeForDecl)
5401 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5402
5403 const Type *CanonicalType = getTagTypeInternal(
5404 ElaboratedTypeKeyword::None,
5405 /*Qualifier=*/std::nullopt, TD,
5406 /*OwnsTag=*/false, /*IsInjected=*/false, /*CanonicalType=*/nullptr,
5407 /*WithFoldingSetNode=*/false);
5408 TD->TypeForDecl = CanonicalType;
5409 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5410 }
5411
5412 QualType ASTContext::getTagType(ElaboratedTypeKeyword Keyword,
5413 NestedNameSpecifier Qualifier,
5414 const TagDecl *TD, bool OwnsTag) const {
5415
5416 const TagDecl *NonInjectedTD = ::getNonInjectedClassName(TD);
5417 bool IsInjected = TD != NonInjectedTD;
5418
5419 ElaboratedTypeKeyword PreferredKeyword =
5420 getLangOpts().CPlusPlus ? ElaboratedTypeKeyword::None
5421 : KeywordHelpers::getKeywordForTagTypeKind(
5422 NonInjectedTD->getTagKind());
5423
5424 if (Keyword == PreferredKeyword && !Qualifier && !OwnsTag) {
5425 if (const Type *T = TD->TypeForDecl; T && !T->isCanonicalUnqualified())
5426 return QualType(T, 0);
5427
5428 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5429 const Type *T =
5430 getTagTypeInternal(Keyword,
5431 /*Qualifier=*/std::nullopt, NonInjectedTD,
5432 /*OwnsTag=*/false, IsInjected, CanonicalType,
5433 /*WithFoldingSetNode=*/false);
5434 TD->TypeForDecl = T;
5435 return QualType(T, 0);
5436 }
5437
5438 llvm::FoldingSetNodeID ID;
5439 TagTypeFoldingSetPlaceholder::Profile(ID, Keyword, Qualifier, NonInjectedTD,
5440 OwnsTag, IsInjected);
5441
5442 void *InsertPos = nullptr;
5443 if (TagTypeFoldingSetPlaceholder *T =
5444 TagTypes.FindNodeOrInsertPos(ID, InsertPos))
5445 return QualType(T->getTagType(), 0);
5446
5447 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5448 TagType *T =
5449 getTagTypeInternal(Keyword, Qualifier, NonInjectedTD, OwnsTag, IsInjected,
5450 CanonicalType, /*WithFoldingSetNode=*/true);
5451 TagTypes.InsertNode(TagTypeFoldingSetPlaceholder::fromTagType(T), InsertPos);
5452 return QualType(T, 0);
5453 }
5454
5455 bool ASTContext::computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits,
5456 unsigned NumPositiveBits,
5457 QualType &BestType,
5458 QualType &BestPromotionType) {
5459 unsigned IntWidth = Target->getIntWidth();
5460 unsigned CharWidth = Target->getCharWidth();
5461 unsigned ShortWidth = Target->getShortWidth();
5462 bool EnumTooLarge = false;
5463 unsigned BestWidth;
5464 if (NumNegativeBits) {
5465 // If there is a negative value, figure out the smallest integer type (of
5466 // int/long/longlong) that fits.
5467 // If it's packed, check also if it fits a char or a short.
5468 if (IsPacked && NumNegativeBits <= CharWidth &&
5469 NumPositiveBits < CharWidth) {
5470 BestType = SignedCharTy;
5471 BestWidth = CharWidth;
5472 } else if (IsPacked && NumNegativeBits <= ShortWidth &&
5473 NumPositiveBits < ShortWidth) {
5474 BestType = ShortTy;
5475 BestWidth = ShortWidth;
5476 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5477 BestType = IntTy;
5478 BestWidth = IntWidth;
5479 } else {
5480 BestWidth = Target->getLongWidth();
5481
5482 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
5483 BestType = LongTy;
5484 } else {
5485 BestWidth = Target->getLongLongWidth();
5486
5487 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5488 EnumTooLarge = true;
5489 BestType = LongLongTy;
5490 }
5491 }
5492 BestPromotionType = (BestWidth <= IntWidth ? IntTy : BestType);
5493 } else {
5494 // If there is no negative value, figure out the smallest type that fits
5495 // all of the enumerator values.
5496 // If it's packed, check also if it fits a char or a short.
5497 if (IsPacked && NumPositiveBits <= CharWidth) {
5498 BestType = UnsignedCharTy;
5499 BestPromotionType = IntTy;
5500 BestWidth = CharWidth;
5501 } else if (IsPacked && NumPositiveBits <= ShortWidth) {
5502 BestType = UnsignedShortTy;
5503 BestPromotionType = IntTy;
5504 BestWidth = ShortWidth;
5505 } else if (NumPositiveBits <= IntWidth) {
5506 BestType = UnsignedIntTy;
5507 BestWidth = IntWidth;
5508 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5509 ? UnsignedIntTy
5510 : IntTy;
5511 } else if (NumPositiveBits <= (BestWidth = Target->getLongWidth())) {
5512 BestType = UnsignedLongTy;
5513 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5514 ? UnsignedLongTy
5515 : LongTy;
5516 } else {
5517 BestWidth = Target->getLongLongWidth();
5518 if (NumPositiveBits > BestWidth) {
5519 // This can happen with bit-precise integer types, but those are not
5520 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
5521 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
5522 // a 128-bit integer, we should consider doing the same.
5523 EnumTooLarge = true;
5524 }
5525 BestType = UnsignedLongLongTy;
5526 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5527 ? UnsignedLongLongTy
5528 : LongLongTy;
5529 }
5530 }
5531 return EnumTooLarge;
5532 }
5533
5534 bool ASTContext::isRepresentableIntegerValue(llvm::APSInt &Value, QualType T) {
5535 assert((T->isIntegralType(*this) || T->isEnumeralType()) &&
5536 "Integral type required!");
5537 unsigned BitWidth = getIntWidth(T);
5538
5539 if (Value.isUnsigned() || Value.isNonNegative()) {
5540 if (T->isSignedIntegerOrEnumerationType())
5541 --BitWidth;
5542 return Value.getActiveBits() <= BitWidth;
5543 }
5544 return Value.getSignificantBits() <= BitWidth;
5545 }
5546
5547 UnresolvedUsingType *ASTContext::getUnresolvedUsingTypeInternal(
5548 ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier,
5549 const UnresolvedUsingTypenameDecl *D, void *InsertPos,
5550 const Type *CanonicalType) const {
5551 void *Mem = Allocate(
5552 UnresolvedUsingType::totalSizeToAlloc<
5553 FoldingSetPlaceholder<UnresolvedUsingType>, NestedNameSpecifier>(
5554 !!InsertPos, !!Qualifier),
5555 alignof(UnresolvedUsingType));
5556 auto *T = new (Mem) UnresolvedUsingType(Keyword, Qualifier, D, CanonicalType);
5557 if (InsertPos) {
5558 auto *Placeholder = new (T->getFoldingSetPlaceholder())
5559 FoldingSetPlaceholder<TypedefType>();
5560 TypedefTypes.InsertNode(Placeholder, InsertPos);
5561 }
5562 Types.push_back(T);
5563 return T;
5564 }
5565
5566 CanQualType ASTContext::getCanonicalUnresolvedUsingType(
5567 const UnresolvedUsingTypenameDecl *D) const {
5568 D = D->getCanonicalDecl();
5569 if (D->TypeForDecl)
5570 return D->TypeForDecl->getCanonicalTypeUnqualified();
5571
5572 const Type *CanonicalType = getUnresolvedUsingTypeInternal(
5573 ElaboratedTypeKeyword::None,
5574 /*Qualifier=*/std::nullopt, D,
5575 /*InsertPos=*/nullptr, /*CanonicalType=*/nullptr);
5576 D->TypeForDecl = CanonicalType;
5577 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5578 }
5579
5580 QualType
5581 ASTContext::getUnresolvedUsingType(ElaboratedTypeKeyword Keyword,
5582 NestedNameSpecifier Qualifier,
5583 const UnresolvedUsingTypenameDecl *D) const {
5584 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier) {
5585 if (const Type *T = D->TypeForDecl; T && !T->isCanonicalUnqualified())
5586 return QualType(T, 0);
5587
5588 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5589 const Type *T =
5590 getUnresolvedUsingTypeInternal(ElaboratedTypeKeyword::None,
5591 /*Qualifier=*/std::nullopt, D,
5592 /*InsertPos=*/nullptr, CanonicalType);
5593 D->TypeForDecl = T;
5594 return QualType(T, 0);
5595 }
5596
5597 llvm::FoldingSetNodeID ID;
5598 UnresolvedUsingType::Profile(ID, Keyword, Qualifier, D);
5599
5600 void *InsertPos = nullptr;
5601 if (FoldingSetPlaceholder<UnresolvedUsingType> *Placeholder =
5602 UnresolvedUsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5603 return QualType(Placeholder->getType(), 0);
5604 assert(InsertPos);
5605
5606 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5607 const Type *T = getUnresolvedUsingTypeInternal(Keyword, Qualifier, D,
5608 InsertPos, CanonicalType);
5609 return QualType(T, 0);
5610 }
5611
5612 QualType ASTContext::getAttributedType(attr::Kind attrKind,
5613 QualType modifiedType,
5614 QualType equivalentType,
5615 const Attr *attr) const {
5616 llvm::FoldingSetNodeID id;
5617 AttributedType::Profile(id, attrKind, modifiedType, equivalentType, attr);
5618
5619 void *insertPos = nullptr;
5620 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
5621 if (type) return QualType(type, 0);
5622
5623 assert(!attr || attr->getKind() == attrKind);
5624
5625 QualType canon = getCanonicalType(equivalentType);
5626 type = new (*this, alignof(AttributedType))
5627 AttributedType(canon, attrKind, attr, modifiedType, equivalentType);
5628
5629 Types.push_back(type);
5630 AttributedTypes.InsertNode(type, insertPos);
5631
5632 return QualType(type, 0);
5633 }
5634
5635 QualType ASTContext::getAttributedType(const Attr *attr, QualType modifiedType,
5636 QualType equivalentType) const {
5637 return getAttributedType(attr->getKind(), modifiedType, equivalentType, attr);
5638 }
5639
5640 QualType ASTContext::getAttributedType(NullabilityKind nullability,
5641 QualType modifiedType,
5642 QualType equivalentType) {
5643 switch (nullability) {
5644 case NullabilityKind::NonNull:
5645 return getAttributedType(attr::TypeNonNull, modifiedType, equivalentType);
5646
5647 case NullabilityKind::Nullable:
5648 return getAttributedType(attr::TypeNullable, modifiedType, equivalentType);
5649
5650 case NullabilityKind::NullableResult:
5651 return getAttributedType(attr::TypeNullableResult, modifiedType,
5652 equivalentType);
5653
5654 case NullabilityKind::Unspecified:
5655 return getAttributedType(attr::TypeNullUnspecified, modifiedType,
5656 equivalentType);
5657 }
5658
5659 llvm_unreachable("Unknown nullability kind");
5660 }
5661
5662 QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
5663 QualType Wrapped) const {
5664 llvm::FoldingSetNodeID ID;
5665 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
5666
5667 void *InsertPos = nullptr;
5668 BTFTagAttributedType *Ty =
5669 BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
5670 if (Ty)
5671 return QualType(Ty, 0);
5672
5673 QualType Canon = getCanonicalType(Wrapped);
5674 Ty = new (*this, alignof(BTFTagAttributedType))
5675 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
5676
5677 Types.push_back(Ty);
5678 BTFTagAttributedTypes.InsertNode(Ty, InsertPos);
5679
5680 return QualType(Ty, 0);
5681 }
5682
5683 QualType ASTContext::getHLSLAttributedResourceType(
5684 QualType Wrapped, QualType Contained,
5685 const HLSLAttributedResourceType::Attributes &Attrs) {
5686
5687 llvm::FoldingSetNodeID ID;
5688 HLSLAttributedResourceType::Profile(ID, Wrapped, Contained, Attrs);
5689
5690 void *InsertPos = nullptr;
5691 HLSLAttributedResourceType *Ty =
5692 HLSLAttributedResourceTypes.FindNodeOrInsertPos(ID, InsertPos);
5693 if (Ty)
5694 return QualType(Ty, 0);
5695
5696 Ty = new (*this, alignof(HLSLAttributedResourceType))
5697 HLSLAttributedResourceType(Wrapped, Contained, Attrs);
5698
5699 Types.push_back(Ty);
5700 HLSLAttributedResourceTypes.InsertNode(Ty, InsertPos);
5701
5702 return QualType(Ty, 0);
5703 }
5704
5705 QualType ASTContext::getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size,
5706 uint32_t Alignment,
5707 ArrayRef<SpirvOperand> Operands) {
5708 llvm::FoldingSetNodeID ID;
5709 HLSLInlineSpirvType::Profile(ID, Opcode, Size, Alignment, Operands);
5710
5711 void *InsertPos = nullptr;
5712 HLSLInlineSpirvType *Ty =
5713 HLSLInlineSpirvTypes.FindNodeOrInsertPos(ID, InsertPos);
5714 if (Ty)
5715 return QualType(Ty, 0);
5716
5717 void *Mem = Allocate(
5718 HLSLInlineSpirvType::totalSizeToAlloc<SpirvOperand>(Operands.size()),
5719 alignof(HLSLInlineSpirvType));
5720
5721 Ty = new (Mem) HLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
5722
5723 Types.push_back(Ty);
5724 HLSLInlineSpirvTypes.InsertNode(Ty, InsertPos);
5725
5726 return QualType(Ty, 0);
5727 }
5728
5729 /// Retrieve a substitution-result type.
5730 QualType ASTContext::getSubstTemplateTypeParmType(QualType Replacement,
5731 Decl *AssociatedDecl,
5732 unsigned Index,
5733 UnsignedOrNone PackIndex,
5734 bool Final) const {
5735 llvm::FoldingSetNodeID ID;
5736 SubstTemplateTypeParmType::Profile(ID, Replacement, AssociatedDecl, Index,
5737 PackIndex, Final);
5738 void *InsertPos = nullptr;
5739 SubstTemplateTypeParmType *SubstParm =
5740 SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5741
5742 if (!SubstParm) {
5743 void *Mem = Allocate(SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
5744 !Replacement.isCanonical()),
5745 alignof(SubstTemplateTypeParmType));
5746 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
5747 Index, PackIndex, Final);
5748 Types.push_back(SubstParm);
5749 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
5750 }
5751
5752 return QualType(SubstParm, 0);
5753 }
5754
5755 QualType
5756 ASTContext::getSubstTemplateTypeParmPackType(Decl *AssociatedDecl,
5757 unsigned Index, bool Final,
5758 const TemplateArgument &ArgPack) {
5759 #ifndef NDEBUG
5760 for (const auto &P : ArgPack.pack_elements())
5761 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
5762 #endif
5763
5764 llvm::FoldingSetNodeID ID;
5765 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
5766 ArgPack);
5767 void *InsertPos = nullptr;
5768 if (SubstTemplateTypeParmPackType *SubstParm =
5769 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
5770 return QualType(SubstParm, 0);
5771
5772 QualType Canon;
5773 {
5774 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5775 if (!AssociatedDecl->isCanonicalDecl() ||
5776 !CanonArgPack.structurallyEquals(ArgPack)) {
5777 Canon = getSubstTemplateTypeParmPackType(
5778 AssociatedDecl->getCanonicalDecl(), Index, Final, CanonArgPack);
5779 [[maybe_unused]] const auto *Nothing =
5780 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
5781 assert(!Nothing);
5782 }
5783 }
5784
5785 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
5786 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
5787 ArgPack);
5788 Types.push_back(SubstParm);
5789 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
5790 return QualType(SubstParm, 0);
5791 }
5792
5793 QualType
5794 ASTContext::getSubstBuiltinTemplatePack(const TemplateArgument &ArgPack) {
5795 assert(llvm::all_of(ArgPack.pack_elements(),
5796 [](const auto &P) {
5797 return P.getKind() == TemplateArgument::Type;
5798 }) &&
5799 "Pack contains a non-type");
5800
5801 llvm::FoldingSetNodeID ID;
5802 SubstBuiltinTemplatePackType::Profile(ID, ArgPack);
5803
5804 void *InsertPos = nullptr;
5805 if (auto *T =
5806 SubstBuiltinTemplatePackTypes.FindNodeOrInsertPos(ID, InsertPos))
5807 return QualType(T, 0);
5808
5809 QualType Canon;
5810 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5811 if (!CanonArgPack.structurallyEquals(ArgPack)) {
5812 Canon = getSubstBuiltinTemplatePack(CanonArgPack);
5813 // Refresh InsertPos, in case the recursive call above caused rehashing,
5814 // which would invalidate the bucket pointer.
5815 [[maybe_unused]] const auto *Nothing =
5816 SubstBuiltinTemplatePackTypes.FindNodeOrInsertPos(ID, InsertPos);
5817 assert(!Nothing);
5818 }
5819
5820 auto *PackType = new (*this, alignof(SubstBuiltinTemplatePackType))
5821 SubstBuiltinTemplatePackType(Canon, ArgPack);
5822 Types.push_back(PackType);
5823 SubstBuiltinTemplatePackTypes.InsertNode(PackType, InsertPos);
5824 return QualType(PackType, 0);
5825 }
5826
5827 /// Retrieve the template type parameter type for a template
5828 /// parameter or parameter pack with the given depth, index, and (optionally)
5829 /// name.
5830 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
5831 bool ParameterPack,
5832 TemplateTypeParmDecl *TTPDecl) const {
5833 llvm::FoldingSetNodeID ID;
5834 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
5835 void *InsertPos = nullptr;
5836 TemplateTypeParmType *TypeParm
5837 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5838
5839 if (TypeParm)
5840 return QualType(TypeParm, 0);
5841
5842 if (TTPDecl) {
5843 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
5844 TypeParm = new (*this, alignof(TemplateTypeParmType))
5845 TemplateTypeParmType(Depth, Index, ParameterPack, TTPDecl, Canon);
5846
5847 TemplateTypeParmType *TypeCheck
5848 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5849 assert(!TypeCheck && "Template type parameter canonical type broken");
5850 (void)TypeCheck;
5851 } else
5852 TypeParm = new (*this, alignof(TemplateTypeParmType)) TemplateTypeParmType(
5853 Depth, Index, ParameterPack, /*TTPDecl=*/nullptr, /*Canon=*/QualType());
5854
5855 Types.push_back(TypeParm);
5856 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
5857
5858 return QualType(TypeParm, 0);
5859 }
5860
5861 static ElaboratedTypeKeyword
5862 getCanonicalElaboratedTypeKeyword(ElaboratedTypeKeyword Keyword) {
5863 switch (Keyword) {
5864 // These are just themselves.
5865 case ElaboratedTypeKeyword::None:
5866 case ElaboratedTypeKeyword::Struct:
5867 case ElaboratedTypeKeyword::Union:
5868 case ElaboratedTypeKeyword::Enum:
5869 case ElaboratedTypeKeyword::Interface:
5870 return Keyword;
5871
5872 // These are equivalent.
5873 case ElaboratedTypeKeyword::Typename:
5874 return ElaboratedTypeKeyword::None;
5875
5876 // These are functionally equivalent, so relying on their equivalence is
5877 // IFNDR. By making them equivalent, we disallow overloading, which at least
5878 // can produce a diagnostic.
5879 case ElaboratedTypeKeyword::Class:
5880 return ElaboratedTypeKeyword::Struct;
5881 }
5882 llvm_unreachable("unexpected keyword kind");
5883 }
5884
5885 TypeSourceInfo *ASTContext::getTemplateSpecializationTypeInfo(
5886 ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc,
5887 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc,
5888 TemplateName Name, SourceLocation NameLoc,
5889 const TemplateArgumentListInfo &SpecifiedArgs,
5890 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
5891 QualType TST = getTemplateSpecializationType(
5892 Keyword, Name, SpecifiedArgs.arguments(), CanonicalArgs, Underlying);
5893
5894 TypeSourceInfo *TSI = CreateTypeSourceInfo(TST);
5895 TSI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>().set(
5896 ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
5897 SpecifiedArgs);
5898 return TSI;
5899 }
5900
5901 QualType ASTContext::getTemplateSpecializationType(
5902 ElaboratedTypeKeyword Keyword, TemplateName Template,
5903 ArrayRef<TemplateArgumentLoc> SpecifiedArgs,
5904 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
5905 SmallVector<TemplateArgument, 4> SpecifiedArgVec;
5906 SpecifiedArgVec.reserve(SpecifiedArgs.size());
5907 for (const TemplateArgumentLoc &Arg : SpecifiedArgs)
5908 SpecifiedArgVec.push_back(Arg.getArgument());
5909
5910 return getTemplateSpecializationType(Keyword, Template, SpecifiedArgVec,
5911 CanonicalArgs, Underlying);
5912 }
5913
5914 [[maybe_unused]] static bool
5915 hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
5916 for (const TemplateArgument &Arg : Args)
5917 if (Arg.isPackExpansion())
5918 return true;
5919 return false;
5920 }
5921
5922 QualType ASTContext::getCanonicalTemplateSpecializationType(
5923 ElaboratedTypeKeyword Keyword, TemplateName Template,
5924 ArrayRef<TemplateArgument> Args) const {
5925 assert(Template ==
5926 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true));
5927 assert((Keyword == ElaboratedTypeKeyword::None ||
5928 Template.getAsDependentTemplateName()));
5929 #ifndef NDEBUG
5930 for (const auto &Arg : Args)
5931 assert(Arg.structurallyEquals(getCanonicalTemplateArgument(Arg)));
5932 #endif
5933
5934 llvm::FoldingSetNodeID ID;
5935 TemplateSpecializationType::Profile(ID, Keyword, Template, Args, QualType(),
5936 *this);
5937 void *InsertPos = nullptr;
5938 if (auto *T = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
5939 return QualType(T, 0);
5940
5941 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
5942 sizeof(TemplateArgument) * Args.size(),
5943 alignof(TemplateSpecializationType));
5944 auto *Spec =
5945 new (Mem) TemplateSpecializationType(Keyword, Template,
5946 /*IsAlias=*/false, Args, QualType());
5947 assert(Spec->isDependentType() &&
5948 "canonical template specialization must be dependent");
5949 Types.push_back(Spec);
5950 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
5951 return QualType(Spec, 0);
5952 }
5953
5954 QualType ASTContext::getTemplateSpecializationType(
5955 ElaboratedTypeKeyword Keyword, TemplateName Template,
5956 ArrayRef<TemplateArgument> SpecifiedArgs,
5957 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
5958 const auto *TD = Template.getAsTemplateDecl(/*IgnoreDeduced=*/true);
5959 bool IsTypeAlias = TD && TD->isTypeAlias();
5960 if (Underlying.isNull()) {
5961 TemplateName CanonTemplate =
5962 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true);
5963 ElaboratedTypeKeyword CanonKeyword =
5964 CanonTemplate.getAsDependentTemplateName()
5965 ? getCanonicalElaboratedTypeKeyword(Keyword)
5966 : ElaboratedTypeKeyword::None;
5967 bool NonCanonical = Template != CanonTemplate || Keyword != CanonKeyword;
5968 SmallVector<TemplateArgument, 4> CanonArgsVec;
5969 if (CanonicalArgs.empty()) {
5970 CanonArgsVec = SmallVector<TemplateArgument, 4>(SpecifiedArgs);
5971 NonCanonical |= canonicalizeTemplateArguments(CanonArgsVec);
5972 CanonicalArgs = CanonArgsVec;
5973 } else {
5974 NonCanonical |= !llvm::equal(
5975 SpecifiedArgs, CanonicalArgs,
5976 [](const TemplateArgument &A, const TemplateArgument &B) {
5977 return A.structurallyEquals(B);
5978 });
5979 }
5980
5981 // We can get here with an alias template when the specialization
5982 // contains a pack expansion that does not match up with a parameter
5983 // pack, or a builtin template which cannot be resolved due to dependency.
5984 assert((!isa_and_nonnull<TypeAliasTemplateDecl>(TD) ||
5985 hasAnyPackExpansions(CanonicalArgs)) &&
5986 "Caller must compute aliased type");
5987 IsTypeAlias = false;
5988
5989 Underlying = getCanonicalTemplateSpecializationType(
5990 CanonKeyword, CanonTemplate, CanonicalArgs);
5991 if (!NonCanonical)
5992 return Underlying;
5993 }
5994 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
5995 sizeof(TemplateArgument) * SpecifiedArgs.size() +
5996 (IsTypeAlias ? sizeof(QualType) : 0),
5997 alignof(TemplateSpecializationType));
5998 auto *Spec = new (Mem) TemplateSpecializationType(
5999 Keyword, Template, IsTypeAlias, SpecifiedArgs, Underlying);
6000 Types.push_back(Spec);
6001 return QualType(Spec, 0);
6002 }
6003
6004 QualType
6005 ASTContext::getParenType(QualType InnerType) const {
6006 llvm::FoldingSetNodeID ID;
6007 ParenType::Profile(ID, InnerType);
6008
6009 void *InsertPos = nullptr;
6010 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6011 if (T)
6012 return QualType(T, 0);
6013
6014 QualType Canon = InnerType;
6015 if (!Canon.isCanonical()) {
6016 Canon = getCanonicalType(InnerType);
6017 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6018 assert(!CheckT && "Paren canonical type broken");
6019 (void)CheckT;
6020 }
6021
6022 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
6023 Types.push_back(T);
6024 ParenTypes.InsertNode(T, InsertPos);
6025 return QualType(T, 0);
6026 }
6027
6028 QualType
6029 ASTContext::getMacroQualifiedType(QualType UnderlyingTy,
6030 const IdentifierInfo *MacroII) const {
6031 QualType Canon = UnderlyingTy;
6032 if (!Canon.isCanonical())
6033 Canon = getCanonicalType(UnderlyingTy);
6034
6035 auto *newType = new (*this, alignof(MacroQualifiedType))
6036 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
6037 Types.push_back(newType);
6038 return QualType(newType, 0);
6039 }
6040
6041 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
6042 NestedNameSpecifier NNS,
6043 const IdentifierInfo *Name) const {
6044 llvm::FoldingSetNodeID ID;
6045 DependentNameType::Profile(ID, Keyword, NNS, Name);
6046
6047 void *InsertPos = nullptr;
6048 if (DependentNameType *T =
6049 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos))
6050 return QualType(T, 0);
6051
6052 ElaboratedTypeKeyword CanonKeyword =
6053 getCanonicalElaboratedTypeKeyword(Keyword);
6054 NestedNameSpecifier CanonNNS = NNS.getCanonical();
6055
6056 QualType Canon;
6057 if (CanonKeyword != Keyword || CanonNNS != NNS) {
6058 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
6059 [[maybe_unused]] DependentNameType *T =
6060 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
6061 assert(!T && "broken canonicalization");
6062 assert(Canon.isCanonical());
6063 }
6064
6065 DependentNameType *T = new (*this, alignof(DependentNameType))
6066 DependentNameType(Keyword, NNS, Name, Canon);
6067 Types.push_back(T);
6068 DependentNameTypes.InsertNode(T, InsertPos);
6069 return QualType(T, 0);
6070 }
6071
6072 TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) const {
6073 TemplateArgument Arg;
6074 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6075 QualType ArgType = getTypeDeclType(TTP);
6076 if (TTP->isParameterPack())
6077 ArgType = getPackExpansionType(ArgType, std::nullopt);
6078
6079 Arg = TemplateArgument(ArgType);
6080 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6081 QualType T =
6082 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
6083 // For class NTTPs, ensure we include the 'const' so the type matches that
6084 // of a real template argument.
6085 // FIXME: It would be more faithful to model this as something like an
6086 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
6087 ExprValueKind VK;
6088 if (T->isRecordType()) {
6089 // C++ [temp.param]p8: An id-expression naming a non-type
6090 // template-parameter of class type T denotes a static storage duration
6091 // object of type const T.
6092 T.addConst();
6093 VK = VK_LValue;
6094 } else {
6095 VK = Expr::getValueKindForType(NTTP->getType());
6096 }
6097 Expr *E = new (*this)
6098 DeclRefExpr(*this, NTTP, /*RefersToEnclosingVariableOrCapture=*/false,
6099 T, VK, NTTP->getLocation());
6100
6101 if (NTTP->isParameterPack())
6102 E = new (*this) PackExpansionExpr(E, NTTP->getLocation(), std::nullopt);
6103 Arg = TemplateArgument(E, /*IsCanonical=*/false);
6104 } else {
6105 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
6106 TemplateName Name = getQualifiedTemplateName(
6107 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
6108 TemplateName(TTP));
6109 if (TTP->isParameterPack())
6110 Arg = TemplateArgument(Name, /*NumExpansions=*/std::nullopt);
6111 else
6112 Arg = TemplateArgument(Name);
6113 }
6114
6115 if (Param->isTemplateParameterPack())
6116 Arg =
6117 TemplateArgument::CreatePackCopy(const_cast<ASTContext &>(*this), Arg);
6118
6119 return Arg;
6120 }
6121
6122 QualType ASTContext::getPackExpansionType(QualType Pattern,
6123 UnsignedOrNone NumExpansions,
6124 bool ExpectPackInType) const {
6125 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
6126 "Pack expansions must expand one or more parameter packs");
6127
6128 llvm::FoldingSetNodeID ID;
6129 PackExpansionType::Profile(ID, Pattern, NumExpansions);
6130
6131 void *InsertPos = nullptr;
6132 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6133 if (T)
6134 return QualType(T, 0);
6135
6136 QualType Canon;
6137 if (!Pattern.isCanonical()) {
6138 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
6139 /*ExpectPackInType=*/false);
6140
6141 // Find the insert position again, in case we inserted an element into
6142 // PackExpansionTypes and invalidated our insert position.
6143 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6144 }
6145
6146 T = new (*this, alignof(PackExpansionType))
6147 PackExpansionType(Pattern, Canon, NumExpansions);
6148 Types.push_back(T);
6149 PackExpansionTypes.InsertNode(T, InsertPos);
6150 return QualType(T, 0);
6151 }
6152
6153 /// CmpProtocolNames - Comparison predicate for sorting protocols
6154 /// alphabetically.
6155 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
6156 ObjCProtocolDecl *const *RHS) {
6157 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
6158 }
6159
6160 static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
6161 if (Protocols.empty()) return true;
6162
6163 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
6164 return false;
6165
6166 for (unsigned i = 1; i != Protocols.size(); ++i)
6167 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
6168 Protocols[i]->getCanonicalDecl() != Protocols[i])
6169 return false;
6170 return true;
6171 }
6172
6173 static void
6174 SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
6175 // Sort protocols, keyed by name.
6176 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
6177
6178 // Canonicalize.
6179 for (ObjCProtocolDecl *&P : Protocols)
6180 P = P->getCanonicalDecl();
6181
6182 // Remove duplicates.
6183 auto ProtocolsEnd = llvm::unique(Protocols);
6184 Protocols.erase(ProtocolsEnd, Protocols.end());
6185 }
6186
6187 QualType ASTContext::getObjCObjectType(QualType BaseType,
6188 ObjCProtocolDecl * const *Protocols,
6189 unsigned NumProtocols) const {
6190 return getObjCObjectType(BaseType, {}, ArrayRef(Protocols, NumProtocols),
6191 /*isKindOf=*/false);
6192 }
6193
6194 QualType ASTContext::getObjCObjectType(
6195 QualType baseType,
6196 ArrayRef<QualType> typeArgs,
6197 ArrayRef<ObjCProtocolDecl *> protocols,
6198 bool isKindOf) const {
6199 // If the base type is an interface and there aren't any protocols or
6200 // type arguments to add, then the interface type will do just fine.
6201 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
6202 isa<ObjCInterfaceType>(baseType))
6203 return baseType;
6204
6205 // Look in the folding set for an existing type.
6206 llvm::FoldingSetNodeID ID;
6207 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
6208 void *InsertPos = nullptr;
6209 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
6210 return QualType(QT, 0);
6211
6212 // Determine the type arguments to be used for canonicalization,
6213 // which may be explicitly specified here or written on the base
6214 // type.
6215 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
6216 if (effectiveTypeArgs.empty()) {
6217 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
6218 effectiveTypeArgs = baseObject->getTypeArgs();
6219 }
6220
6221 // Build the canonical type, which has the canonical base type and a
6222 // sorted-and-uniqued list of protocols and the type arguments
6223 // canonicalized.
6224 QualType canonical;
6225 bool typeArgsAreCanonical = llvm::all_of(
6226 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
6227 bool protocolsSorted = areSortedAndUniqued(protocols);
6228 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
6229 // Determine the canonical type arguments.
6230 ArrayRef<QualType> canonTypeArgs;
6231 SmallVector<QualType, 4> canonTypeArgsVec;
6232 if (!typeArgsAreCanonical) {
6233 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
6234 for (auto typeArg : effectiveTypeArgs)
6235 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
6236 canonTypeArgs = canonTypeArgsVec;
6237 } else {
6238 canonTypeArgs = effectiveTypeArgs;
6239 }
6240
6241 ArrayRef<ObjCProtocolDecl *> canonProtocols;
6242 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
6243 if (!protocolsSorted) {
6244 canonProtocolsVec.append(protocols.begin(), protocols.end());
6245 SortAndUniqueProtocols(canonProtocolsVec);
6246 canonProtocols = canonProtocolsVec;
6247 } else {
6248 canonProtocols = protocols;
6249 }
6250
6251 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
6252 canonProtocols, isKindOf);
6253
6254 // Regenerate InsertPos.
6255 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
6256 }
6257
6258 unsigned size = sizeof(ObjCObjectTypeImpl);
6259 size += typeArgs.size() * sizeof(QualType);
6260 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6261 void *mem = Allocate(size, alignof(ObjCObjectTypeImpl));
6262 auto *T =
6263 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
6264 isKindOf);
6265
6266 Types.push_back(T);
6267 ObjCObjectTypes.InsertNode(T, InsertPos);
6268 return QualType(T, 0);
6269 }
6270
6271 /// Apply Objective-C protocol qualifiers to the given type.
6272 /// If this is for the canonical type of a type parameter, we can apply
6273 /// protocol qualifiers on the ObjCObjectPointerType.
6274 QualType
6275 ASTContext::applyObjCProtocolQualifiers(QualType type,
6276 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
6277 bool allowOnPointerType) const {
6278 hasError = false;
6279
6280 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
6281 return getObjCTypeParamType(objT->getDecl(), protocols);
6282 }
6283
6284 // Apply protocol qualifiers to ObjCObjectPointerType.
6285 if (allowOnPointerType) {
6286 if (const auto *objPtr =
6287 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
6288 const ObjCObjectType *objT = objPtr->getObjectType();
6289 // Merge protocol lists and construct ObjCObjectType.
6290 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
6291 protocolsVec.append(objT->qual_begin(),
6292 objT->qual_end());
6293 protocolsVec.append(protocols.begin(), protocols.end());
6294 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
6295 type = getObjCObjectType(
6296 objT->getBaseType(),
6297 objT->getTypeArgsAsWritten(),
6298 protocols,
6299 objT->isKindOfTypeAsWritten());
6300 return getObjCObjectPointerType(type);
6301 }
6302 }
6303
6304 // Apply protocol qualifiers to ObjCObjectType.
6305 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
6306 // FIXME: Check for protocols to which the class type is already
6307 // known to conform.
6308
6309 return getObjCObjectType(objT->getBaseType(),
6310 objT->getTypeArgsAsWritten(),
6311 protocols,
6312 objT->isKindOfTypeAsWritten());
6313 }
6314
6315 // If the canonical type is ObjCObjectType, ...
6316 if (type->isObjCObjectType()) {
6317 // Silently overwrite any existing protocol qualifiers.
6318 // TODO: determine whether that's the right thing to do.
6319
6320 // FIXME: Check for protocols to which the class type is already
6321 // known to conform.
6322 return getObjCObjectType(type, {}, protocols, false);
6323 }
6324
6325 // id<protocol-list>
6326 if (type->isObjCIdType()) {
6327 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6328 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
6329 objPtr->isKindOfType());
6330 return getObjCObjectPointerType(type);
6331 }
6332
6333 // Class<protocol-list>
6334 if (type->isObjCClassType()) {
6335 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6336 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
6337 objPtr->isKindOfType());
6338 return getObjCObjectPointerType(type);
6339 }
6340
6341 hasError = true;
6342 return type;
6343 }
6344
6345 QualType
6346 ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
6347 ArrayRef<ObjCProtocolDecl *> protocols) const {
6348 // Look in the folding set for an existing type.
6349 llvm::FoldingSetNodeID ID;
6350 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
6351 void *InsertPos = nullptr;
6352 if (ObjCTypeParamType *TypeParam =
6353 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
6354 return QualType(TypeParam, 0);
6355
6356 // We canonicalize to the underlying type.
6357 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
6358 if (!protocols.empty()) {
6359 // Apply the protocol qualifers.
6360 bool hasError;
6361 Canonical = getCanonicalType(applyObjCProtocolQualifiers(
6362 Canonical, protocols, hasError, true /*allowOnPointerType*/));
6363 assert(!hasError && "Error when apply protocol qualifier to bound type");
6364 }
6365
6366 unsigned size = sizeof(ObjCTypeParamType);
6367 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6368 void *mem = Allocate(size, alignof(ObjCTypeParamType));
6369 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
6370
6371 Types.push_back(newType);
6372 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
6373 return QualType(newType, 0);
6374 }
6375
6376 void ASTContext::adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig,
6377 ObjCTypeParamDecl *New) const {
6378 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
6379 // Update TypeForDecl after updating TypeSourceInfo.
6380 auto *NewTypeParamTy = cast<ObjCTypeParamType>(New->TypeForDecl);
6381 SmallVector<ObjCProtocolDecl *, 8> protocols;
6382 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
6383 QualType UpdatedTy = getObjCTypeParamType(New, protocols);
6384 New->TypeForDecl = UpdatedTy.getTypePtr();
6385 }
6386
6387 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
6388 /// protocol list adopt all protocols in QT's qualified-id protocol
6389 /// list.
6390 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
6391 ObjCInterfaceDecl *IC) {
6392 if (!QT->isObjCQualifiedIdType())
6393 return false;
6394
6395 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
6396 // If both the right and left sides have qualifiers.
6397 for (auto *Proto : OPT->quals()) {
6398 if (!IC->ClassImplementsProtocol(Proto, false))
6399 return false;
6400 }
6401 return true;
6402 }
6403 return false;
6404 }
6405
6406 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
6407 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
6408 /// of protocols.
6409 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
6410 ObjCInterfaceDecl *IDecl) {
6411 if (!QT->isObjCQualifiedIdType())
6412 return false;
6413 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
6414 if (!OPT)
6415 return false;
6416 if (!IDecl->hasDefinition())
6417 return false;
6418 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
6419 CollectInheritedProtocols(IDecl, InheritedProtocols);
6420 if (InheritedProtocols.empty())
6421 return false;
6422 // Check that if every protocol in list of id<plist> conforms to a protocol
6423 // of IDecl's, then bridge casting is ok.
6424 bool Conforms = false;
6425 for (auto *Proto : OPT->quals()) {
6426 Conforms = false;
6427 for (auto *PI : InheritedProtocols) {
6428 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
6429 Conforms = true;
6430 break;
6431 }
6432 }
6433 if (!Conforms)
6434 break;
6435 }
6436 if (Conforms)
6437 return true;
6438
6439 for (auto *PI : InheritedProtocols) {
6440 // If both the right and left sides have qualifiers.
6441 bool Adopts = false;
6442 for (auto *Proto : OPT->quals()) {
6443 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
6444 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
6445 break;
6446 }
6447 if (!Adopts)
6448 return false;
6449 }
6450 return true;
6451 }
6452
6453 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
6454 /// the given object type.
6455 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
6456 llvm::FoldingSetNodeID ID;
6457 ObjCObjectPointerType::Profile(ID, ObjectT);
6458
6459 void *InsertPos = nullptr;
6460 if (ObjCObjectPointerType *QT =
6461 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
6462 return QualType(QT, 0);
6463
6464 // Find the canonical object type.
6465 QualType Canonical;
6466 if (!ObjectT.isCanonical()) {
6467 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
6468
6469 // Regenerate InsertPos.
6470 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
6471 }
6472
6473 // No match.
6474 void *Mem =
6475 Allocate(sizeof(ObjCObjectPointerType), alignof(ObjCObjectPointerType));
6476 auto *QType =
6477 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
6478
6479 Types.push_back(QType);
6480 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
6481 return QualType(QType, 0);
6482 }
6483
6484 /// getObjCInterfaceType - Return the unique reference to the type for the
6485 /// specified ObjC interface decl. The list of protocols is optional.
6486 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
6487 ObjCInterfaceDecl *PrevDecl) const {
6488 if (Decl->TypeForDecl)
6489 return QualType(Decl->TypeForDecl, 0);
6490
6491 if (PrevDecl) {
6492 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
6493 Decl->TypeForDecl = PrevDecl->TypeForDecl;
6494 return QualType(PrevDecl->TypeForDecl, 0);
6495 }
6496
6497 // Prefer the definition, if there is one.
6498 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
6499 Decl = Def;
6500
6501 void *Mem = Allocate(sizeof(ObjCInterfaceType), alignof(ObjCInterfaceType));
6502 auto *T = new (Mem) ObjCInterfaceType(Decl);
6503 Decl->TypeForDecl = T;
6504 Types.push_back(T);
6505 return QualType(T, 0);
6506 }
6507
6508 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
6509 /// TypeOfExprType AST's (since expression's are never shared). For example,
6510 /// multiple declarations that refer to "typeof(x)" all contain different
6511 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
6512 /// on canonical type's (which are always unique).
6513 QualType ASTContext::getTypeOfExprType(Expr *tofExpr, TypeOfKind Kind) const {
6514 TypeOfExprType *toe;
6515 if (tofExpr->isTypeDependent()) {
6516 llvm::FoldingSetNodeID ID;
6517 DependentTypeOfExprType::Profile(ID, *this, tofExpr,
6518 Kind == TypeOfKind::Unqualified);
6519
6520 void *InsertPos = nullptr;
6521 DependentTypeOfExprType *Canon =
6522 DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
6523 if (Canon) {
6524 // We already have a "canonical" version of an identical, dependent
6525 // typeof(expr) type. Use that as our canonical type.
6526 toe = new (*this, alignof(TypeOfExprType)) TypeOfExprType(
6527 *this, tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
6528 } else {
6529 // Build a new, canonical typeof(expr) type.
6530 Canon = new (*this, alignof(DependentTypeOfExprType))
6531 DependentTypeOfExprType(*this, tofExpr, Kind);
6532 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
6533 toe = Canon;
6534 }
6535 } else {
6536 QualType Canonical = getCanonicalType(tofExpr->getType());
6537 toe = new (*this, alignof(TypeOfExprType))
6538 TypeOfExprType(*this, tofExpr, Kind, Canonical);
6539 }
6540 Types.push_back(toe);
6541 return QualType(toe, 0);
6542 }
6543
6544 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
6545 /// TypeOfType nodes. The only motivation to unique these nodes would be
6546 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
6547 /// an issue. This doesn't affect the type checker, since it operates
6548 /// on canonical types (which are always unique).
6549 QualType ASTContext::getTypeOfType(QualType tofType, TypeOfKind Kind) const {
6550 QualType Canonical = getCanonicalType(tofType);
6551 auto *tot = new (*this, alignof(TypeOfType))
6552 TypeOfType(*this, tofType, Canonical, Kind);
6553 Types.push_back(tot);
6554 return QualType(tot, 0);
6555 }
6556
6557 /// getReferenceQualifiedType - Given an expr, will return the type for
6558 /// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
6559 /// and class member access into account.
6560 QualType ASTContext::getReferenceQualifiedType(const Expr *E) const {
6561 // C++11 [dcl.type.simple]p4:
6562 // [...]
6563 QualType T = E->getType();
6564 switch (E->getValueKind()) {
6565 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6566 // type of e;
6567 case VK_XValue:
6568 return getRValueReferenceType(T);
6569 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6570 // type of e;
6571 case VK_LValue:
6572 return getLValueReferenceType(T);
6573 // - otherwise, decltype(e) is the type of e.
6574 case VK_PRValue:
6575 return T;
6576 }
6577 llvm_unreachable("Unknown value kind");
6578 }
6579
6580 /// Unlike many "get<Type>" functions, we don't unique DecltypeType
6581 /// nodes. This would never be helpful, since each such type has its own
6582 /// expression, and would not give a significant memory saving, since there
6583 /// is an Expr tree under each such type.
6584 QualType ASTContext::getDecltypeType(Expr *E, QualType UnderlyingType) const {
6585 // C++11 [temp.type]p2:
6586 // If an expression e involves a template parameter, decltype(e) denotes a
6587 // unique dependent type. Two such decltype-specifiers refer to the same
6588 // type only if their expressions are equivalent (14.5.6.1).
6589 QualType CanonType;
6590 if (!E->isInstantiationDependent()) {
6591 CanonType = getCanonicalType(UnderlyingType);
6592 } else if (!UnderlyingType.isNull()) {
6593 CanonType = getDecltypeType(E, QualType());
6594 } else {
6595 llvm::FoldingSetNodeID ID;
6596 DependentDecltypeType::Profile(ID, *this, E);
6597
6598 void *InsertPos = nullptr;
6599 if (DependentDecltypeType *Canon =
6600 DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos))
6601 return QualType(Canon, 0);
6602
6603 // Build a new, canonical decltype(expr) type.
6604 auto *DT =
6605 new (*this, alignof(DependentDecltypeType)) DependentDecltypeType(E);
6606 DependentDecltypeTypes.InsertNode(DT, InsertPos);
6607 Types.push_back(DT);
6608 return QualType(DT, 0);
6609 }
6610 auto *DT = new (*this, alignof(DecltypeType))
6611 DecltypeType(E, UnderlyingType, CanonType);
6612 Types.push_back(DT);
6613 return QualType(DT, 0);
6614 }
6615
6616 QualType ASTContext::getPackIndexingType(QualType Pattern, Expr *IndexExpr,
6617 bool FullySubstituted,
6618 ArrayRef<QualType> Expansions,
6619 UnsignedOrNone Index) const {
6620 QualType Canonical;
6621 if (FullySubstituted && Index) {
6622 Canonical = getCanonicalType(Expansions[*Index]);
6623 } else {
6624 llvm::FoldingSetNodeID ID;
6625 PackIndexingType::Profile(ID, *this, Pattern.getCanonicalType(), IndexExpr,
6626 FullySubstituted, Expansions);
6627 void *InsertPos = nullptr;
6628 PackIndexingType *Canon =
6629 DependentPackIndexingTypes.FindNodeOrInsertPos(ID, InsertPos);
6630 if (!Canon) {
6631 void *Mem = Allocate(
6632 PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6633 TypeAlignment);
6634 Canon =
6635 new (Mem) PackIndexingType(QualType(), Pattern.getCanonicalType(),
6636 IndexExpr, FullySubstituted, Expansions);
6637 DependentPackIndexingTypes.InsertNode(Canon, InsertPos);
6638 }
6639 Canonical = QualType(Canon, 0);
6640 }
6641
6642 void *Mem =
6643 Allocate(PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6644 TypeAlignment);
6645 auto *T = new (Mem) PackIndexingType(Canonical, Pattern, IndexExpr,
6646 FullySubstituted, Expansions);
6647 Types.push_back(T);
6648 return QualType(T, 0);
6649 }
6650
6651 /// getUnaryTransformationType - We don't unique these, since the memory
6652 /// savings are minimal and these are rare.
6653 QualType
6654 ASTContext::getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
6655 UnaryTransformType::UTTKind Kind) const {
6656
6657 llvm::FoldingSetNodeID ID;
6658 UnaryTransformType::Profile(ID, BaseType, UnderlyingType, Kind);
6659
6660 void *InsertPos = nullptr;
6661 if (UnaryTransformType *UT =
6662 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos))
6663 return QualType(UT, 0);
6664
6665 QualType CanonType;
6666 if (!BaseType->isDependentType()) {
6667 CanonType = UnderlyingType.getCanonicalType();
6668 } else {
6669 assert(UnderlyingType.isNull() || BaseType == UnderlyingType);
6670 UnderlyingType = QualType();
6671 if (QualType CanonBase = BaseType.getCanonicalType();
6672 BaseType != CanonBase) {
6673 CanonType = getUnaryTransformType(CanonBase, QualType(), Kind);
6674 assert(CanonType.isCanonical());
6675
6676 // Find the insertion position again.
6677 [[maybe_unused]] UnaryTransformType *UT =
6678 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
6679 assert(!UT && "broken canonicalization");
6680 }
6681 }
6682
6683 auto *UT = new (*this, alignof(UnaryTransformType))
6684 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
6685 UnaryTransformTypes.InsertNode(UT, InsertPos);
6686 Types.push_back(UT);
6687 return QualType(UT, 0);
6688 }
6689
6690 QualType ASTContext::getAutoTypeInternal(
6691 QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent,
6692 bool IsPack, TemplateDecl *TypeConstraintConcept,
6693 ArrayRef<TemplateArgument> TypeConstraintArgs, bool IsCanon) const {
6694 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
6695 !TypeConstraintConcept && !IsDependent)
6696 return getAutoDeductType();
6697
6698 // Look in the folding set for an existing type.
6699 llvm::FoldingSetNodeID ID;
6700 bool IsDeducedDependent =
6701 isa_and_nonnull<TemplateTemplateParmDecl>(TypeConstraintConcept) ||
6702 (!DeducedType.isNull() && DeducedType->isDependentType());
6703 AutoType::Profile(ID, *this, DeducedType, Keyword,
6704 IsDependent || IsDeducedDependent, TypeConstraintConcept,
6705 TypeConstraintArgs);
6706 if (auto const AT_iter = AutoTypes.find(ID); AT_iter != AutoTypes.end())
6707 return QualType(AT_iter->getSecond(), 0);
6708
6709 QualType Canon;
6710 if (!IsCanon) {
6711 if (!DeducedType.isNull()) {
6712 Canon = DeducedType.getCanonicalType();
6713 } else if (TypeConstraintConcept) {
6714 bool AnyNonCanonArgs = false;
6715 auto *CanonicalConcept =
6716 cast<TemplateDecl>(TypeConstraintConcept->getCanonicalDecl());
6717 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
6718 *this, TypeConstraintArgs, AnyNonCanonArgs);
6719 if (CanonicalConcept != TypeConstraintConcept || AnyNonCanonArgs) {
6720 Canon = getAutoTypeInternal(QualType(), Keyword, IsDependent, IsPack,
6721 CanonicalConcept, CanonicalConceptArgs,
6722 /*IsCanon=*/true);
6723 }
6724 }
6725 }
6726
6727 void *Mem = Allocate(sizeof(AutoType) +
6728 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
6729 alignof(AutoType));
6730 auto *AT = new (Mem) AutoType(
6731 DeducedType, Keyword,
6732 (IsDependent ? TypeDependence::DependentInstantiation
6733 : TypeDependence::None) |
6734 (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None),
6735 Canon, TypeConstraintConcept, TypeConstraintArgs);
6736 #ifndef NDEBUG
6737 llvm::FoldingSetNodeID InsertedID;
6738 AT->Profile(InsertedID, *this);
6739 assert(InsertedID == ID && "ID does not match");
6740 #endif
6741 Types.push_back(AT);
6742 AutoTypes.try_emplace(ID, AT);
6743 return QualType(AT, 0);
6744 }
6745
6746 /// getAutoType - Return the uniqued reference to the 'auto' type which has been
6747 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
6748 /// canonical deduced-but-dependent 'auto' type.
6749 QualType
6750 ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
6751 bool IsDependent, bool IsPack,
6752 TemplateDecl *TypeConstraintConcept,
6753 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
6754 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
6755 assert((!IsDependent || DeducedType.isNull()) &&
6756 "A dependent auto should be undeduced");
6757 return getAutoTypeInternal(DeducedType, Keyword, IsDependent, IsPack,
6758 TypeConstraintConcept, TypeConstraintArgs);
6759 }
6760
6761 QualType ASTContext::getUnconstrainedType(QualType T) const {
6762 QualType CanonT = T.getNonPackExpansionType().getCanonicalType();
6763
6764 // Remove a type-constraint from a top-level auto or decltype(auto).
6765 if (auto *AT = CanonT->getAs<AutoType>()) {
6766 if (!AT->isConstrained())
6767 return T;
6768 return getQualifiedType(getAutoType(QualType(), AT->getKeyword(),
6769 AT->isDependentType(),
6770 AT->containsUnexpandedParameterPack()),
6771 T.getQualifiers());
6772 }
6773
6774 // FIXME: We only support constrained auto at the top level in the type of a
6775 // non-type template parameter at the moment. Once we lift that restriction,
6776 // we'll need to recursively build types containing auto here.
6777 assert(!CanonT->getContainedAutoType() ||
6778 !CanonT->getContainedAutoType()->isConstrained());
6779 return T;
6780 }
6781
6782 QualType ASTContext::getDeducedTemplateSpecializationTypeInternal(
6783 ElaboratedTypeKeyword Keyword, TemplateName Template, QualType DeducedType,
6784 bool IsDependent, QualType Canon) const {
6785 // Look in the folding set for an existing type.
6786 void *InsertPos = nullptr;
6787 llvm::FoldingSetNodeID ID;
6788 DeducedTemplateSpecializationType::Profile(ID, Keyword, Template, DeducedType,
6789 IsDependent);
6790 if (DeducedTemplateSpecializationType *DTST =
6791 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6792 return QualType(DTST, 0);
6793
6794 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
6795 DeducedTemplateSpecializationType(Keyword, Template, DeducedType,
6796 IsDependent, Canon);
6797
6798 #ifndef NDEBUG
6799 llvm::FoldingSetNodeID TempID;
6800 DTST->Profile(TempID);
6801 assert(ID == TempID && "ID does not match");
6802 #endif
6803 Types.push_back(DTST);
6804 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
6805 return QualType(DTST, 0);
6806 }
6807
6808 /// Return the uniqued reference to the deduced template specialization type
6809 /// which has been deduced to the given type, or to the canonical undeduced
6810 /// such type, or the canonical deduced-but-dependent such type.
6811 QualType ASTContext::getDeducedTemplateSpecializationType(
6812 ElaboratedTypeKeyword Keyword, TemplateName Template, QualType DeducedType,
6813 bool IsDependent) const {
6814 // FIXME: This could save an extra hash table lookup if it handled all the
6815 // parameters already being canonical.
6816 // FIXME: Can this be formed from a DependentTemplateName, such that the
6817 // keyword should be part of the canonical type?
6818 QualType Canon =
6819 DeducedType.isNull()
6820 ? getDeducedTemplateSpecializationTypeInternal(
6821 ElaboratedTypeKeyword::None, getCanonicalTemplateName(Template),
6822 QualType(), IsDependent, QualType())
6823 : DeducedType.getCanonicalType();
6824 return getDeducedTemplateSpecializationTypeInternal(
6825 Keyword, Template, DeducedType, IsDependent, Canon);
6826 }
6827
6828 /// getAtomicType - Return the uniqued reference to the atomic type for
6829 /// the given value type.
6830 QualType ASTContext::getAtomicType(QualType T) const {
6831 // Unique pointers, to guarantee there is only one pointer of a particular
6832 // structure.
6833 llvm::FoldingSetNodeID ID;
6834 AtomicType::Profile(ID, T);
6835
6836 void *InsertPos = nullptr;
6837 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
6838 return QualType(AT, 0);
6839
6840 // If the atomic value type isn't canonical, this won't be a canonical type
6841 // either, so fill in the canonical type field.
6842 QualType Canonical;
6843 if (!T.isCanonical()) {
6844 Canonical = getAtomicType(getCanonicalType(T));
6845
6846 // Get the new insert position for the node we care about.
6847 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
6848 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
6849 }
6850 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
6851 Types.push_back(New);
6852 AtomicTypes.InsertNode(New, InsertPos);
6853 return QualType(New, 0);
6854 }
6855
6856 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
6857 QualType ASTContext::getAutoDeductType() const {
6858 if (AutoDeductTy.isNull())
6859 AutoDeductTy = QualType(new (*this, alignof(AutoType))
6860 AutoType(QualType(), AutoTypeKeyword::Auto,
6861 TypeDependence::None, QualType(),
6862 /*concept*/ nullptr, /*args*/ {}),
6863 0);
6864 return AutoDeductTy;
6865 }
6866
6867 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
6868 QualType ASTContext::getAutoRRefDeductType() const {
6869 if (AutoRRefDeductTy.isNull())
6870 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
6871 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
6872 return AutoRRefDeductTy;
6873 }
6874
6875 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
6876 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
6877 /// needs to agree with the definition in <stddef.h>.
6878 QualType ASTContext::getSizeType() const {
6879 return getPredefinedSugarType(PredefinedSugarType::Kind::SizeT);
6880 }
6881
6882 CanQualType ASTContext::getCanonicalSizeType() const {
6883 return getFromTargetType(Target->getSizeType());
6884 }
6885
6886 /// Return the unique signed counterpart of the integer type
6887 /// corresponding to size_t.
6888 QualType ASTContext::getSignedSizeType() const {
6889 return getPredefinedSugarType(PredefinedSugarType::Kind::SignedSizeT);
6890 }
6891
6892 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
6893 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
6894 QualType ASTContext::getPointerDiffType() const {
6895 return getPredefinedSugarType(PredefinedSugarType::Kind::PtrdiffT);
6896 }
6897
6898 /// Return the unique unsigned counterpart of "ptrdiff_t"
6899 /// integer type. The standard (C11 7.21.6.1p7) refers to this type
6900 /// in the definition of %tu format specifier.
6901 QualType ASTContext::getUnsignedPointerDiffType() const {
6902 return getFromTargetType(Target->getUnsignedPtrDiffType(LangAS::Default));
6903 }
6904
6905 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
6906 CanQualType ASTContext::getIntMaxType() const {
6907 return getFromTargetType(Target->getIntMaxType());
6908 }
6909
6910 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
6911 CanQualType ASTContext::getUIntMaxType() const {
6912 return getFromTargetType(Target->getUIntMaxType());
6913 }
6914
6915 /// getSignedWCharType - Return the type of "signed wchar_t".
6916 /// Used when in C++, as a GCC extension.
6917 QualType ASTContext::getSignedWCharType() const {
6918 // FIXME: derive from "Target" ?
6919 return WCharTy;
6920 }
6921
6922 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
6923 /// Used when in C++, as a GCC extension.
6924 QualType ASTContext::getUnsignedWCharType() const {
6925 // FIXME: derive from "Target" ?
6926 return UnsignedIntTy;
6927 }
6928
6929 QualType ASTContext::getIntPtrType() const {
6930 return getFromTargetType(Target->getIntPtrType());
6931 }
6932
6933 QualType ASTContext::getUIntPtrType() const {
6934 return getCorrespondingUnsignedType(getIntPtrType());
6935 }
6936
6937 /// Return the unique type for "pid_t" defined in
6938 /// <sys/types.h>. We need this to compute the correct type for vfork().
6939 QualType ASTContext::getProcessIDType() const {
6940 return getFromTargetType(Target->getProcessIDType());
6941 }
6942
6943 //===----------------------------------------------------------------------===//
6944 // Type Operators
6945 //===----------------------------------------------------------------------===//
6946
6947 CanQualType ASTContext::getCanonicalParamType(QualType T) const {
6948 // Push qualifiers into arrays, and then discard any remaining
6949 // qualifiers.
6950 T = getCanonicalType(T);
6951 T = getVariableArrayDecayedType(T);
6952 const Type *Ty = T.getTypePtr();
6953 QualType Result;
6954 if (getLangOpts().HLSL && isa<ConstantArrayType>(Ty)) {
6955 Result = getArrayParameterType(QualType(Ty, 0));
6956 } else if (isa<ArrayType>(Ty)) {
6957 Result = getArrayDecayedType(QualType(Ty,0));
6958 } else if (isa<FunctionType>(Ty)) {
6959 Result = getPointerType(QualType(Ty, 0));
6960 } else {
6961 Result = QualType(Ty, 0);
6962 }
6963
6964 return CanQualType::CreateUnsafe(Result);
6965 }
6966
6967 QualType ASTContext::getUnqualifiedArrayType(QualType type,
6968 Qualifiers &quals) const {
6969 SplitQualType splitType = type.getSplitUnqualifiedType();
6970
6971 // FIXME: getSplitUnqualifiedType() actually walks all the way to
6972 // the unqualified desugared type and then drops it on the floor.
6973 // We then have to strip that sugar back off with
6974 // getUnqualifiedDesugaredType(), which is silly.
6975 const auto *AT =
6976 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
6977
6978 // If we don't have an array, just use the results in splitType.
6979 if (!AT) {
6980 quals = splitType.Quals;
6981 return QualType(splitType.Ty, 0);
6982 }
6983
6984 // Otherwise, recurse on the array's element type.
6985 QualType elementType = AT->getElementType();
6986 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
6987
6988 // If that didn't change the element type, AT has no qualifiers, so we
6989 // can just use the results in splitType.
6990 if (elementType == unqualElementType) {
6991 assert(quals.empty()); // from the recursive call
6992 quals = splitType.Quals;
6993 return QualType(splitType.Ty, 0);
6994 }
6995
6996 // Otherwise, add in the qualifiers from the outermost type, then
6997 // build the type back up.
6998 quals.addConsistentQualifiers(splitType.Quals);
6999
7000 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
7001 return getConstantArrayType(unqualElementType, CAT->getSize(),
7002 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
7003 }
7004
7005 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
7006 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
7007 }
7008
7009 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
7010 return getVariableArrayType(unqualElementType, VAT->getSizeExpr(),
7011 VAT->getSizeModifier(),
7012 VAT->getIndexTypeCVRQualifiers());
7013 }
7014
7015 const auto *DSAT = cast<DependentSizedArrayType>(AT);
7016 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
7017 DSAT->getSizeModifier(), 0);
7018 }
7019
7020 /// Attempt to unwrap two types that may both be array types with the same bound
7021 /// (or both be array types of unknown bound) for the purpose of comparing the
7022 /// cv-decomposition of two types per C++ [conv.qual].
7023 ///
7024 /// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7025 /// C++20 [conv.qual], if permitted by the current language mode.
7026 void ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2,
7027 bool AllowPiMismatch) const {
7028 while (true) {
7029 auto *AT1 = getAsArrayType(T1);
7030 if (!AT1)
7031 return;
7032
7033 auto *AT2 = getAsArrayType(T2);
7034 if (!AT2)
7035 return;
7036
7037 // If we don't have two array types with the same constant bound nor two
7038 // incomplete array types, we've unwrapped everything we can.
7039 // C++20 also permits one type to be a constant array type and the other
7040 // to be an incomplete array type.
7041 // FIXME: Consider also unwrapping array of unknown bound and VLA.
7042 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
7043 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
7044 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
7045 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7046 isa<IncompleteArrayType>(AT2))))
7047 return;
7048 } else if (isa<IncompleteArrayType>(AT1)) {
7049 if (!(isa<IncompleteArrayType>(AT2) ||
7050 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7051 isa<ConstantArrayType>(AT2))))
7052 return;
7053 } else {
7054 return;
7055 }
7056
7057 T1 = AT1->getElementType();
7058 T2 = AT2->getElementType();
7059 }
7060 }
7061
7062 /// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
7063 ///
7064 /// If T1 and T2 are both pointer types of the same kind, or both array types
7065 /// with the same bound, unwraps layers from T1 and T2 until a pointer type is
7066 /// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
7067 ///
7068 /// This function will typically be called in a loop that successively
7069 /// "unwraps" pointer and pointer-to-member types to compare them at each
7070 /// level.
7071 ///
7072 /// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7073 /// C++20 [conv.qual], if permitted by the current language mode.
7074 ///
7075 /// \return \c true if a pointer type was unwrapped, \c false if we reached a
7076 /// pair of types that can't be unwrapped further.
7077 bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2,
7078 bool AllowPiMismatch) const {
7079 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
7080
7081 const auto *T1PtrType = T1->getAs<PointerType>();
7082 const auto *T2PtrType = T2->getAs<PointerType>();
7083 if (T1PtrType && T2PtrType) {
7084 T1 = T1PtrType->getPointeeType();
7085 T2 = T2PtrType->getPointeeType();
7086 return true;
7087 }
7088
7089 if (const auto *T1MPType = T1->getAsCanonical<MemberPointerType>(),
7090 *T2MPType = T2->getAsCanonical<MemberPointerType>();
7091 T1MPType && T2MPType) {
7092 // Compare the qualifiers of the canonical type, as the non-canonical type
7093 // may have qualifiers pointing to a base or derived class.
7094 if (T1MPType->getQualifier() != T2MPType->getQualifier())
7095 return false;
7096 // Get the pointee types of the non-canonical type, in order to preserve
7097 // their sugar.
7098 T1 = T1->getAs<MemberPointerType>()->getPointeeType();
7099 T2 = T2->getAs<MemberPointerType>()->getPointeeType();
7100 return true;
7101 }
7102
7103 if (getLangOpts().ObjC) {
7104 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
7105 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
7106 if (T1OPType && T2OPType) {
7107 T1 = T1OPType->getPointeeType();
7108 T2 = T2OPType->getPointeeType();
7109 return true;
7110 }
7111 }
7112
7113 // FIXME: Block pointers, too?
7114
7115 return false;
7116 }
7117
7118 bool ASTContext::hasSimilarType(QualType T1, QualType T2) const {
7119 while (true) {
7120 Qualifiers Quals;
7121 T1 = getUnqualifiedArrayType(T1, Quals);
7122 T2 = getUnqualifiedArrayType(T2, Quals);
7123 if (hasSameType(T1, T2))
7124 return true;
7125 if (!UnwrapSimilarTypes(T1, T2))
7126 return false;
7127 }
7128 }
7129
7130 bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
7131 while (true) {
7132 Qualifiers Quals1, Quals2;
7133 T1 = getUnqualifiedArrayType(T1, Quals1);
7134 T2 = getUnqualifiedArrayType(T2, Quals2);
7135
7136 Quals1.removeCVRQualifiers();
7137 Quals2.removeCVRQualifiers();
7138 if (Quals1 != Quals2)
7139 return false;
7140
7141 if (hasSameType(T1, T2))
7142 return true;
7143
7144 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
7145 return false;
7146 }
7147 }
7148
7149 DeclarationNameInfo
7150 ASTContext::getNameForTemplate(TemplateName Name,
7151 SourceLocation NameLoc) const {
7152 switch (Name.getKind()) {
7153 case TemplateName::QualifiedTemplate:
7154 case TemplateName::Template:
7155 // DNInfo work in progress: CHECKME: what about DNLoc?
7156 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
7157 NameLoc);
7158
7159 case TemplateName::OverloadedTemplate: {
7160 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
7161 // DNInfo work in progress: CHECKME: what about DNLoc?
7162 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
7163 }
7164
7165 case TemplateName::AssumedTemplate: {
7166 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
7167 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
7168 }
7169
7170 case TemplateName::DependentTemplate: {
7171 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
7172 IdentifierOrOverloadedOperator TN = DTN->getName();
7173 DeclarationName DName;
7174 if (const IdentifierInfo *II = TN.getIdentifier()) {
7175 DName = DeclarationNames.getIdentifier(II);
7176 return DeclarationNameInfo(DName, NameLoc);
7177 } else {
7178 DName = DeclarationNames.getCXXOperatorName(TN.getOperator());
7179 // DNInfo work in progress: FIXME: source locations?
7180 DeclarationNameLoc DNLoc =
7181 DeclarationNameLoc::makeCXXOperatorNameLoc(SourceRange());
7182 return DeclarationNameInfo(DName, NameLoc, DNLoc);
7183 }
7184 }
7185
7186 case TemplateName::SubstTemplateTemplateParm: {
7187 SubstTemplateTemplateParmStorage *subst
7188 = Name.getAsSubstTemplateTemplateParm();
7189 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
7190 NameLoc);
7191 }
7192
7193 case TemplateName::SubstTemplateTemplateParmPack: {
7194 SubstTemplateTemplateParmPackStorage *subst
7195 = Name.getAsSubstTemplateTemplateParmPack();
7196 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
7197 NameLoc);
7198 }
7199 case TemplateName::UsingTemplate:
7200 return DeclarationNameInfo(Name.getAsUsingShadowDecl()->getDeclName(),
7201 NameLoc);
7202 case TemplateName::DeducedTemplate: {
7203 DeducedTemplateStorage *DTS = Name.getAsDeducedTemplateName();
7204 return getNameForTemplate(DTS->getUnderlying(), NameLoc);
7205 }
7206 }
7207
7208 llvm_unreachable("bad template name kind!");
7209 }
7210
7211 static const TemplateArgument *
7212 getDefaultTemplateArgumentOrNone(const NamedDecl *P) {
7213 auto handleParam = [](auto *TP) -> const TemplateArgument * {
7214 if (!TP->hasDefaultArgument())
7215 return nullptr;
7216 return &TP->getDefaultArgument().getArgument();
7217 };
7218 switch (P->getKind()) {
7219 case NamedDecl::TemplateTypeParm:
7220 return handleParam(cast<TemplateTypeParmDecl>(P));
7221 case NamedDecl::NonTypeTemplateParm:
7222 return handleParam(cast<NonTypeTemplateParmDecl>(P));
7223 case NamedDecl::TemplateTemplateParm:
7224 return handleParam(cast<TemplateTemplateParmDecl>(P));
7225 default:
7226 llvm_unreachable("Unexpected template parameter kind");
7227 }
7228 }
7229
7230 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name,
7231 bool IgnoreDeduced) const {
7232 while (std::optional<TemplateName> UnderlyingOrNone =
7233 Name.desugar(IgnoreDeduced))
7234 Name = *UnderlyingOrNone;
7235
7236 switch (Name.getKind()) {
7237 case TemplateName::Template: {
7238 TemplateDecl *Template = Name.getAsTemplateDecl();
7239 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
7240 Template = getCanonicalTemplateTemplateParmDecl(TTP);
7241
7242 // The canonical template name is the canonical template declaration.
7243 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
7244 }
7245
7246 case TemplateName::AssumedTemplate:
7247 // An assumed template is just a name, so it is already canonical.
7248 return Name;
7249
7250 case TemplateName::OverloadedTemplate:
7251 llvm_unreachable("cannot canonicalize overloaded template");
7252
7253 case TemplateName::DependentTemplate: {
7254 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
7255 assert(DTN && "Non-dependent template names must refer to template decls.");
7256 NestedNameSpecifier Qualifier = DTN->getQualifier();
7257 NestedNameSpecifier CanonQualifier = Qualifier.getCanonical();
7258 if (Qualifier != CanonQualifier || !DTN->hasTemplateKeyword())
7259 return getDependentTemplateName({CanonQualifier, DTN->getName(),
7260 /*HasTemplateKeyword=*/true});
7261 return Name;
7262 }
7263
7264 case TemplateName::SubstTemplateTemplateParmPack: {
7265 SubstTemplateTemplateParmPackStorage *subst =
7266 Name.getAsSubstTemplateTemplateParmPack();
7267 TemplateArgument canonArgPack =
7268 getCanonicalTemplateArgument(subst->getArgumentPack());
7269 return getSubstTemplateTemplateParmPack(
7270 canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
7271 subst->getIndex(), subst->getFinal());
7272 }
7273 case TemplateName::DeducedTemplate: {
7274 assert(IgnoreDeduced == false);
7275 DeducedTemplateStorage *DTS = Name.getAsDeducedTemplateName();
7276 DefaultArguments DefArgs = DTS->getDefaultArguments();
7277 TemplateName Underlying = DTS->getUnderlying();
7278
7279 TemplateName CanonUnderlying =
7280 getCanonicalTemplateName(Underlying, /*IgnoreDeduced=*/true);
7281 bool NonCanonical = CanonUnderlying != Underlying;
7282 auto CanonArgs =
7283 getCanonicalTemplateArguments(*this, DefArgs.Args, NonCanonical);
7284
7285 ArrayRef<NamedDecl *> Params =
7286 CanonUnderlying.getAsTemplateDecl()->getTemplateParameters()->asArray();
7287 assert(CanonArgs.size() <= Params.size());
7288 // A deduced template name which deduces the same default arguments already
7289 // declared in the underlying template is the same template as the
7290 // underlying template. We need need to note any arguments which differ from
7291 // the corresponding declaration. If any argument differs, we must build a
7292 // deduced template name.
7293 for (int I = CanonArgs.size() - 1; I >= 0; --I) {
7294 const TemplateArgument *A = getDefaultTemplateArgumentOrNone(Params[I]);
7295 if (!A)
7296 break;
7297 auto CanonParamDefArg = getCanonicalTemplateArgument(*A);
7298 TemplateArgument &CanonDefArg = CanonArgs[I];
7299 if (CanonDefArg.structurallyEquals(CanonParamDefArg))
7300 continue;
7301 // Keep popping from the back any deault arguments which are the same.
7302 if (I == int(CanonArgs.size() - 1))
7303 CanonArgs.pop_back();
7304 NonCanonical = true;
7305 }
7306 return NonCanonical ? getDeducedTemplateName(
7307 CanonUnderlying,
7308 /*DefaultArgs=*/{DefArgs.StartPos, CanonArgs})
7309 : Name;
7310 }
7311 case TemplateName::UsingTemplate:
7312 case TemplateName::QualifiedTemplate:
7313 case TemplateName::SubstTemplateTemplateParm:
7314 llvm_unreachable("always sugar node");
7315 }
7316
7317 llvm_unreachable("bad template name!");
7318 }
7319
7320 bool ASTContext::hasSameTemplateName(const TemplateName &X,
7321 const TemplateName &Y,
7322 bool IgnoreDeduced) const {
7323 return getCanonicalTemplateName(X, IgnoreDeduced) ==
7324 getCanonicalTemplateName(Y, IgnoreDeduced);
7325 }
7326
7327 bool ASTContext::isSameAssociatedConstraint(
7328 const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const {
7329 if (ACX.ArgPackSubstIndex != ACY.ArgPackSubstIndex)
7330 return false;
7331 if (!isSameConstraintExpr(ACX.ConstraintExpr, ACY.ConstraintExpr))
7332 return false;
7333 return true;
7334 }
7335
7336 bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
7337 if (!XCE != !YCE)
7338 return false;
7339
7340 if (!XCE)
7341 return true;
7342
7343 llvm::FoldingSetNodeID XCEID, YCEID;
7344 XCE->Profile(XCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7345 YCE->Profile(YCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7346 return XCEID == YCEID;
7347 }
7348
7349 bool ASTContext::isSameTypeConstraint(const TypeConstraint *XTC,
7350 const TypeConstraint *YTC) const {
7351 if (!XTC != !YTC)
7352 return false;
7353
7354 if (!XTC)
7355 return true;
7356
7357 auto *NCX = XTC->getNamedConcept();
7358 auto *NCY = YTC->getNamedConcept();
7359 if (!NCX || !NCY || !isSameEntity(NCX, NCY))
7360 return false;
7361 if (XTC->getConceptReference()->hasExplicitTemplateArgs() !=
7362 YTC->getConceptReference()->hasExplicitTemplateArgs())
7363 return false;
7364 if (XTC->getConceptReference()->hasExplicitTemplateArgs())
7365 if (XTC->getConceptReference()
7366 ->getTemplateArgsAsWritten()
7367 ->NumTemplateArgs !=
7368 YTC->getConceptReference()->getTemplateArgsAsWritten()->NumTemplateArgs)
7369 return false;
7370
7371 // Compare slowly by profiling.
7372 //
7373 // We couldn't compare the profiling result for the template
7374 // args here. Consider the following example in different modules:
7375 //
7376 // template <__integer_like _Tp, C<_Tp> Sentinel>
7377 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
7378 // return __t;
7379 // }
7380 //
7381 // When we compare the profiling result for `C<_Tp>` in different
7382 // modules, it will compare the type of `_Tp` in different modules.
7383 // However, the type of `_Tp` in different modules refer to different
7384 // types here naturally. So we couldn't compare the profiling result
7385 // for the template args directly.
7386 return isSameConstraintExpr(XTC->getImmediatelyDeclaredConstraint(),
7387 YTC->getImmediatelyDeclaredConstraint());
7388 }
7389
7390 bool ASTContext::isSameTemplateParameter(const NamedDecl *X,
7391 const NamedDecl *Y) const {
7392 if (X->getKind() != Y->getKind())
7393 return false;
7394
7395 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
7396 auto *TY = cast<TemplateTypeParmDecl>(Y);
7397 if (TX->isParameterPack() != TY->isParameterPack())
7398 return false;
7399 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
7400 return false;
7401 return isSameTypeConstraint(TX->getTypeConstraint(),
7402 TY->getTypeConstraint());
7403 }
7404
7405 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7406 auto *TY = cast<NonTypeTemplateParmDecl>(Y);
7407 return TX->isParameterPack() == TY->isParameterPack() &&
7408 TX->getASTContext().hasSameType(TX->getType(), TY->getType()) &&
7409 isSameConstraintExpr(TX->getPlaceholderTypeConstraint(),
7410 TY->getPlaceholderTypeConstraint());
7411 }
7412
7413 auto *TX = cast<TemplateTemplateParmDecl>(X);
7414 auto *TY = cast<TemplateTemplateParmDecl>(Y);
7415 return TX->isParameterPack() == TY->isParameterPack() &&
7416 isSameTemplateParameterList(TX->getTemplateParameters(),
7417 TY->getTemplateParameters());
7418 }
7419
7420 bool ASTContext::isSameTemplateParameterList(
7421 const TemplateParameterList *X, const TemplateParameterList *Y) const {
7422 if (X->size() != Y->size())
7423 return false;
7424
7425 for (unsigned I = 0, N = X->size(); I != N; ++I)
7426 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
7427 return false;
7428
7429 return isSameConstraintExpr(X->getRequiresClause(), Y->getRequiresClause());
7430 }
7431
7432 bool ASTContext::isSameDefaultTemplateArgument(const NamedDecl *X,
7433 const NamedDecl *Y) const {
7434 // If the type parameter isn't the same already, we don't need to check the
7435 // default argument further.
7436 if (!isSameTemplateParameter(X, Y))
7437 return false;
7438
7439 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(X)) {
7440 auto *TTPY = cast<TemplateTypeParmDecl>(Y);
7441 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7442 return false;
7443
7444 return hasSameType(TTPX->getDefaultArgument().getArgument().getAsType(),
7445 TTPY->getDefaultArgument().getArgument().getAsType());
7446 }
7447
7448 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7449 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Y);
7450 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
7451 return false;
7452
7453 Expr *DefaultArgumentX =
7454 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7455 Expr *DefaultArgumentY =
7456 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7457 llvm::FoldingSetNodeID XID, YID;
7458 DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true);
7459 DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true);
7460 return XID == YID;
7461 }
7462
7463 auto *TTPX = cast<TemplateTemplateParmDecl>(X);
7464 auto *TTPY = cast<TemplateTemplateParmDecl>(Y);
7465
7466 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7467 return false;
7468
7469 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
7470 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
7471 return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate());
7472 }
7473
7474 static bool isSameQualifier(const NestedNameSpecifier X,
7475 const NestedNameSpecifier Y) {
7476 if (X == Y)
7477 return true;
7478 if (!X || !Y)
7479 return false;
7480
7481 auto Kind = X.getKind();
7482 if (Kind != Y.getKind())
7483 return false;
7484
7485 // FIXME: For namespaces and types, we're permitted to check that the entity
7486 // is named via the same tokens. We should probably do so.
7487 switch (Kind) {
7488 case NestedNameSpecifier::Kind::Namespace: {
7489 auto [NamespaceX, PrefixX] = X.getAsNamespaceAndPrefix();
7490 auto [NamespaceY, PrefixY] = Y.getAsNamespaceAndPrefix();
7491 if (!declaresSameEntity(NamespaceX->getNamespace(),
7492 NamespaceY->getNamespace()))
7493 return false;
7494 return isSameQualifier(PrefixX, PrefixY);
7495 }
7496 case NestedNameSpecifier::Kind::Type: {
7497 const auto *TX = X.getAsType(), *TY = Y.getAsType();
7498 if (TX->getCanonicalTypeInternal() != TY->getCanonicalTypeInternal())
7499 return false;
7500 return isSameQualifier(TX->getPrefix(), TY->getPrefix());
7501 }
7502 case NestedNameSpecifier::Kind::Null:
7503 case NestedNameSpecifier::Kind::Global:
7504 case NestedNameSpecifier::Kind::MicrosoftSuper:
7505 return true;
7506 }
7507 llvm_unreachable("unhandled qualifier kind");
7508 }
7509
7510 static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B) {
7511 if (!A->getASTContext().getLangOpts().CUDA)
7512 return true; // Target attributes are overloadable in CUDA compilation only.
7513 if (A->hasAttr<CUDADeviceAttr>() != B->hasAttr<CUDADeviceAttr>())
7514 return false;
7515 if (A->hasAttr<CUDADeviceAttr>() && B->hasAttr<CUDADeviceAttr>())
7516 return A->hasAttr<CUDAHostAttr>() == B->hasAttr<CUDAHostAttr>();
7517 return true; // unattributed and __host__ functions are the same.
7518 }
7519
7520 /// Determine whether the attributes we can overload on are identical for A and
7521 /// B. Will ignore any overloadable attrs represented in the type of A and B.
7522 static bool hasSameOverloadableAttrs(const FunctionDecl *A,
7523 const FunctionDecl *B) {
7524 // Note that pass_object_size attributes are represented in the function's
7525 // ExtParameterInfo, so we don't need to check them here.
7526
7527 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
7528 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
7529 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
7530
7531 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
7532 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
7533 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
7534
7535 // Return false if the number of enable_if attributes is different.
7536 if (!Cand1A || !Cand2A)
7537 return false;
7538
7539 Cand1ID.clear();
7540 Cand2ID.clear();
7541
7542 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
7543 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
7544
7545 // Return false if any of the enable_if expressions of A and B are
7546 // different.
7547 if (Cand1ID != Cand2ID)
7548 return false;
7549 }
7550 return hasSameCudaAttrs(A, B);
7551 }
7552
7553 bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
7554 // Caution: this function is called by the AST reader during deserialization,
7555 // so it cannot rely on AST invariants being met. Non-trivial accessors
7556 // should be avoided, along with any traversal of redeclaration chains.
7557
7558 if (X == Y)
7559 return true;
7560
7561 if (X->getDeclName() != Y->getDeclName())
7562 return false;
7563
7564 // Must be in the same context.
7565 //
7566 // Note that we can't use DeclContext::Equals here, because the DeclContexts
7567 // could be two different declarations of the same function. (We will fix the
7568 // semantic DC to refer to the primary definition after merging.)
7569 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
7570 cast<Decl>(Y->getDeclContext()->getRedeclContext())))
7571 return false;
7572
7573 // If either X or Y are local to the owning module, they are only possible to
7574 // be the same entity if they are in the same module.
7575 if (X->isModuleLocal() || Y->isModuleLocal())
7576 if (!isInSameModule(X->getOwningModule(), Y->getOwningModule()))
7577 return false;
7578
7579 // Two typedefs refer to the same entity if they have the same underlying
7580 // type.
7581 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
7582 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
7583 return hasSameType(TypedefX->getUnderlyingType(),
7584 TypedefY->getUnderlyingType());
7585
7586 // Must have the same kind.
7587 if (X->getKind() != Y->getKind())
7588 return false;
7589
7590 // Objective-C classes and protocols with the same name always match.
7591 if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
7592 return true;
7593
7594 if (isa<ClassTemplateSpecializationDecl>(X)) {
7595 // No need to handle these here: we merge them when adding them to the
7596 // template.
7597 return false;
7598 }
7599
7600 // Compatible tags match.
7601 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
7602 const auto *TagY = cast<TagDecl>(Y);
7603 return (TagX->getTagKind() == TagY->getTagKind()) ||
7604 ((TagX->getTagKind() == TagTypeKind::Struct ||
7605 TagX->getTagKind() == TagTypeKind::Class ||
7606 TagX->getTagKind() == TagTypeKind::Interface) &&
7607 (TagY->getTagKind() == TagTypeKind::Struct ||
7608 TagY->getTagKind() == TagTypeKind::Class ||
7609 TagY->getTagKind() == TagTypeKind::Interface));
7610 }
7611
7612 // Functions with the same type and linkage match.
7613 // FIXME: This needs to cope with merging of prototyped/non-prototyped
7614 // functions, etc.
7615 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
7616 const auto *FuncY = cast<FunctionDecl>(Y);
7617 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
7618 const auto *CtorY = cast<CXXConstructorDecl>(Y);
7619 if (CtorX->getInheritedConstructor() &&
7620 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
7621 CtorY->getInheritedConstructor().getConstructor()))
7622 return false;
7623 }
7624
7625 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
7626 return false;
7627
7628 // Multiversioned functions with different feature strings are represented
7629 // as separate declarations.
7630 if (FuncX->isMultiVersion()) {
7631 const auto *TAX = FuncX->getAttr<TargetAttr>();
7632 const auto *TAY = FuncY->getAttr<TargetAttr>();
7633 assert(TAX && TAY && "Multiversion Function without target attribute");
7634
7635 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
7636 return false;
7637 }
7638
7639 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
7640 // not the same entity if they are constrained.
7641 if ((FuncX->isMemberLikeConstrainedFriend() ||
7642 FuncY->isMemberLikeConstrainedFriend()) &&
7643 !FuncX->getLexicalDeclContext()->Equals(
7644 FuncY->getLexicalDeclContext())) {
7645 return false;
7646 }
7647
7648 if (!isSameAssociatedConstraint(FuncX->getTrailingRequiresClause(),
7649 FuncY->getTrailingRequiresClause()))
7650 return false;
7651
7652 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
7653 // Map to the first declaration that we've already merged into this one.
7654 // The TSI of redeclarations might not match (due to calling conventions
7655 // being inherited onto the type but not the TSI), but the TSI type of
7656 // the first declaration of the function should match across modules.
7657 FD = FD->getCanonicalDecl();
7658 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
7659 : FD->getType();
7660 };
7661 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
7662 if (!hasSameType(XT, YT)) {
7663 // We can get functions with different types on the redecl chain in C++17
7664 // if they have differing exception specifications and at least one of
7665 // the excpetion specs is unresolved.
7666 auto *XFPT = XT->getAs<FunctionProtoType>();
7667 auto *YFPT = YT->getAs<FunctionProtoType>();
7668 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
7669 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
7670 isUnresolvedExceptionSpec(YFPT->getExceptionSpecType())) &&
7671 hasSameFunctionTypeIgnoringExceptionSpec(XT, YT))
7672 return true;
7673 return false;
7674 }
7675
7676 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
7677 hasSameOverloadableAttrs(FuncX, FuncY);
7678 }
7679
7680 // Variables with the same type and linkage match.
7681 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
7682 const auto *VarY = cast<VarDecl>(Y);
7683 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
7684 // During deserialization, we might compare variables before we load
7685 // their types. Assume the types will end up being the same.
7686 if (VarX->getType().isNull() || VarY->getType().isNull())
7687 return true;
7688
7689 if (hasSameType(VarX->getType(), VarY->getType()))
7690 return true;
7691
7692 // We can get decls with different types on the redecl chain. Eg.
7693 // template <typename T> struct S { static T Var[]; }; // #1
7694 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
7695 // Only? happens when completing an incomplete array type. In this case
7696 // when comparing #1 and #2 we should go through their element type.
7697 const ArrayType *VarXTy = getAsArrayType(VarX->getType());
7698 const ArrayType *VarYTy = getAsArrayType(VarY->getType());
7699 if (!VarXTy || !VarYTy)
7700 return false;
7701 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
7702 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
7703 }
7704 return false;
7705 }
7706
7707 // Namespaces with the same name and inlinedness match.
7708 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
7709 const auto *NamespaceY = cast<NamespaceDecl>(Y);
7710 return NamespaceX->isInline() == NamespaceY->isInline();
7711 }
7712
7713 // Identical template names and kinds match if their template parameter lists
7714 // and patterns match.
7715 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
7716 const auto *TemplateY = cast<TemplateDecl>(Y);
7717
7718 // ConceptDecl wouldn't be the same if their constraint expression differs.
7719 if (const auto *ConceptX = dyn_cast<ConceptDecl>(X)) {
7720 const auto *ConceptY = cast<ConceptDecl>(Y);
7721 if (!isSameConstraintExpr(ConceptX->getConstraintExpr(),
7722 ConceptY->getConstraintExpr()))
7723 return false;
7724 }
7725
7726 return isSameEntity(TemplateX->getTemplatedDecl(),
7727 TemplateY->getTemplatedDecl()) &&
7728 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
7729 TemplateY->getTemplateParameters());
7730 }
7731
7732 // Fields with the same name and the same type match.
7733 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
7734 const auto *FDY = cast<FieldDecl>(Y);
7735 // FIXME: Also check the bitwidth is odr-equivalent, if any.
7736 return hasSameType(FDX->getType(), FDY->getType());
7737 }
7738
7739 // Indirect fields with the same target field match.
7740 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
7741 const auto *IFDY = cast<IndirectFieldDecl>(Y);
7742 return IFDX->getAnonField()->getCanonicalDecl() ==
7743 IFDY->getAnonField()->getCanonicalDecl();
7744 }
7745
7746 // Enumerators with the same name match.
7747 if (isa<EnumConstantDecl>(X))
7748 // FIXME: Also check the value is odr-equivalent.
7749 return true;
7750
7751 // Using shadow declarations with the same target match.
7752 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
7753 const auto *USY = cast<UsingShadowDecl>(Y);
7754 return declaresSameEntity(USX->getTargetDecl(), USY->getTargetDecl());
7755 }
7756
7757 // Using declarations with the same qualifier match. (We already know that
7758 // the name matches.)
7759 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
7760 const auto *UY = cast<UsingDecl>(Y);
7761 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7762 UX->hasTypename() == UY->hasTypename() &&
7763 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7764 }
7765 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
7766 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
7767 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7768 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7769 }
7770 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
7771 return isSameQualifier(
7772 UX->getQualifier(),
7773 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
7774 }
7775
7776 // Using-pack declarations are only created by instantiation, and match if
7777 // they're instantiated from matching UnresolvedUsing...Decls.
7778 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
7779 return declaresSameEntity(
7780 UX->getInstantiatedFromUsingDecl(),
7781 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
7782 }
7783
7784 // Namespace alias definitions with the same target match.
7785 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
7786 const auto *NAY = cast<NamespaceAliasDecl>(Y);
7787 return NAX->getNamespace()->Equals(NAY->getNamespace());
7788 }
7789
7790 return false;
7791 }
7792
7793 TemplateArgument
7794 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
7795 switch (Arg.getKind()) {
7796 case TemplateArgument::Null:
7797 return Arg;
7798
7799 case TemplateArgument::Expression:
7800 return TemplateArgument(Arg.getAsExpr(), /*IsCanonical=*/true,
7801 Arg.getIsDefaulted());
7802
7803 case TemplateArgument::Declaration: {
7804 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
7805 return TemplateArgument(D, getCanonicalType(Arg.getParamTypeForDecl()),
7806 Arg.getIsDefaulted());
7807 }
7808
7809 case TemplateArgument::NullPtr:
7810 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
7811 /*isNullPtr*/ true, Arg.getIsDefaulted());
7812
7813 case TemplateArgument::Template:
7814 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()),
7815 Arg.getIsDefaulted());
7816
7817 case TemplateArgument::TemplateExpansion:
7818 return TemplateArgument(
7819 getCanonicalTemplateName(Arg.getAsTemplateOrTemplatePattern()),
7820 Arg.getNumTemplateExpansions(), Arg.getIsDefaulted());
7821
7822 case TemplateArgument::Integral:
7823 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
7824
7825 case TemplateArgument::StructuralValue:
7826 return TemplateArgument(*this,
7827 getCanonicalType(Arg.getStructuralValueType()),
7828 Arg.getAsStructuralValue(), Arg.getIsDefaulted());
7829
7830 case TemplateArgument::Type:
7831 return TemplateArgument(getCanonicalType(Arg.getAsType()),
7832 /*isNullPtr*/ false, Arg.getIsDefaulted());
7833
7834 case TemplateArgument::Pack: {
7835 bool AnyNonCanonArgs = false;
7836 auto CanonArgs = ::getCanonicalTemplateArguments(
7837 *this, Arg.pack_elements(), AnyNonCanonArgs);
7838 if (!AnyNonCanonArgs)
7839 return Arg;
7840 auto NewArg = TemplateArgument::CreatePackCopy(
7841 const_cast<ASTContext &>(*this), CanonArgs);
7842 NewArg.setIsDefaulted(Arg.getIsDefaulted());
7843 return NewArg;
7844 }
7845 }
7846
7847 // Silence GCC warning
7848 llvm_unreachable("Unhandled template argument kind");
7849 }
7850
7851 bool ASTContext::isSameTemplateArgument(const TemplateArgument &Arg1,
7852 const TemplateArgument &Arg2) const {
7853 if (Arg1.getKind() != Arg2.getKind())
7854 return false;
7855
7856 switch (Arg1.getKind()) {
7857 case TemplateArgument::Null:
7858 llvm_unreachable("Comparing NULL template argument");
7859
7860 case TemplateArgument::Type:
7861 return hasSameType(Arg1.getAsType(), Arg2.getAsType());
7862
7863 case TemplateArgument::Declaration:
7864 return Arg1.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl() ==
7865 Arg2.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl();
7866
7867 case TemplateArgument::NullPtr:
7868 return hasSameType(Arg1.getNullPtrType(), Arg2.getNullPtrType());
7869
7870 case TemplateArgument::Template:
7871 case TemplateArgument::TemplateExpansion:
7872 return getCanonicalTemplateName(Arg1.getAsTemplateOrTemplatePattern()) ==
7873 getCanonicalTemplateName(Arg2.getAsTemplateOrTemplatePattern());
7874
7875 case TemplateArgument::Integral:
7876 return llvm::APSInt::isSameValue(Arg1.getAsIntegral(),
7877 Arg2.getAsIntegral());
7878
7879 case TemplateArgument::StructuralValue:
7880 return Arg1.structurallyEquals(Arg2);
7881
7882 case TemplateArgument::Expression: {
7883 llvm::FoldingSetNodeID ID1, ID2;
7884 Arg1.getAsExpr()->Profile(ID1, *this, /*Canonical=*/true);
7885 Arg2.getAsExpr()->Profile(ID2, *this, /*Canonical=*/true);
7886 return ID1 == ID2;
7887 }
7888
7889 case TemplateArgument::Pack:
7890 return llvm::equal(
7891 Arg1.getPackAsArray(), Arg2.getPackAsArray(),
7892 [&](const TemplateArgument &Arg1, const TemplateArgument &Arg2) {
7893 return isSameTemplateArgument(Arg1, Arg2);
7894 });
7895 }
7896
7897 llvm_unreachable("Unhandled template argument kind");
7898 }
7899
7900 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
7901 // Handle the non-qualified case efficiently.
7902 if (!T.hasLocalQualifiers()) {
7903 // Handle the common positive case fast.
7904 if (const auto *AT = dyn_cast<ArrayType>(T))
7905 return AT;
7906 }
7907
7908 // Handle the common negative case fast.
7909 if (!isa<ArrayType>(T.getCanonicalType()))
7910 return nullptr;
7911
7912 // Apply any qualifiers from the array type to the element type. This
7913 // implements C99 6.7.3p8: "If the specification of an array type includes
7914 // any type qualifiers, the element type is so qualified, not the array type."
7915
7916 // If we get here, we either have type qualifiers on the type, or we have
7917 // sugar such as a typedef in the way. If we have type qualifiers on the type
7918 // we must propagate them down into the element type.
7919
7920 SplitQualType split = T.getSplitDesugaredType();
7921 Qualifiers qs = split.Quals;
7922
7923 // If we have a simple case, just return now.
7924 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
7925 if (!ATy || qs.empty())
7926 return ATy;
7927
7928 // Otherwise, we have an array and we have qualifiers on it. Push the
7929 // qualifiers into the array element type and return a new array type.
7930 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
7931
7932 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
7933 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
7934 CAT->getSizeExpr(),
7935 CAT->getSizeModifier(),
7936 CAT->getIndexTypeCVRQualifiers()));
7937 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
7938 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
7939 IAT->getSizeModifier(),
7940 IAT->getIndexTypeCVRQualifiers()));
7941
7942 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
7943 return cast<ArrayType>(getDependentSizedArrayType(
7944 NewEltTy, DSAT->getSizeExpr(), DSAT->getSizeModifier(),
7945 DSAT->getIndexTypeCVRQualifiers()));
7946
7947 const auto *VAT = cast<VariableArrayType>(ATy);
7948 return cast<ArrayType>(
7949 getVariableArrayType(NewEltTy, VAT->getSizeExpr(), VAT->getSizeModifier(),
7950 VAT->getIndexTypeCVRQualifiers()));
7951 }
7952
7953 QualType ASTContext::getAdjustedParameterType(QualType T) const {
7954 if (getLangOpts().HLSL && T->isConstantArrayType())
7955 return getArrayParameterType(T);
7956 if (T->isArrayType() || T->isFunctionType())
7957 return getDecayedType(T);
7958 return T;
7959 }
7960
7961 QualType ASTContext::getSignatureParameterType(QualType T) const {
7962 T = getVariableArrayDecayedType(T);
7963 T = getAdjustedParameterType(T);
7964 return T.getUnqualifiedType();
7965 }
7966
7967 QualType ASTContext::getExceptionObjectType(QualType T) const {
7968 // C++ [except.throw]p3:
7969 // A throw-expression initializes a temporary object, called the exception
7970 // object, the type of which is determined by removing any top-level
7971 // cv-qualifiers from the static type of the operand of throw and adjusting
7972 // the type from "array of T" or "function returning T" to "pointer to T"
7973 // or "pointer to function returning T", [...]
7974 T = getVariableArrayDecayedType(T);
7975 if (T->isArrayType() || T->isFunctionType())
7976 T = getDecayedType(T);
7977 return T.getUnqualifiedType();
7978 }
7979
7980 /// getArrayDecayedType - Return the properly qualified result of decaying the
7981 /// specified array type to a pointer. This operation is non-trivial when
7982 /// handling typedefs etc. The canonical type of "T" must be an array type,
7983 /// this returns a pointer to a properly qualified element of the array.
7984 ///
7985 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
7986 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
7987 // Get the element type with 'getAsArrayType' so that we don't lose any
7988 // typedefs in the element type of the array. This also handles propagation
7989 // of type qualifiers from the array type into the element type if present
7990 // (C99 6.7.3p8).
7991 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
7992 assert(PrettyArrayType && "Not an array type!");
7993
7994 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
7995
7996 // int x[restrict 4] -> int *restrict
7997 QualType Result = getQualifiedType(PtrTy,
7998 PrettyArrayType->getIndexTypeQualifiers());
7999
8000 // int x[_Nullable] -> int * _Nullable
8001 if (auto Nullability = Ty->getNullability()) {
8002 Result = const_cast<ASTContext *>(this)->getAttributedType(*Nullability,
8003 Result, Result);
8004 }
8005 return Result;
8006 }
8007
8008 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
8009 return getBaseElementType(array->getElementType());
8010 }
8011
8012 QualType ASTContext::getBaseElementType(QualType type) const {
8013 Qualifiers qs;
8014 while (true) {
8015 SplitQualType split = type.getSplitDesugaredType();
8016 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
8017 if (!array) break;
8018
8019 type = array->getElementType();
8020 qs.addConsistentQualifiers(split.Quals);
8021 }
8022
8023 return getQualifiedType(type, qs);
8024 }
8025
8026 /// getConstantArrayElementCount - Returns number of constant array elements.
8027 uint64_t
8028 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
8029 uint64_t ElementCount = 1;
8030 do {
8031 ElementCount *= CA->getZExtSize();
8032 CA = dyn_cast_or_null<ConstantArrayType>(
8033 CA->getElementType()->getAsArrayTypeUnsafe());
8034 } while (CA);
8035 return ElementCount;
8036 }
8037
8038 uint64_t ASTContext::getArrayInitLoopExprElementCount(
8039 const ArrayInitLoopExpr *AILE) const {
8040 if (!AILE)
8041 return 0;
8042
8043 uint64_t ElementCount = 1;
8044
8045 do {
8046 ElementCount *= AILE->getArraySize().getZExtValue();
8047 AILE = dyn_cast<ArrayInitLoopExpr>(AILE->getSubExpr());
8048 } while (AILE);
8049
8050 return ElementCount;
8051 }
8052
8053 /// getFloatingRank - Return a relative rank for floating point types.
8054 /// This routine will assert if passed a built-in type that isn't a float.
8055 static FloatingRank getFloatingRank(QualType T) {
8056 if (const auto *CT = T->getAs<ComplexType>())
8057 return getFloatingRank(CT->getElementType());
8058
8059 switch (T->castAs<BuiltinType>()->getKind()) {
8060 default: llvm_unreachable("getFloatingRank(): not a floating type");
8061 case BuiltinType::Float16: return Float16Rank;
8062 case BuiltinType::Half: return HalfRank;
8063 case BuiltinType::Float: return FloatRank;
8064 case BuiltinType::Double: return DoubleRank;
8065 case BuiltinType::LongDouble: return LongDoubleRank;
8066 case BuiltinType::Float128: return Float128Rank;
8067 case BuiltinType::BFloat16: return BFloat16Rank;
8068 case BuiltinType::Ibm128: return Ibm128Rank;
8069 }
8070 }
8071
8072 /// getFloatingTypeOrder - Compare the rank of the two specified floating
8073 /// point types, ignoring the domain of the type (i.e. 'double' ==
8074 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
8075 /// LHS < RHS, return -1.
8076 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
8077 FloatingRank LHSR = getFloatingRank(LHS);
8078 FloatingRank RHSR = getFloatingRank(RHS);
8079
8080 if (LHSR == RHSR)
8081 return 0;
8082 if (LHSR > RHSR)
8083 return 1;
8084 return -1;
8085 }
8086
8087 int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
8088 if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS))
8089 return 0;
8090 return getFloatingTypeOrder(LHS, RHS);
8091 }
8092
8093 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
8094 /// routine will assert if passed a built-in type that isn't an integer or enum,
8095 /// or if it is not canonicalized.
8096 unsigned ASTContext::getIntegerRank(const Type *T) const {
8097 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
8098
8099 // Results in this 'losing' to any type of the same size, but winning if
8100 // larger.
8101 if (const auto *EIT = dyn_cast<BitIntType>(T))
8102 return 0 + (EIT->getNumBits() << 3);
8103
8104 switch (cast<BuiltinType>(T)->getKind()) {
8105 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
8106 case BuiltinType::Bool:
8107 return 1 + (getIntWidth(BoolTy) << 3);
8108 case BuiltinType::Char_S:
8109 case BuiltinType::Char_U:
8110 case BuiltinType::SChar:
8111 case BuiltinType::UChar:
8112 return 2 + (getIntWidth(CharTy) << 3);
8113 case BuiltinType::Short:
8114 case BuiltinType::UShort:
8115 return 3 + (getIntWidth(ShortTy) << 3);
8116 case BuiltinType::Int:
8117 case BuiltinType::UInt:
8118 return 4 + (getIntWidth(IntTy) << 3);
8119 case BuiltinType::Long:
8120 case BuiltinType::ULong:
8121 return 5 + (getIntWidth(LongTy) << 3);
8122 case BuiltinType::LongLong:
8123 case BuiltinType::ULongLong:
8124 return 6 + (getIntWidth(LongLongTy) << 3);
8125 case BuiltinType::Int128:
8126 case BuiltinType::UInt128:
8127 return 7 + (getIntWidth(Int128Ty) << 3);
8128
8129 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
8130 // their underlying types" [c++20 conv.rank]
8131 case BuiltinType::Char8:
8132 return getIntegerRank(UnsignedCharTy.getTypePtr());
8133 case BuiltinType::Char16:
8134 return getIntegerRank(
8135 getFromTargetType(Target->getChar16Type()).getTypePtr());
8136 case BuiltinType::Char32:
8137 return getIntegerRank(
8138 getFromTargetType(Target->getChar32Type()).getTypePtr());
8139 case BuiltinType::WChar_S:
8140 case BuiltinType::WChar_U:
8141 return getIntegerRank(
8142 getFromTargetType(Target->getWCharType()).getTypePtr());
8143 }
8144 }
8145
8146 /// Whether this is a promotable bitfield reference according
8147 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
8148 ///
8149 /// \returns the type this bit-field will promote to, or NULL if no
8150 /// promotion occurs.
8151 QualType ASTContext::isPromotableBitField(Expr *E) const {
8152 if (E->isTypeDependent() || E->isValueDependent())
8153 return {};
8154
8155 // C++ [conv.prom]p5:
8156 // If the bit-field has an enumerated type, it is treated as any other
8157 // value of that type for promotion purposes.
8158 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
8159 return {};
8160
8161 // FIXME: We should not do this unless E->refersToBitField() is true. This
8162 // matters in C where getSourceBitField() will find bit-fields for various
8163 // cases where the source expression is not a bit-field designator.
8164
8165 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
8166 if (!Field)
8167 return {};
8168
8169 QualType FT = Field->getType();
8170
8171 uint64_t BitWidth = Field->getBitWidthValue();
8172 uint64_t IntSize = getTypeSize(IntTy);
8173 // C++ [conv.prom]p5:
8174 // A prvalue for an integral bit-field can be converted to a prvalue of type
8175 // int if int can represent all the values of the bit-field; otherwise, it
8176 // can be converted to unsigned int if unsigned int can represent all the
8177 // values of the bit-field. If the bit-field is larger yet, no integral
8178 // promotion applies to it.
8179 // C11 6.3.1.1/2:
8180 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
8181 // If an int can represent all values of the original type (as restricted by
8182 // the width, for a bit-field), the value is converted to an int; otherwise,
8183 // it is converted to an unsigned int.
8184 //
8185 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
8186 // We perform that promotion here to match GCC and C++.
8187 // FIXME: C does not permit promotion of an enum bit-field whose rank is
8188 // greater than that of 'int'. We perform that promotion to match GCC.
8189 //
8190 // C23 6.3.1.1p2:
8191 // The value from a bit-field of a bit-precise integer type is converted to
8192 // the corresponding bit-precise integer type. (The rest is the same as in
8193 // C11.)
8194 if (QualType QT = Field->getType(); QT->isBitIntType())
8195 return QT;
8196
8197 if (BitWidth < IntSize)
8198 return IntTy;
8199
8200 if (BitWidth == IntSize)
8201 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
8202
8203 // Bit-fields wider than int are not subject to promotions, and therefore act
8204 // like the base type. GCC has some weird bugs in this area that we
8205 // deliberately do not follow (GCC follows a pre-standard resolution to
8206 // C's DR315 which treats bit-width as being part of the type, and this leaks
8207 // into their semantics in some cases).
8208 return {};
8209 }
8210
8211 /// getPromotedIntegerType - Returns the type that Promotable will
8212 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
8213 /// integer type.
8214 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
8215 assert(!Promotable.isNull());
8216 assert(isPromotableIntegerType(Promotable));
8217 if (const auto *ED = Promotable->getAsEnumDecl())
8218 return ED->getPromotionType();
8219
8220 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
8221 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
8222 // (3.9.1) can be converted to a prvalue of the first of the following
8223 // types that can represent all the values of its underlying type:
8224 // int, unsigned int, long int, unsigned long int, long long int, or
8225 // unsigned long long int [...]
8226 // FIXME: Is there some better way to compute this?
8227 if (BT->getKind() == BuiltinType::WChar_S ||
8228 BT->getKind() == BuiltinType::WChar_U ||
8229 BT->getKind() == BuiltinType::Char8 ||
8230 BT->getKind() == BuiltinType::Char16 ||
8231 BT->getKind() == BuiltinType::Char32) {
8232 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
8233 uint64_t FromSize = getTypeSize(BT);
8234 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
8235 LongLongTy, UnsignedLongLongTy };
8236 for (const auto &PT : PromoteTypes) {
8237 uint64_t ToSize = getTypeSize(PT);
8238 if (FromSize < ToSize ||
8239 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
8240 return PT;
8241 }
8242 llvm_unreachable("char type should fit into long long");
8243 }
8244 }
8245
8246 // At this point, we should have a signed or unsigned integer type.
8247 if (Promotable->isSignedIntegerType())
8248 return IntTy;
8249 uint64_t PromotableSize = getIntWidth(Promotable);
8250 uint64_t IntSize = getIntWidth(IntTy);
8251 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
8252 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
8253 }
8254
8255 /// Recurses in pointer/array types until it finds an objc retainable
8256 /// type and returns its ownership.
8257 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
8258 while (!T.isNull()) {
8259 if (T.getObjCLifetime() != Qualifiers::OCL_None)
8260 return T.getObjCLifetime();
8261 if (T->isArrayType())
8262 T = getBaseElementType(T);
8263 else if (const auto *PT = T->getAs<PointerType>())
8264 T = PT->getPointeeType();
8265 else if (const auto *RT = T->getAs<ReferenceType>())
8266 T = RT->getPointeeType();
8267 else
8268 break;
8269 }
8270
8271 return Qualifiers::OCL_None;
8272 }
8273
8274 static const Type *getIntegerTypeForEnum(const EnumType *ET) {
8275 // Incomplete enum types are not treated as integer types.
8276 // FIXME: In C++, enum types are never integer types.
8277 const EnumDecl *ED = ET->getDecl()->getDefinitionOrSelf();
8278 if (ED->isComplete() && !ED->isScoped())
8279 return ED->getIntegerType().getTypePtr();
8280 return nullptr;
8281 }
8282
8283 /// getIntegerTypeOrder - Returns the highest ranked integer type:
8284 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
8285 /// LHS < RHS, return -1.
8286 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
8287 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
8288 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
8289
8290 // Unwrap enums to their underlying type.
8291 if (const auto *ET = dyn_cast<EnumType>(LHSC))
8292 LHSC = getIntegerTypeForEnum(ET);
8293 if (const auto *ET = dyn_cast<EnumType>(RHSC))
8294 RHSC = getIntegerTypeForEnum(ET);
8295
8296 if (LHSC == RHSC) return 0;
8297
8298 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
8299 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
8300
8301 unsigned LHSRank = getIntegerRank(LHSC);
8302 unsigned RHSRank = getIntegerRank(RHSC);
8303
8304 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
8305 if (LHSRank == RHSRank) return 0;
8306 return LHSRank > RHSRank ? 1 : -1;
8307 }
8308
8309 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
8310 if (LHSUnsigned) {
8311 // If the unsigned [LHS] type is larger, return it.
8312 if (LHSRank >= RHSRank)
8313 return 1;
8314
8315 // If the signed type can represent all values of the unsigned type, it
8316 // wins. Because we are dealing with 2's complement and types that are
8317 // powers of two larger than each other, this is always safe.
8318 return -1;
8319 }
8320
8321 // If the unsigned [RHS] type is larger, return it.
8322 if (RHSRank >= LHSRank)
8323 return -1;
8324
8325 // If the signed type can represent all values of the unsigned type, it
8326 // wins. Because we are dealing with 2's complement and types that are
8327 // powers of two larger than each other, this is always safe.
8328 return 1;
8329 }
8330
8331 TypedefDecl *ASTContext::getCFConstantStringDecl() const {
8332 if (CFConstantStringTypeDecl)
8333 return CFConstantStringTypeDecl;
8334
8335 assert(!CFConstantStringTagDecl &&
8336 "tag and typedef should be initialized together");
8337 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
8338 CFConstantStringTagDecl->startDefinition();
8339
8340 struct {
8341 QualType Type;
8342 const char *Name;
8343 } Fields[5];
8344 unsigned Count = 0;
8345
8346 /// Objective-C ABI
8347 ///
8348 /// typedef struct __NSConstantString_tag {
8349 /// const int *isa;
8350 /// int flags;
8351 /// const char *str;
8352 /// long length;
8353 /// } __NSConstantString;
8354 ///
8355 /// Swift ABI (4.1, 4.2)
8356 ///
8357 /// typedef struct __NSConstantString_tag {
8358 /// uintptr_t _cfisa;
8359 /// uintptr_t _swift_rc;
8360 /// _Atomic(uint64_t) _cfinfoa;
8361 /// const char *_ptr;
8362 /// uint32_t _length;
8363 /// } __NSConstantString;
8364 ///
8365 /// Swift ABI (5.0)
8366 ///
8367 /// typedef struct __NSConstantString_tag {
8368 /// uintptr_t _cfisa;
8369 /// uintptr_t _swift_rc;
8370 /// _Atomic(uint64_t) _cfinfoa;
8371 /// const char *_ptr;
8372 /// uintptr_t _length;
8373 /// } __NSConstantString;
8374
8375 const auto CFRuntime = getLangOpts().CFRuntime;
8376 if (static_cast<unsigned>(CFRuntime) <
8377 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
8378 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
8379 Fields[Count++] = { IntTy, "flags" };
8380 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
8381 Fields[Count++] = { LongTy, "length" };
8382 } else {
8383 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
8384 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
8385 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
8386 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
8387 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
8388 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
8389 Fields[Count++] = { IntTy, "_ptr" };
8390 else
8391 Fields[Count++] = { getUIntPtrType(), "_ptr" };
8392 }
8393
8394 // Create fields
8395 for (unsigned i = 0; i < Count; ++i) {
8396 FieldDecl *Field =
8397 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
8398 SourceLocation(), &Idents.get(Fields[i].Name),
8399 Fields[i].Type, /*TInfo=*/nullptr,
8400 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8401 Field->setAccess(AS_public);
8402 CFConstantStringTagDecl->addDecl(Field);
8403 }
8404
8405 CFConstantStringTagDecl->completeDefinition();
8406 // This type is designed to be compatible with NSConstantString, but cannot
8407 // use the same name, since NSConstantString is an interface.
8408 CanQualType tagType = getCanonicalTagType(CFConstantStringTagDecl);
8409 CFConstantStringTypeDecl =
8410 buildImplicitTypedef(tagType, "__NSConstantString");
8411
8412 return CFConstantStringTypeDecl;
8413 }
8414
8415 RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
8416 if (!CFConstantStringTagDecl)
8417 getCFConstantStringDecl(); // Build the tag and the typedef.
8418 return CFConstantStringTagDecl;
8419 }
8420
8421 // getCFConstantStringType - Return the type used for constant CFStrings.
8422 QualType ASTContext::getCFConstantStringType() const {
8423 return getTypedefType(ElaboratedTypeKeyword::None, /*Qualifier=*/std::nullopt,
8424 getCFConstantStringDecl());
8425 }
8426
8427 QualType ASTContext::getObjCSuperType() const {
8428 if (ObjCSuperType.isNull()) {
8429 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
8430 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
8431 ObjCSuperType = getCanonicalTagType(ObjCSuperTypeDecl);
8432 }
8433 return ObjCSuperType;
8434 }
8435
8436 void ASTContext::setCFConstantStringType(QualType T) {
8437 const auto *TT = T->castAs<TypedefType>();
8438 CFConstantStringTypeDecl = cast<TypedefDecl>(TT->getDecl());
8439 CFConstantStringTagDecl = TT->castAsRecordDecl();
8440 }
8441
8442 QualType ASTContext::getBlockDescriptorType() const {
8443 if (BlockDescriptorType)
8444 return getCanonicalTagType(BlockDescriptorType);
8445
8446 RecordDecl *RD;
8447 // FIXME: Needs the FlagAppleBlock bit.
8448 RD = buildImplicitRecord("__block_descriptor");
8449 RD->startDefinition();
8450
8451 QualType FieldTypes[] = {
8452 UnsignedLongTy,
8453 UnsignedLongTy,
8454 };
8455
8456 static const char *const FieldNames[] = {
8457 "reserved",
8458 "Size"
8459 };
8460
8461 for (size_t i = 0; i < 2; ++i) {
8462 FieldDecl *Field = FieldDecl::Create(
8463 *this, RD, SourceLocation(), SourceLocation(),
8464 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8465 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8466 Field->setAccess(AS_public);
8467 RD->addDecl(Field);
8468 }
8469
8470 RD->completeDefinition();
8471
8472 BlockDescriptorType = RD;
8473
8474 return getCanonicalTagType(BlockDescriptorType);
8475 }
8476
8477 QualType ASTContext::getBlockDescriptorExtendedType() const {
8478 if (BlockDescriptorExtendedType)
8479 return getCanonicalTagType(BlockDescriptorExtendedType);
8480
8481 RecordDecl *RD;
8482 // FIXME: Needs the FlagAppleBlock bit.
8483 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
8484 RD->startDefinition();
8485
8486 QualType FieldTypes[] = {
8487 UnsignedLongTy,
8488 UnsignedLongTy,
8489 getPointerType(VoidPtrTy),
8490 getPointerType(VoidPtrTy)
8491 };
8492
8493 static const char *const FieldNames[] = {
8494 "reserved",
8495 "Size",
8496 "CopyFuncPtr",
8497 "DestroyFuncPtr"
8498 };
8499
8500 for (size_t i = 0; i < 4; ++i) {
8501 FieldDecl *Field = FieldDecl::Create(
8502 *this, RD, SourceLocation(), SourceLocation(),
8503 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8504 /*BitWidth=*/nullptr,
8505 /*Mutable=*/false, ICIS_NoInit);
8506 Field->setAccess(AS_public);
8507 RD->addDecl(Field);
8508 }
8509
8510 RD->completeDefinition();
8511
8512 BlockDescriptorExtendedType = RD;
8513 return getCanonicalTagType(BlockDescriptorExtendedType);
8514 }
8515
8516 OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
8517 const auto *BT = dyn_cast<BuiltinType>(T);
8518
8519 if (!BT) {
8520 if (isa<PipeType>(T))
8521 return OCLTK_Pipe;
8522
8523 return OCLTK_Default;
8524 }
8525
8526 switch (BT->getKind()) {
8527 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8528 case BuiltinType::Id: \
8529 return OCLTK_Image;
8530 #include "clang/Basic/OpenCLImageTypes.def"
8531
8532 case BuiltinType::OCLClkEvent:
8533 return OCLTK_ClkEvent;
8534
8535 case BuiltinType::OCLEvent:
8536 return OCLTK_Event;
8537
8538 case BuiltinType::OCLQueue:
8539 return OCLTK_Queue;
8540
8541 case BuiltinType::OCLReserveID:
8542 return OCLTK_ReserveID;
8543
8544 case BuiltinType::OCLSampler:
8545 return OCLTK_Sampler;
8546
8547 default:
8548 return OCLTK_Default;
8549 }
8550 }
8551
8552 LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
8553 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
8554 }
8555
8556 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
8557 /// requires copy/dispose. Note that this must match the logic
8558 /// in buildByrefHelpers.
8559 bool ASTContext::BlockRequiresCopying(QualType Ty,
8560 const VarDecl *D) {
8561 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
8562 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
8563 if (!copyExpr && record->hasTrivialDestructor()) return false;
8564
8565 return true;
8566 }
8567
8568 if (Ty.hasAddressDiscriminatedPointerAuth())
8569 return true;
8570
8571 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
8572 // move or destroy.
8573 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
8574 return true;
8575
8576 if (!Ty->isObjCRetainableType()) return false;
8577
8578 Qualifiers qs = Ty.getQualifiers();
8579
8580 // If we have lifetime, that dominates.
8581 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
8582 switch (lifetime) {
8583 case Qualifiers::OCL_None: llvm_unreachable("impossible");
8584
8585 // These are just bits as far as the runtime is concerned.
8586 case Qualifiers::OCL_ExplicitNone:
8587 case Qualifiers::OCL_Autoreleasing:
8588 return false;
8589
8590 // These cases should have been taken care of when checking the type's
8591 // non-triviality.
8592 case Qualifiers::OCL_Weak:
8593 case Qualifiers::OCL_Strong:
8594 llvm_unreachable("impossible");
8595 }
8596 llvm_unreachable("fell out of lifetime switch!");
8597 }
8598 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
8599 Ty->isObjCObjectPointerType());
8600 }
8601
8602 bool ASTContext::getByrefLifetime(QualType Ty,
8603 Qualifiers::ObjCLifetime &LifeTime,
8604 bool &HasByrefExtendedLayout) const {
8605 if (!getLangOpts().ObjC ||
8606 getLangOpts().getGC() != LangOptions::NonGC)
8607 return false;
8608
8609 HasByrefExtendedLayout = false;
8610 if (Ty->isRecordType()) {
8611 HasByrefExtendedLayout = true;
8612 LifeTime = Qualifiers::OCL_None;
8613 } else if ((LifeTime = Ty.getObjCLifetime())) {
8614 // Honor the ARC qualifiers.
8615 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
8616 // The MRR rule.
8617 LifeTime = Qualifiers::OCL_ExplicitNone;
8618 } else {
8619 LifeTime = Qualifiers::OCL_None;
8620 }
8621 return true;
8622 }
8623
8624 CanQualType ASTContext::getNSUIntegerType() const {
8625 assert(Target && "Expected target to be initialized");
8626 const llvm::Triple &T = Target->getTriple();
8627 // Windows is LLP64 rather than LP64
8628 if (T.isOSWindows() && T.isArch64Bit())
8629 return UnsignedLongLongTy;
8630 return UnsignedLongTy;
8631 }
8632
8633 CanQualType ASTContext::getNSIntegerType() const {
8634 assert(Target && "Expected target to be initialized");
8635 const llvm::Triple &T = Target->getTriple();
8636 // Windows is LLP64 rather than LP64
8637 if (T.isOSWindows() && T.isArch64Bit())
8638 return LongLongTy;
8639 return LongTy;
8640 }
8641
8642 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
8643 if (!ObjCInstanceTypeDecl)
8644 ObjCInstanceTypeDecl =
8645 buildImplicitTypedef(getObjCIdType(), "instancetype");
8646 return ObjCInstanceTypeDecl;
8647 }
8648
8649 // This returns true if a type has been typedefed to BOOL:
8650 // typedef <type> BOOL;
8651 static bool isTypeTypedefedAsBOOL(QualType T) {
8652 if (const auto *TT = dyn_cast<TypedefType>(T))
8653 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
8654 return II->isStr("BOOL");
8655
8656 return false;
8657 }
8658
8659 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
8660 /// purpose.
8661 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
8662 if (!type->isIncompleteArrayType() && type->isIncompleteType())
8663 return CharUnits::Zero();
8664
8665 CharUnits sz = getTypeSizeInChars(type);
8666
8667 // Make all integer and enum types at least as large as an int
8668 if (sz.isPositive() && type->isIntegralOrEnumerationType())
8669 sz = std::max(sz, getTypeSizeInChars(IntTy));
8670 // Treat arrays as pointers, since that's how they're passed in.
8671 else if (type->isArrayType())
8672 sz = getTypeSizeInChars(VoidPtrTy);
8673 return sz;
8674 }
8675
8676 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
8677 return getTargetInfo().getCXXABI().isMicrosoft() &&
8678 VD->isStaticDataMember() &&
8679 VD->getType()->isIntegralOrEnumerationType() &&
8680 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
8681 }
8682
8683 ASTContext::InlineVariableDefinitionKind
8684 ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
8685 if (!VD->isInline())
8686 return InlineVariableDefinitionKind::None;
8687
8688 // In almost all cases, it's a weak definition.
8689 auto *First = VD->getFirstDecl();
8690 if (First->isInlineSpecified() || !First->isStaticDataMember())
8691 return InlineVariableDefinitionKind::Weak;
8692
8693 // If there's a file-context declaration in this translation unit, it's a
8694 // non-discardable definition.
8695 for (auto *D : VD->redecls())
8696 if (D->getLexicalDeclContext()->isFileContext() &&
8697 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
8698 return InlineVariableDefinitionKind::Strong;
8699
8700 // If we've not seen one yet, we don't know.
8701 return InlineVariableDefinitionKind::WeakUnknown;
8702 }
8703
8704 static std::string charUnitsToString(const CharUnits &CU) {
8705 return llvm::itostr(CU.getQuantity());
8706 }
8707
8708 /// getObjCEncodingForBlock - Return the encoded type for this block
8709 /// declaration.
8710 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
8711 std::string S;
8712
8713 const BlockDecl *Decl = Expr->getBlockDecl();
8714 QualType BlockTy =
8715 Expr->getType()->castAs<BlockPointerType>()->getPointeeType();
8716 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
8717 // Encode result type.
8718 if (getLangOpts().EncodeExtendedBlockSig)
8719 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, BlockReturnTy, S,
8720 true /*Extended*/);
8721 else
8722 getObjCEncodingForType(BlockReturnTy, S);
8723 // Compute size of all parameters.
8724 // Start with computing size of a pointer in number of bytes.
8725 // FIXME: There might(should) be a better way of doing this computation!
8726 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
8727 CharUnits ParmOffset = PtrSize;
8728 for (auto *PI : Decl->parameters()) {
8729 QualType PType = PI->getType();
8730 CharUnits sz = getObjCEncodingTypeSize(PType);
8731 if (sz.isZero())
8732 continue;
8733 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
8734 ParmOffset += sz;
8735 }
8736 // Size of the argument frame
8737 S += charUnitsToString(ParmOffset);
8738 // Block pointer and offset.
8739 S += "@?0";
8740
8741 // Argument types.
8742 ParmOffset = PtrSize;
8743 for (auto *PVDecl : Decl->parameters()) {
8744 QualType PType = PVDecl->getOriginalType();
8745 if (const auto *AT =
8746 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8747 // Use array's original type only if it has known number of
8748 // elements.
8749 if (!isa<ConstantArrayType>(AT))
8750 PType = PVDecl->getType();
8751 } else if (PType->isFunctionType())
8752 PType = PVDecl->getType();
8753 if (getLangOpts().EncodeExtendedBlockSig)
8754 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
8755 S, true /*Extended*/);
8756 else
8757 getObjCEncodingForType(PType, S);
8758 S += charUnitsToString(ParmOffset);
8759 ParmOffset += getObjCEncodingTypeSize(PType);
8760 }
8761
8762 return S;
8763 }
8764
8765 std::string
8766 ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
8767 std::string S;
8768 // Encode result type.
8769 getObjCEncodingForType(Decl->getReturnType(), S);
8770 CharUnits ParmOffset;
8771 // Compute size of all parameters.
8772 for (auto *PI : Decl->parameters()) {
8773 QualType PType = PI->getType();
8774 CharUnits sz = getObjCEncodingTypeSize(PType);
8775 if (sz.isZero())
8776 continue;
8777
8778 assert(sz.isPositive() &&
8779 "getObjCEncodingForFunctionDecl - Incomplete param type");
8780 ParmOffset += sz;
8781 }
8782 S += charUnitsToString(ParmOffset);
8783 ParmOffset = CharUnits::Zero();
8784
8785 // Argument types.
8786 for (auto *PVDecl : Decl->parameters()) {
8787 QualType PType = PVDecl->getOriginalType();
8788 if (const auto *AT =
8789 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8790 // Use array's original type only if it has known number of
8791 // elements.
8792 if (!isa<ConstantArrayType>(AT))
8793 PType = PVDecl->getType();
8794 } else if (PType->isFunctionType())
8795 PType = PVDecl->getType();
8796 getObjCEncodingForType(PType, S);
8797 S += charUnitsToString(ParmOffset);
8798 ParmOffset += getObjCEncodingTypeSize(PType);
8799 }
8800
8801 return S;
8802 }
8803
8804 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
8805 /// method parameter or return type. If Extended, include class names and
8806 /// block object types.
8807 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
8808 QualType T, std::string& S,
8809 bool Extended) const {
8810 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
8811 getObjCEncodingForTypeQualifier(QT, S);
8812 // Encode parameter type.
8813 ObjCEncOptions Options = ObjCEncOptions()
8814 .setExpandPointedToStructures()
8815 .setExpandStructures()
8816 .setIsOutermostType();
8817 if (Extended)
8818 Options.setEncodeBlockParameters().setEncodeClassNames();
8819 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
8820 }
8821
8822 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
8823 /// declaration.
8824 std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
8825 bool Extended) const {
8826 // FIXME: This is not very efficient.
8827 // Encode return type.
8828 std::string S;
8829 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
8830 Decl->getReturnType(), S, Extended);
8831 // Compute size of all parameters.
8832 // Start with computing size of a pointer in number of bytes.
8833 // FIXME: There might(should) be a better way of doing this computation!
8834 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
8835 // The first two arguments (self and _cmd) are pointers; account for
8836 // their size.
8837 CharUnits ParmOffset = 2 * PtrSize;
8838 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8839 E = Decl->sel_param_end(); PI != E; ++PI) {
8840 QualType PType = (*PI)->getType();
8841 CharUnits sz = getObjCEncodingTypeSize(PType);
8842 if (sz.isZero())
8843 continue;
8844
8845 assert(sz.isPositive() &&
8846 "getObjCEncodingForMethodDecl - Incomplete param type");
8847 ParmOffset += sz;
8848 }
8849 S += charUnitsToString(ParmOffset);
8850 S += "@0:";
8851 S += charUnitsToString(PtrSize);
8852
8853 // Argument types.
8854 ParmOffset = 2 * PtrSize;
8855 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8856 E = Decl->sel_param_end(); PI != E; ++PI) {
8857 const ParmVarDecl *PVDecl = *PI;
8858 QualType PType = PVDecl->getOriginalType();
8859 if (const auto *AT =
8860 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8861 // Use array's original type only if it has known number of
8862 // elements.
8863 if (!isa<ConstantArrayType>(AT))
8864 PType = PVDecl->getType();
8865 } else if (PType->isFunctionType())
8866 PType = PVDecl->getType();
8867 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
8868 PType, S, Extended);
8869 S += charUnitsToString(ParmOffset);
8870 ParmOffset += getObjCEncodingTypeSize(PType);
8871 }
8872
8873 return S;
8874 }
8875
8876 ObjCPropertyImplDecl *
8877 ASTContext::getObjCPropertyImplDeclForPropertyDecl(
8878 const ObjCPropertyDecl *PD,
8879 const Decl *Container) const {
8880 if (!Container)
8881 return nullptr;
8882 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
8883 for (auto *PID : CID->property_impls())
8884 if (PID->getPropertyDecl() == PD)
8885 return PID;
8886 } else {
8887 const auto *OID = cast<ObjCImplementationDecl>(Container);
8888 for (auto *PID : OID->property_impls())
8889 if (PID->getPropertyDecl() == PD)
8890 return PID;
8891 }
8892 return nullptr;
8893 }
8894
8895 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
8896 /// property declaration. If non-NULL, Container must be either an
8897 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
8898 /// NULL when getting encodings for protocol properties.
8899 /// Property attributes are stored as a comma-delimited C string. The simple
8900 /// attributes readonly and bycopy are encoded as single characters. The
8901 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
8902 /// encoded as single characters, followed by an identifier. Property types
8903 /// are also encoded as a parametrized attribute. The characters used to encode
8904 /// these attributes are defined by the following enumeration:
8905 /// @code
8906 /// enum PropertyAttributes {
8907 /// kPropertyReadOnly = 'R', // property is read-only.
8908 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned
8909 /// kPropertyByref = '&', // property is a reference to the value last assigned
8910 /// kPropertyDynamic = 'D', // property is dynamic
8911 /// kPropertyGetter = 'G', // followed by getter selector name
8912 /// kPropertySetter = 'S', // followed by setter selector name
8913 /// kPropertyInstanceVariable = 'V' // followed by instance variable name
8914 /// kPropertyType = 'T' // followed by old-style type encoding.
8915 /// kPropertyWeak = 'W' // 'weak' property
8916 /// kPropertyStrong = 'P' // property GC'able
8917 /// kPropertyNonAtomic = 'N' // property non-atomic
8918 /// kPropertyOptional = '?' // property optional
8919 /// };
8920 /// @endcode
8921 std::string
8922 ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
8923 const Decl *Container) const {
8924 // Collect information from the property implementation decl(s).
8925 bool Dynamic = false;
8926 ObjCPropertyImplDecl *SynthesizePID = nullptr;
8927
8928 if (ObjCPropertyImplDecl *PropertyImpDecl =
8929 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
8930 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
8931 Dynamic = true;
8932 else
8933 SynthesizePID = PropertyImpDecl;
8934 }
8935
8936 // FIXME: This is not very efficient.
8937 std::string S = "T";
8938
8939 // Encode result type.
8940 // GCC has some special rules regarding encoding of properties which
8941 // closely resembles encoding of ivars.
8942 getObjCEncodingForPropertyType(PD->getType(), S);
8943
8944 if (PD->isOptional())
8945 S += ",?";
8946
8947 if (PD->isReadOnly()) {
8948 S += ",R";
8949 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy)
8950 S += ",C";
8951 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain)
8952 S += ",&";
8953 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak)
8954 S += ",W";
8955 } else {
8956 switch (PD->getSetterKind()) {
8957 case ObjCPropertyDecl::Assign: break;
8958 case ObjCPropertyDecl::Copy: S += ",C"; break;
8959 case ObjCPropertyDecl::Retain: S += ",&"; break;
8960 case ObjCPropertyDecl::Weak: S += ",W"; break;
8961 }
8962 }
8963
8964 // It really isn't clear at all what this means, since properties
8965 // are "dynamic by default".
8966 if (Dynamic)
8967 S += ",D";
8968
8969 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_nonatomic)
8970 S += ",N";
8971
8972 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) {
8973 S += ",G";
8974 S += PD->getGetterName().getAsString();
8975 }
8976
8977 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) {
8978 S += ",S";
8979 S += PD->getSetterName().getAsString();
8980 }
8981
8982 if (SynthesizePID) {
8983 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
8984 S += ",V";
8985 S += OID->getNameAsString();
8986 }
8987
8988 // FIXME: OBJCGC: weak & strong
8989 return S;
8990 }
8991
8992 /// getLegacyIntegralTypeEncoding -
8993 /// Another legacy compatibility encoding: 32-bit longs are encoded as
8994 /// 'l' or 'L' , but not always. For typedefs, we need to use
8995 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
8996 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
8997 if (PointeeTy->getAs<TypedefType>()) {
8998 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
8999 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
9000 PointeeTy = UnsignedIntTy;
9001 else
9002 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
9003 PointeeTy = IntTy;
9004 }
9005 }
9006 }
9007
9008 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
9009 const FieldDecl *Field,
9010 QualType *NotEncodedT) const {
9011 // We follow the behavior of gcc, expanding structures which are
9012 // directly pointed to, and expanding embedded structures. Note that
9013 // these rules are sufficient to prevent recursive encoding of the
9014 // same type.
9015 getObjCEncodingForTypeImpl(T, S,
9016 ObjCEncOptions()
9017 .setExpandPointedToStructures()
9018 .setExpandStructures()
9019 .setIsOutermostType(),
9020 Field, NotEncodedT);
9021 }
9022
9023 void ASTContext::getObjCEncodingForPropertyType(QualType T,
9024 std::string& S) const {
9025 // Encode result type.
9026 // GCC has some special rules regarding encoding of properties which
9027 // closely resembles encoding of ivars.
9028 getObjCEncodingForTypeImpl(T, S,
9029 ObjCEncOptions()
9030 .setExpandPointedToStructures()
9031 .setExpandStructures()
9032 .setIsOutermostType()
9033 .setEncodingProperty(),
9034 /*Field=*/nullptr);
9035 }
9036
9037 static char getObjCEncodingForPrimitiveType(const ASTContext *C,
9038 const BuiltinType *BT) {
9039 BuiltinType::Kind kind = BT->getKind();
9040 switch (kind) {
9041 case BuiltinType::Void: return 'v';
9042 case BuiltinType::Bool: return 'B';
9043 case BuiltinType::Char8:
9044 case BuiltinType::Char_U:
9045 case BuiltinType::UChar: return 'C';
9046 case BuiltinType::Char16:
9047 case BuiltinType::UShort: return 'S';
9048 case BuiltinType::Char32:
9049 case BuiltinType::UInt: return 'I';
9050 case BuiltinType::ULong:
9051 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
9052 case BuiltinType::UInt128: return 'T';
9053 case BuiltinType::ULongLong: return 'Q';
9054 case BuiltinType::Char_S:
9055 case BuiltinType::SChar: return 'c';
9056 case BuiltinType::Short: return 's';
9057 case BuiltinType::WChar_S:
9058 case BuiltinType::WChar_U:
9059 case BuiltinType::Int: return 'i';
9060 case BuiltinType::Long:
9061 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
9062 case BuiltinType::LongLong: return 'q';
9063 case BuiltinType::Int128: return 't';
9064 case BuiltinType::Float: return 'f';
9065 case BuiltinType::Double: return 'd';
9066 case BuiltinType::LongDouble: return 'D';
9067 case BuiltinType::NullPtr: return '*'; // like char*
9068
9069 case BuiltinType::BFloat16:
9070 case BuiltinType::Float16:
9071 case BuiltinType::Float128:
9072 case BuiltinType::Ibm128:
9073 case BuiltinType::Half:
9074 case BuiltinType::ShortAccum:
9075 case BuiltinType::Accum:
9076 case BuiltinType::LongAccum:
9077 case BuiltinType::UShortAccum:
9078 case BuiltinType::UAccum:
9079 case BuiltinType::ULongAccum:
9080 case BuiltinType::ShortFract:
9081 case BuiltinType::Fract:
9082 case BuiltinType::LongFract:
9083 case BuiltinType::UShortFract:
9084 case BuiltinType::UFract:
9085 case BuiltinType::ULongFract:
9086 case BuiltinType::SatShortAccum:
9087 case BuiltinType::SatAccum:
9088 case BuiltinType::SatLongAccum:
9089 case BuiltinType::SatUShortAccum:
9090 case BuiltinType::SatUAccum:
9091 case BuiltinType::SatULongAccum:
9092 case BuiltinType::SatShortFract:
9093 case BuiltinType::SatFract:
9094 case BuiltinType::SatLongFract:
9095 case BuiltinType::SatUShortFract:
9096 case BuiltinType::SatUFract:
9097 case BuiltinType::SatULongFract:
9098 // FIXME: potentially need @encodes for these!
9099 return ' ';
9100
9101 #define SVE_TYPE(Name, Id, SingletonId) \
9102 case BuiltinType::Id:
9103 #include "clang/Basic/AArch64ACLETypes.def"
9104 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9105 #include "clang/Basic/RISCVVTypes.def"
9106 #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9107 #include "clang/Basic/WebAssemblyReferenceTypes.def"
9108 #define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
9109 #include "clang/Basic/AMDGPUTypes.def"
9110 {
9111 DiagnosticsEngine &Diags = C->getDiagnostics();
9112 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
9113 "cannot yet @encode type %0");
9114 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
9115 return ' ';
9116 }
9117
9118 case BuiltinType::ObjCId:
9119 case BuiltinType::ObjCClass:
9120 case BuiltinType::ObjCSel:
9121 llvm_unreachable("@encoding ObjC primitive type");
9122
9123 // OpenCL and placeholder types don't need @encodings.
9124 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
9125 case BuiltinType::Id:
9126 #include "clang/Basic/OpenCLImageTypes.def"
9127 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9128 case BuiltinType::Id:
9129 #include "clang/Basic/OpenCLExtensionTypes.def"
9130 case BuiltinType::OCLEvent:
9131 case BuiltinType::OCLClkEvent:
9132 case BuiltinType::OCLQueue:
9133 case BuiltinType::OCLReserveID:
9134 case BuiltinType::OCLSampler:
9135 case BuiltinType::Dependent:
9136 #define PPC_VECTOR_TYPE(Name, Id, Size) \
9137 case BuiltinType::Id:
9138 #include "clang/Basic/PPCTypes.def"
9139 #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9140 #include "clang/Basic/HLSLIntangibleTypes.def"
9141 #define BUILTIN_TYPE(KIND, ID)
9142 #define PLACEHOLDER_TYPE(KIND, ID) \
9143 case BuiltinType::KIND:
9144 #include "clang/AST/BuiltinTypes.def"
9145 llvm_unreachable("invalid builtin type for @encode");
9146 }
9147 llvm_unreachable("invalid BuiltinType::Kind value");
9148 }
9149
9150 static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED) {
9151 EnumDecl *Enum = ED->getDefinitionOrSelf();
9152
9153 // The encoding of an non-fixed enum type is always 'i', regardless of size.
9154 if (!Enum->isFixed())
9155 return 'i';
9156
9157 // The encoding of a fixed enum type matches its fixed underlying type.
9158 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
9159 return getObjCEncodingForPrimitiveType(C, BT);
9160 }
9161
9162 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
9163 QualType T, const FieldDecl *FD) {
9164 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
9165 S += 'b';
9166 // The NeXT runtime encodes bit fields as b followed by the number of bits.
9167 // The GNU runtime requires more information; bitfields are encoded as b,
9168 // then the offset (in bits) of the first element, then the type of the
9169 // bitfield, then the size in bits. For example, in this structure:
9170 //
9171 // struct
9172 // {
9173 // int integer;
9174 // int flags:2;
9175 // };
9176 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
9177 // runtime, but b32i2 for the GNU runtime. The reason for this extra
9178 // information is not especially sensible, but we're stuck with it for
9179 // compatibility with GCC, although providing it breaks anything that
9180 // actually uses runtime introspection and wants to work on both runtimes...
9181 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
9182 uint64_t Offset;
9183
9184 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
9185 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), IVD);
9186 } else {
9187 const RecordDecl *RD = FD->getParent();
9188 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
9189 Offset = RL.getFieldOffset(FD->getFieldIndex());
9190 }
9191
9192 S += llvm::utostr(Offset);
9193
9194 if (const auto *ET = T->getAsCanonical<EnumType>())
9195 S += ObjCEncodingForEnumDecl(Ctx, ET->getDecl());
9196 else {
9197 const auto *BT = T->castAs<BuiltinType>();
9198 S += getObjCEncodingForPrimitiveType(Ctx, BT);
9199 }
9200 }
9201 S += llvm::utostr(FD->getBitWidthValue());
9202 }
9203
9204 // Helper function for determining whether the encoded type string would include
9205 // a template specialization type.
9206 static bool hasTemplateSpecializationInEncodedString(const Type *T,
9207 bool VisitBasesAndFields) {
9208 T = T->getBaseElementTypeUnsafe();
9209
9210 if (auto *PT = T->getAs<PointerType>())
9211 return hasTemplateSpecializationInEncodedString(
9212 PT->getPointeeType().getTypePtr(), false);
9213
9214 auto *CXXRD = T->getAsCXXRecordDecl();
9215
9216 if (!CXXRD)
9217 return false;
9218
9219 if (isa<ClassTemplateSpecializationDecl>(CXXRD))
9220 return true;
9221
9222 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
9223 return false;
9224
9225 for (const auto &B : CXXRD->bases())
9226 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
9227 true))
9228 return true;
9229
9230 for (auto *FD : CXXRD->fields())
9231 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
9232 true))
9233 return true;
9234
9235 return false;
9236 }
9237
9238 // FIXME: Use SmallString for accumulating string.
9239 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
9240 const ObjCEncOptions Options,
9241 const FieldDecl *FD,
9242 QualType *NotEncodedT) const {
9243 CanQualType CT = getCanonicalType(T);
9244 switch (CT->getTypeClass()) {
9245 case Type::Builtin:
9246 case Type::Enum:
9247 if (FD && FD->isBitField())
9248 return EncodeBitField(this, S, T, FD);
9249 if (const auto *BT = dyn_cast<BuiltinType>(CT))
9250 S += getObjCEncodingForPrimitiveType(this, BT);
9251 else
9252 S += ObjCEncodingForEnumDecl(this, cast<EnumType>(CT)->getDecl());
9253 return;
9254
9255 case Type::Complex:
9256 S += 'j';
9257 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
9258 ObjCEncOptions(),
9259 /*Field=*/nullptr);
9260 return;
9261
9262 case Type::Atomic:
9263 S += 'A';
9264 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
9265 ObjCEncOptions(),
9266 /*Field=*/nullptr);
9267 return;
9268
9269 // encoding for pointer or reference types.
9270 case Type::Pointer:
9271 case Type::LValueReference:
9272 case Type::RValueReference: {
9273 QualType PointeeTy;
9274 if (isa<PointerType>(CT)) {
9275 const auto *PT = T->castAs<PointerType>();
9276 if (PT->isObjCSelType()) {
9277 S += ':';
9278 return;
9279 }
9280 PointeeTy = PT->getPointeeType();
9281 } else {
9282 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
9283 }
9284
9285 bool isReadOnly = false;
9286 // For historical/compatibility reasons, the read-only qualifier of the
9287 // pointee gets emitted _before_ the '^'. The read-only qualifier of
9288 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
9289 // Also, do not emit the 'r' for anything but the outermost type!
9290 if (T->getAs<TypedefType>()) {
9291 if (Options.IsOutermostType() && T.isConstQualified()) {
9292 isReadOnly = true;
9293 S += 'r';
9294 }
9295 } else if (Options.IsOutermostType()) {
9296 QualType P = PointeeTy;
9297 while (auto PT = P->getAs<PointerType>())
9298 P = PT->getPointeeType();
9299 if (P.isConstQualified()) {
9300 isReadOnly = true;
9301 S += 'r';
9302 }
9303 }
9304 if (isReadOnly) {
9305 // Another legacy compatibility encoding. Some ObjC qualifier and type
9306 // combinations need to be rearranged.
9307 // Rewrite "in const" from "nr" to "rn"
9308 if (StringRef(S).ends_with("nr"))
9309 S.replace(S.end()-2, S.end(), "rn");
9310 }
9311
9312 if (PointeeTy->isCharType()) {
9313 // char pointer types should be encoded as '*' unless it is a
9314 // type that has been typedef'd to 'BOOL'.
9315 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
9316 S += '*';
9317 return;
9318 }
9319 } else if (const auto *RTy = PointeeTy->getAsCanonical<RecordType>()) {
9320 const IdentifierInfo *II = RTy->getDecl()->getIdentifier();
9321 // GCC binary compat: Need to convert "struct objc_class *" to "#".
9322 if (II == &Idents.get("objc_class")) {
9323 S += '#';
9324 return;
9325 }
9326 // GCC binary compat: Need to convert "struct objc_object *" to "@".
9327 if (II == &Idents.get("objc_object")) {
9328 S += '@';
9329 return;
9330 }
9331 // If the encoded string for the class includes template names, just emit
9332 // "^v" for pointers to the class.
9333 if (getLangOpts().CPlusPlus &&
9334 (!getLangOpts().EncodeCXXClassTemplateSpec &&
9335 hasTemplateSpecializationInEncodedString(
9336 RTy, Options.ExpandPointedToStructures()))) {
9337 S += "^v";
9338 return;
9339 }
9340 // fall through...
9341 }
9342 S += '^';
9343 getLegacyIntegralTypeEncoding(PointeeTy);
9344
9345 ObjCEncOptions NewOptions;
9346 if (Options.ExpandPointedToStructures())
9347 NewOptions.setExpandStructures();
9348 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
9349 /*Field=*/nullptr, NotEncodedT);
9350 return;
9351 }
9352
9353 case Type::ConstantArray:
9354 case Type::IncompleteArray:
9355 case Type::VariableArray: {
9356 const auto *AT = cast<ArrayType>(CT);
9357
9358 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
9359 // Incomplete arrays are encoded as a pointer to the array element.
9360 S += '^';
9361
9362 getObjCEncodingForTypeImpl(
9363 AT->getElementType(), S,
9364 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
9365 } else {
9366 S += '[';
9367
9368 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
9369 S += llvm::utostr(CAT->getZExtSize());
9370 else {
9371 //Variable length arrays are encoded as a regular array with 0 elements.
9372 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
9373 "Unknown array type!");
9374 S += '0';
9375 }
9376
9377 getObjCEncodingForTypeImpl(
9378 AT->getElementType(), S,
9379 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
9380 NotEncodedT);
9381 S += ']';
9382 }
9383 return;
9384 }
9385
9386 case Type::FunctionNoProto:
9387 case Type::FunctionProto:
9388 S += '?';
9389 return;
9390
9391 case Type::Record: {
9392 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
9393 S += RDecl->isUnion() ? '(' : '{';
9394 // Anonymous structures print as '?'
9395 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
9396 S += II->getName();
9397 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
9398 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
9399 llvm::raw_string_ostream OS(S);
9400 printTemplateArgumentList(OS, TemplateArgs.asArray(),
9401 getPrintingPolicy());
9402 }
9403 } else {
9404 S += '?';
9405 }
9406 if (Options.ExpandStructures()) {
9407 S += '=';
9408 if (!RDecl->isUnion()) {
9409 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
9410 } else {
9411 for (const auto *Field : RDecl->fields()) {
9412 if (FD) {
9413 S += '"';
9414 S += Field->getNameAsString();
9415 S += '"';
9416 }
9417
9418 // Special case bit-fields.
9419 if (Field->isBitField()) {
9420 getObjCEncodingForTypeImpl(Field->getType(), S,
9421 ObjCEncOptions().setExpandStructures(),
9422 Field);
9423 } else {
9424 QualType qt = Field->getType();
9425 getLegacyIntegralTypeEncoding(qt);
9426 getObjCEncodingForTypeImpl(
9427 qt, S,
9428 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
9429 NotEncodedT);
9430 }
9431 }
9432 }
9433 }
9434 S += RDecl->isUnion() ? ')' : '}';
9435 return;
9436 }
9437
9438 case Type::BlockPointer: {
9439 const auto *BT = T->castAs<BlockPointerType>();
9440 S += "@?"; // Unlike a pointer-to-function, which is "^?".
9441 if (Options.EncodeBlockParameters()) {
9442 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
9443
9444 S += '<';
9445 // Block return type
9446 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
9447 Options.forComponentType(), FD, NotEncodedT);
9448 // Block self
9449 S += "@?";
9450 // Block parameters
9451 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
9452 for (const auto &I : FPT->param_types())
9453 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
9454 NotEncodedT);
9455 }
9456 S += '>';
9457 }
9458 return;
9459 }
9460
9461 case Type::ObjCObject: {
9462 // hack to match legacy encoding of *id and *Class
9463 QualType Ty = getObjCObjectPointerType(CT);
9464 if (Ty->isObjCIdType()) {
9465 S += "{objc_object=}";
9466 return;
9467 }
9468 else if (Ty->isObjCClassType()) {
9469 S += "{objc_class=}";
9470 return;
9471 }
9472 // TODO: Double check to make sure this intentionally falls through.
9473 [[fallthrough]];
9474 }
9475
9476 case Type::ObjCInterface: {
9477 // Ignore protocol qualifiers when mangling at this level.
9478 // @encode(class_name)
9479 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
9480 S += '{';
9481 S += OI->getObjCRuntimeNameAsString();
9482 if (Options.ExpandStructures()) {
9483 S += '=';
9484 SmallVector<const ObjCIvarDecl*, 32> Ivars;
9485 DeepCollectObjCIvars(OI, true, Ivars);
9486 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
9487 const FieldDecl *Field = Ivars[i];
9488 if (Field->isBitField())
9489 getObjCEncodingForTypeImpl(Field->getType(), S,
9490 ObjCEncOptions().setExpandStructures(),
9491 Field);
9492 else
9493 getObjCEncodingForTypeImpl(Field->getType(), S,
9494 ObjCEncOptions().setExpandStructures(), FD,
9495 NotEncodedT);
9496 }
9497 }
9498 S += '}';
9499 return;
9500 }
9501
9502 case Type::ObjCObjectPointer: {
9503 const auto *OPT = T->castAs<ObjCObjectPointerType>();
9504 if (OPT->isObjCIdType()) {
9505 S += '@';
9506 return;
9507 }
9508
9509 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
9510 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
9511 // Since this is a binary compatibility issue, need to consult with
9512 // runtime folks. Fortunately, this is a *very* obscure construct.
9513 S += '#';
9514 return;
9515 }
9516
9517 if (OPT->isObjCQualifiedIdType()) {
9518 getObjCEncodingForTypeImpl(
9519 getObjCIdType(), S,
9520 Options.keepingOnly(ObjCEncOptions()
9521 .setExpandPointedToStructures()
9522 .setExpandStructures()),
9523 FD);
9524 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
9525 // Note that we do extended encoding of protocol qualifier list
9526 // Only when doing ivar or property encoding.
9527 S += '"';
9528 for (const auto *I : OPT->quals()) {
9529 S += '<';
9530 S += I->getObjCRuntimeNameAsString();
9531 S += '>';
9532 }
9533 S += '"';
9534 }
9535 return;
9536 }
9537
9538 S += '@';
9539 if (OPT->getInterfaceDecl() &&
9540 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
9541 S += '"';
9542 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
9543 for (const auto *I : OPT->quals()) {
9544 S += '<';
9545 S += I->getObjCRuntimeNameAsString();
9546 S += '>';
9547 }
9548 S += '"';
9549 }
9550 return;
9551 }
9552
9553 // gcc just blithely ignores member pointers.
9554 // FIXME: we should do better than that. 'M' is available.
9555 case Type::MemberPointer:
9556 // This matches gcc's encoding, even though technically it is insufficient.
9557 //FIXME. We should do a better job than gcc.
9558 case Type::Vector:
9559 case Type::ExtVector:
9560 // Until we have a coherent encoding of these three types, issue warning.
9561 if (NotEncodedT)
9562 *NotEncodedT = T;
9563 return;
9564
9565 case Type::ConstantMatrix:
9566 if (NotEncodedT)
9567 *NotEncodedT = T;
9568 return;
9569
9570 case Type::BitInt:
9571 if (NotEncodedT)
9572 *NotEncodedT = T;
9573 return;
9574
9575 // We could see an undeduced auto type here during error recovery.
9576 // Just ignore it.
9577 case Type::Auto:
9578 case Type::DeducedTemplateSpecialization:
9579 return;
9580
9581 case Type::HLSLAttributedResource:
9582 case Type::HLSLInlineSpirv:
9583 llvm_unreachable("unexpected type");
9584
9585 case Type::ArrayParameter:
9586 case Type::Pipe:
9587 #define ABSTRACT_TYPE(KIND, BASE)
9588 #define TYPE(KIND, BASE)
9589 #define DEPENDENT_TYPE(KIND, BASE) \
9590 case Type::KIND:
9591 #define NON_CANONICAL_TYPE(KIND, BASE) \
9592 case Type::KIND:
9593 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
9594 case Type::KIND:
9595 #include "clang/AST/TypeNodes.inc"
9596 llvm_unreachable("@encode for dependent type!");
9597 }
9598 llvm_unreachable("bad type kind!");
9599 }
9600
9601 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
9602 std::string &S,
9603 const FieldDecl *FD,
9604 bool includeVBases,
9605 QualType *NotEncodedT) const {
9606 assert(RDecl && "Expected non-null RecordDecl");
9607 assert(!RDecl->isUnion() && "Should not be called for unions");
9608 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
9609 return;
9610
9611 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
9612 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
9613 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
9614
9615 if (CXXRec) {
9616 for (const auto &BI : CXXRec->bases()) {
9617 if (!BI.isVirtual()) {
9618 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9619 if (base->isEmpty())
9620 continue;
9621 uint64_t offs = toBits(layout.getBaseClassOffset(base));
9622 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9623 std::make_pair(offs, base));
9624 }
9625 }
9626 }
9627
9628 for (FieldDecl *Field : RDecl->fields()) {
9629 if (!Field->isZeroLengthBitField() && Field->isZeroSize(*this))
9630 continue;
9631 uint64_t offs = layout.getFieldOffset(Field->getFieldIndex());
9632 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9633 std::make_pair(offs, Field));
9634 }
9635
9636 if (CXXRec && includeVBases) {
9637 for (const auto &BI : CXXRec->vbases()) {
9638 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9639 if (base->isEmpty())
9640 continue;
9641 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
9642 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
9643 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
9644 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
9645 std::make_pair(offs, base));
9646 }
9647 }
9648
9649 CharUnits size;
9650 if (CXXRec) {
9651 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
9652 } else {
9653 size = layout.getSize();
9654 }
9655
9656 #ifndef NDEBUG
9657 uint64_t CurOffs = 0;
9658 #endif
9659 std::multimap<uint64_t, NamedDecl *>::iterator
9660 CurLayObj = FieldOrBaseOffsets.begin();
9661
9662 if (CXXRec && CXXRec->isDynamicClass() &&
9663 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
9664 if (FD) {
9665 S += "\"_vptr$";
9666 std::string recname = CXXRec->getNameAsString();
9667 if (recname.empty()) recname = "?";
9668 S += recname;
9669 S += '"';
9670 }
9671 S += "^^?";
9672 #ifndef NDEBUG
9673 CurOffs += getTypeSize(VoidPtrTy);
9674 #endif
9675 }
9676
9677 if (!RDecl->hasFlexibleArrayMember()) {
9678 // Mark the end of the structure.
9679 uint64_t offs = toBits(size);
9680 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9681 std::make_pair(offs, nullptr));
9682 }
9683
9684 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
9685 #ifndef NDEBUG
9686 assert(CurOffs <= CurLayObj->first);
9687 if (CurOffs < CurLayObj->first) {
9688 uint64_t padding = CurLayObj->first - CurOffs;
9689 // FIXME: There doesn't seem to be a way to indicate in the encoding that
9690 // packing/alignment of members is different that normal, in which case
9691 // the encoding will be out-of-sync with the real layout.
9692 // If the runtime switches to just consider the size of types without
9693 // taking into account alignment, we could make padding explicit in the
9694 // encoding (e.g. using arrays of chars). The encoding strings would be
9695 // longer then though.
9696 CurOffs += padding;
9697 }
9698 #endif
9699
9700 NamedDecl *dcl = CurLayObj->second;
9701 if (!dcl)
9702 break; // reached end of structure.
9703
9704 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
9705 // We expand the bases without their virtual bases since those are going
9706 // in the initial structure. Note that this differs from gcc which
9707 // expands virtual bases each time one is encountered in the hierarchy,
9708 // making the encoding type bigger than it really is.
9709 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
9710 NotEncodedT);
9711 assert(!base->isEmpty());
9712 #ifndef NDEBUG
9713 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
9714 #endif
9715 } else {
9716 const auto *field = cast<FieldDecl>(dcl);
9717 if (FD) {
9718 S += '"';
9719 S += field->getNameAsString();
9720 S += '"';
9721 }
9722
9723 if (field->isBitField()) {
9724 EncodeBitField(this, S, field->getType(), field);
9725 #ifndef NDEBUG
9726 CurOffs += field->getBitWidthValue();
9727 #endif
9728 } else {
9729 QualType qt = field->getType();
9730 getLegacyIntegralTypeEncoding(qt);
9731 getObjCEncodingForTypeImpl(
9732 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
9733 FD, NotEncodedT);
9734 #ifndef NDEBUG
9735 CurOffs += getTypeSize(field->getType());
9736 #endif
9737 }
9738 }
9739 }
9740 }
9741
9742 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
9743 std::string& S) const {
9744 if (QT & Decl::OBJC_TQ_In)
9745 S += 'n';
9746 if (QT & Decl::OBJC_TQ_Inout)
9747 S += 'N';
9748 if (QT & Decl::OBJC_TQ_Out)
9749 S += 'o';
9750 if (QT & Decl::OBJC_TQ_Bycopy)
9751 S += 'O';
9752 if (QT & Decl::OBJC_TQ_Byref)
9753 S += 'R';
9754 if (QT & Decl::OBJC_TQ_Oneway)
9755 S += 'V';
9756 }
9757
9758 TypedefDecl *ASTContext::getObjCIdDecl() const {
9759 if (!ObjCIdDecl) {
9760 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
9761 T = getObjCObjectPointerType(T);
9762 ObjCIdDecl = buildImplicitTypedef(T, "id");
9763 }
9764 return ObjCIdDecl;
9765 }
9766
9767 TypedefDecl *ASTContext::getObjCSelDecl() const {
9768 if (!ObjCSelDecl) {
9769 QualType T = getPointerType(ObjCBuiltinSelTy);
9770 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
9771 }
9772 return ObjCSelDecl;
9773 }
9774
9775 TypedefDecl *ASTContext::getObjCClassDecl() const {
9776 if (!ObjCClassDecl) {
9777 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
9778 T = getObjCObjectPointerType(T);
9779 ObjCClassDecl = buildImplicitTypedef(T, "Class");
9780 }
9781 return ObjCClassDecl;
9782 }
9783
9784 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
9785 if (!ObjCProtocolClassDecl) {
9786 ObjCProtocolClassDecl
9787 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
9788 SourceLocation(),
9789 &Idents.get("Protocol"),
9790 /*typeParamList=*/nullptr,
9791 /*PrevDecl=*/nullptr,
9792 SourceLocation(), true);
9793 }
9794
9795 return ObjCProtocolClassDecl;
9796 }
9797
9798 PointerAuthQualifier ASTContext::getObjCMemberSelTypePtrAuth() {
9799 if (!getLangOpts().PointerAuthObjcInterfaceSel)
9800 return PointerAuthQualifier();
9801 return PointerAuthQualifier::Create(
9802 getLangOpts().PointerAuthObjcInterfaceSelKey,
9803 /*isAddressDiscriminated=*/true, SelPointerConstantDiscriminator,
9804 PointerAuthenticationMode::SignAndAuth,
9805 /*isIsaPointer=*/false,
9806 /*authenticatesNullValues=*/false);
9807 }
9808
9809 //===----------------------------------------------------------------------===//
9810 // __builtin_va_list Construction Functions
9811 //===----------------------------------------------------------------------===//
9812
9813 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
9814 StringRef Name) {
9815 // typedef char* __builtin[_ms]_va_list;
9816 QualType T = Context->getPointerType(Context->CharTy);
9817 return Context->buildImplicitTypedef(T, Name);
9818 }
9819
9820 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
9821 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
9822 }
9823
9824 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
9825 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
9826 }
9827
9828 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
9829 // typedef void* __builtin_va_list;
9830 QualType T = Context->getPointerType(Context->VoidTy);
9831 return Context->buildImplicitTypedef(T, "__builtin_va_list");
9832 }
9833
9834 static TypedefDecl *
9835 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
9836 // struct __va_list
9837 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
9838 if (Context->getLangOpts().CPlusPlus) {
9839 // namespace std { struct __va_list {
9840 auto *NS = NamespaceDecl::Create(
9841 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
9842 /*Inline=*/false, SourceLocation(), SourceLocation(),
9843 &Context->Idents.get("std"),
9844 /*PrevDecl=*/nullptr, /*Nested=*/false);
9845 NS->setImplicit();
9846 VaListTagDecl->setDeclContext(NS);
9847 }
9848
9849 VaListTagDecl->startDefinition();
9850
9851 const size_t NumFields = 5;
9852 QualType FieldTypes[NumFields];
9853 const char *FieldNames[NumFields];
9854
9855 // void *__stack;
9856 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
9857 FieldNames[0] = "__stack";
9858
9859 // void *__gr_top;
9860 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
9861 FieldNames[1] = "__gr_top";
9862
9863 // void *__vr_top;
9864 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9865 FieldNames[2] = "__vr_top";
9866
9867 // int __gr_offs;
9868 FieldTypes[3] = Context->IntTy;
9869 FieldNames[3] = "__gr_offs";
9870
9871 // int __vr_offs;
9872 FieldTypes[4] = Context->IntTy;
9873 FieldNames[4] = "__vr_offs";
9874
9875 // Create fields
9876 for (unsigned i = 0; i < NumFields; ++i) {
9877 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9878 VaListTagDecl,
9879 SourceLocation(),
9880 SourceLocation(),
9881 &Context->Idents.get(FieldNames[i]),
9882 FieldTypes[i], /*TInfo=*/nullptr,
9883 /*BitWidth=*/nullptr,
9884 /*Mutable=*/false,
9885 ICIS_NoInit);
9886 Field->setAccess(AS_public);
9887 VaListTagDecl->addDecl(Field);
9888 }
9889 VaListTagDecl->completeDefinition();
9890 Context->VaListTagDecl = VaListTagDecl;
9891 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
9892
9893 // } __builtin_va_list;
9894 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
9895 }
9896
9897 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
9898 // typedef struct __va_list_tag {
9899 RecordDecl *VaListTagDecl;
9900
9901 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9902 VaListTagDecl->startDefinition();
9903
9904 const size_t NumFields = 5;
9905 QualType FieldTypes[NumFields];
9906 const char *FieldNames[NumFields];
9907
9908 // unsigned char gpr;
9909 FieldTypes[0] = Context->UnsignedCharTy;
9910 FieldNames[0] = "gpr";
9911
9912 // unsigned char fpr;
9913 FieldTypes[1] = Context->UnsignedCharTy;
9914 FieldNames[1] = "fpr";
9915
9916 // unsigned short reserved;
9917 FieldTypes[2] = Context->UnsignedShortTy;
9918 FieldNames[2] = "reserved";
9919
9920 // void* overflow_arg_area;
9921 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
9922 FieldNames[3] = "overflow_arg_area";
9923
9924 // void* reg_save_area;
9925 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
9926 FieldNames[4] = "reg_save_area";
9927
9928 // Create fields
9929 for (unsigned i = 0; i < NumFields; ++i) {
9930 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
9931 SourceLocation(),
9932 SourceLocation(),
9933 &Context->Idents.get(FieldNames[i]),
9934 FieldTypes[i], /*TInfo=*/nullptr,
9935 /*BitWidth=*/nullptr,
9936 /*Mutable=*/false,
9937 ICIS_NoInit);
9938 Field->setAccess(AS_public);
9939 VaListTagDecl->addDecl(Field);
9940 }
9941 VaListTagDecl->completeDefinition();
9942 Context->VaListTagDecl = VaListTagDecl;
9943 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
9944
9945 // } __va_list_tag;
9946 TypedefDecl *VaListTagTypedefDecl =
9947 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
9948
9949 QualType VaListTagTypedefType =
9950 Context->getTypedefType(ElaboratedTypeKeyword::None,
9951 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
9952
9953 // typedef __va_list_tag __builtin_va_list[1];
9954 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9955 QualType VaListTagArrayType = Context->getConstantArrayType(
9956 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
9957 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9958 }
9959
9960 static TypedefDecl *
9961 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
9962 // struct __va_list_tag {
9963 RecordDecl *VaListTagDecl;
9964 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9965 VaListTagDecl->startDefinition();
9966
9967 const size_t NumFields = 4;
9968 QualType FieldTypes[NumFields];
9969 const char *FieldNames[NumFields];
9970
9971 // unsigned gp_offset;
9972 FieldTypes[0] = Context->UnsignedIntTy;
9973 FieldNames[0] = "gp_offset";
9974
9975 // unsigned fp_offset;
9976 FieldTypes[1] = Context->UnsignedIntTy;
9977 FieldNames[1] = "fp_offset";
9978
9979 // void* overflow_arg_area;
9980 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9981 FieldNames[2] = "overflow_arg_area";
9982
9983 // void* reg_save_area;
9984 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
9985 FieldNames[3] = "reg_save_area";
9986
9987 // Create fields
9988 for (unsigned i = 0; i < NumFields; ++i) {
9989 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9990 VaListTagDecl,
9991 SourceLocation(),
9992 SourceLocation(),
9993 &Context->Idents.get(FieldNames[i]),
9994 FieldTypes[i], /*TInfo=*/nullptr,
9995 /*BitWidth=*/nullptr,
9996 /*Mutable=*/false,
9997 ICIS_NoInit);
9998 Field->setAccess(AS_public);
9999 VaListTagDecl->addDecl(Field);
10000 }
10001 VaListTagDecl->completeDefinition();
10002 Context->VaListTagDecl = VaListTagDecl;
10003 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10004
10005 // };
10006
10007 // typedef struct __va_list_tag __builtin_va_list[1];
10008 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10009 QualType VaListTagArrayType = Context->getConstantArrayType(
10010 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10011 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10012 }
10013
10014 static TypedefDecl *
10015 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
10016 // struct __va_list
10017 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
10018 if (Context->getLangOpts().CPlusPlus) {
10019 // namespace std { struct __va_list {
10020 NamespaceDecl *NS;
10021 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
10022 Context->getTranslationUnitDecl(),
10023 /*Inline=*/false, SourceLocation(),
10024 SourceLocation(), &Context->Idents.get("std"),
10025 /*PrevDecl=*/nullptr, /*Nested=*/false);
10026 NS->setImplicit();
10027 VaListDecl->setDeclContext(NS);
10028 }
10029
10030 VaListDecl->startDefinition();
10031
10032 // void * __ap;
10033 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10034 VaListDecl,
10035 SourceLocation(),
10036 SourceLocation(),
10037 &Context->Idents.get("__ap"),
10038 Context->getPointerType(Context->VoidTy),
10039 /*TInfo=*/nullptr,
10040 /*BitWidth=*/nullptr,
10041 /*Mutable=*/false,
10042 ICIS_NoInit);
10043 Field->setAccess(AS_public);
10044 VaListDecl->addDecl(Field);
10045
10046 // };
10047 VaListDecl->completeDefinition();
10048 Context->VaListTagDecl = VaListDecl;
10049
10050 // typedef struct __va_list __builtin_va_list;
10051 CanQualType T = Context->getCanonicalTagType(VaListDecl);
10052 return Context->buildImplicitTypedef(T, "__builtin_va_list");
10053 }
10054
10055 static TypedefDecl *
10056 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
10057 // struct __va_list_tag {
10058 RecordDecl *VaListTagDecl;
10059 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10060 VaListTagDecl->startDefinition();
10061
10062 const size_t NumFields = 4;
10063 QualType FieldTypes[NumFields];
10064 const char *FieldNames[NumFields];
10065
10066 // long __gpr;
10067 FieldTypes[0] = Context->LongTy;
10068 FieldNames[0] = "__gpr";
10069
10070 // long __fpr;
10071 FieldTypes[1] = Context->LongTy;
10072 FieldNames[1] = "__fpr";
10073
10074 // void *__overflow_arg_area;
10075 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10076 FieldNames[2] = "__overflow_arg_area";
10077
10078 // void *__reg_save_area;
10079 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10080 FieldNames[3] = "__reg_save_area";
10081
10082 // Create fields
10083 for (unsigned i = 0; i < NumFields; ++i) {
10084 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10085 VaListTagDecl,
10086 SourceLocation(),
10087 SourceLocation(),
10088 &Context->Idents.get(FieldNames[i]),
10089 FieldTypes[i], /*TInfo=*/nullptr,
10090 /*BitWidth=*/nullptr,
10091 /*Mutable=*/false,
10092 ICIS_NoInit);
10093 Field->setAccess(AS_public);
10094 VaListTagDecl->addDecl(Field);
10095 }
10096 VaListTagDecl->completeDefinition();
10097 Context->VaListTagDecl = VaListTagDecl;
10098 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10099
10100 // };
10101
10102 // typedef __va_list_tag __builtin_va_list[1];
10103 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10104 QualType VaListTagArrayType = Context->getConstantArrayType(
10105 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10106
10107 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10108 }
10109
10110 static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) {
10111 // typedef struct __va_list_tag {
10112 RecordDecl *VaListTagDecl;
10113 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10114 VaListTagDecl->startDefinition();
10115
10116 const size_t NumFields = 3;
10117 QualType FieldTypes[NumFields];
10118 const char *FieldNames[NumFields];
10119
10120 // void *CurrentSavedRegisterArea;
10121 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
10122 FieldNames[0] = "__current_saved_reg_area_pointer";
10123
10124 // void *SavedRegAreaEnd;
10125 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
10126 FieldNames[1] = "__saved_reg_area_end_pointer";
10127
10128 // void *OverflowArea;
10129 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10130 FieldNames[2] = "__overflow_area_pointer";
10131
10132 // Create fields
10133 for (unsigned i = 0; i < NumFields; ++i) {
10134 FieldDecl *Field = FieldDecl::Create(
10135 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
10136 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
10137 /*TInfo=*/nullptr,
10138 /*BitWidth=*/nullptr,
10139 /*Mutable=*/false, ICIS_NoInit);
10140 Field->setAccess(AS_public);
10141 VaListTagDecl->addDecl(Field);
10142 }
10143 VaListTagDecl->completeDefinition();
10144 Context->VaListTagDecl = VaListTagDecl;
10145 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10146
10147 // } __va_list_tag;
10148 TypedefDecl *VaListTagTypedefDecl =
10149 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10150
10151 QualType VaListTagTypedefType =
10152 Context->getTypedefType(ElaboratedTypeKeyword::None,
10153 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10154
10155 // typedef __va_list_tag __builtin_va_list[1];
10156 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10157 QualType VaListTagArrayType = Context->getConstantArrayType(
10158 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10159
10160 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10161 }
10162
10163 static TypedefDecl *
10164 CreateXtensaABIBuiltinVaListDecl(const ASTContext *Context) {
10165 // typedef struct __va_list_tag {
10166 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10167
10168 VaListTagDecl->startDefinition();
10169
10170 // int* __va_stk;
10171 // int* __va_reg;
10172 // int __va_ndx;
10173 constexpr size_t NumFields = 3;
10174 QualType FieldTypes[NumFields] = {Context->getPointerType(Context->IntTy),
10175 Context->getPointerType(Context->IntTy),
10176 Context->IntTy};
10177 const char *FieldNames[NumFields] = {"__va_stk", "__va_reg", "__va_ndx"};
10178
10179 // Create fields
10180 for (unsigned i = 0; i < NumFields; ++i) {
10181 FieldDecl *Field = FieldDecl::Create(
10182 *Context, VaListTagDecl, SourceLocation(), SourceLocation(),
10183 &Context->Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
10184 /*BitWidth=*/nullptr,
10185 /*Mutable=*/false, ICIS_NoInit);
10186 Field->setAccess(AS_public);
10187 VaListTagDecl->addDecl(Field);
10188 }
10189 VaListTagDecl->completeDefinition();
10190 Context->VaListTagDecl = VaListTagDecl;
10191 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10192
10193 // } __va_list_tag;
10194 TypedefDecl *VaListTagTypedefDecl =
10195 Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10196
10197 return VaListTagTypedefDecl;
10198 }
10199
10200 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
10201 TargetInfo::BuiltinVaListKind Kind) {
10202 switch (Kind) {
10203 case TargetInfo::CharPtrBuiltinVaList:
10204 return CreateCharPtrBuiltinVaListDecl(Context);
10205 case TargetInfo::VoidPtrBuiltinVaList:
10206 return CreateVoidPtrBuiltinVaListDecl(Context);
10207 case TargetInfo::AArch64ABIBuiltinVaList:
10208 return CreateAArch64ABIBuiltinVaListDecl(Context);
10209 case TargetInfo::PowerABIBuiltinVaList:
10210 return CreatePowerABIBuiltinVaListDecl(Context);
10211 case TargetInfo::X86_64ABIBuiltinVaList:
10212 return CreateX86_64ABIBuiltinVaListDecl(Context);
10213 case TargetInfo::AAPCSABIBuiltinVaList:
10214 return CreateAAPCSABIBuiltinVaListDecl(Context);
10215 case TargetInfo::SystemZBuiltinVaList:
10216 return CreateSystemZBuiltinVaListDecl(Context);
10217 case TargetInfo::HexagonBuiltinVaList:
10218 return CreateHexagonBuiltinVaListDecl(Context);
10219 case TargetInfo::XtensaABIBuiltinVaList:
10220 return CreateXtensaABIBuiltinVaListDecl(Context);
10221 }
10222
10223 llvm_unreachable("Unhandled __builtin_va_list type kind");
10224 }
10225
10226 TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
10227 if (!BuiltinVaListDecl) {
10228 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
10229 assert(BuiltinVaListDecl->isImplicit());
10230 }
10231
10232 return BuiltinVaListDecl;
10233 }
10234
10235 Decl *ASTContext::getVaListTagDecl() const {
10236 // Force the creation of VaListTagDecl by building the __builtin_va_list
10237 // declaration.
10238 if (!VaListTagDecl)
10239 (void)getBuiltinVaListDecl();
10240
10241 return VaListTagDecl;
10242 }
10243
10244 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
10245 if (!BuiltinMSVaListDecl)
10246 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
10247
10248 return BuiltinMSVaListDecl;
10249 }
10250
10251 bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
10252 // Allow redecl custom type checking builtin for HLSL.
10253 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
10254 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10255 return true;
10256 // Allow redecl custom type checking builtin for SPIR-V.
10257 if (getTargetInfo().getTriple().isSPIROrSPIRV() &&
10258 BuiltinInfo.isTSBuiltin(FD->getBuiltinID()) &&
10259 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10260 return true;
10261 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
10262 }
10263
10264 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
10265 assert(ObjCConstantStringType.isNull() &&
10266 "'NSConstantString' type already set!");
10267
10268 ObjCConstantStringType = getObjCInterfaceType(Decl);
10269 }
10270
10271 /// Retrieve the template name that corresponds to a non-empty
10272 /// lookup.
10273 TemplateName
10274 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
10275 UnresolvedSetIterator End) const {
10276 unsigned size = End - Begin;
10277 assert(size > 1 && "set is not overloaded!");
10278
10279 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
10280 size * sizeof(FunctionTemplateDecl*));
10281 auto *OT = new (memory) OverloadedTemplateStorage(size);
10282
10283 NamedDecl **Storage = OT->getStorage();
10284 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
10285 NamedDecl *D = *I;
10286 assert(isa<FunctionTemplateDecl>(D) ||
10287 isa<UnresolvedUsingValueDecl>(D) ||
10288 (isa<UsingShadowDecl>(D) &&
10289 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
10290 *Storage++ = D;
10291 }
10292
10293 return TemplateName(OT);
10294 }
10295
10296 /// Retrieve a template name representing an unqualified-id that has been
10297 /// assumed to name a template for ADL purposes.
10298 TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const {
10299 auto *OT = new (*this) AssumedTemplateStorage(Name);
10300 return TemplateName(OT);
10301 }
10302
10303 /// Retrieve the template name that represents a qualified
10304 /// template name such as \c std::vector.
10305 TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier Qualifier,
10306 bool TemplateKeyword,
10307 TemplateName Template) const {
10308 assert(Template.getKind() == TemplateName::Template ||
10309 Template.getKind() == TemplateName::UsingTemplate);
10310
10311 if (Template.getAsTemplateDecl()->getKind() == Decl::TemplateTemplateParm) {
10312 assert(!Qualifier && "unexpected qualified template template parameter");
10313 assert(TemplateKeyword == false);
10314 return Template;
10315 }
10316
10317 // FIXME: Canonicalization?
10318 llvm::FoldingSetNodeID ID;
10319 QualifiedTemplateName::Profile(ID, Qualifier, TemplateKeyword, Template);
10320
10321 void *InsertPos = nullptr;
10322 QualifiedTemplateName *QTN =
10323 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
10324 if (!QTN) {
10325 QTN = new (*this, alignof(QualifiedTemplateName))
10326 QualifiedTemplateName(Qualifier, TemplateKeyword, Template);
10327 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
10328 }
10329
10330 return TemplateName(QTN);
10331 }
10332
10333 /// Retrieve the template name that represents a dependent
10334 /// template name such as \c MetaFun::template operator+.
10335 TemplateName
10336 ASTContext::getDependentTemplateName(const DependentTemplateStorage &S) const {
10337 llvm::FoldingSetNodeID ID;
10338 S.Profile(ID);
10339
10340 void *InsertPos = nullptr;
10341 if (DependentTemplateName *QTN =
10342 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos))
10343 return TemplateName(QTN);
10344
10345 DependentTemplateName *QTN =
10346 new (*this, alignof(DependentTemplateName)) DependentTemplateName(S);
10347 DependentTemplateNames.InsertNode(QTN, InsertPos);
10348 return TemplateName(QTN);
10349 }
10350
10351 TemplateName ASTContext::getSubstTemplateTemplateParm(TemplateName Replacement,
10352 Decl *AssociatedDecl,
10353 unsigned Index,
10354 UnsignedOrNone PackIndex,
10355 bool Final) const {
10356 llvm::FoldingSetNodeID ID;
10357 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
10358 Index, PackIndex, Final);
10359
10360 void *insertPos = nullptr;
10361 SubstTemplateTemplateParmStorage *subst
10362 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
10363
10364 if (!subst) {
10365 subst = new (*this) SubstTemplateTemplateParmStorage(
10366 Replacement, AssociatedDecl, Index, PackIndex, Final);
10367 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
10368 }
10369
10370 return TemplateName(subst);
10371 }
10372
10373 TemplateName
10374 ASTContext::getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack,
10375 Decl *AssociatedDecl,
10376 unsigned Index, bool Final) const {
10377 auto &Self = const_cast<ASTContext &>(*this);
10378 llvm::FoldingSetNodeID ID;
10379 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, ArgPack,
10380 AssociatedDecl, Index, Final);
10381
10382 void *InsertPos = nullptr;
10383 SubstTemplateTemplateParmPackStorage *Subst
10384 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
10385
10386 if (!Subst) {
10387 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
10388 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
10389 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
10390 }
10391
10392 return TemplateName(Subst);
10393 }
10394
10395 /// Retrieve the template name that represents a template name
10396 /// deduced from a specialization.
10397 TemplateName
10398 ASTContext::getDeducedTemplateName(TemplateName Underlying,
10399 DefaultArguments DefaultArgs) const {
10400 if (!DefaultArgs)
10401 return Underlying;
10402
10403 llvm::FoldingSetNodeID ID;
10404 DeducedTemplateStorage::Profile(ID, *this, Underlying, DefaultArgs);
10405
10406 void *InsertPos = nullptr;
10407 DeducedTemplateStorage *DTS =
10408 DeducedTemplates.FindNodeOrInsertPos(ID, InsertPos);
10409 if (!DTS) {
10410 void *Mem = Allocate(sizeof(DeducedTemplateStorage) +
10411 sizeof(TemplateArgument) * DefaultArgs.Args.size(),
10412 alignof(DeducedTemplateStorage));
10413 DTS = new (Mem) DeducedTemplateStorage(Underlying, DefaultArgs);
10414 DeducedTemplates.InsertNode(DTS, InsertPos);
10415 }
10416 return TemplateName(DTS);
10417 }
10418
10419 /// getFromTargetType - Given one of the integer types provided by
10420 /// TargetInfo, produce the corresponding type. The unsigned @p Type
10421 /// is actually a value of type @c TargetInfo::IntType.
10422 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
10423 switch (Type) {
10424 case TargetInfo::NoInt: return {};
10425 case TargetInfo::SignedChar: return SignedCharTy;
10426 case TargetInfo::UnsignedChar: return UnsignedCharTy;
10427 case TargetInfo::SignedShort: return ShortTy;
10428 case TargetInfo::UnsignedShort: return UnsignedShortTy;
10429 case TargetInfo::SignedInt: return IntTy;
10430 case TargetInfo::UnsignedInt: return UnsignedIntTy;
10431 case TargetInfo::SignedLong: return LongTy;
10432 case TargetInfo::UnsignedLong: return UnsignedLongTy;
10433 case TargetInfo::SignedLongLong: return LongLongTy;
10434 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
10435 }
10436
10437 llvm_unreachable("Unhandled TargetInfo::IntType value");
10438 }
10439
10440 //===----------------------------------------------------------------------===//
10441 // Type Predicates.
10442 //===----------------------------------------------------------------------===//
10443
10444 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
10445 /// garbage collection attribute.
10446 ///
10447 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
10448 if (getLangOpts().getGC() == LangOptions::NonGC)
10449 return Qualifiers::GCNone;
10450
10451 assert(getLangOpts().ObjC);
10452 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
10453
10454 // Default behaviour under objective-C's gc is for ObjC pointers
10455 // (or pointers to them) be treated as though they were declared
10456 // as __strong.
10457 if (GCAttrs == Qualifiers::GCNone) {
10458 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
10459 return Qualifiers::Strong;
10460 else if (Ty->isPointerType())
10461 return getObjCGCAttrKind(Ty->castAs<PointerType>()->getPointeeType());
10462 } else {
10463 // It's not valid to set GC attributes on anything that isn't a
10464 // pointer.
10465 #ifndef NDEBUG
10466 QualType CT = Ty->getCanonicalTypeInternal();
10467 while (const auto *AT = dyn_cast<ArrayType>(CT))
10468 CT = AT->getElementType();
10469 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
10470 #endif
10471 }
10472 return GCAttrs;
10473 }
10474
10475 //===----------------------------------------------------------------------===//
10476 // Type Compatibility Testing
10477 //===----------------------------------------------------------------------===//
10478
10479 /// areCompatVectorTypes - Return true if the two specified vector types are
10480 /// compatible.
10481 static bool areCompatVectorTypes(const VectorType *LHS,
10482 const VectorType *RHS) {
10483 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10484 return LHS->getElementType() == RHS->getElementType() &&
10485 LHS->getNumElements() == RHS->getNumElements();
10486 }
10487
10488 /// areCompatMatrixTypes - Return true if the two specified matrix types are
10489 /// compatible.
10490 static bool areCompatMatrixTypes(const ConstantMatrixType *LHS,
10491 const ConstantMatrixType *RHS) {
10492 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10493 return LHS->getElementType() == RHS->getElementType() &&
10494 LHS->getNumRows() == RHS->getNumRows() &&
10495 LHS->getNumColumns() == RHS->getNumColumns();
10496 }
10497
10498 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
10499 QualType SecondVec) {
10500 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
10501 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
10502
10503 if (hasSameUnqualifiedType(FirstVec, SecondVec))
10504 return true;
10505
10506 // Treat Neon vector types and most AltiVec vector types as if they are the
10507 // equivalent GCC vector types.
10508 const auto *First = FirstVec->castAs<VectorType>();
10509 const auto *Second = SecondVec->castAs<VectorType>();
10510 if (First->getNumElements() == Second->getNumElements() &&
10511 hasSameType(First->getElementType(), Second->getElementType()) &&
10512 First->getVectorKind() != VectorKind::AltiVecPixel &&
10513 First->getVectorKind() != VectorKind::AltiVecBool &&
10514 Second->getVectorKind() != VectorKind::AltiVecPixel &&
10515 Second->getVectorKind() != VectorKind::AltiVecBool &&
10516 First->getVectorKind() != VectorKind::SveFixedLengthData &&
10517 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10518 Second->getVectorKind() != VectorKind::SveFixedLengthData &&
10519 Second->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10520 First->getVectorKind() != VectorKind::RVVFixedLengthData &&
10521 Second->getVectorKind() != VectorKind::RVVFixedLengthData &&
10522 First->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10523 Second->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10524 First->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10525 Second->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10526 First->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10527 Second->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10528 First->getVectorKind() != VectorKind::RVVFixedLengthMask_4 &&
10529 Second->getVectorKind() != VectorKind::RVVFixedLengthMask_4)
10530 return true;
10531
10532 // In OpenCL, treat half and _Float16 vector types as compatible.
10533 if (getLangOpts().OpenCL &&
10534 First->getNumElements() == Second->getNumElements()) {
10535 QualType FirstElt = First->getElementType();
10536 QualType SecondElt = Second->getElementType();
10537
10538 if ((FirstElt->isFloat16Type() && SecondElt->isHalfType()) ||
10539 (FirstElt->isHalfType() && SecondElt->isFloat16Type())) {
10540 if (First->getVectorKind() != VectorKind::AltiVecPixel &&
10541 First->getVectorKind() != VectorKind::AltiVecBool &&
10542 Second->getVectorKind() != VectorKind::AltiVecPixel &&
10543 Second->getVectorKind() != VectorKind::AltiVecBool)
10544 return true;
10545 }
10546 }
10547 return false;
10548 }
10549
10550 /// getRVVTypeSize - Return RVV vector register size.
10551 static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
10552 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
10553 auto VScale = Context.getTargetInfo().getVScaleRange(
10554 Context.getLangOpts(), TargetInfo::ArmStreamingKind::NotStreaming);
10555 if (!VScale)
10556 return 0;
10557
10558 ASTContext::BuiltinVectorTypeInfo Info = Context.getBuiltinVectorTypeInfo(Ty);
10559
10560 uint64_t EltSize = Context.getTypeSize(Info.ElementType);
10561 if (Info.ElementType == Context.BoolTy)
10562 EltSize = 1;
10563
10564 uint64_t MinElts = Info.EC.getKnownMinValue();
10565 return VScale->first * MinElts * EltSize;
10566 }
10567
10568 bool ASTContext::areCompatibleRVVTypes(QualType FirstType,
10569 QualType SecondType) {
10570 assert(
10571 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10572 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10573 "Expected RVV builtin type and vector type!");
10574
10575 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10576 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10577 if (const auto *VT = SecondType->getAs<VectorType>()) {
10578 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10579 BuiltinVectorTypeInfo Info = getBuiltinVectorTypeInfo(BT);
10580 return FirstType->isRVVVLSBuiltinType() &&
10581 Info.ElementType == BoolTy &&
10582 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)));
10583 }
10584 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1) {
10585 BuiltinVectorTypeInfo Info = getBuiltinVectorTypeInfo(BT);
10586 return FirstType->isRVVVLSBuiltinType() &&
10587 Info.ElementType == BoolTy &&
10588 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT) * 8));
10589 }
10590 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2) {
10591 BuiltinVectorTypeInfo Info = getBuiltinVectorTypeInfo(BT);
10592 return FirstType->isRVVVLSBuiltinType() &&
10593 Info.ElementType == BoolTy &&
10594 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 4);
10595 }
10596 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10597 BuiltinVectorTypeInfo Info = getBuiltinVectorTypeInfo(BT);
10598 return FirstType->isRVVVLSBuiltinType() &&
10599 Info.ElementType == BoolTy &&
10600 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 2);
10601 }
10602 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
10603 VT->getVectorKind() == VectorKind::Generic)
10604 return FirstType->isRVVVLSBuiltinType() &&
10605 getTypeSize(SecondType) == getRVVTypeSize(*this, BT) &&
10606 hasSameType(VT->getElementType(),
10607 getBuiltinVectorTypeInfo(BT).ElementType);
10608 }
10609 }
10610 return false;
10611 };
10612
10613 return IsValidCast(FirstType, SecondType) ||
10614 IsValidCast(SecondType, FirstType);
10615 }
10616
10617 bool ASTContext::areLaxCompatibleRVVTypes(QualType FirstType,
10618 QualType SecondType) {
10619 assert(
10620 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10621 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10622 "Expected RVV builtin type and vector type!");
10623
10624 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10625 const auto *BT = FirstType->getAs<BuiltinType>();
10626 if (!BT)
10627 return false;
10628
10629 if (!BT->isRVVVLSBuiltinType())
10630 return false;
10631
10632 const auto *VecTy = SecondType->getAs<VectorType>();
10633 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
10634 const LangOptions::LaxVectorConversionKind LVCKind =
10635 getLangOpts().getLaxVectorConversions();
10636
10637 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
10638 if (getTypeSize(SecondType) != getRVVTypeSize(*this, BT))
10639 return false;
10640
10641 // If -flax-vector-conversions=all is specified, the types are
10642 // certainly compatible.
10643 if (LVCKind == LangOptions::LaxVectorConversionKind::All)
10644 return true;
10645
10646 // If -flax-vector-conversions=integer is specified, the types are
10647 // compatible if the elements are integer types.
10648 if (LVCKind == LangOptions::LaxVectorConversionKind::Integer)
10649 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10650 FirstType->getRVVEltType(*this)->isIntegerType();
10651 }
10652
10653 return false;
10654 };
10655
10656 return IsLaxCompatible(FirstType, SecondType) ||
10657 IsLaxCompatible(SecondType, FirstType);
10658 }
10659
10660 bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const {
10661 while (true) {
10662 // __strong id
10663 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
10664 if (Attr->getAttrKind() == attr::ObjCOwnership)
10665 return true;
10666
10667 Ty = Attr->getModifiedType();
10668
10669 // X *__strong (...)
10670 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
10671 Ty = Paren->getInnerType();
10672
10673 // We do not want to look through typedefs, typeof(expr),
10674 // typeof(type), or any other way that the type is somehow
10675 // abstracted.
10676 } else {
10677 return false;
10678 }
10679 }
10680 }
10681
10682 //===----------------------------------------------------------------------===//
10683 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
10684 //===----------------------------------------------------------------------===//
10685
10686 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
10687 /// inheritance hierarchy of 'rProto'.
10688 bool
10689 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
10690 ObjCProtocolDecl *rProto) const {
10691 if (declaresSameEntity(lProto, rProto))
10692 return true;
10693 for (auto *PI : rProto->protocols())
10694 if (ProtocolCompatibleWithProtocol(lProto, PI))
10695 return true;
10696 return false;
10697 }
10698
10699 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
10700 /// Class<pr1, ...>.
10701 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(
10702 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
10703 for (auto *lhsProto : lhs->quals()) {
10704 bool match = false;
10705 for (auto *rhsProto : rhs->quals()) {
10706 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
10707 match = true;
10708 break;
10709 }
10710 }
10711 if (!match)
10712 return false;
10713 }
10714 return true;
10715 }
10716
10717 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
10718 /// ObjCQualifiedIDType.
10719 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(
10720 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
10721 bool compare) {
10722 // Allow id<P..> and an 'id' in all cases.
10723 if (lhs->isObjCIdType() || rhs->isObjCIdType())
10724 return true;
10725
10726 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
10727 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
10728 rhs->isObjCClassType() || rhs->isObjCQualifiedClassType())
10729 return false;
10730
10731 if (lhs->isObjCQualifiedIdType()) {
10732 if (rhs->qual_empty()) {
10733 // If the RHS is a unqualified interface pointer "NSString*",
10734 // make sure we check the class hierarchy.
10735 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10736 for (auto *I : lhs->quals()) {
10737 // when comparing an id<P> on lhs with a static type on rhs,
10738 // see if static class implements all of id's protocols, directly or
10739 // through its super class and categories.
10740 if (!rhsID->ClassImplementsProtocol(I, true))
10741 return false;
10742 }
10743 }
10744 // If there are no qualifiers and no interface, we have an 'id'.
10745 return true;
10746 }
10747 // Both the right and left sides have qualifiers.
10748 for (auto *lhsProto : lhs->quals()) {
10749 bool match = false;
10750
10751 // when comparing an id<P> on lhs with a static type on rhs,
10752 // see if static class implements all of id's protocols, directly or
10753 // through its super class and categories.
10754 for (auto *rhsProto : rhs->quals()) {
10755 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10756 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10757 match = true;
10758 break;
10759 }
10760 }
10761 // If the RHS is a qualified interface pointer "NSString<P>*",
10762 // make sure we check the class hierarchy.
10763 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10764 for (auto *I : lhs->quals()) {
10765 // when comparing an id<P> on lhs with a static type on rhs,
10766 // see if static class implements all of id's protocols, directly or
10767 // through its super class and categories.
10768 if (rhsID->ClassImplementsProtocol(I, true)) {
10769 match = true;
10770 break;
10771 }
10772 }
10773 }
10774 if (!match)
10775 return false;
10776 }
10777
10778 return true;
10779 }
10780
10781 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
10782
10783 if (lhs->getInterfaceType()) {
10784 // If both the right and left sides have qualifiers.
10785 for (auto *lhsProto : lhs->quals()) {
10786 bool match = false;
10787
10788 // when comparing an id<P> on rhs with a static type on lhs,
10789 // see if static class implements all of id's protocols, directly or
10790 // through its super class and categories.
10791 // First, lhs protocols in the qualifier list must be found, direct
10792 // or indirect in rhs's qualifier list or it is a mismatch.
10793 for (auto *rhsProto : rhs->quals()) {
10794 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10795 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10796 match = true;
10797 break;
10798 }
10799 }
10800 if (!match)
10801 return false;
10802 }
10803
10804 // Static class's protocols, or its super class or category protocols
10805 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
10806 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
10807 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
10808 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
10809 // This is rather dubious but matches gcc's behavior. If lhs has
10810 // no type qualifier and its class has no static protocol(s)
10811 // assume that it is mismatch.
10812 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
10813 return false;
10814 for (auto *lhsProto : LHSInheritedProtocols) {
10815 bool match = false;
10816 for (auto *rhsProto : rhs->quals()) {
10817 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10818 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10819 match = true;
10820 break;
10821 }
10822 }
10823 if (!match)
10824 return false;
10825 }
10826 }
10827 return true;
10828 }
10829 return false;
10830 }
10831
10832 /// canAssignObjCInterfaces - Return true if the two interface types are
10833 /// compatible for assignment from RHS to LHS. This handles validation of any
10834 /// protocol qualifiers on the LHS or RHS.
10835 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
10836 const ObjCObjectPointerType *RHSOPT) {
10837 const ObjCObjectType* LHS = LHSOPT->getObjectType();
10838 const ObjCObjectType* RHS = RHSOPT->getObjectType();
10839
10840 // If either type represents the built-in 'id' type, return true.
10841 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
10842 return true;
10843
10844 // Function object that propagates a successful result or handles
10845 // __kindof types.
10846 auto finish = [&](bool succeeded) -> bool {
10847 if (succeeded)
10848 return true;
10849
10850 if (!RHS->isKindOfType())
10851 return false;
10852
10853 // Strip off __kindof and protocol qualifiers, then check whether
10854 // we can assign the other way.
10855 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
10856 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
10857 };
10858
10859 // Casts from or to id<P> are allowed when the other side has compatible
10860 // protocols.
10861 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
10862 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
10863 }
10864
10865 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
10866 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
10867 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
10868 }
10869
10870 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
10871 if (LHS->isObjCClass() && RHS->isObjCClass()) {
10872 return true;
10873 }
10874
10875 // If we have 2 user-defined types, fall into that path.
10876 if (LHS->getInterface() && RHS->getInterface()) {
10877 return finish(canAssignObjCInterfaces(LHS, RHS));
10878 }
10879
10880 return false;
10881 }
10882
10883 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
10884 /// for providing type-safety for objective-c pointers used to pass/return
10885 /// arguments in block literals. When passed as arguments, passing 'A*' where
10886 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
10887 /// not OK. For the return type, the opposite is not OK.
10888 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
10889 const ObjCObjectPointerType *LHSOPT,
10890 const ObjCObjectPointerType *RHSOPT,
10891 bool BlockReturnType) {
10892
10893 // Function object that propagates a successful result or handles
10894 // __kindof types.
10895 auto finish = [&](bool succeeded) -> bool {
10896 if (succeeded)
10897 return true;
10898
10899 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
10900 if (!Expected->isKindOfType())
10901 return false;
10902
10903 // Strip off __kindof and protocol qualifiers, then check whether
10904 // we can assign the other way.
10905 return canAssignObjCInterfacesInBlockPointer(
10906 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
10907 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
10908 BlockReturnType);
10909 };
10910
10911 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
10912 return true;
10913
10914 if (LHSOPT->isObjCBuiltinType()) {
10915 return finish(RHSOPT->isObjCBuiltinType() ||
10916 RHSOPT->isObjCQualifiedIdType());
10917 }
10918
10919 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
10920 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
10921 // Use for block parameters previous type checking for compatibility.
10922 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
10923 // Or corrected type checking as in non-compat mode.
10924 (!BlockReturnType &&
10925 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
10926 else
10927 return finish(ObjCQualifiedIdTypesAreCompatible(
10928 (BlockReturnType ? LHSOPT : RHSOPT),
10929 (BlockReturnType ? RHSOPT : LHSOPT), false));
10930 }
10931
10932 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
10933 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
10934 if (LHS && RHS) { // We have 2 user-defined types.
10935 if (LHS != RHS) {
10936 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
10937 return finish(BlockReturnType);
10938 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
10939 return finish(!BlockReturnType);
10940 }
10941 else
10942 return true;
10943 }
10944 return false;
10945 }
10946
10947 /// Comparison routine for Objective-C protocols to be used with
10948 /// llvm::array_pod_sort.
10949 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
10950 ObjCProtocolDecl * const *rhs) {
10951 return (*lhs)->getName().compare((*rhs)->getName());
10952 }
10953
10954 /// getIntersectionOfProtocols - This routine finds the intersection of set
10955 /// of protocols inherited from two distinct objective-c pointer objects with
10956 /// the given common base.
10957 /// It is used to build composite qualifier list of the composite type of
10958 /// the conditional expression involving two objective-c pointer objects.
10959 static
10960 void getIntersectionOfProtocols(ASTContext &Context,
10961 const ObjCInterfaceDecl *CommonBase,
10962 const ObjCObjectPointerType *LHSOPT,
10963 const ObjCObjectPointerType *RHSOPT,
10964 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
10965
10966 const ObjCObjectType* LHS = LHSOPT->getObjectType();
10967 const ObjCObjectType* RHS = RHSOPT->getObjectType();
10968 assert(LHS->getInterface() && "LHS must have an interface base");
10969 assert(RHS->getInterface() && "RHS must have an interface base");
10970
10971 // Add all of the protocols for the LHS.
10972 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
10973
10974 // Start with the protocol qualifiers.
10975 for (auto *proto : LHS->quals()) {
10976 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
10977 }
10978
10979 // Also add the protocols associated with the LHS interface.
10980 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
10981
10982 // Add all of the protocols for the RHS.
10983 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
10984
10985 // Start with the protocol qualifiers.
10986 for (auto *proto : RHS->quals()) {
10987 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
10988 }
10989
10990 // Also add the protocols associated with the RHS interface.
10991 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
10992
10993 // Compute the intersection of the collected protocol sets.
10994 for (auto *proto : LHSProtocolSet) {
10995 if (RHSProtocolSet.count(proto))
10996 IntersectionSet.push_back(proto);
10997 }
10998
10999 // Compute the set of protocols that is implied by either the common type or
11000 // the protocols within the intersection.
11001 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
11002 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
11003
11004 // Remove any implied protocols from the list of inherited protocols.
11005 if (!ImpliedProtocols.empty()) {
11006 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
11007 return ImpliedProtocols.contains(proto);
11008 });
11009 }
11010
11011 // Sort the remaining protocols by name.
11012 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
11013 compareObjCProtocolsByName);
11014 }
11015
11016 /// Determine whether the first type is a subtype of the second.
11017 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
11018 QualType rhs) {
11019 // Common case: two object pointers.
11020 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
11021 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
11022 if (lhsOPT && rhsOPT)
11023 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
11024
11025 // Two block pointers.
11026 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
11027 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
11028 if (lhsBlock && rhsBlock)
11029 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
11030
11031 // If either is an unqualified 'id' and the other is a block, it's
11032 // acceptable.
11033 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
11034 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
11035 return true;
11036
11037 return false;
11038 }
11039
11040 // Check that the given Objective-C type argument lists are equivalent.
11041 static bool sameObjCTypeArgs(ASTContext &ctx,
11042 const ObjCInterfaceDecl *iface,
11043 ArrayRef<QualType> lhsArgs,
11044 ArrayRef<QualType> rhsArgs,
11045 bool stripKindOf) {
11046 if (lhsArgs.size() != rhsArgs.size())
11047 return false;
11048
11049 ObjCTypeParamList *typeParams = iface->getTypeParamList();
11050 if (!typeParams)
11051 return false;
11052
11053 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
11054 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
11055 continue;
11056
11057 switch (typeParams->begin()[i]->getVariance()) {
11058 case ObjCTypeParamVariance::Invariant:
11059 if (!stripKindOf ||
11060 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
11061 rhsArgs[i].stripObjCKindOfType(ctx))) {
11062 return false;
11063 }
11064 break;
11065
11066 case ObjCTypeParamVariance::Covariant:
11067 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
11068 return false;
11069 break;
11070
11071 case ObjCTypeParamVariance::Contravariant:
11072 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
11073 return false;
11074 break;
11075 }
11076 }
11077
11078 return true;
11079 }
11080
11081 QualType ASTContext::areCommonBaseCompatible(
11082 const ObjCObjectPointerType *Lptr,
11083 const ObjCObjectPointerType *Rptr) {
11084 const ObjCObjectType *LHS = Lptr->getObjectType();
11085 const ObjCObjectType *RHS = Rptr->getObjectType();
11086 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
11087 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
11088
11089 if (!LDecl || !RDecl)
11090 return {};
11091
11092 // When either LHS or RHS is a kindof type, we should return a kindof type.
11093 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
11094 // kindof(A).
11095 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
11096
11097 // Follow the left-hand side up the class hierarchy until we either hit a
11098 // root or find the RHS. Record the ancestors in case we don't find it.
11099 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
11100 LHSAncestors;
11101 while (true) {
11102 // Record this ancestor. We'll need this if the common type isn't in the
11103 // path from the LHS to the root.
11104 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
11105
11106 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
11107 // Get the type arguments.
11108 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
11109 bool anyChanges = false;
11110 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11111 // Both have type arguments, compare them.
11112 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11113 LHS->getTypeArgs(), RHS->getTypeArgs(),
11114 /*stripKindOf=*/true))
11115 return {};
11116 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11117 // If only one has type arguments, the result will not have type
11118 // arguments.
11119 LHSTypeArgs = {};
11120 anyChanges = true;
11121 }
11122
11123 // Compute the intersection of protocols.
11124 SmallVector<ObjCProtocolDecl *, 8> Protocols;
11125 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
11126 Protocols);
11127 if (!Protocols.empty())
11128 anyChanges = true;
11129
11130 // If anything in the LHS will have changed, build a new result type.
11131 // If we need to return a kindof type but LHS is not a kindof type, we
11132 // build a new result type.
11133 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
11134 QualType Result = getObjCInterfaceType(LHS->getInterface());
11135 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
11136 anyKindOf || LHS->isKindOfType());
11137 return getObjCObjectPointerType(Result);
11138 }
11139
11140 return getObjCObjectPointerType(QualType(LHS, 0));
11141 }
11142
11143 // Find the superclass.
11144 QualType LHSSuperType = LHS->getSuperClassType();
11145 if (LHSSuperType.isNull())
11146 break;
11147
11148 LHS = LHSSuperType->castAs<ObjCObjectType>();
11149 }
11150
11151 // We didn't find anything by following the LHS to its root; now check
11152 // the RHS against the cached set of ancestors.
11153 while (true) {
11154 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
11155 if (KnownLHS != LHSAncestors.end()) {
11156 LHS = KnownLHS->second;
11157
11158 // Get the type arguments.
11159 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
11160 bool anyChanges = false;
11161 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11162 // Both have type arguments, compare them.
11163 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11164 LHS->getTypeArgs(), RHS->getTypeArgs(),
11165 /*stripKindOf=*/true))
11166 return {};
11167 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11168 // If only one has type arguments, the result will not have type
11169 // arguments.
11170 RHSTypeArgs = {};
11171 anyChanges = true;
11172 }
11173
11174 // Compute the intersection of protocols.
11175 SmallVector<ObjCProtocolDecl *, 8> Protocols;
11176 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
11177 Protocols);
11178 if (!Protocols.empty())
11179 anyChanges = true;
11180
11181 // If we need to return a kindof type but RHS is not a kindof type, we
11182 // build a new result type.
11183 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
11184 QualType Result = getObjCInterfaceType(RHS->getInterface());
11185 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
11186 anyKindOf || RHS->isKindOfType());
11187 return getObjCObjectPointerType(Result);
11188 }
11189
11190 return getObjCObjectPointerType(QualType(RHS, 0));
11191 }
11192
11193 // Find the superclass of the RHS.
11194 QualType RHSSuperType = RHS->getSuperClassType();
11195 if (RHSSuperType.isNull())
11196 break;
11197
11198 RHS = RHSSuperType->castAs<ObjCObjectType>();
11199 }
11200
11201 return {};
11202 }
11203
11204 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
11205 const ObjCObjectType *RHS) {
11206 assert(LHS->getInterface() && "LHS is not an interface type");
11207 assert(RHS->getInterface() && "RHS is not an interface type");
11208
11209 // Verify that the base decls are compatible: the RHS must be a subclass of
11210 // the LHS.
11211 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
11212 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
11213 if (!IsSuperClass)
11214 return false;
11215
11216 // If the LHS has protocol qualifiers, determine whether all of them are
11217 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
11218 // LHS).
11219 if (LHS->getNumProtocols() > 0) {
11220 // OK if conversion of LHS to SuperClass results in narrowing of types
11221 // ; i.e., SuperClass may implement at least one of the protocols
11222 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
11223 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
11224 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
11225 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
11226 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
11227 // qualifiers.
11228 for (auto *RHSPI : RHS->quals())
11229 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
11230 // If there is no protocols associated with RHS, it is not a match.
11231 if (SuperClassInheritedProtocols.empty())
11232 return false;
11233
11234 for (const auto *LHSProto : LHS->quals()) {
11235 bool SuperImplementsProtocol = false;
11236 for (auto *SuperClassProto : SuperClassInheritedProtocols)
11237 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
11238 SuperImplementsProtocol = true;
11239 break;
11240 }
11241 if (!SuperImplementsProtocol)
11242 return false;
11243 }
11244 }
11245
11246 // If the LHS is specialized, we may need to check type arguments.
11247 if (LHS->isSpecialized()) {
11248 // Follow the superclass chain until we've matched the LHS class in the
11249 // hierarchy. This substitutes type arguments through.
11250 const ObjCObjectType *RHSSuper = RHS;
11251 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
11252 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
11253
11254 // If the RHS is specializd, compare type arguments.
11255 if (RHSSuper->isSpecialized() &&
11256 !sameObjCTypeArgs(*this, LHS->getInterface(),
11257 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
11258 /*stripKindOf=*/true)) {
11259 return false;
11260 }
11261 }
11262
11263 return true;
11264 }
11265
11266 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
11267 // get the "pointed to" types
11268 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
11269 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
11270
11271 if (!LHSOPT || !RHSOPT)
11272 return false;
11273
11274 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
11275 canAssignObjCInterfaces(RHSOPT, LHSOPT);
11276 }
11277
11278 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
11279 return canAssignObjCInterfaces(
11280 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
11281 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
11282 }
11283
11284 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
11285 /// both shall have the identically qualified version of a compatible type.
11286 /// C99 6.2.7p1: Two types have compatible types if their types are the
11287 /// same. See 6.7.[2,3,5] for additional rules.
11288 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
11289 bool CompareUnqualified) {
11290 if (getLangOpts().CPlusPlus)
11291 return hasSameType(LHS, RHS);
11292
11293 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
11294 }
11295
11296 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
11297 return typesAreCompatible(LHS, RHS);
11298 }
11299
11300 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
11301 return !mergeTypes(LHS, RHS, true).isNull();
11302 }
11303
11304 /// mergeTransparentUnionType - if T is a transparent union type and a member
11305 /// of T is compatible with SubType, return the merged type, else return
11306 /// QualType()
11307 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
11308 bool OfBlockPointer,
11309 bool Unqualified) {
11310 if (const RecordType *UT = T->getAsUnionType()) {
11311 RecordDecl *UD = UT->getDecl()->getMostRecentDecl();
11312 if (UD->hasAttr<TransparentUnionAttr>()) {
11313 for (const auto *I : UD->fields()) {
11314 QualType ET = I->getType().getUnqualifiedType();
11315 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
11316 if (!MT.isNull())
11317 return MT;
11318 }
11319 }
11320 }
11321
11322 return {};
11323 }
11324
11325 /// mergeFunctionParameterTypes - merge two types which appear as function
11326 /// parameter types
11327 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
11328 bool OfBlockPointer,
11329 bool Unqualified) {
11330 // GNU extension: two types are compatible if they appear as a function
11331 // argument, one of the types is a transparent union type and the other
11332 // type is compatible with a union member
11333 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
11334 Unqualified);
11335 if (!lmerge.isNull())
11336 return lmerge;
11337
11338 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
11339 Unqualified);
11340 if (!rmerge.isNull())
11341 return rmerge;
11342
11343 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
11344 }
11345
11346 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
11347 bool OfBlockPointer, bool Unqualified,
11348 bool AllowCXX,
11349 bool IsConditionalOperator) {
11350 const auto *lbase = lhs->castAs<FunctionType>();
11351 const auto *rbase = rhs->castAs<FunctionType>();
11352 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
11353 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
11354 bool allLTypes = true;
11355 bool allRTypes = true;
11356
11357 // Check return type
11358 QualType retType;
11359 if (OfBlockPointer) {
11360 QualType RHS = rbase->getReturnType();
11361 QualType LHS = lbase->getReturnType();
11362 bool UnqualifiedResult = Unqualified;
11363 if (!UnqualifiedResult)
11364 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
11365 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
11366 }
11367 else
11368 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
11369 Unqualified);
11370 if (retType.isNull())
11371 return {};
11372
11373 if (Unqualified)
11374 retType = retType.getUnqualifiedType();
11375
11376 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
11377 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
11378 if (Unqualified) {
11379 LRetType = LRetType.getUnqualifiedType();
11380 RRetType = RRetType.getUnqualifiedType();
11381 }
11382
11383 if (getCanonicalType(retType) != LRetType)
11384 allLTypes = false;
11385 if (getCanonicalType(retType) != RRetType)
11386 allRTypes = false;
11387
11388 // FIXME: double check this
11389 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
11390 // rbase->getRegParmAttr() != 0 &&
11391 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
11392 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
11393 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
11394
11395 // Compatible functions must have compatible calling conventions
11396 if (lbaseInfo.getCC() != rbaseInfo.getCC())
11397 return {};
11398
11399 // Regparm is part of the calling convention.
11400 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
11401 return {};
11402 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
11403 return {};
11404
11405 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
11406 return {};
11407 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
11408 return {};
11409 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
11410 return {};
11411
11412 // When merging declarations, it's common for supplemental information like
11413 // attributes to only be present in one of the declarations, and we generally
11414 // want type merging to preserve the union of information. So a merged
11415 // function type should be noreturn if it was noreturn in *either* operand
11416 // type.
11417 //
11418 // But for the conditional operator, this is backwards. The result of the
11419 // operator could be either operand, and its type should conservatively
11420 // reflect that. So a function type in a composite type is noreturn only
11421 // if it's noreturn in *both* operand types.
11422 //
11423 // Arguably, noreturn is a kind of subtype, and the conditional operator
11424 // ought to produce the most specific common supertype of its operand types.
11425 // That would differ from this rule in contravariant positions. However,
11426 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
11427 // as a practical matter, it would only affect C code that does abstraction of
11428 // higher-order functions (taking noreturn callbacks!), which is uncommon to
11429 // say the least. So we use the simpler rule.
11430 bool NoReturn = IsConditionalOperator
11431 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
11432 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
11433 if (lbaseInfo.getNoReturn() != NoReturn)
11434 allLTypes = false;
11435 if (rbaseInfo.getNoReturn() != NoReturn)
11436 allRTypes = false;
11437
11438 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
11439
11440 std::optional<FunctionEffectSet> MergedFX;
11441
11442 if (lproto && rproto) { // two C99 style function prototypes
11443 assert((AllowCXX ||
11444 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
11445 "C++ shouldn't be here");
11446 // Compatible functions must have the same number of parameters
11447 if (lproto->getNumParams() != rproto->getNumParams())
11448 return {};
11449
11450 // Variadic and non-variadic functions aren't compatible
11451 if (lproto->isVariadic() != rproto->isVariadic())
11452 return {};
11453
11454 if (lproto->getMethodQuals() != rproto->getMethodQuals())
11455 return {};
11456
11457 // Function protos with different 'cfi_salt' values aren't compatible.
11458 if (lproto->getExtraAttributeInfo().CFISalt !=
11459 rproto->getExtraAttributeInfo().CFISalt)
11460 return {};
11461
11462 // Function effects are handled similarly to noreturn, see above.
11463 FunctionEffectsRef LHSFX = lproto->getFunctionEffects();
11464 FunctionEffectsRef RHSFX = rproto->getFunctionEffects();
11465 if (LHSFX != RHSFX) {
11466 if (IsConditionalOperator)
11467 MergedFX = FunctionEffectSet::getIntersection(LHSFX, RHSFX);
11468 else {
11469 FunctionEffectSet::Conflicts Errs;
11470 MergedFX = FunctionEffectSet::getUnion(LHSFX, RHSFX, Errs);
11471 // Here we're discarding a possible error due to conflicts in the effect
11472 // sets. But we're not in a context where we can report it. The
11473 // operation does however guarantee maintenance of invariants.
11474 }
11475 if (*MergedFX != LHSFX)
11476 allLTypes = false;
11477 if (*MergedFX != RHSFX)
11478 allRTypes = false;
11479 }
11480
11481 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
11482 bool canUseLeft, canUseRight;
11483 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
11484 newParamInfos))
11485 return {};
11486
11487 if (!canUseLeft)
11488 allLTypes = false;
11489 if (!canUseRight)
11490 allRTypes = false;
11491
11492 // Check parameter type compatibility
11493 SmallVector<QualType, 10> types;
11494 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
11495 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
11496 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
11497 QualType paramType = mergeFunctionParameterTypes(
11498 lParamType, rParamType, OfBlockPointer, Unqualified);
11499 if (paramType.isNull())
11500 return {};
11501
11502 if (Unqualified)
11503 paramType = paramType.getUnqualifiedType();
11504
11505 types.push_back(paramType);
11506 if (Unqualified) {
11507 lParamType = lParamType.getUnqualifiedType();
11508 rParamType = rParamType.getUnqualifiedType();
11509 }
11510
11511 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
11512 allLTypes = false;
11513 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
11514 allRTypes = false;
11515 }
11516
11517 if (allLTypes) return lhs;
11518 if (allRTypes) return rhs;
11519
11520 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
11521 EPI.ExtInfo = einfo;
11522 EPI.ExtParameterInfos =
11523 newParamInfos.empty() ? nullptr : newParamInfos.data();
11524 if (MergedFX)
11525 EPI.FunctionEffects = *MergedFX;
11526 return getFunctionType(retType, types, EPI);
11527 }
11528
11529 if (lproto) allRTypes = false;
11530 if (rproto) allLTypes = false;
11531
11532 const FunctionProtoType *proto = lproto ? lproto : rproto;
11533 if (proto) {
11534 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
11535 if (proto->isVariadic())
11536 return {};
11537 // Check that the types are compatible with the types that
11538 // would result from default argument promotions (C99 6.7.5.3p15).
11539 // The only types actually affected are promotable integer
11540 // types and floats, which would be passed as a different
11541 // type depending on whether the prototype is visible.
11542 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
11543 QualType paramTy = proto->getParamType(i);
11544
11545 // Look at the converted type of enum types, since that is the type used
11546 // to pass enum values.
11547 if (const auto *ED = paramTy->getAsEnumDecl()) {
11548 paramTy = ED->getIntegerType();
11549 if (paramTy.isNull())
11550 return {};
11551 }
11552
11553 if (isPromotableIntegerType(paramTy) ||
11554 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
11555 return {};
11556 }
11557
11558 if (allLTypes) return lhs;
11559 if (allRTypes) return rhs;
11560
11561 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
11562 EPI.ExtInfo = einfo;
11563 if (MergedFX)
11564 EPI.FunctionEffects = *MergedFX;
11565 return getFunctionType(retType, proto->getParamTypes(), EPI);
11566 }
11567
11568 if (allLTypes) return lhs;
11569 if (allRTypes) return rhs;
11570 return getFunctionNoProtoType(retType, einfo);
11571 }
11572
11573 /// Given that we have an enum type and a non-enum type, try to merge them.
11574 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
11575 QualType other, bool isBlockReturnType) {
11576 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
11577 // a signed integer type, or an unsigned integer type.
11578 // Compatibility is based on the underlying type, not the promotion
11579 // type.
11580 QualType underlyingType =
11581 ET->getDecl()->getDefinitionOrSelf()->getIntegerType();
11582 if (underlyingType.isNull())
11583 return {};
11584 if (Context.hasSameType(underlyingType, other))
11585 return other;
11586
11587 // In block return types, we're more permissive and accept any
11588 // integral type of the same size.
11589 if (isBlockReturnType && other->isIntegerType() &&
11590 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
11591 return other;
11592
11593 return {};
11594 }
11595
11596 QualType ASTContext::mergeTagDefinitions(QualType LHS, QualType RHS) {
11597 // C17 and earlier and C++ disallow two tag definitions within the same TU
11598 // from being compatible.
11599 if (LangOpts.CPlusPlus || !LangOpts.C23)
11600 return {};
11601
11602 // Nameless tags are comparable only within outer definitions. At the top
11603 // level they are not comparable.
11604 const TagDecl *LTagD = LHS->castAsTagDecl(), *RTagD = RHS->castAsTagDecl();
11605 if (!LTagD->getIdentifier() || !RTagD->getIdentifier())
11606 return {};
11607
11608 // C23, on the other hand, requires the members to be "the same enough", so
11609 // we use a structural equivalence check.
11610 StructuralEquivalenceContext::NonEquivalentDeclSet NonEquivalentDecls;
11611 StructuralEquivalenceContext Ctx(
11612 getLangOpts(), *this, *this, NonEquivalentDecls,
11613 StructuralEquivalenceKind::Default, /*StrictTypeSpelling=*/false,
11614 /*Complain=*/false, /*ErrorOnTagTypeMismatch=*/true);
11615 return Ctx.IsEquivalent(LHS, RHS) ? LHS : QualType{};
11616 }
11617
11618 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
11619 bool Unqualified, bool BlockReturnType,
11620 bool IsConditionalOperator) {
11621 // For C++ we will not reach this code with reference types (see below),
11622 // for OpenMP variant call overloading we might.
11623 //
11624 // C++ [expr]: If an expression initially has the type "reference to T", the
11625 // type is adjusted to "T" prior to any further analysis, the expression
11626 // designates the object or function denoted by the reference, and the
11627 // expression is an lvalue unless the reference is an rvalue reference and
11628 // the expression is a function call (possibly inside parentheses).
11629 auto *LHSRefTy = LHS->getAs<ReferenceType>();
11630 auto *RHSRefTy = RHS->getAs<ReferenceType>();
11631 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
11632 LHS->getTypeClass() == RHS->getTypeClass())
11633 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
11634 OfBlockPointer, Unqualified, BlockReturnType);
11635 if (LHSRefTy || RHSRefTy)
11636 return {};
11637
11638 if (Unqualified) {
11639 LHS = LHS.getUnqualifiedType();
11640 RHS = RHS.getUnqualifiedType();
11641 }
11642
11643 QualType LHSCan = getCanonicalType(LHS),
11644 RHSCan = getCanonicalType(RHS);
11645
11646 // If two types are identical, they are compatible.
11647 if (LHSCan == RHSCan)
11648 return LHS;
11649
11650 // If the qualifiers are different, the types aren't compatible... mostly.
11651 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11652 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11653 if (LQuals != RQuals) {
11654 // If any of these qualifiers are different, we have a type
11655 // mismatch.
11656 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11657 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
11658 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
11659 !LQuals.getPointerAuth().isEquivalent(RQuals.getPointerAuth()) ||
11660 LQuals.hasUnaligned() != RQuals.hasUnaligned())
11661 return {};
11662
11663 // Exactly one GC qualifier difference is allowed: __strong is
11664 // okay if the other type has no GC qualifier but is an Objective
11665 // C object pointer (i.e. implicitly strong by default). We fix
11666 // this by pretending that the unqualified type was actually
11667 // qualified __strong.
11668 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11669 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11670 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11671
11672 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11673 return {};
11674
11675 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
11676 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
11677 }
11678 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
11679 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
11680 }
11681 return {};
11682 }
11683
11684 // Okay, qualifiers are equal.
11685
11686 Type::TypeClass LHSClass = LHSCan->getTypeClass();
11687 Type::TypeClass RHSClass = RHSCan->getTypeClass();
11688
11689 // We want to consider the two function types to be the same for these
11690 // comparisons, just force one to the other.
11691 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
11692 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
11693
11694 // Same as above for arrays
11695 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
11696 LHSClass = Type::ConstantArray;
11697 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
11698 RHSClass = Type::ConstantArray;
11699
11700 // ObjCInterfaces are just specialized ObjCObjects.
11701 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
11702 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
11703
11704 // Canonicalize ExtVector -> Vector.
11705 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
11706 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
11707
11708 // If the canonical type classes don't match.
11709 if (LHSClass != RHSClass) {
11710 // Note that we only have special rules for turning block enum
11711 // returns into block int returns, not vice-versa.
11712 if (const auto *ETy = LHS->getAsCanonical<EnumType>()) {
11713 return mergeEnumWithInteger(*this, ETy, RHS, false);
11714 }
11715 if (const EnumType *ETy = RHS->getAsCanonical<EnumType>()) {
11716 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
11717 }
11718 // allow block pointer type to match an 'id' type.
11719 if (OfBlockPointer && !BlockReturnType) {
11720 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
11721 return LHS;
11722 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
11723 return RHS;
11724 }
11725 // Allow __auto_type to match anything; it merges to the type with more
11726 // information.
11727 if (const auto *AT = LHS->getAs<AutoType>()) {
11728 if (!AT->isDeduced() && AT->isGNUAutoType())
11729 return RHS;
11730 }
11731 if (const auto *AT = RHS->getAs<AutoType>()) {
11732 if (!AT->isDeduced() && AT->isGNUAutoType())
11733 return LHS;
11734 }
11735 return {};
11736 }
11737
11738 // The canonical type classes match.
11739 switch (LHSClass) {
11740 #define TYPE(Class, Base)
11741 #define ABSTRACT_TYPE(Class, Base)
11742 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
11743 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
11744 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
11745 #include "clang/AST/TypeNodes.inc"
11746 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
11747
11748 case Type::Auto:
11749 case Type::DeducedTemplateSpecialization:
11750 case Type::LValueReference:
11751 case Type::RValueReference:
11752 case Type::MemberPointer:
11753 llvm_unreachable("C++ should never be in mergeTypes");
11754
11755 case Type::ObjCInterface:
11756 case Type::IncompleteArray:
11757 case Type::VariableArray:
11758 case Type::FunctionProto:
11759 case Type::ExtVector:
11760 llvm_unreachable("Types are eliminated above");
11761
11762 case Type::Pointer:
11763 {
11764 // Merge two pointer types, while trying to preserve typedef info
11765 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
11766 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
11767 if (Unqualified) {
11768 LHSPointee = LHSPointee.getUnqualifiedType();
11769 RHSPointee = RHSPointee.getUnqualifiedType();
11770 }
11771 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
11772 Unqualified);
11773 if (ResultType.isNull())
11774 return {};
11775 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11776 return LHS;
11777 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
11778 return RHS;
11779 return getPointerType(ResultType);
11780 }
11781 case Type::BlockPointer:
11782 {
11783 // Merge two block pointer types, while trying to preserve typedef info
11784 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
11785 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
11786 if (Unqualified) {
11787 LHSPointee = LHSPointee.getUnqualifiedType();
11788 RHSPointee = RHSPointee.getUnqualifiedType();
11789 }
11790 if (getLangOpts().OpenCL) {
11791 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
11792 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
11793 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
11794 // 6.12.5) thus the following check is asymmetric.
11795 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual, *this))
11796 return {};
11797 LHSPteeQual.removeAddressSpace();
11798 RHSPteeQual.removeAddressSpace();
11799 LHSPointee =
11800 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
11801 RHSPointee =
11802 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
11803 }
11804 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
11805 Unqualified);
11806 if (ResultType.isNull())
11807 return {};
11808 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11809 return LHS;
11810 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
11811 return RHS;
11812 return getBlockPointerType(ResultType);
11813 }
11814 case Type::Atomic:
11815 {
11816 // Merge two pointer types, while trying to preserve typedef info
11817 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
11818 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
11819 if (Unqualified) {
11820 LHSValue = LHSValue.getUnqualifiedType();
11821 RHSValue = RHSValue.getUnqualifiedType();
11822 }
11823 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
11824 Unqualified);
11825 if (ResultType.isNull())
11826 return {};
11827 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
11828 return LHS;
11829 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
11830 return RHS;
11831 return getAtomicType(ResultType);
11832 }
11833 case Type::ConstantArray:
11834 {
11835 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
11836 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
11837 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
11838 return {};
11839
11840 QualType LHSElem = getAsArrayType(LHS)->getElementType();
11841 QualType RHSElem = getAsArrayType(RHS)->getElementType();
11842 if (Unqualified) {
11843 LHSElem = LHSElem.getUnqualifiedType();
11844 RHSElem = RHSElem.getUnqualifiedType();
11845 }
11846
11847 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
11848 if (ResultType.isNull())
11849 return {};
11850
11851 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
11852 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
11853
11854 // If either side is a variable array, and both are complete, check whether
11855 // the current dimension is definite.
11856 if (LVAT || RVAT) {
11857 auto SizeFetch = [this](const VariableArrayType* VAT,
11858 const ConstantArrayType* CAT)
11859 -> std::pair<bool,llvm::APInt> {
11860 if (VAT) {
11861 std::optional<llvm::APSInt> TheInt;
11862 Expr *E = VAT->getSizeExpr();
11863 if (E && (TheInt = E->getIntegerConstantExpr(*this)))
11864 return std::make_pair(true, *TheInt);
11865 return std::make_pair(false, llvm::APSInt());
11866 }
11867 if (CAT)
11868 return std::make_pair(true, CAT->getSize());
11869 return std::make_pair(false, llvm::APInt());
11870 };
11871
11872 bool HaveLSize, HaveRSize;
11873 llvm::APInt LSize, RSize;
11874 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
11875 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
11876 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
11877 return {}; // Definite, but unequal, array dimension
11878 }
11879
11880 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
11881 return LHS;
11882 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
11883 return RHS;
11884 if (LCAT)
11885 return getConstantArrayType(ResultType, LCAT->getSize(),
11886 LCAT->getSizeExpr(), ArraySizeModifier(), 0);
11887 if (RCAT)
11888 return getConstantArrayType(ResultType, RCAT->getSize(),
11889 RCAT->getSizeExpr(), ArraySizeModifier(), 0);
11890 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
11891 return LHS;
11892 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
11893 return RHS;
11894 if (LVAT) {
11895 // FIXME: This isn't correct! But tricky to implement because
11896 // the array's size has to be the size of LHS, but the type
11897 // has to be different.
11898 return LHS;
11899 }
11900 if (RVAT) {
11901 // FIXME: This isn't correct! But tricky to implement because
11902 // the array's size has to be the size of RHS, but the type
11903 // has to be different.
11904 return RHS;
11905 }
11906 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
11907 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
11908 return getIncompleteArrayType(ResultType, ArraySizeModifier(), 0);
11909 }
11910 case Type::FunctionNoProto:
11911 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified,
11912 /*AllowCXX=*/false, IsConditionalOperator);
11913 case Type::Record:
11914 case Type::Enum:
11915 return mergeTagDefinitions(LHS, RHS);
11916 case Type::Builtin:
11917 // Only exactly equal builtin types are compatible, which is tested above.
11918 return {};
11919 case Type::Complex:
11920 // Distinct complex types are incompatible.
11921 return {};
11922 case Type::Vector:
11923 // FIXME: The merged type should be an ExtVector!
11924 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
11925 RHSCan->castAs<VectorType>()))
11926 return LHS;
11927 return {};
11928 case Type::ConstantMatrix:
11929 if (areCompatMatrixTypes(LHSCan->castAs<ConstantMatrixType>(),
11930 RHSCan->castAs<ConstantMatrixType>()))
11931 return LHS;
11932 return {};
11933 case Type::ObjCObject: {
11934 // Check if the types are assignment compatible.
11935 // FIXME: This should be type compatibility, e.g. whether
11936 // "LHS x; RHS x;" at global scope is legal.
11937 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectType>(),
11938 RHS->castAs<ObjCObjectType>()))
11939 return LHS;
11940 return {};
11941 }
11942 case Type::ObjCObjectPointer:
11943 if (OfBlockPointer) {
11944 if (canAssignObjCInterfacesInBlockPointer(
11945 LHS->castAs<ObjCObjectPointerType>(),
11946 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
11947 return LHS;
11948 return {};
11949 }
11950 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectPointerType>(),
11951 RHS->castAs<ObjCObjectPointerType>()))
11952 return LHS;
11953 return {};
11954 case Type::Pipe:
11955 assert(LHS != RHS &&
11956 "Equivalent pipe types should have already been handled!");
11957 return {};
11958 case Type::ArrayParameter:
11959 assert(LHS != RHS &&
11960 "Equivalent ArrayParameter types should have already been handled!");
11961 return {};
11962 case Type::BitInt: {
11963 // Merge two bit-precise int types, while trying to preserve typedef info.
11964 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
11965 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
11966 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
11967 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
11968
11969 // Like unsigned/int, shouldn't have a type if they don't match.
11970 if (LHSUnsigned != RHSUnsigned)
11971 return {};
11972
11973 if (LHSBits != RHSBits)
11974 return {};
11975 return LHS;
11976 }
11977 case Type::HLSLAttributedResource: {
11978 const HLSLAttributedResourceType *LHSTy =
11979 LHS->castAs<HLSLAttributedResourceType>();
11980 const HLSLAttributedResourceType *RHSTy =
11981 RHS->castAs<HLSLAttributedResourceType>();
11982 assert(LHSTy->getWrappedType() == RHSTy->getWrappedType() &&
11983 LHSTy->getWrappedType()->isHLSLResourceType() &&
11984 "HLSLAttributedResourceType should always wrap __hlsl_resource_t");
11985
11986 if (LHSTy->getAttrs() == RHSTy->getAttrs() &&
11987 LHSTy->getContainedType() == RHSTy->getContainedType())
11988 return LHS;
11989 return {};
11990 }
11991 case Type::HLSLInlineSpirv:
11992 const HLSLInlineSpirvType *LHSTy = LHS->castAs<HLSLInlineSpirvType>();
11993 const HLSLInlineSpirvType *RHSTy = RHS->castAs<HLSLInlineSpirvType>();
11994
11995 if (LHSTy->getOpcode() == RHSTy->getOpcode() &&
11996 LHSTy->getSize() == RHSTy->getSize() &&
11997 LHSTy->getAlignment() == RHSTy->getAlignment()) {
11998 for (size_t I = 0; I < LHSTy->getOperands().size(); I++)
11999 if (LHSTy->getOperands()[I] != RHSTy->getOperands()[I])
12000 return {};
12001
12002 return LHS;
12003 }
12004 return {};
12005 }
12006
12007 llvm_unreachable("Invalid Type::Class!");
12008 }
12009
12010 bool ASTContext::mergeExtParameterInfo(
12011 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
12012 bool &CanUseFirst, bool &CanUseSecond,
12013 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
12014 assert(NewParamInfos.empty() && "param info list not empty");
12015 CanUseFirst = CanUseSecond = true;
12016 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
12017 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
12018
12019 // Fast path: if the first type doesn't have ext parameter infos,
12020 // we match if and only if the second type also doesn't have them.
12021 if (!FirstHasInfo && !SecondHasInfo)
12022 return true;
12023
12024 bool NeedParamInfo = false;
12025 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
12026 : SecondFnType->getExtParameterInfos().size();
12027
12028 for (size_t I = 0; I < E; ++I) {
12029 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
12030 if (FirstHasInfo)
12031 FirstParam = FirstFnType->getExtParameterInfo(I);
12032 if (SecondHasInfo)
12033 SecondParam = SecondFnType->getExtParameterInfo(I);
12034
12035 // Cannot merge unless everything except the noescape flag matches.
12036 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
12037 return false;
12038
12039 bool FirstNoEscape = FirstParam.isNoEscape();
12040 bool SecondNoEscape = SecondParam.isNoEscape();
12041 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
12042 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
12043 if (NewParamInfos.back().getOpaqueValue())
12044 NeedParamInfo = true;
12045 if (FirstNoEscape != IsNoEscape)
12046 CanUseFirst = false;
12047 if (SecondNoEscape != IsNoEscape)
12048 CanUseSecond = false;
12049 }
12050
12051 if (!NeedParamInfo)
12052 NewParamInfos.clear();
12053
12054 return true;
12055 }
12056
12057 void ASTContext::ResetObjCLayout(const ObjCInterfaceDecl *D) {
12058 if (auto It = ObjCLayouts.find(D); It != ObjCLayouts.end()) {
12059 It->second = nullptr;
12060 for (auto *SubClass : ObjCSubClasses.lookup(D))
12061 ResetObjCLayout(SubClass);
12062 }
12063 }
12064
12065 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
12066 /// 'RHS' attributes and returns the merged version; including for function
12067 /// return types.
12068 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
12069 QualType LHSCan = getCanonicalType(LHS),
12070 RHSCan = getCanonicalType(RHS);
12071 // If two types are identical, they are compatible.
12072 if (LHSCan == RHSCan)
12073 return LHS;
12074 if (RHSCan->isFunctionType()) {
12075 if (!LHSCan->isFunctionType())
12076 return {};
12077 QualType OldReturnType =
12078 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
12079 QualType NewReturnType =
12080 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
12081 QualType ResReturnType =
12082 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
12083 if (ResReturnType.isNull())
12084 return {};
12085 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
12086 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
12087 // In either case, use OldReturnType to build the new function type.
12088 const auto *F = LHS->castAs<FunctionType>();
12089 if (const auto *FPT = cast<FunctionProtoType>(F)) {
12090 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12091 EPI.ExtInfo = getFunctionExtInfo(LHS);
12092 QualType ResultType =
12093 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
12094 return ResultType;
12095 }
12096 }
12097 return {};
12098 }
12099
12100 // If the qualifiers are different, the types can still be merged.
12101 Qualifiers LQuals = LHSCan.getLocalQualifiers();
12102 Qualifiers RQuals = RHSCan.getLocalQualifiers();
12103 if (LQuals != RQuals) {
12104 // If any of these qualifiers are different, we have a type mismatch.
12105 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
12106 LQuals.getAddressSpace() != RQuals.getAddressSpace())
12107 return {};
12108
12109 // Exactly one GC qualifier difference is allowed: __strong is
12110 // okay if the other type has no GC qualifier but is an Objective
12111 // C object pointer (i.e. implicitly strong by default). We fix
12112 // this by pretending that the unqualified type was actually
12113 // qualified __strong.
12114 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
12115 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
12116 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
12117
12118 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
12119 return {};
12120
12121 if (GC_L == Qualifiers::Strong)
12122 return LHS;
12123 if (GC_R == Qualifiers::Strong)
12124 return RHS;
12125 return {};
12126 }
12127
12128 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
12129 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12130 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12131 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
12132 if (ResQT == LHSBaseQT)
12133 return LHS;
12134 if (ResQT == RHSBaseQT)
12135 return RHS;
12136 }
12137 return {};
12138 }
12139
12140 //===----------------------------------------------------------------------===//
12141 // Integer Predicates
12142 //===----------------------------------------------------------------------===//
12143
12144 unsigned ASTContext::getIntWidth(QualType T) const {
12145 if (const auto *ED = T->getAsEnumDecl())
12146 T = ED->getIntegerType();
12147 if (T->isBooleanType())
12148 return 1;
12149 if (const auto *EIT = T->getAs<BitIntType>())
12150 return EIT->getNumBits();
12151 // For builtin types, just use the standard type sizing method
12152 return (unsigned)getTypeSize(T);
12153 }
12154
12155 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
12156 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12157 T->isFixedPointType()) &&
12158 "Unexpected type");
12159
12160 // Turn <4 x signed int> -> <4 x unsigned int>
12161 if (const auto *VTy = T->getAs<VectorType>())
12162 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
12163 VTy->getNumElements(), VTy->getVectorKind());
12164
12165 // For _BitInt, return an unsigned _BitInt with same width.
12166 if (const auto *EITy = T->getAs<BitIntType>())
12167 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
12168
12169 // For enums, get the underlying integer type of the enum, and let the general
12170 // integer type signchanging code handle it.
12171 if (const auto *ED = T->getAsEnumDecl())
12172 T = ED->getIntegerType();
12173
12174 switch (T->castAs<BuiltinType>()->getKind()) {
12175 case BuiltinType::Char_U:
12176 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
12177 case BuiltinType::Char_S:
12178 case BuiltinType::SChar:
12179 case BuiltinType::Char8:
12180 return UnsignedCharTy;
12181 case BuiltinType::Short:
12182 return UnsignedShortTy;
12183 case BuiltinType::Int:
12184 return UnsignedIntTy;
12185 case BuiltinType::Long:
12186 return UnsignedLongTy;
12187 case BuiltinType::LongLong:
12188 return UnsignedLongLongTy;
12189 case BuiltinType::Int128:
12190 return UnsignedInt128Ty;
12191 // wchar_t is special. It is either signed or not, but when it's signed,
12192 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
12193 // version of its underlying type instead.
12194 case BuiltinType::WChar_S:
12195 return getUnsignedWCharType();
12196
12197 case BuiltinType::ShortAccum:
12198 return UnsignedShortAccumTy;
12199 case BuiltinType::Accum:
12200 return UnsignedAccumTy;
12201 case BuiltinType::LongAccum:
12202 return UnsignedLongAccumTy;
12203 case BuiltinType::SatShortAccum:
12204 return SatUnsignedShortAccumTy;
12205 case BuiltinType::SatAccum:
12206 return SatUnsignedAccumTy;
12207 case BuiltinType::SatLongAccum:
12208 return SatUnsignedLongAccumTy;
12209 case BuiltinType::ShortFract:
12210 return UnsignedShortFractTy;
12211 case BuiltinType::Fract:
12212 return UnsignedFractTy;
12213 case BuiltinType::LongFract:
12214 return UnsignedLongFractTy;
12215 case BuiltinType::SatShortFract:
12216 return SatUnsignedShortFractTy;
12217 case BuiltinType::SatFract:
12218 return SatUnsignedFractTy;
12219 case BuiltinType::SatLongFract:
12220 return SatUnsignedLongFractTy;
12221 default:
12222 assert((T->hasUnsignedIntegerRepresentation() ||
12223 T->isUnsignedFixedPointType()) &&
12224 "Unexpected signed integer or fixed point type");
12225 return T;
12226 }
12227 }
12228
12229 QualType ASTContext::getCorrespondingSignedType(QualType T) const {
12230 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12231 T->isFixedPointType()) &&
12232 "Unexpected type");
12233
12234 // Turn <4 x unsigned int> -> <4 x signed int>
12235 if (const auto *VTy = T->getAs<VectorType>())
12236 return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
12237 VTy->getNumElements(), VTy->getVectorKind());
12238
12239 // For _BitInt, return a signed _BitInt with same width.
12240 if (const auto *EITy = T->getAs<BitIntType>())
12241 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
12242
12243 // For enums, get the underlying integer type of the enum, and let the general
12244 // integer type signchanging code handle it.
12245 if (const auto *ED = T->getAsEnumDecl())
12246 T = ED->getIntegerType();
12247
12248 switch (T->castAs<BuiltinType>()->getKind()) {
12249 case BuiltinType::Char_S:
12250 // Plain `char` is mapped to `signed char` even if it's already signed
12251 case BuiltinType::Char_U:
12252 case BuiltinType::UChar:
12253 case BuiltinType::Char8:
12254 return SignedCharTy;
12255 case BuiltinType::UShort:
12256 return ShortTy;
12257 case BuiltinType::UInt:
12258 return IntTy;
12259 case BuiltinType::ULong:
12260 return LongTy;
12261 case BuiltinType::ULongLong:
12262 return LongLongTy;
12263 case BuiltinType::UInt128:
12264 return Int128Ty;
12265 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
12266 // there's no matching "signed wchar_t". Therefore we return the signed
12267 // version of its underlying type instead.
12268 case BuiltinType::WChar_U:
12269 return getSignedWCharType();
12270
12271 case BuiltinType::UShortAccum:
12272 return ShortAccumTy;
12273 case BuiltinType::UAccum:
12274 return AccumTy;
12275 case BuiltinType::ULongAccum:
12276 return LongAccumTy;
12277 case BuiltinType::SatUShortAccum:
12278 return SatShortAccumTy;
12279 case BuiltinType::SatUAccum:
12280 return SatAccumTy;
12281 case BuiltinType::SatULongAccum:
12282 return SatLongAccumTy;
12283 case BuiltinType::UShortFract:
12284 return ShortFractTy;
12285 case BuiltinType::UFract:
12286 return FractTy;
12287 case BuiltinType::ULongFract:
12288 return LongFractTy;
12289 case BuiltinType::SatUShortFract:
12290 return SatShortFractTy;
12291 case BuiltinType::SatUFract:
12292 return SatFractTy;
12293 case BuiltinType::SatULongFract:
12294 return SatLongFractTy;
12295 default:
12296 assert(
12297 (T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
12298 "Unexpected signed integer or fixed point type");
12299 return T;
12300 }
12301 }
12302
12303 ASTMutationListener::~ASTMutationListener() = default;
12304
12305 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
12306 QualType ReturnType) {}
12307
12308 //===----------------------------------------------------------------------===//
12309 // Builtin Type Computation
12310 //===----------------------------------------------------------------------===//
12311
12312 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
12313 /// pointer over the consumed characters. This returns the resultant type. If
12314 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
12315 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
12316 /// a vector of "i*".
12317 ///
12318 /// RequiresICE is filled in on return to indicate whether the value is required
12319 /// to be an Integer Constant Expression.
12320 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
12321 ASTContext::GetBuiltinTypeError &Error,
12322 bool &RequiresICE,
12323 bool AllowTypeModifiers) {
12324 // Modifiers.
12325 int HowLong = 0;
12326 bool Signed = false, Unsigned = false;
12327 RequiresICE = false;
12328
12329 // Read the prefixed modifiers first.
12330 bool Done = false;
12331 #ifndef NDEBUG
12332 bool IsSpecial = false;
12333 #endif
12334 while (!Done) {
12335 switch (*Str++) {
12336 default: Done = true; --Str; break;
12337 case 'I':
12338 RequiresICE = true;
12339 break;
12340 case 'S':
12341 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
12342 assert(!Signed && "Can't use 'S' modifier multiple times!");
12343 Signed = true;
12344 break;
12345 case 'U':
12346 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
12347 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
12348 Unsigned = true;
12349 break;
12350 case 'L':
12351 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
12352 assert(HowLong <= 2 && "Can't have LLLL modifier");
12353 ++HowLong;
12354 break;
12355 case 'N':
12356 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
12357 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12358 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
12359 #ifndef NDEBUG
12360 IsSpecial = true;
12361 #endif
12362 if (Context.getTargetInfo().getLongWidth() == 32)
12363 ++HowLong;
12364 break;
12365 case 'W':
12366 // This modifier represents int64 type.
12367 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12368 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
12369 #ifndef NDEBUG
12370 IsSpecial = true;
12371 #endif
12372 switch (Context.getTargetInfo().getInt64Type()) {
12373 default:
12374 llvm_unreachable("Unexpected integer type");
12375 case TargetInfo::SignedLong:
12376 HowLong = 1;
12377 break;
12378 case TargetInfo::SignedLongLong:
12379 HowLong = 2;
12380 break;
12381 }
12382 break;
12383 case 'Z':
12384 // This modifier represents int32 type.
12385 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12386 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
12387 #ifndef NDEBUG
12388 IsSpecial = true;
12389 #endif
12390 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
12391 default:
12392 llvm_unreachable("Unexpected integer type");
12393 case TargetInfo::SignedInt:
12394 HowLong = 0;
12395 break;
12396 case TargetInfo::SignedLong:
12397 HowLong = 1;
12398 break;
12399 case TargetInfo::SignedLongLong:
12400 HowLong = 2;
12401 break;
12402 }
12403 break;
12404 case 'O':
12405 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12406 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
12407 #ifndef NDEBUG
12408 IsSpecial = true;
12409 #endif
12410 if (Context.getLangOpts().OpenCL)
12411 HowLong = 1;
12412 else
12413 HowLong = 2;
12414 break;
12415 }
12416 }
12417
12418 QualType Type;
12419
12420 // Read the base type.
12421 switch (*Str++) {
12422 default:
12423 llvm_unreachable("Unknown builtin type letter!");
12424 case 'x':
12425 assert(HowLong == 0 && !Signed && !Unsigned &&
12426 "Bad modifiers used with 'x'!");
12427 Type = Context.Float16Ty;
12428 break;
12429 case 'y':
12430 assert(HowLong == 0 && !Signed && !Unsigned &&
12431 "Bad modifiers used with 'y'!");
12432 Type = Context.BFloat16Ty;
12433 break;
12434 case 'v':
12435 assert(HowLong == 0 && !Signed && !Unsigned &&
12436 "Bad modifiers used with 'v'!");
12437 Type = Context.VoidTy;
12438 break;
12439 case 'h':
12440 assert(HowLong == 0 && !Signed && !Unsigned &&
12441 "Bad modifiers used with 'h'!");
12442 Type = Context.HalfTy;
12443 break;
12444 case 'f':
12445 assert(HowLong == 0 && !Signed && !Unsigned &&
12446 "Bad modifiers used with 'f'!");
12447 Type = Context.FloatTy;
12448 break;
12449 case 'd':
12450 assert(HowLong < 3 && !Signed && !Unsigned &&
12451 "Bad modifiers used with 'd'!");
12452 if (HowLong == 1)
12453 Type = Context.LongDoubleTy;
12454 else if (HowLong == 2)
12455 Type = Context.Float128Ty;
12456 else
12457 Type = Context.DoubleTy;
12458 break;
12459 case 's':
12460 assert(HowLong == 0 && "Bad modifiers used with 's'!");
12461 if (Unsigned)
12462 Type = Context.UnsignedShortTy;
12463 else
12464 Type = Context.ShortTy;
12465 break;
12466 case 'i':
12467 if (HowLong == 3)
12468 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
12469 else if (HowLong == 2)
12470 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
12471 else if (HowLong == 1)
12472 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
12473 else
12474 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
12475 break;
12476 case 'c':
12477 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
12478 if (Signed)
12479 Type = Context.SignedCharTy;
12480 else if (Unsigned)
12481 Type = Context.UnsignedCharTy;
12482 else
12483 Type = Context.CharTy;
12484 break;
12485 case 'b': // boolean
12486 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
12487 Type = Context.BoolTy;
12488 break;
12489 case 'z': // size_t.
12490 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
12491 Type = Context.getSizeType();
12492 break;
12493 case 'w': // wchar_t.
12494 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
12495 Type = Context.getWideCharType();
12496 break;
12497 case 'F':
12498 Type = Context.getCFConstantStringType();
12499 break;
12500 case 'G':
12501 Type = Context.getObjCIdType();
12502 break;
12503 case 'H':
12504 Type = Context.getObjCSelType();
12505 break;
12506 case 'M':
12507 Type = Context.getObjCSuperType();
12508 break;
12509 case 'a':
12510 Type = Context.getBuiltinVaListType();
12511 assert(!Type.isNull() && "builtin va list type not initialized!");
12512 break;
12513 case 'A':
12514 // This is a "reference" to a va_list; however, what exactly
12515 // this means depends on how va_list is defined. There are two
12516 // different kinds of va_list: ones passed by value, and ones
12517 // passed by reference. An example of a by-value va_list is
12518 // x86, where va_list is a char*. An example of by-ref va_list
12519 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
12520 // we want this argument to be a char*&; for x86-64, we want
12521 // it to be a __va_list_tag*.
12522 Type = Context.getBuiltinVaListType();
12523 assert(!Type.isNull() && "builtin va list type not initialized!");
12524 if (Type->isArrayType())
12525 Type = Context.getArrayDecayedType(Type);
12526 else
12527 Type = Context.getLValueReferenceType(Type);
12528 break;
12529 case 'q': {
12530 char *End;
12531 unsigned NumElements = strtoul(Str, &End, 10);
12532 assert(End != Str && "Missing vector size");
12533 Str = End;
12534
12535 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12536 RequiresICE, false);
12537 assert(!RequiresICE && "Can't require vector ICE");
12538
12539 Type = Context.getScalableVectorType(ElementType, NumElements);
12540 break;
12541 }
12542 case 'Q': {
12543 switch (*Str++) {
12544 case 'a': {
12545 Type = Context.SveCountTy;
12546 break;
12547 }
12548 case 'b': {
12549 Type = Context.AMDGPUBufferRsrcTy;
12550 break;
12551 }
12552 case 't': {
12553 Type = Context.AMDGPUTextureTy;
12554 break;
12555 }
12556 case 'r': {
12557 Type = Context.HLSLResourceTy;
12558 break;
12559 }
12560 default:
12561 llvm_unreachable("Unexpected target builtin type");
12562 }
12563 break;
12564 }
12565 case 'V': {
12566 char *End;
12567 unsigned NumElements = strtoul(Str, &End, 10);
12568 assert(End != Str && "Missing vector size");
12569 Str = End;
12570
12571 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12572 RequiresICE, false);
12573 assert(!RequiresICE && "Can't require vector ICE");
12574
12575 // TODO: No way to make AltiVec vectors in builtins yet.
12576 Type = Context.getVectorType(ElementType, NumElements, VectorKind::Generic);
12577 break;
12578 }
12579 case 'E': {
12580 char *End;
12581
12582 unsigned NumElements = strtoul(Str, &End, 10);
12583 assert(End != Str && "Missing vector size");
12584
12585 Str = End;
12586
12587 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12588 false);
12589 Type = Context.getExtVectorType(ElementType, NumElements);
12590 break;
12591 }
12592 case 'X': {
12593 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12594 false);
12595 assert(!RequiresICE && "Can't require complex ICE");
12596 Type = Context.getComplexType(ElementType);
12597 break;
12598 }
12599 case 'Y':
12600 Type = Context.getPointerDiffType();
12601 break;
12602 case 'P':
12603 Type = Context.getFILEType();
12604 if (Type.isNull()) {
12605 Error = ASTContext::GE_Missing_stdio;
12606 return {};
12607 }
12608 break;
12609 case 'J':
12610 if (Signed)
12611 Type = Context.getsigjmp_bufType();
12612 else
12613 Type = Context.getjmp_bufType();
12614
12615 if (Type.isNull()) {
12616 Error = ASTContext::GE_Missing_setjmp;
12617 return {};
12618 }
12619 break;
12620 case 'K':
12621 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
12622 Type = Context.getucontext_tType();
12623
12624 if (Type.isNull()) {
12625 Error = ASTContext::GE_Missing_ucontext;
12626 return {};
12627 }
12628 break;
12629 case 'p':
12630 Type = Context.getProcessIDType();
12631 break;
12632 case 'm':
12633 Type = Context.MFloat8Ty;
12634 break;
12635 }
12636
12637 // If there are modifiers and if we're allowed to parse them, go for it.
12638 Done = !AllowTypeModifiers;
12639 while (!Done) {
12640 switch (char c = *Str++) {
12641 default: Done = true; --Str; break;
12642 case '*':
12643 case '&': {
12644 // Both pointers and references can have their pointee types
12645 // qualified with an address space.
12646 char *End;
12647 unsigned AddrSpace = strtoul(Str, &End, 10);
12648 if (End != Str) {
12649 // Note AddrSpace == 0 is not the same as an unspecified address space.
12650 Type = Context.getAddrSpaceQualType(
12651 Type,
12652 Context.getLangASForBuiltinAddressSpace(AddrSpace));
12653 Str = End;
12654 }
12655 if (c == '*')
12656 Type = Context.getPointerType(Type);
12657 else
12658 Type = Context.getLValueReferenceType(Type);
12659 break;
12660 }
12661 // FIXME: There's no way to have a built-in with an rvalue ref arg.
12662 case 'C':
12663 Type = Type.withConst();
12664 break;
12665 case 'D':
12666 Type = Context.getVolatileType(Type);
12667 break;
12668 case 'R':
12669 Type = Type.withRestrict();
12670 break;
12671 }
12672 }
12673
12674 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
12675 "Integer constant 'I' type must be an integer");
12676
12677 return Type;
12678 }
12679
12680 // On some targets such as PowerPC, some of the builtins are defined with custom
12681 // type descriptors for target-dependent types. These descriptors are decoded in
12682 // other functions, but it may be useful to be able to fall back to default
12683 // descriptor decoding to define builtins mixing target-dependent and target-
12684 // independent types. This function allows decoding one type descriptor with
12685 // default decoding.
12686 QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
12687 GetBuiltinTypeError &Error, bool &RequireICE,
12688 bool AllowTypeModifiers) const {
12689 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
12690 }
12691
12692 /// GetBuiltinType - Return the type for the specified builtin.
12693 QualType ASTContext::GetBuiltinType(unsigned Id,
12694 GetBuiltinTypeError &Error,
12695 unsigned *IntegerConstantArgs) const {
12696 const char *TypeStr = BuiltinInfo.getTypeString(Id);
12697 if (TypeStr[0] == '\0') {
12698 Error = GE_Missing_type;
12699 return {};
12700 }
12701
12702 SmallVector<QualType, 8> ArgTypes;
12703
12704 bool RequiresICE = false;
12705 Error = GE_None;
12706 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
12707 RequiresICE, true);
12708 if (Error != GE_None)
12709 return {};
12710
12711 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
12712
12713 while (TypeStr[0] && TypeStr[0] != '.') {
12714 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
12715 if (Error != GE_None)
12716 return {};
12717
12718 // If this argument is required to be an IntegerConstantExpression and the
12719 // caller cares, fill in the bitmask we return.
12720 if (RequiresICE && IntegerConstantArgs)
12721 *IntegerConstantArgs |= 1 << ArgTypes.size();
12722
12723 // Do array -> pointer decay. The builtin should use the decayed type.
12724 if (Ty->isArrayType())
12725 Ty = getArrayDecayedType(Ty);
12726
12727 ArgTypes.push_back(Ty);
12728 }
12729
12730 if (Id == Builtin::BI__GetExceptionInfo)
12731 return {};
12732
12733 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
12734 "'.' should only occur at end of builtin type list!");
12735
12736 bool Variadic = (TypeStr[0] == '.');
12737
12738 FunctionType::ExtInfo EI(Target->getDefaultCallingConv());
12739 if (BuiltinInfo.isNoReturn(Id))
12740 EI = EI.withNoReturn(true);
12741
12742 // We really shouldn't be making a no-proto type here.
12743 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
12744 return getFunctionNoProtoType(ResType, EI);
12745
12746 FunctionProtoType::ExtProtoInfo EPI;
12747 EPI.ExtInfo = EI;
12748 EPI.Variadic = Variadic;
12749 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
12750 EPI.ExceptionSpec.Type =
12751 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
12752
12753 return getFunctionType(ResType, ArgTypes, EPI);
12754 }
12755
12756 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
12757 const FunctionDecl *FD) {
12758 if (!FD->isExternallyVisible())
12759 return GVA_Internal;
12760
12761 // Non-user-provided functions get emitted as weak definitions with every
12762 // use, no matter whether they've been explicitly instantiated etc.
12763 if (!FD->isUserProvided())
12764 return GVA_DiscardableODR;
12765
12766 GVALinkage External;
12767 switch (FD->getTemplateSpecializationKind()) {
12768 case TSK_Undeclared:
12769 case TSK_ExplicitSpecialization:
12770 External = GVA_StrongExternal;
12771 break;
12772
12773 case TSK_ExplicitInstantiationDefinition:
12774 return GVA_StrongODR;
12775
12776 // C++11 [temp.explicit]p10:
12777 // [ Note: The intent is that an inline function that is the subject of
12778 // an explicit instantiation declaration will still be implicitly
12779 // instantiated when used so that the body can be considered for
12780 // inlining, but that no out-of-line copy of the inline function would be
12781 // generated in the translation unit. -- end note ]
12782 case TSK_ExplicitInstantiationDeclaration:
12783 return GVA_AvailableExternally;
12784
12785 case TSK_ImplicitInstantiation:
12786 External = GVA_DiscardableODR;
12787 break;
12788 }
12789
12790 if (!FD->isInlined())
12791 return External;
12792
12793 if ((!Context.getLangOpts().CPlusPlus &&
12794 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12795 !FD->hasAttr<DLLExportAttr>()) ||
12796 FD->hasAttr<GNUInlineAttr>()) {
12797 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
12798
12799 // GNU or C99 inline semantics. Determine whether this symbol should be
12800 // externally visible.
12801 if (FD->isInlineDefinitionExternallyVisible())
12802 return External;
12803
12804 // C99 inline semantics, where the symbol is not externally visible.
12805 return GVA_AvailableExternally;
12806 }
12807
12808 // Functions specified with extern and inline in -fms-compatibility mode
12809 // forcibly get emitted. While the body of the function cannot be later
12810 // replaced, the function definition cannot be discarded.
12811 if (FD->isMSExternInline())
12812 return GVA_StrongODR;
12813
12814 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12815 isa<CXXConstructorDecl>(FD) &&
12816 cast<CXXConstructorDecl>(FD)->isInheritingConstructor())
12817 // Our approach to inheriting constructors is fundamentally different from
12818 // that used by the MS ABI, so keep our inheriting constructor thunks
12819 // internal rather than trying to pick an unambiguous mangling for them.
12820 return GVA_Internal;
12821
12822 return GVA_DiscardableODR;
12823 }
12824
12825 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
12826 const Decl *D, GVALinkage L) {
12827 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
12828 // dllexport/dllimport on inline functions.
12829 if (D->hasAttr<DLLImportAttr>()) {
12830 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
12831 return GVA_AvailableExternally;
12832 } else if (D->hasAttr<DLLExportAttr>()) {
12833 if (L == GVA_DiscardableODR)
12834 return GVA_StrongODR;
12835 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
12836 // Device-side functions with __global__ attribute must always be
12837 // visible externally so they can be launched from host.
12838 if (D->hasAttr<CUDAGlobalAttr>() &&
12839 (L == GVA_DiscardableODR || L == GVA_Internal))
12840 return GVA_StrongODR;
12841 // Single source offloading languages like CUDA/HIP need to be able to
12842 // access static device variables from host code of the same compilation
12843 // unit. This is done by externalizing the static variable with a shared
12844 // name between the host and device compilation which is the same for the
12845 // same compilation unit whereas different among different compilation
12846 // units.
12847 if (Context.shouldExternalize(D))
12848 return GVA_StrongExternal;
12849 }
12850 return L;
12851 }
12852
12853 /// Adjust the GVALinkage for a declaration based on what an external AST source
12854 /// knows about whether there can be other definitions of this declaration.
12855 static GVALinkage
12856 adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
12857 GVALinkage L) {
12858 ExternalASTSource *Source = Ctx.getExternalSource();
12859 if (!Source)
12860 return L;
12861
12862 switch (Source->hasExternalDefinitions(D)) {
12863 case ExternalASTSource::EK_Never:
12864 // Other translation units rely on us to provide the definition.
12865 if (L == GVA_DiscardableODR)
12866 return GVA_StrongODR;
12867 break;
12868
12869 case ExternalASTSource::EK_Always:
12870 return GVA_AvailableExternally;
12871
12872 case ExternalASTSource::EK_ReplyHazy:
12873 break;
12874 }
12875 return L;
12876 }
12877
12878 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
12879 return adjustGVALinkageForExternalDefinitionKind(*this, FD,
12880 adjustGVALinkageForAttributes(*this, FD,
12881 basicGVALinkageForFunction(*this, FD)));
12882 }
12883
12884 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
12885 const VarDecl *VD) {
12886 // As an extension for interactive REPLs, make sure constant variables are
12887 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
12888 // marking them as internal.
12889 if (Context.getLangOpts().CPlusPlus &&
12890 Context.getLangOpts().IncrementalExtensions &&
12891 VD->getType().isConstQualified() &&
12892 !VD->getType().isVolatileQualified() && !VD->isInline() &&
12893 !isa<VarTemplateSpecializationDecl>(VD) && !VD->getDescribedVarTemplate())
12894 return GVA_DiscardableODR;
12895
12896 if (!VD->isExternallyVisible())
12897 return GVA_Internal;
12898
12899 if (VD->isStaticLocal()) {
12900 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
12901 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
12902 LexicalContext = LexicalContext->getLexicalParent();
12903
12904 // ObjC Blocks can create local variables that don't have a FunctionDecl
12905 // LexicalContext.
12906 if (!LexicalContext)
12907 return GVA_DiscardableODR;
12908
12909 // Otherwise, let the static local variable inherit its linkage from the
12910 // nearest enclosing function.
12911 auto StaticLocalLinkage =
12912 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
12913
12914 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
12915 // be emitted in any object with references to the symbol for the object it
12916 // contains, whether inline or out-of-line."
12917 // Similar behavior is observed with MSVC. An alternative ABI could use
12918 // StrongODR/AvailableExternally to match the function, but none are
12919 // known/supported currently.
12920 if (StaticLocalLinkage == GVA_StrongODR ||
12921 StaticLocalLinkage == GVA_AvailableExternally)
12922 return GVA_DiscardableODR;
12923 return StaticLocalLinkage;
12924 }
12925
12926 // MSVC treats in-class initialized static data members as definitions.
12927 // By giving them non-strong linkage, out-of-line definitions won't
12928 // cause link errors.
12929 if (Context.isMSStaticDataMemberInlineDefinition(VD))
12930 return GVA_DiscardableODR;
12931
12932 // Most non-template variables have strong linkage; inline variables are
12933 // linkonce_odr or (occasionally, for compatibility) weak_odr.
12934 GVALinkage StrongLinkage;
12935 switch (Context.getInlineVariableDefinitionKind(VD)) {
12936 case ASTContext::InlineVariableDefinitionKind::None:
12937 StrongLinkage = GVA_StrongExternal;
12938 break;
12939 case ASTContext::InlineVariableDefinitionKind::Weak:
12940 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
12941 StrongLinkage = GVA_DiscardableODR;
12942 break;
12943 case ASTContext::InlineVariableDefinitionKind::Strong:
12944 StrongLinkage = GVA_StrongODR;
12945 break;
12946 }
12947
12948 switch (VD->getTemplateSpecializationKind()) {
12949 case TSK_Undeclared:
12950 return StrongLinkage;
12951
12952 case TSK_ExplicitSpecialization:
12953 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12954 VD->isStaticDataMember()
12955 ? GVA_StrongODR
12956 : StrongLinkage;
12957
12958 case TSK_ExplicitInstantiationDefinition:
12959 return GVA_StrongODR;
12960
12961 case TSK_ExplicitInstantiationDeclaration:
12962 return GVA_AvailableExternally;
12963
12964 case TSK_ImplicitInstantiation:
12965 return GVA_DiscardableODR;
12966 }
12967
12968 llvm_unreachable("Invalid Linkage!");
12969 }
12970
12971 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) const {
12972 return adjustGVALinkageForExternalDefinitionKind(*this, VD,
12973 adjustGVALinkageForAttributes(*this, VD,
12974 basicGVALinkageForVariable(*this, VD)));
12975 }
12976
12977 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
12978 if (const auto *VD = dyn_cast<VarDecl>(D)) {
12979 if (!VD->isFileVarDecl())
12980 return false;
12981 // Global named register variables (GNU extension) are never emitted.
12982 if (VD->getStorageClass() == SC_Register)
12983 return false;
12984 if (VD->getDescribedVarTemplate() ||
12985 isa<VarTemplatePartialSpecializationDecl>(VD))
12986 return false;
12987 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
12988 // We never need to emit an uninstantiated function template.
12989 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12990 return false;
12991 } else if (isa<PragmaCommentDecl>(D))
12992 return true;
12993 else if (isa<PragmaDetectMismatchDecl>(D))
12994 return true;
12995 else if (isa<OMPRequiresDecl>(D))
12996 return true;
12997 else if (isa<OMPThreadPrivateDecl>(D))
12998 return !D->getDeclContext()->isDependentContext();
12999 else if (isa<OMPAllocateDecl>(D))
13000 return !D->getDeclContext()->isDependentContext();
13001 else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D))
13002 return !D->getDeclContext()->isDependentContext();
13003 else if (isa<ImportDecl>(D))
13004 return true;
13005 else
13006 return false;
13007
13008 // If this is a member of a class template, we do not need to emit it.
13009 if (D->getDeclContext()->isDependentContext())
13010 return false;
13011
13012 // Weak references don't produce any output by themselves.
13013 if (D->hasAttr<WeakRefAttr>())
13014 return false;
13015
13016 // SYCL device compilation requires that functions defined with the
13017 // sycl_kernel_entry_point or sycl_external attributes be emitted. All
13018 // other entities are emitted only if they are used by a function
13019 // defined with one of those attributes.
13020 if (LangOpts.SYCLIsDevice)
13021 return isa<FunctionDecl>(D) && (D->hasAttr<SYCLKernelEntryPointAttr>() ||
13022 D->hasAttr<SYCLExternalAttr>());
13023
13024 // Aliases and used decls are required.
13025 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
13026 return true;
13027
13028 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13029 // Forward declarations aren't required.
13030 if (!FD->doesThisDeclarationHaveABody())
13031 return FD->doesDeclarationForceExternallyVisibleDefinition();
13032
13033 // Constructors and destructors are required.
13034 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
13035 return true;
13036
13037 // The key function for a class is required. This rule only comes
13038 // into play when inline functions can be key functions, though.
13039 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13040 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13041 const CXXRecordDecl *RD = MD->getParent();
13042 if (MD->isOutOfLine() && RD->isDynamicClass()) {
13043 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
13044 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
13045 return true;
13046 }
13047 }
13048 }
13049
13050 GVALinkage Linkage = GetGVALinkageForFunction(FD);
13051
13052 // static, static inline, always_inline, and extern inline functions can
13053 // always be deferred. Normal inline functions can be deferred in C99/C++.
13054 // Implicit template instantiations can also be deferred in C++.
13055 return !isDiscardableGVALinkage(Linkage);
13056 }
13057
13058 const auto *VD = cast<VarDecl>(D);
13059 assert(VD->isFileVarDecl() && "Expected file scoped var");
13060
13061 // If the decl is marked as `declare target to`, it should be emitted for the
13062 // host and for the device.
13063 if (LangOpts.OpenMP &&
13064 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
13065 return true;
13066
13067 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
13068 !isMSStaticDataMemberInlineDefinition(VD))
13069 return false;
13070
13071 if (VD->shouldEmitInExternalSource())
13072 return false;
13073
13074 // Variables that can be needed in other TUs are required.
13075 auto Linkage = GetGVALinkageForVariable(VD);
13076 if (!isDiscardableGVALinkage(Linkage))
13077 return true;
13078
13079 // We never need to emit a variable that is available in another TU.
13080 if (Linkage == GVA_AvailableExternally)
13081 return false;
13082
13083 // Variables that have destruction with side-effects are required.
13084 if (VD->needsDestruction(*this))
13085 return true;
13086
13087 // Variables that have initialization with side-effects are required.
13088 if (VD->hasInitWithSideEffects())
13089 return true;
13090
13091 // Likewise, variables with tuple-like bindings are required if their
13092 // bindings have side-effects.
13093 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) {
13094 for (const auto *BD : DD->flat_bindings())
13095 if (const auto *BindingVD = BD->getHoldingVar())
13096 if (DeclMustBeEmitted(BindingVD))
13097 return true;
13098 }
13099
13100 return false;
13101 }
13102
13103 void ASTContext::forEachMultiversionedFunctionVersion(
13104 const FunctionDecl *FD,
13105 llvm::function_ref<void(FunctionDecl *)> Pred) const {
13106 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
13107 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
13108 FD = FD->getMostRecentDecl();
13109 // FIXME: The order of traversal here matters and depends on the order of
13110 // lookup results, which happens to be (mostly) oldest-to-newest, but we
13111 // shouldn't rely on that.
13112 for (auto *CurDecl :
13113 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
13114 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
13115 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
13116 SeenDecls.insert(CurFD).second) {
13117 Pred(CurFD);
13118 }
13119 }
13120 }
13121
13122 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
13123 bool IsCXXMethod) const {
13124 // Pass through to the C++ ABI object
13125 if (IsCXXMethod)
13126 return ABI->getDefaultMethodCallConv(IsVariadic);
13127
13128 switch (LangOpts.getDefaultCallingConv()) {
13129 case LangOptions::DCC_None:
13130 break;
13131 case LangOptions::DCC_CDecl:
13132 return CC_C;
13133 case LangOptions::DCC_FastCall:
13134 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
13135 return CC_X86FastCall;
13136 break;
13137 case LangOptions::DCC_StdCall:
13138 if (!IsVariadic)
13139 return CC_X86StdCall;
13140 break;
13141 case LangOptions::DCC_VectorCall:
13142 // __vectorcall cannot be applied to variadic functions.
13143 if (!IsVariadic)
13144 return CC_X86VectorCall;
13145 break;
13146 case LangOptions::DCC_RegCall:
13147 // __regcall cannot be applied to variadic functions.
13148 if (!IsVariadic)
13149 return CC_X86RegCall;
13150 break;
13151 case LangOptions::DCC_RtdCall:
13152 if (!IsVariadic)
13153 return CC_M68kRTD;
13154 break;
13155 }
13156 return Target->getDefaultCallingConv();
13157 }
13158
13159 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
13160 // Pass through to the C++ ABI object
13161 return ABI->isNearlyEmpty(RD);
13162 }
13163
13164 VTableContextBase *ASTContext::getVTableContext() {
13165 if (!VTContext) {
13166 auto ABI = Target->getCXXABI();
13167 if (ABI.isMicrosoft())
13168 VTContext.reset(new MicrosoftVTableContext(*this));
13169 else {
13170 auto ComponentLayout = getLangOpts().RelativeCXXABIVTables
13171 ? ItaniumVTableContext::Relative
13172 : ItaniumVTableContext::Pointer;
13173 VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout));
13174 }
13175 }
13176 return VTContext.get();
13177 }
13178
13179 MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
13180 if (!T)
13181 T = Target;
13182 switch (T->getCXXABI().getKind()) {
13183 case TargetCXXABI::AppleARM64:
13184 case TargetCXXABI::Fuchsia:
13185 case TargetCXXABI::GenericAArch64:
13186 case TargetCXXABI::GenericItanium:
13187 case TargetCXXABI::GenericARM:
13188 case TargetCXXABI::GenericMIPS:
13189 case TargetCXXABI::iOS:
13190 case TargetCXXABI::WebAssembly:
13191 case TargetCXXABI::WatchOS:
13192 case TargetCXXABI::XL:
13193 return ItaniumMangleContext::create(*this, getDiagnostics());
13194 case TargetCXXABI::Microsoft:
13195 return MicrosoftMangleContext::create(*this, getDiagnostics());
13196 }
13197 llvm_unreachable("Unsupported ABI");
13198 }
13199
13200 MangleContext *ASTContext::createDeviceMangleContext(const TargetInfo &T) {
13201 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
13202 "Device mangle context does not support Microsoft mangling.");
13203 switch (T.getCXXABI().getKind()) {
13204 case TargetCXXABI::AppleARM64:
13205 case TargetCXXABI::Fuchsia:
13206 case TargetCXXABI::GenericAArch64:
13207 case TargetCXXABI::GenericItanium:
13208 case TargetCXXABI::GenericARM:
13209 case TargetCXXABI::GenericMIPS:
13210 case TargetCXXABI::iOS:
13211 case TargetCXXABI::WebAssembly:
13212 case TargetCXXABI::WatchOS:
13213 case TargetCXXABI::XL:
13214 return ItaniumMangleContext::create(
13215 *this, getDiagnostics(),
13216 [](ASTContext &, const NamedDecl *ND) -> UnsignedOrNone {
13217 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
13218 return RD->getDeviceLambdaManglingNumber();
13219 return std::nullopt;
13220 },
13221 /*IsAux=*/true);
13222 case TargetCXXABI::Microsoft:
13223 return MicrosoftMangleContext::create(*this, getDiagnostics(),
13224 /*IsAux=*/true);
13225 }
13226 llvm_unreachable("Unsupported ABI");
13227 }
13228
13229 CXXABI::~CXXABI() = default;
13230
13231 size_t ASTContext::getSideTableAllocatedMemory() const {
13232 return ASTRecordLayouts.getMemorySize() +
13233 llvm::capacity_in_bytes(ObjCLayouts) +
13234 llvm::capacity_in_bytes(KeyFunctions) +
13235 llvm::capacity_in_bytes(ObjCImpls) +
13236 llvm::capacity_in_bytes(BlockVarCopyInits) +
13237 llvm::capacity_in_bytes(DeclAttrs) +
13238 llvm::capacity_in_bytes(TemplateOrInstantiation) +
13239 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
13240 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
13241 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
13242 llvm::capacity_in_bytes(OverriddenMethods) +
13243 llvm::capacity_in_bytes(Types) +
13244 llvm::capacity_in_bytes(VariableArrayTypes);
13245 }
13246
13247 /// getIntTypeForBitwidth -
13248 /// sets integer QualTy according to specified details:
13249 /// bitwidth, signed/unsigned.
13250 /// Returns empty type if there is no appropriate target types.
13251 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
13252 unsigned Signed) const {
13253 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
13254 CanQualType QualTy = getFromTargetType(Ty);
13255 if (!QualTy && DestWidth == 128)
13256 return Signed ? Int128Ty : UnsignedInt128Ty;
13257 return QualTy;
13258 }
13259
13260 /// getRealTypeForBitwidth -
13261 /// sets floating point QualTy according to specified bitwidth.
13262 /// Returns empty type if there is no appropriate target types.
13263 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth,
13264 FloatModeKind ExplicitType) const {
13265 FloatModeKind Ty =
13266 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
13267 switch (Ty) {
13268 case FloatModeKind::Half:
13269 return HalfTy;
13270 case FloatModeKind::Float:
13271 return FloatTy;
13272 case FloatModeKind::Double:
13273 return DoubleTy;
13274 case FloatModeKind::LongDouble:
13275 return LongDoubleTy;
13276 case FloatModeKind::Float128:
13277 return Float128Ty;
13278 case FloatModeKind::Ibm128:
13279 return Ibm128Ty;
13280 case FloatModeKind::NoFloat:
13281 return {};
13282 }
13283
13284 llvm_unreachable("Unhandled TargetInfo::RealType value");
13285 }
13286
13287 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
13288 if (Number <= 1)
13289 return;
13290
13291 MangleNumbers[ND] = Number;
13292
13293 if (Listener)
13294 Listener->AddedManglingNumber(ND, Number);
13295 }
13296
13297 unsigned ASTContext::getManglingNumber(const NamedDecl *ND,
13298 bool ForAuxTarget) const {
13299 auto I = MangleNumbers.find(ND);
13300 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
13301 // CUDA/HIP host compilation encodes host and device mangling numbers
13302 // as lower and upper half of 32 bit integer.
13303 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
13304 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
13305 } else {
13306 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
13307 "number for aux target");
13308 }
13309 return Res > 1 ? Res : 1;
13310 }
13311
13312 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
13313 if (Number <= 1)
13314 return;
13315
13316 StaticLocalNumbers[VD] = Number;
13317
13318 if (Listener)
13319 Listener->AddedStaticLocalNumbers(VD, Number);
13320 }
13321
13322 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
13323 auto I = StaticLocalNumbers.find(VD);
13324 return I != StaticLocalNumbers.end() ? I->second : 1;
13325 }
13326
13327 void ASTContext::setIsDestroyingOperatorDelete(const FunctionDecl *FD,
13328 bool IsDestroying) {
13329 if (!IsDestroying) {
13330 assert(!DestroyingOperatorDeletes.contains(FD->getCanonicalDecl()));
13331 return;
13332 }
13333 DestroyingOperatorDeletes.insert(FD->getCanonicalDecl());
13334 }
13335
13336 bool ASTContext::isDestroyingOperatorDelete(const FunctionDecl *FD) const {
13337 return DestroyingOperatorDeletes.contains(FD->getCanonicalDecl());
13338 }
13339
13340 void ASTContext::setIsTypeAwareOperatorNewOrDelete(const FunctionDecl *FD,
13341 bool IsTypeAware) {
13342 if (!IsTypeAware) {
13343 assert(!TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl()));
13344 return;
13345 }
13346 TypeAwareOperatorNewAndDeletes.insert(FD->getCanonicalDecl());
13347 }
13348
13349 bool ASTContext::isTypeAwareOperatorNewOrDelete(const FunctionDecl *FD) const {
13350 return TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl());
13351 }
13352
13353 void ASTContext::addOperatorDeleteForVDtor(const CXXDestructorDecl *Dtor,
13354 FunctionDecl *OperatorDelete,
13355 OperatorDeleteKind K) const {
13356 switch (K) {
13357 case OperatorDeleteKind::Regular:
13358 OperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] = OperatorDelete;
13359 break;
13360 case OperatorDeleteKind::GlobalRegular:
13361 GlobalOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13362 OperatorDelete;
13363 break;
13364 case OperatorDeleteKind::Array:
13365 ArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13366 OperatorDelete;
13367 break;
13368 case OperatorDeleteKind::ArrayGlobal:
13369 GlobalArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13370 OperatorDelete;
13371 break;
13372 }
13373 }
13374
13375 bool ASTContext::dtorHasOperatorDelete(const CXXDestructorDecl *Dtor,
13376 OperatorDeleteKind K) const {
13377 switch (K) {
13378 case OperatorDeleteKind::Regular:
13379 return OperatorDeletesForVirtualDtor.contains(Dtor->getCanonicalDecl());
13380 case OperatorDeleteKind::GlobalRegular:
13381 return GlobalOperatorDeletesForVirtualDtor.contains(
13382 Dtor->getCanonicalDecl());
13383 case OperatorDeleteKind::Array:
13384 return ArrayOperatorDeletesForVirtualDtor.contains(
13385 Dtor->getCanonicalDecl());
13386 case OperatorDeleteKind::ArrayGlobal:
13387 return GlobalArrayOperatorDeletesForVirtualDtor.contains(
13388 Dtor->getCanonicalDecl());
13389 }
13390 return false;
13391 }
13392
13393 FunctionDecl *
13394 ASTContext::getOperatorDeleteForVDtor(const CXXDestructorDecl *Dtor,
13395 OperatorDeleteKind K) const {
13396 const CXXDestructorDecl *Canon = Dtor->getCanonicalDecl();
13397 switch (K) {
13398 case OperatorDeleteKind::Regular:
13399 if (OperatorDeletesForVirtualDtor.contains(Canon))
13400 return OperatorDeletesForVirtualDtor[Canon];
13401 return nullptr;
13402 case OperatorDeleteKind::GlobalRegular:
13403 if (GlobalOperatorDeletesForVirtualDtor.contains(Canon))
13404 return GlobalOperatorDeletesForVirtualDtor[Canon];
13405 return nullptr;
13406 case OperatorDeleteKind::Array:
13407 if (ArrayOperatorDeletesForVirtualDtor.contains(Canon))
13408 return ArrayOperatorDeletesForVirtualDtor[Canon];
13409 return nullptr;
13410 case OperatorDeleteKind::ArrayGlobal:
13411 if (GlobalArrayOperatorDeletesForVirtualDtor.contains(Canon))
13412 return GlobalArrayOperatorDeletesForVirtualDtor[Canon];
13413 return nullptr;
13414 }
13415 return nullptr;
13416 }
13417
13418 bool ASTContext::classNeedsVectorDeletingDestructor(const CXXRecordDecl *RD) {
13419 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13420 return false;
13421 CXXDestructorDecl *Dtor = RD->getDestructor();
13422 // The compiler can't know if new[]/delete[] will be used outside of the DLL,
13423 // so just force vector deleting destructor emission if dllexport is present.
13424 // This matches MSVC behavior.
13425 if (Dtor && Dtor->isVirtual() && Dtor->hasAttr<DLLExportAttr>())
13426 return true;
13427
13428 return RequireVectorDeletingDtor.count(RD);
13429 }
13430
13431 void ASTContext::setClassNeedsVectorDeletingDestructor(
13432 const CXXRecordDecl *RD) {
13433 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13434 return;
13435 RequireVectorDeletingDtor.insert(RD);
13436 }
13437
13438 MangleNumberingContext &
13439 ASTContext::getManglingNumberContext(const DeclContext *DC) {
13440 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13441 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
13442 if (!MCtx)
13443 MCtx = createMangleNumberingContext();
13444 return *MCtx;
13445 }
13446
13447 MangleNumberingContext &
13448 ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) {
13449 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13450 std::unique_ptr<MangleNumberingContext> &MCtx =
13451 ExtraMangleNumberingContexts[D];
13452 if (!MCtx)
13453 MCtx = createMangleNumberingContext();
13454 return *MCtx;
13455 }
13456
13457 std::unique_ptr<MangleNumberingContext>
13458 ASTContext::createMangleNumberingContext() const {
13459 return ABI->createMangleNumberingContext();
13460 }
13461
13462 const CXXConstructorDecl *
13463 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
13464 return ABI->getCopyConstructorForExceptionObject(
13465 cast<CXXRecordDecl>(RD->getFirstDecl()));
13466 }
13467
13468 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
13469 CXXConstructorDecl *CD) {
13470 return ABI->addCopyConstructorForExceptionObject(
13471 cast<CXXRecordDecl>(RD->getFirstDecl()),
13472 cast<CXXConstructorDecl>(CD->getFirstDecl()));
13473 }
13474
13475 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
13476 TypedefNameDecl *DD) {
13477 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
13478 }
13479
13480 TypedefNameDecl *
13481 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
13482 return ABI->getTypedefNameForUnnamedTagDecl(TD);
13483 }
13484
13485 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
13486 DeclaratorDecl *DD) {
13487 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
13488 }
13489
13490 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
13491 return ABI->getDeclaratorForUnnamedTagDecl(TD);
13492 }
13493
13494 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
13495 ParamIndices[D] = index;
13496 }
13497
13498 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
13499 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
13500 assert(I != ParamIndices.end() &&
13501 "ParmIndices lacks entry set by ParmVarDecl");
13502 return I->second;
13503 }
13504
13505 QualType ASTContext::getStringLiteralArrayType(QualType EltTy,
13506 unsigned Length) const {
13507 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
13508 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
13509 EltTy = EltTy.withConst();
13510
13511 EltTy = adjustStringLiteralBaseType(EltTy);
13512
13513 // Get an array type for the string, according to C99 6.4.5. This includes
13514 // the null terminator character.
13515 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
13516 ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
13517 }
13518
13519 StringLiteral *
13520 ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const {
13521 StringLiteral *&Result = StringLiteralCache[Key];
13522 if (!Result)
13523 Result = StringLiteral::Create(
13524 *this, Key, StringLiteralKind::Ordinary,
13525 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
13526 SourceLocation());
13527 return Result;
13528 }
13529
13530 MSGuidDecl *
13531 ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const {
13532 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
13533
13534 llvm::FoldingSetNodeID ID;
13535 MSGuidDecl::Profile(ID, Parts);
13536
13537 void *InsertPos;
13538 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
13539 return Existing;
13540
13541 QualType GUIDType = getMSGuidType().withConst();
13542 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
13543 MSGuidDecls.InsertNode(New, InsertPos);
13544 return New;
13545 }
13546
13547 UnnamedGlobalConstantDecl *
13548 ASTContext::getUnnamedGlobalConstantDecl(QualType Ty,
13549 const APValue &APVal) const {
13550 llvm::FoldingSetNodeID ID;
13551 UnnamedGlobalConstantDecl::Profile(ID, Ty, APVal);
13552
13553 void *InsertPos;
13554 if (UnnamedGlobalConstantDecl *Existing =
13555 UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos))
13556 return Existing;
13557
13558 UnnamedGlobalConstantDecl *New =
13559 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
13560 UnnamedGlobalConstantDecls.InsertNode(New, InsertPos);
13561 return New;
13562 }
13563
13564 TemplateParamObjectDecl *
13565 ASTContext::getTemplateParamObjectDecl(QualType T, const APValue &V) const {
13566 assert(T->isRecordType() && "template param object of unexpected type");
13567
13568 // C++ [temp.param]p8:
13569 // [...] a static storage duration object of type 'const T' [...]
13570 T.addConst();
13571
13572 llvm::FoldingSetNodeID ID;
13573 TemplateParamObjectDecl::Profile(ID, T, V);
13574
13575 void *InsertPos;
13576 if (TemplateParamObjectDecl *Existing =
13577 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
13578 return Existing;
13579
13580 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
13581 TemplateParamObjectDecls.InsertNode(New, InsertPos);
13582 return New;
13583 }
13584
13585 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
13586 const llvm::Triple &T = getTargetInfo().getTriple();
13587 if (!T.isOSDarwin())
13588 return false;
13589
13590 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
13591 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
13592 return false;
13593
13594 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
13595 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
13596 uint64_t Size = sizeChars.getQuantity();
13597 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
13598 unsigned Align = alignChars.getQuantity();
13599 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
13600 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
13601 }
13602
13603 bool
13604 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
13605 const ObjCMethodDecl *MethodImpl) {
13606 // No point trying to match an unavailable/deprecated mothod.
13607 if (MethodDecl->hasAttr<UnavailableAttr>()
13608 || MethodDecl->hasAttr<DeprecatedAttr>())
13609 return false;
13610 if (MethodDecl->getObjCDeclQualifier() !=
13611 MethodImpl->getObjCDeclQualifier())
13612 return false;
13613 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
13614 return false;
13615
13616 if (MethodDecl->param_size() != MethodImpl->param_size())
13617 return false;
13618
13619 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
13620 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
13621 EF = MethodDecl->param_end();
13622 IM != EM && IF != EF; ++IM, ++IF) {
13623 const ParmVarDecl *DeclVar = (*IF);
13624 const ParmVarDecl *ImplVar = (*IM);
13625 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
13626 return false;
13627 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
13628 return false;
13629 }
13630
13631 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
13632 }
13633
13634 uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
13635 LangAS AS;
13636 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
13637 AS = LangAS::Default;
13638 else
13639 AS = QT->getPointeeType().getAddressSpace();
13640
13641 return getTargetInfo().getNullPointerValue(AS);
13642 }
13643
13644 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
13645 return getTargetInfo().getTargetAddressSpace(AS);
13646 }
13647
13648 bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
13649 if (X == Y)
13650 return true;
13651 if (!X || !Y)
13652 return false;
13653 llvm::FoldingSetNodeID IDX, IDY;
13654 X->Profile(IDX, *this, /*Canonical=*/true);
13655 Y->Profile(IDY, *this, /*Canonical=*/true);
13656 return IDX == IDY;
13657 }
13658
13659 // The getCommon* helpers return, for given 'same' X and Y entities given as
13660 // inputs, another entity which is also the 'same' as the inputs, but which
13661 // is closer to the canonical form of the inputs, each according to a given
13662 // criteria.
13663 // The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
13664 // the regular ones.
13665
13666 static Decl *getCommonDecl(Decl *X, Decl *Y) {
13667 if (!declaresSameEntity(X, Y))
13668 return nullptr;
13669 for (const Decl *DX : X->redecls()) {
13670 // If we reach Y before reaching the first decl, that means X is older.
13671 if (DX == Y)
13672 return X;
13673 // If we reach the first decl, then Y is older.
13674 if (DX->isFirstDecl())
13675 return Y;
13676 }
13677 llvm_unreachable("Corrupt redecls chain");
13678 }
13679
13680 template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13681 static T *getCommonDecl(T *X, T *Y) {
13682 return cast_or_null<T>(
13683 getCommonDecl(const_cast<Decl *>(cast_or_null<Decl>(X)),
13684 const_cast<Decl *>(cast_or_null<Decl>(Y))));
13685 }
13686
13687 template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13688 static T *getCommonDeclChecked(T *X, T *Y) {
13689 return cast<T>(getCommonDecl(const_cast<Decl *>(cast<Decl>(X)),
13690 const_cast<Decl *>(cast<Decl>(Y))));
13691 }
13692
13693 static TemplateName getCommonTemplateName(const ASTContext &Ctx, TemplateName X,
13694 TemplateName Y,
13695 bool IgnoreDeduced = false) {
13696 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
13697 return X;
13698 // FIXME: There are cases here where we could find a common template name
13699 // with more sugar. For example one could be a SubstTemplateTemplate*
13700 // replacing the other.
13701 TemplateName CX = Ctx.getCanonicalTemplateName(X, IgnoreDeduced);
13702 if (CX.getAsVoidPointer() !=
13703 Ctx.getCanonicalTemplateName(Y).getAsVoidPointer())
13704 return TemplateName();
13705 return CX;
13706 }
13707
13708 static TemplateName getCommonTemplateNameChecked(const ASTContext &Ctx,
13709 TemplateName X, TemplateName Y,
13710 bool IgnoreDeduced) {
13711 TemplateName R = getCommonTemplateName(Ctx, X, Y, IgnoreDeduced);
13712 assert(R.getAsVoidPointer() != nullptr);
13713 return R;
13714 }
13715
13716 static auto getCommonTypes(const ASTContext &Ctx, ArrayRef<QualType> Xs,
13717 ArrayRef<QualType> Ys, bool Unqualified = false) {
13718 assert(Xs.size() == Ys.size());
13719 SmallVector<QualType, 8> Rs(Xs.size());
13720 for (size_t I = 0; I < Rs.size(); ++I)
13721 Rs[I] = Ctx.getCommonSugaredType(Xs[I], Ys[I], Unqualified);
13722 return Rs;
13723 }
13724
13725 template <class T>
13726 static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
13727 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
13728 : SourceLocation();
13729 }
13730
13731 static TemplateArgument getCommonTemplateArgument(const ASTContext &Ctx,
13732 const TemplateArgument &X,
13733 const TemplateArgument &Y) {
13734 if (X.getKind() != Y.getKind())
13735 return TemplateArgument();
13736
13737 switch (X.getKind()) {
13738 case TemplateArgument::ArgKind::Type:
13739 if (!Ctx.hasSameType(X.getAsType(), Y.getAsType()))
13740 return TemplateArgument();
13741 return TemplateArgument(
13742 Ctx.getCommonSugaredType(X.getAsType(), Y.getAsType()));
13743 case TemplateArgument::ArgKind::NullPtr:
13744 if (!Ctx.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
13745 return TemplateArgument();
13746 return TemplateArgument(
13747 Ctx.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
13748 /*Unqualified=*/true);
13749 case TemplateArgument::ArgKind::Expression:
13750 if (!Ctx.hasSameType(X.getAsExpr()->getType(), Y.getAsExpr()->getType()))
13751 return TemplateArgument();
13752 // FIXME: Try to keep the common sugar.
13753 return X;
13754 case TemplateArgument::ArgKind::Template: {
13755 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
13756 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13757 if (!CTN.getAsVoidPointer())
13758 return TemplateArgument();
13759 return TemplateArgument(CTN);
13760 }
13761 case TemplateArgument::ArgKind::TemplateExpansion: {
13762 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
13763 TY = Y.getAsTemplateOrTemplatePattern();
13764 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13765 if (!CTN.getAsVoidPointer())
13766 return TemplateName();
13767 auto NExpX = X.getNumTemplateExpansions();
13768 assert(NExpX == Y.getNumTemplateExpansions());
13769 return TemplateArgument(CTN, NExpX);
13770 }
13771 default:
13772 // FIXME: Handle the other argument kinds.
13773 return X;
13774 }
13775 }
13776
13777 static bool getCommonTemplateArguments(const ASTContext &Ctx,
13778 SmallVectorImpl<TemplateArgument> &R,
13779 ArrayRef<TemplateArgument> Xs,
13780 ArrayRef<TemplateArgument> Ys) {
13781 if (Xs.size() != Ys.size())
13782 return true;
13783 R.resize(Xs.size());
13784 for (size_t I = 0; I < R.size(); ++I) {
13785 R[I] = getCommonTemplateArgument(Ctx, Xs[I], Ys[I]);
13786 if (R[I].isNull())
13787 return true;
13788 }
13789 return false;
13790 }
13791
13792 static auto getCommonTemplateArguments(const ASTContext &Ctx,
13793 ArrayRef<TemplateArgument> Xs,
13794 ArrayRef<TemplateArgument> Ys) {
13795 SmallVector<TemplateArgument, 8> R;
13796 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
13797 assert(!Different);
13798 (void)Different;
13799 return R;
13800 }
13801
13802 template <class T>
13803 static ElaboratedTypeKeyword getCommonTypeKeyword(const T *X, const T *Y,
13804 bool IsSame) {
13805 ElaboratedTypeKeyword KX = X->getKeyword(), KY = Y->getKeyword();
13806 if (KX == KY)
13807 return KX;
13808 KX = getCanonicalElaboratedTypeKeyword(KX);
13809 assert(!IsSame || KX == getCanonicalElaboratedTypeKeyword(KY));
13810 return KX;
13811 }
13812
13813 /// Returns a NestedNameSpecifier which has only the common sugar
13814 /// present in both NNS1 and NNS2.
13815 static NestedNameSpecifier getCommonNNS(const ASTContext &Ctx,
13816 NestedNameSpecifier NNS1,
13817 NestedNameSpecifier NNS2, bool IsSame) {
13818 // If they are identical, all sugar is common.
13819 if (NNS1 == NNS2)
13820 return NNS1;
13821
13822 // IsSame implies both Qualifiers are equivalent.
13823 NestedNameSpecifier Canon = NNS1.getCanonical();
13824 if (Canon != NNS2.getCanonical()) {
13825 assert(!IsSame && "Should be the same NestedNameSpecifier");
13826 // If they are not the same, there is nothing to unify.
13827 return std::nullopt;
13828 }
13829
13830 NestedNameSpecifier R = std::nullopt;
13831 NestedNameSpecifier::Kind Kind = NNS1.getKind();
13832 assert(Kind == NNS2.getKind());
13833 switch (Kind) {
13834 case NestedNameSpecifier::Kind::Namespace: {
13835 auto [Namespace1, Prefix1] = NNS1.getAsNamespaceAndPrefix();
13836 auto [Namespace2, Prefix2] = NNS2.getAsNamespaceAndPrefix();
13837 auto Kind = Namespace1->getKind();
13838 if (Kind != Namespace2->getKind() ||
13839 (Kind == Decl::NamespaceAlias &&
13840 !declaresSameEntity(Namespace1, Namespace2))) {
13841 R = NestedNameSpecifier(
13842 Ctx,
13843 ::getCommonDeclChecked(Namespace1->getNamespace(),
13844 Namespace2->getNamespace()),
13845 /*Prefix=*/std::nullopt);
13846 break;
13847 }
13848 // The prefixes for namespaces are not significant, its declaration
13849 // identifies it uniquely.
13850 NestedNameSpecifier Prefix = ::getCommonNNS(Ctx, Prefix1, Prefix2,
13851 /*IsSame=*/false);
13852 R = NestedNameSpecifier(Ctx, ::getCommonDeclChecked(Namespace1, Namespace2),
13853 Prefix);
13854 break;
13855 }
13856 case NestedNameSpecifier::Kind::Type: {
13857 const Type *T1 = NNS1.getAsType(), *T2 = NNS2.getAsType();
13858 const Type *T = Ctx.getCommonSugaredType(QualType(T1, 0), QualType(T2, 0),
13859 /*Unqualified=*/true)
13860 .getTypePtr();
13861 R = NestedNameSpecifier(T);
13862 break;
13863 }
13864 case NestedNameSpecifier::Kind::MicrosoftSuper: {
13865 // FIXME: Can __super even be used with data members?
13866 // If it's only usable in functions, we will never see it here,
13867 // unless we save the qualifiers used in function types.
13868 // In that case, it might be possible NNS2 is a type,
13869 // in which case we should degrade the result to
13870 // a CXXRecordType.
13871 R = NestedNameSpecifier(getCommonDeclChecked(NNS1.getAsMicrosoftSuper(),
13872 NNS2.getAsMicrosoftSuper()));
13873 break;
13874 }
13875 case NestedNameSpecifier::Kind::Null:
13876 case NestedNameSpecifier::Kind::Global:
13877 // These are singletons.
13878 llvm_unreachable("singletons did not compare equal");
13879 }
13880 assert(R.getCanonical() == Canon);
13881 return R;
13882 }
13883
13884 template <class T>
13885 static NestedNameSpecifier getCommonQualifier(const ASTContext &Ctx, const T *X,
13886 const T *Y, bool IsSame) {
13887 return ::getCommonNNS(Ctx, X->getQualifier(), Y->getQualifier(), IsSame);
13888 }
13889
13890 template <class T>
13891 static QualType getCommonElementType(const ASTContext &Ctx, const T *X,
13892 const T *Y) {
13893 return Ctx.getCommonSugaredType(X->getElementType(), Y->getElementType());
13894 }
13895
13896 template <class T>
13897 static QualType getCommonArrayElementType(const ASTContext &Ctx, const T *X,
13898 Qualifiers &QX, const T *Y,
13899 Qualifiers &QY) {
13900 QualType EX = X->getElementType(), EY = Y->getElementType();
13901 QualType R = Ctx.getCommonSugaredType(EX, EY,
13902 /*Unqualified=*/true);
13903 // Qualifiers common to both element types.
13904 Qualifiers RQ = R.getQualifiers();
13905 // For each side, move to the top level any qualifiers which are not common to
13906 // both element types. The caller must assume top level qualifiers might
13907 // be different, even if they are the same type, and can be treated as sugar.
13908 QX += EX.getQualifiers() - RQ;
13909 QY += EY.getQualifiers() - RQ;
13910 return R;
13911 }
13912
13913 template <class T>
13914 static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X,
13915 const T *Y) {
13916 return Ctx.getCommonSugaredType(X->getPointeeType(), Y->getPointeeType());
13917 }
13918
13919 template <class T>
13920 static auto *getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y) {
13921 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
13922 return X->getSizeExpr();
13923 }
13924
13925 static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
13926 assert(X->getSizeModifier() == Y->getSizeModifier());
13927 return X->getSizeModifier();
13928 }
13929
13930 static auto getCommonIndexTypeCVRQualifiers(const ArrayType *X,
13931 const ArrayType *Y) {
13932 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
13933 return X->getIndexTypeCVRQualifiers();
13934 }
13935
13936 // Merges two type lists such that the resulting vector will contain
13937 // each type (in a canonical sense) only once, in the order they appear
13938 // from X to Y. If they occur in both X and Y, the result will contain
13939 // the common sugared type between them.
13940 static void mergeTypeLists(const ASTContext &Ctx,
13941 SmallVectorImpl<QualType> &Out, ArrayRef<QualType> X,
13942 ArrayRef<QualType> Y) {
13943 llvm::DenseMap<QualType, unsigned> Found;
13944 for (auto Ts : {X, Y}) {
13945 for (QualType T : Ts) {
13946 auto Res = Found.try_emplace(Ctx.getCanonicalType(T), Out.size());
13947 if (!Res.second) {
13948 QualType &U = Out[Res.first->second];
13949 U = Ctx.getCommonSugaredType(U, T);
13950 } else {
13951 Out.emplace_back(T);
13952 }
13953 }
13954 }
13955 }
13956
13957 FunctionProtoType::ExceptionSpecInfo
13958 ASTContext::mergeExceptionSpecs(FunctionProtoType::ExceptionSpecInfo ESI1,
13959 FunctionProtoType::ExceptionSpecInfo ESI2,
13960 SmallVectorImpl<QualType> &ExceptionTypeStorage,
13961 bool AcceptDependent) const {
13962 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
13963
13964 // If either of them can throw anything, that is the result.
13965 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
13966 if (EST1 == I)
13967 return ESI1;
13968 if (EST2 == I)
13969 return ESI2;
13970 }
13971
13972 // If either of them is non-throwing, the result is the other.
13973 for (auto I :
13974 {EST_NoThrow, EST_DynamicNone, EST_BasicNoexcept, EST_NoexceptTrue}) {
13975 if (EST1 == I)
13976 return ESI2;
13977 if (EST2 == I)
13978 return ESI1;
13979 }
13980
13981 // If we're left with value-dependent computed noexcept expressions, we're
13982 // stuck. Before C++17, we can just drop the exception specification entirely,
13983 // since it's not actually part of the canonical type. And this should never
13984 // happen in C++17, because it would mean we were computing the composite
13985 // pointer type of dependent types, which should never happen.
13986 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
13987 assert(AcceptDependent &&
13988 "computing composite pointer type of dependent types");
13989 return FunctionProtoType::ExceptionSpecInfo();
13990 }
13991
13992 // Switch over the possibilities so that people adding new values know to
13993 // update this function.
13994 switch (EST1) {
13995 case EST_None:
13996 case EST_DynamicNone:
13997 case EST_MSAny:
13998 case EST_BasicNoexcept:
13999 case EST_DependentNoexcept:
14000 case EST_NoexceptFalse:
14001 case EST_NoexceptTrue:
14002 case EST_NoThrow:
14003 llvm_unreachable("These ESTs should be handled above");
14004
14005 case EST_Dynamic: {
14006 // This is the fun case: both exception specifications are dynamic. Form
14007 // the union of the two lists.
14008 assert(EST2 == EST_Dynamic && "other cases should already be handled");
14009 mergeTypeLists(*this, ExceptionTypeStorage, ESI1.Exceptions,
14010 ESI2.Exceptions);
14011 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
14012 Result.Exceptions = ExceptionTypeStorage;
14013 return Result;
14014 }
14015
14016 case EST_Unevaluated:
14017 case EST_Uninstantiated:
14018 case EST_Unparsed:
14019 llvm_unreachable("shouldn't see unresolved exception specifications here");
14020 }
14021
14022 llvm_unreachable("invalid ExceptionSpecificationType");
14023 }
14024
14025 static QualType getCommonNonSugarTypeNode(const ASTContext &Ctx, const Type *X,
14026 Qualifiers &QX, const Type *Y,
14027 Qualifiers &QY) {
14028 Type::TypeClass TC = X->getTypeClass();
14029 assert(TC == Y->getTypeClass());
14030 switch (TC) {
14031 #define UNEXPECTED_TYPE(Class, Kind) \
14032 case Type::Class: \
14033 llvm_unreachable("Unexpected " Kind ": " #Class);
14034
14035 #define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
14036 #define TYPE(Class, Base)
14037 #include "clang/AST/TypeNodes.inc"
14038
14039 #define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
14040 SUGAR_FREE_TYPE(Builtin)
14041 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
14042 SUGAR_FREE_TYPE(DependentBitInt)
14043 SUGAR_FREE_TYPE(BitInt)
14044 SUGAR_FREE_TYPE(ObjCInterface)
14045 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
14046 SUGAR_FREE_TYPE(SubstBuiltinTemplatePack)
14047 SUGAR_FREE_TYPE(UnresolvedUsing)
14048 SUGAR_FREE_TYPE(HLSLAttributedResource)
14049 SUGAR_FREE_TYPE(HLSLInlineSpirv)
14050 #undef SUGAR_FREE_TYPE
14051 #define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
14052 NON_UNIQUE_TYPE(TypeOfExpr)
14053 NON_UNIQUE_TYPE(VariableArray)
14054 #undef NON_UNIQUE_TYPE
14055
14056 UNEXPECTED_TYPE(TypeOf, "sugar")
14057
14058 #undef UNEXPECTED_TYPE
14059
14060 case Type::Auto: {
14061 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14062 assert(AX->getDeducedType().isNull());
14063 assert(AY->getDeducedType().isNull());
14064 assert(AX->getKeyword() == AY->getKeyword());
14065 assert(AX->isInstantiationDependentType() ==
14066 AY->isInstantiationDependentType());
14067 auto As = getCommonTemplateArguments(Ctx, AX->getTypeConstraintArguments(),
14068 AY->getTypeConstraintArguments());
14069 return Ctx.getAutoType(QualType(), AX->getKeyword(),
14070 AX->isInstantiationDependentType(),
14071 AX->containsUnexpandedParameterPack(),
14072 getCommonDeclChecked(AX->getTypeConstraintConcept(),
14073 AY->getTypeConstraintConcept()),
14074 As);
14075 }
14076 case Type::IncompleteArray: {
14077 const auto *AX = cast<IncompleteArrayType>(X),
14078 *AY = cast<IncompleteArrayType>(Y);
14079 return Ctx.getIncompleteArrayType(
14080 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14081 getCommonSizeModifier(AX, AY), getCommonIndexTypeCVRQualifiers(AX, AY));
14082 }
14083 case Type::DependentSizedArray: {
14084 const auto *AX = cast<DependentSizedArrayType>(X),
14085 *AY = cast<DependentSizedArrayType>(Y);
14086 return Ctx.getDependentSizedArrayType(
14087 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14088 getCommonSizeExpr(Ctx, AX, AY), getCommonSizeModifier(AX, AY),
14089 getCommonIndexTypeCVRQualifiers(AX, AY));
14090 }
14091 case Type::ConstantArray: {
14092 const auto *AX = cast<ConstantArrayType>(X),
14093 *AY = cast<ConstantArrayType>(Y);
14094 assert(AX->getSize() == AY->getSize());
14095 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14096 ? AX->getSizeExpr()
14097 : nullptr;
14098 return Ctx.getConstantArrayType(
14099 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14100 getCommonSizeModifier(AX, AY), getCommonIndexTypeCVRQualifiers(AX, AY));
14101 }
14102 case Type::ArrayParameter: {
14103 const auto *AX = cast<ArrayParameterType>(X),
14104 *AY = cast<ArrayParameterType>(Y);
14105 assert(AX->getSize() == AY->getSize());
14106 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14107 ? AX->getSizeExpr()
14108 : nullptr;
14109 auto ArrayTy = Ctx.getConstantArrayType(
14110 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14111 getCommonSizeModifier(AX, AY), getCommonIndexTypeCVRQualifiers(AX, AY));
14112 return Ctx.getArrayParameterType(ArrayTy);
14113 }
14114 case Type::Atomic: {
14115 const auto *AX = cast<AtomicType>(X), *AY = cast<AtomicType>(Y);
14116 return Ctx.getAtomicType(
14117 Ctx.getCommonSugaredType(AX->getValueType(), AY->getValueType()));
14118 }
14119 case Type::Complex: {
14120 const auto *CX = cast<ComplexType>(X), *CY = cast<ComplexType>(Y);
14121 return Ctx.getComplexType(getCommonArrayElementType(Ctx, CX, QX, CY, QY));
14122 }
14123 case Type::Pointer: {
14124 const auto *PX = cast<PointerType>(X), *PY = cast<PointerType>(Y);
14125 return Ctx.getPointerType(getCommonPointeeType(Ctx, PX, PY));
14126 }
14127 case Type::BlockPointer: {
14128 const auto *PX = cast<BlockPointerType>(X), *PY = cast<BlockPointerType>(Y);
14129 return Ctx.getBlockPointerType(getCommonPointeeType(Ctx, PX, PY));
14130 }
14131 case Type::ObjCObjectPointer: {
14132 const auto *PX = cast<ObjCObjectPointerType>(X),
14133 *PY = cast<ObjCObjectPointerType>(Y);
14134 return Ctx.getObjCObjectPointerType(getCommonPointeeType(Ctx, PX, PY));
14135 }
14136 case Type::MemberPointer: {
14137 const auto *PX = cast<MemberPointerType>(X),
14138 *PY = cast<MemberPointerType>(Y);
14139 assert(declaresSameEntity(PX->getMostRecentCXXRecordDecl(),
14140 PY->getMostRecentCXXRecordDecl()));
14141 return Ctx.getMemberPointerType(
14142 getCommonPointeeType(Ctx, PX, PY),
14143 getCommonQualifier(Ctx, PX, PY, /*IsSame=*/true),
14144 PX->getMostRecentCXXRecordDecl());
14145 }
14146 case Type::LValueReference: {
14147 const auto *PX = cast<LValueReferenceType>(X),
14148 *PY = cast<LValueReferenceType>(Y);
14149 // FIXME: Preserve PointeeTypeAsWritten.
14150 return Ctx.getLValueReferenceType(getCommonPointeeType(Ctx, PX, PY),
14151 PX->isSpelledAsLValue() ||
14152 PY->isSpelledAsLValue());
14153 }
14154 case Type::RValueReference: {
14155 const auto *PX = cast<RValueReferenceType>(X),
14156 *PY = cast<RValueReferenceType>(Y);
14157 // FIXME: Preserve PointeeTypeAsWritten.
14158 return Ctx.getRValueReferenceType(getCommonPointeeType(Ctx, PX, PY));
14159 }
14160 case Type::DependentAddressSpace: {
14161 const auto *PX = cast<DependentAddressSpaceType>(X),
14162 *PY = cast<DependentAddressSpaceType>(Y);
14163 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
14164 return Ctx.getDependentAddressSpaceType(getCommonPointeeType(Ctx, PX, PY),
14165 PX->getAddrSpaceExpr(),
14166 getCommonAttrLoc(PX, PY));
14167 }
14168 case Type::FunctionNoProto: {
14169 const auto *FX = cast<FunctionNoProtoType>(X),
14170 *FY = cast<FunctionNoProtoType>(Y);
14171 assert(FX->getExtInfo() == FY->getExtInfo());
14172 return Ctx.getFunctionNoProtoType(
14173 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType()),
14174 FX->getExtInfo());
14175 }
14176 case Type::FunctionProto: {
14177 const auto *FX = cast<FunctionProtoType>(X),
14178 *FY = cast<FunctionProtoType>(Y);
14179 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
14180 EPIY = FY->getExtProtoInfo();
14181 assert(EPIX.ExtInfo == EPIY.ExtInfo);
14182 assert(!EPIX.ExtParameterInfos == !EPIY.ExtParameterInfos);
14183 assert(!EPIX.ExtParameterInfos ||
14184 llvm::equal(
14185 llvm::ArrayRef(EPIX.ExtParameterInfos, FX->getNumParams()),
14186 llvm::ArrayRef(EPIY.ExtParameterInfos, FY->getNumParams())));
14187 assert(EPIX.RefQualifier == EPIY.RefQualifier);
14188 assert(EPIX.TypeQuals == EPIY.TypeQuals);
14189 assert(EPIX.Variadic == EPIY.Variadic);
14190
14191 // FIXME: Can we handle an empty EllipsisLoc?
14192 // Use emtpy EllipsisLoc if X and Y differ.
14193
14194 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
14195
14196 QualType R =
14197 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType());
14198 auto P = getCommonTypes(Ctx, FX->param_types(), FY->param_types(),
14199 /*Unqualified=*/true);
14200
14201 SmallVector<QualType, 8> Exceptions;
14202 EPIX.ExceptionSpec = Ctx.mergeExceptionSpecs(
14203 EPIX.ExceptionSpec, EPIY.ExceptionSpec, Exceptions, true);
14204 return Ctx.getFunctionType(R, P, EPIX);
14205 }
14206 case Type::ObjCObject: {
14207 const auto *OX = cast<ObjCObjectType>(X), *OY = cast<ObjCObjectType>(Y);
14208 assert(
14209 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
14210 OY->getProtocols().begin(), OY->getProtocols().end(),
14211 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
14212 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
14213 }) &&
14214 "protocol lists must be the same");
14215 auto TAs = getCommonTypes(Ctx, OX->getTypeArgsAsWritten(),
14216 OY->getTypeArgsAsWritten());
14217 return Ctx.getObjCObjectType(
14218 Ctx.getCommonSugaredType(OX->getBaseType(), OY->getBaseType()), TAs,
14219 OX->getProtocols(),
14220 OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
14221 }
14222 case Type::ConstantMatrix: {
14223 const auto *MX = cast<ConstantMatrixType>(X),
14224 *MY = cast<ConstantMatrixType>(Y);
14225 assert(MX->getNumRows() == MY->getNumRows());
14226 assert(MX->getNumColumns() == MY->getNumColumns());
14227 return Ctx.getConstantMatrixType(getCommonElementType(Ctx, MX, MY),
14228 MX->getNumRows(), MX->getNumColumns());
14229 }
14230 case Type::DependentSizedMatrix: {
14231 const auto *MX = cast<DependentSizedMatrixType>(X),
14232 *MY = cast<DependentSizedMatrixType>(Y);
14233 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
14234 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
14235 return Ctx.getDependentSizedMatrixType(
14236 getCommonElementType(Ctx, MX, MY), MX->getRowExpr(),
14237 MX->getColumnExpr(), getCommonAttrLoc(MX, MY));
14238 }
14239 case Type::Vector: {
14240 const auto *VX = cast<VectorType>(X), *VY = cast<VectorType>(Y);
14241 assert(VX->getNumElements() == VY->getNumElements());
14242 assert(VX->getVectorKind() == VY->getVectorKind());
14243 return Ctx.getVectorType(getCommonElementType(Ctx, VX, VY),
14244 VX->getNumElements(), VX->getVectorKind());
14245 }
14246 case Type::ExtVector: {
14247 const auto *VX = cast<ExtVectorType>(X), *VY = cast<ExtVectorType>(Y);
14248 assert(VX->getNumElements() == VY->getNumElements());
14249 return Ctx.getExtVectorType(getCommonElementType(Ctx, VX, VY),
14250 VX->getNumElements());
14251 }
14252 case Type::DependentSizedExtVector: {
14253 const auto *VX = cast<DependentSizedExtVectorType>(X),
14254 *VY = cast<DependentSizedExtVectorType>(Y);
14255 return Ctx.getDependentSizedExtVectorType(getCommonElementType(Ctx, VX, VY),
14256 getCommonSizeExpr(Ctx, VX, VY),
14257 getCommonAttrLoc(VX, VY));
14258 }
14259 case Type::DependentVector: {
14260 const auto *VX = cast<DependentVectorType>(X),
14261 *VY = cast<DependentVectorType>(Y);
14262 assert(VX->getVectorKind() == VY->getVectorKind());
14263 return Ctx.getDependentVectorType(
14264 getCommonElementType(Ctx, VX, VY), getCommonSizeExpr(Ctx, VX, VY),
14265 getCommonAttrLoc(VX, VY), VX->getVectorKind());
14266 }
14267 case Type::Enum:
14268 case Type::Record:
14269 case Type::InjectedClassName: {
14270 const auto *TX = cast<TagType>(X), *TY = cast<TagType>(Y);
14271 return Ctx.getTagType(::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14272 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false),
14273 ::getCommonDeclChecked(TX->getDecl(), TY->getDecl()),
14274 /*OwnedTag=*/false);
14275 }
14276 case Type::TemplateSpecialization: {
14277 const auto *TX = cast<TemplateSpecializationType>(X),
14278 *TY = cast<TemplateSpecializationType>(Y);
14279 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
14280 TY->template_arguments());
14281 return Ctx.getTemplateSpecializationType(
14282 getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14283 ::getCommonTemplateNameChecked(Ctx, TX->getTemplateName(),
14284 TY->getTemplateName(),
14285 /*IgnoreDeduced=*/true),
14286 As, /*CanonicalArgs=*/{}, X->getCanonicalTypeInternal());
14287 }
14288 case Type::Decltype: {
14289 const auto *DX = cast<DecltypeType>(X);
14290 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Y);
14291 assert(DX->isDependentType());
14292 assert(DY->isDependentType());
14293 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
14294 // As Decltype is not uniqued, building a common type would be wasteful.
14295 return QualType(DX, 0);
14296 }
14297 case Type::PackIndexing: {
14298 const auto *DX = cast<PackIndexingType>(X);
14299 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Y);
14300 assert(DX->isDependentType());
14301 assert(DY->isDependentType());
14302 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
14303 return QualType(DX, 0);
14304 }
14305 case Type::DependentName: {
14306 const auto *NX = cast<DependentNameType>(X),
14307 *NY = cast<DependentNameType>(Y);
14308 assert(NX->getIdentifier() == NY->getIdentifier());
14309 return Ctx.getDependentNameType(
14310 getCommonTypeKeyword(NX, NY, /*IsSame=*/true),
14311 getCommonQualifier(Ctx, NX, NY, /*IsSame=*/true), NX->getIdentifier());
14312 }
14313 case Type::UnaryTransform: {
14314 const auto *TX = cast<UnaryTransformType>(X),
14315 *TY = cast<UnaryTransformType>(Y);
14316 assert(TX->getUTTKind() == TY->getUTTKind());
14317 return Ctx.getUnaryTransformType(
14318 Ctx.getCommonSugaredType(TX->getBaseType(), TY->getBaseType()),
14319 Ctx.getCommonSugaredType(TX->getUnderlyingType(),
14320 TY->getUnderlyingType()),
14321 TX->getUTTKind());
14322 }
14323 case Type::PackExpansion: {
14324 const auto *PX = cast<PackExpansionType>(X),
14325 *PY = cast<PackExpansionType>(Y);
14326 assert(PX->getNumExpansions() == PY->getNumExpansions());
14327 return Ctx.getPackExpansionType(
14328 Ctx.getCommonSugaredType(PX->getPattern(), PY->getPattern()),
14329 PX->getNumExpansions(), false);
14330 }
14331 case Type::Pipe: {
14332 const auto *PX = cast<PipeType>(X), *PY = cast<PipeType>(Y);
14333 assert(PX->isReadOnly() == PY->isReadOnly());
14334 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
14335 : &ASTContext::getWritePipeType;
14336 return (Ctx.*MP)(getCommonElementType(Ctx, PX, PY));
14337 }
14338 case Type::TemplateTypeParm: {
14339 const auto *TX = cast<TemplateTypeParmType>(X),
14340 *TY = cast<TemplateTypeParmType>(Y);
14341 assert(TX->getDepth() == TY->getDepth());
14342 assert(TX->getIndex() == TY->getIndex());
14343 assert(TX->isParameterPack() == TY->isParameterPack());
14344 return Ctx.getTemplateTypeParmType(
14345 TX->getDepth(), TX->getIndex(), TX->isParameterPack(),
14346 getCommonDecl(TX->getDecl(), TY->getDecl()));
14347 }
14348 }
14349 llvm_unreachable("Unknown Type Class");
14350 }
14351
14352 static QualType getCommonSugarTypeNode(const ASTContext &Ctx, const Type *X,
14353 const Type *Y,
14354 SplitQualType Underlying) {
14355 Type::TypeClass TC = X->getTypeClass();
14356 if (TC != Y->getTypeClass())
14357 return QualType();
14358 switch (TC) {
14359 #define UNEXPECTED_TYPE(Class, Kind) \
14360 case Type::Class: \
14361 llvm_unreachable("Unexpected " Kind ": " #Class);
14362 #define TYPE(Class, Base)
14363 #define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
14364 #include "clang/AST/TypeNodes.inc"
14365
14366 #define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
14367 CANONICAL_TYPE(Atomic)
14368 CANONICAL_TYPE(BitInt)
14369 CANONICAL_TYPE(BlockPointer)
14370 CANONICAL_TYPE(Builtin)
14371 CANONICAL_TYPE(Complex)
14372 CANONICAL_TYPE(ConstantArray)
14373 CANONICAL_TYPE(ArrayParameter)
14374 CANONICAL_TYPE(ConstantMatrix)
14375 CANONICAL_TYPE(Enum)
14376 CANONICAL_TYPE(ExtVector)
14377 CANONICAL_TYPE(FunctionNoProto)
14378 CANONICAL_TYPE(FunctionProto)
14379 CANONICAL_TYPE(IncompleteArray)
14380 CANONICAL_TYPE(HLSLAttributedResource)
14381 CANONICAL_TYPE(HLSLInlineSpirv)
14382 CANONICAL_TYPE(LValueReference)
14383 CANONICAL_TYPE(ObjCInterface)
14384 CANONICAL_TYPE(ObjCObject)
14385 CANONICAL_TYPE(ObjCObjectPointer)
14386 CANONICAL_TYPE(Pipe)
14387 CANONICAL_TYPE(Pointer)
14388 CANONICAL_TYPE(Record)
14389 CANONICAL_TYPE(RValueReference)
14390 CANONICAL_TYPE(VariableArray)
14391 CANONICAL_TYPE(Vector)
14392 #undef CANONICAL_TYPE
14393
14394 #undef UNEXPECTED_TYPE
14395
14396 case Type::Adjusted: {
14397 const auto *AX = cast<AdjustedType>(X), *AY = cast<AdjustedType>(Y);
14398 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
14399 if (!Ctx.hasSameType(OX, OY))
14400 return QualType();
14401 // FIXME: It's inefficient to have to unify the original types.
14402 return Ctx.getAdjustedType(Ctx.getCommonSugaredType(OX, OY),
14403 Ctx.getQualifiedType(Underlying));
14404 }
14405 case Type::Decayed: {
14406 const auto *DX = cast<DecayedType>(X), *DY = cast<DecayedType>(Y);
14407 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
14408 if (!Ctx.hasSameType(OX, OY))
14409 return QualType();
14410 // FIXME: It's inefficient to have to unify the original types.
14411 return Ctx.getDecayedType(Ctx.getCommonSugaredType(OX, OY),
14412 Ctx.getQualifiedType(Underlying));
14413 }
14414 case Type::Attributed: {
14415 const auto *AX = cast<AttributedType>(X), *AY = cast<AttributedType>(Y);
14416 AttributedType::Kind Kind = AX->getAttrKind();
14417 if (Kind != AY->getAttrKind())
14418 return QualType();
14419 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
14420 if (!Ctx.hasSameType(MX, MY))
14421 return QualType();
14422 // FIXME: It's inefficient to have to unify the modified types.
14423 return Ctx.getAttributedType(Kind, Ctx.getCommonSugaredType(MX, MY),
14424 Ctx.getQualifiedType(Underlying),
14425 AX->getAttr());
14426 }
14427 case Type::BTFTagAttributed: {
14428 const auto *BX = cast<BTFTagAttributedType>(X);
14429 const BTFTypeTagAttr *AX = BX->getAttr();
14430 // The attribute is not uniqued, so just compare the tag.
14431 if (AX->getBTFTypeTag() !=
14432 cast<BTFTagAttributedType>(Y)->getAttr()->getBTFTypeTag())
14433 return QualType();
14434 return Ctx.getBTFTagAttributedType(AX, Ctx.getQualifiedType(Underlying));
14435 }
14436 case Type::Auto: {
14437 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14438
14439 AutoTypeKeyword KW = AX->getKeyword();
14440 if (KW != AY->getKeyword())
14441 return QualType();
14442
14443 TemplateDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(),
14444 AY->getTypeConstraintConcept());
14445 SmallVector<TemplateArgument, 8> As;
14446 if (CD &&
14447 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
14448 AY->getTypeConstraintArguments())) {
14449 CD = nullptr; // The arguments differ, so make it unconstrained.
14450 As.clear();
14451 }
14452
14453 // Both auto types can't be dependent, otherwise they wouldn't have been
14454 // sugar. This implies they can't contain unexpanded packs either.
14455 return Ctx.getAutoType(Ctx.getQualifiedType(Underlying), AX->getKeyword(),
14456 /*IsDependent=*/false, /*IsPack=*/false, CD, As);
14457 }
14458 case Type::PackIndexing:
14459 case Type::Decltype:
14460 return QualType();
14461 case Type::DeducedTemplateSpecialization:
14462 // FIXME: Try to merge these.
14463 return QualType();
14464 case Type::MacroQualified: {
14465 const auto *MX = cast<MacroQualifiedType>(X),
14466 *MY = cast<MacroQualifiedType>(Y);
14467 const IdentifierInfo *IX = MX->getMacroIdentifier();
14468 if (IX != MY->getMacroIdentifier())
14469 return QualType();
14470 return Ctx.getMacroQualifiedType(Ctx.getQualifiedType(Underlying), IX);
14471 }
14472 case Type::SubstTemplateTypeParm: {
14473 const auto *SX = cast<SubstTemplateTypeParmType>(X),
14474 *SY = cast<SubstTemplateTypeParmType>(Y);
14475 Decl *CD =
14476 ::getCommonDecl(SX->getAssociatedDecl(), SY->getAssociatedDecl());
14477 if (!CD)
14478 return QualType();
14479 unsigned Index = SX->getIndex();
14480 if (Index != SY->getIndex())
14481 return QualType();
14482 auto PackIndex = SX->getPackIndex();
14483 if (PackIndex != SY->getPackIndex())
14484 return QualType();
14485 return Ctx.getSubstTemplateTypeParmType(Ctx.getQualifiedType(Underlying),
14486 CD, Index, PackIndex,
14487 SX->getFinal() && SY->getFinal());
14488 }
14489 case Type::ObjCTypeParam:
14490 // FIXME: Try to merge these.
14491 return QualType();
14492 case Type::Paren:
14493 return Ctx.getParenType(Ctx.getQualifiedType(Underlying));
14494
14495 case Type::TemplateSpecialization: {
14496 const auto *TX = cast<TemplateSpecializationType>(X),
14497 *TY = cast<TemplateSpecializationType>(Y);
14498 TemplateName CTN =
14499 ::getCommonTemplateName(Ctx, TX->getTemplateName(),
14500 TY->getTemplateName(), /*IgnoreDeduced=*/true);
14501 if (!CTN.getAsVoidPointer())
14502 return QualType();
14503 SmallVector<TemplateArgument, 8> As;
14504 if (getCommonTemplateArguments(Ctx, As, TX->template_arguments(),
14505 TY->template_arguments()))
14506 return QualType();
14507 return Ctx.getTemplateSpecializationType(
14508 getCommonTypeKeyword(TX, TY, /*IsSame=*/false), CTN, As,
14509 /*CanonicalArgs=*/{}, Ctx.getQualifiedType(Underlying));
14510 }
14511 case Type::Typedef: {
14512 const auto *TX = cast<TypedefType>(X), *TY = cast<TypedefType>(Y);
14513 const TypedefNameDecl *CD = ::getCommonDecl(TX->getDecl(), TY->getDecl());
14514 if (!CD)
14515 return QualType();
14516 return Ctx.getTypedefType(
14517 ::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14518 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false), CD,
14519 Ctx.getQualifiedType(Underlying));
14520 }
14521 case Type::TypeOf: {
14522 // The common sugar between two typeof expressions, where one is
14523 // potentially a typeof_unqual and the other is not, we unify to the
14524 // qualified type as that retains the most information along with the type.
14525 // We only return a typeof_unqual type when both types are unqual types.
14526 TypeOfKind Kind = TypeOfKind::Qualified;
14527 if (cast<TypeOfType>(X)->getKind() == cast<TypeOfType>(Y)->getKind() &&
14528 cast<TypeOfType>(X)->getKind() == TypeOfKind::Unqualified)
14529 Kind = TypeOfKind::Unqualified;
14530 return Ctx.getTypeOfType(Ctx.getQualifiedType(Underlying), Kind);
14531 }
14532 case Type::TypeOfExpr:
14533 return QualType();
14534
14535 case Type::UnaryTransform: {
14536 const auto *UX = cast<UnaryTransformType>(X),
14537 *UY = cast<UnaryTransformType>(Y);
14538 UnaryTransformType::UTTKind KX = UX->getUTTKind();
14539 if (KX != UY->getUTTKind())
14540 return QualType();
14541 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
14542 if (!Ctx.hasSameType(BX, BY))
14543 return QualType();
14544 // FIXME: It's inefficient to have to unify the base types.
14545 return Ctx.getUnaryTransformType(Ctx.getCommonSugaredType(BX, BY),
14546 Ctx.getQualifiedType(Underlying), KX);
14547 }
14548 case Type::Using: {
14549 const auto *UX = cast<UsingType>(X), *UY = cast<UsingType>(Y);
14550 const UsingShadowDecl *CD = ::getCommonDecl(UX->getDecl(), UY->getDecl());
14551 if (!CD)
14552 return QualType();
14553 return Ctx.getUsingType(::getCommonTypeKeyword(UX, UY, /*IsSame=*/false),
14554 ::getCommonQualifier(Ctx, UX, UY, /*IsSame=*/false),
14555 CD, Ctx.getQualifiedType(Underlying));
14556 }
14557 case Type::MemberPointer: {
14558 const auto *PX = cast<MemberPointerType>(X),
14559 *PY = cast<MemberPointerType>(Y);
14560 CXXRecordDecl *Cls = PX->getMostRecentCXXRecordDecl();
14561 assert(Cls == PY->getMostRecentCXXRecordDecl());
14562 return Ctx.getMemberPointerType(
14563 ::getCommonPointeeType(Ctx, PX, PY),
14564 ::getCommonQualifier(Ctx, PX, PY, /*IsSame=*/false), Cls);
14565 }
14566 case Type::CountAttributed: {
14567 const auto *DX = cast<CountAttributedType>(X),
14568 *DY = cast<CountAttributedType>(Y);
14569 if (DX->isCountInBytes() != DY->isCountInBytes())
14570 return QualType();
14571 if (DX->isOrNull() != DY->isOrNull())
14572 return QualType();
14573 Expr *CEX = DX->getCountExpr();
14574 Expr *CEY = DY->getCountExpr();
14575 ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
14576 if (Ctx.hasSameExpr(CEX, CEY))
14577 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14578 DX->isCountInBytes(), DX->isOrNull(),
14579 CDX);
14580 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
14581 return QualType();
14582 // Two declarations with the same integer constant may still differ in their
14583 // expression pointers, so we need to evaluate them.
14584 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
14585 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
14586 if (VX != VY)
14587 return QualType();
14588 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14589 DX->isCountInBytes(), DX->isOrNull(),
14590 CDX);
14591 }
14592 case Type::PredefinedSugar:
14593 assert(cast<PredefinedSugarType>(X)->getKind() !=
14594 cast<PredefinedSugarType>(Y)->getKind());
14595 return QualType();
14596 }
14597 llvm_unreachable("Unhandled Type Class");
14598 }
14599
14600 static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
14601 SmallVector<SplitQualType, 8> R;
14602 while (true) {
14603 QTotal.addConsistentQualifiers(T.Quals);
14604 QualType NT = T.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
14605 if (NT == QualType(T.Ty, 0))
14606 break;
14607 R.push_back(T);
14608 T = NT.split();
14609 }
14610 return R;
14611 }
14612
14613 QualType ASTContext::getCommonSugaredType(QualType X, QualType Y,
14614 bool Unqualified) const {
14615 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
14616 if (X == Y)
14617 return X;
14618 if (!Unqualified) {
14619 if (X.isCanonical())
14620 return X;
14621 if (Y.isCanonical())
14622 return Y;
14623 }
14624
14625 SplitQualType SX = X.split(), SY = Y.split();
14626 Qualifiers QX, QY;
14627 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
14628 // until we reach their underlying "canonical nodes". Note these are not
14629 // necessarily canonical types, as they may still have sugared properties.
14630 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
14631 auto Xs = ::unwrapSugar(SX, QX), Ys = ::unwrapSugar(SY, QY);
14632
14633 // If this is an ArrayType, the element qualifiers are interchangeable with
14634 // the top level qualifiers.
14635 // * In case the canonical nodes are the same, the elements types are already
14636 // the same.
14637 // * Otherwise, the element types will be made the same, and any different
14638 // element qualifiers will be moved up to the top level qualifiers, per
14639 // 'getCommonArrayElementType'.
14640 // In both cases, this means there may be top level qualifiers which differ
14641 // between X and Y. If so, these differing qualifiers are redundant with the
14642 // element qualifiers, and can be removed without changing the canonical type.
14643 // The desired behaviour is the same as for the 'Unqualified' case here:
14644 // treat the redundant qualifiers as sugar, remove the ones which are not
14645 // common to both sides.
14646 bool KeepCommonQualifiers = Unqualified || isa<ArrayType>(SX.Ty);
14647
14648 if (SX.Ty != SY.Ty) {
14649 // The canonical nodes differ. Build a common canonical node out of the two,
14650 // unifying their sugar. This may recurse back here.
14651 SX.Ty =
14652 ::getCommonNonSugarTypeNode(*this, SX.Ty, QX, SY.Ty, QY).getTypePtr();
14653 } else {
14654 // The canonical nodes were identical: We may have desugared too much.
14655 // Add any common sugar back in.
14656 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
14657 QX -= SX.Quals;
14658 QY -= SY.Quals;
14659 SX = Xs.pop_back_val();
14660 SY = Ys.pop_back_val();
14661 }
14662 }
14663 if (KeepCommonQualifiers)
14664 QX = Qualifiers::removeCommonQualifiers(QX, QY);
14665 else
14666 assert(QX == QY);
14667
14668 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
14669 // related. Walk up these nodes, unifying them and adding the result.
14670 while (!Xs.empty() && !Ys.empty()) {
14671 auto Underlying = SplitQualType(
14672 SX.Ty, Qualifiers::removeCommonQualifiers(SX.Quals, SY.Quals));
14673 SX = Xs.pop_back_val();
14674 SY = Ys.pop_back_val();
14675 SX.Ty = ::getCommonSugarTypeNode(*this, SX.Ty, SY.Ty, Underlying)
14676 .getTypePtrOrNull();
14677 // Stop at the first pair which is unrelated.
14678 if (!SX.Ty) {
14679 SX.Ty = Underlying.Ty;
14680 break;
14681 }
14682 QX -= Underlying.Quals;
14683 };
14684
14685 // Add back the missing accumulated qualifiers, which were stripped off
14686 // with the sugar nodes we could not unify.
14687 QualType R = getQualifiedType(SX.Ty, QX);
14688 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
14689 return R;
14690 }
14691
14692 QualType ASTContext::getCorrespondingUnsaturatedType(QualType Ty) const {
14693 assert(Ty->isFixedPointType());
14694
14695 if (Ty->isUnsaturatedFixedPointType())
14696 return Ty;
14697
14698 switch (Ty->castAs<BuiltinType>()->getKind()) {
14699 default:
14700 llvm_unreachable("Not a saturated fixed point type!");
14701 case BuiltinType::SatShortAccum:
14702 return ShortAccumTy;
14703 case BuiltinType::SatAccum:
14704 return AccumTy;
14705 case BuiltinType::SatLongAccum:
14706 return LongAccumTy;
14707 case BuiltinType::SatUShortAccum:
14708 return UnsignedShortAccumTy;
14709 case BuiltinType::SatUAccum:
14710 return UnsignedAccumTy;
14711 case BuiltinType::SatULongAccum:
14712 return UnsignedLongAccumTy;
14713 case BuiltinType::SatShortFract:
14714 return ShortFractTy;
14715 case BuiltinType::SatFract:
14716 return FractTy;
14717 case BuiltinType::SatLongFract:
14718 return LongFractTy;
14719 case BuiltinType::SatUShortFract:
14720 return UnsignedShortFractTy;
14721 case BuiltinType::SatUFract:
14722 return UnsignedFractTy;
14723 case BuiltinType::SatULongFract:
14724 return UnsignedLongFractTy;
14725 }
14726 }
14727
14728 QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
14729 assert(Ty->isFixedPointType());
14730
14731 if (Ty->isSaturatedFixedPointType()) return Ty;
14732
14733 switch (Ty->castAs<BuiltinType>()->getKind()) {
14734 default:
14735 llvm_unreachable("Not a fixed point type!");
14736 case BuiltinType::ShortAccum:
14737 return SatShortAccumTy;
14738 case BuiltinType::Accum:
14739 return SatAccumTy;
14740 case BuiltinType::LongAccum:
14741 return SatLongAccumTy;
14742 case BuiltinType::UShortAccum:
14743 return SatUnsignedShortAccumTy;
14744 case BuiltinType::UAccum:
14745 return SatUnsignedAccumTy;
14746 case BuiltinType::ULongAccum:
14747 return SatUnsignedLongAccumTy;
14748 case BuiltinType::ShortFract:
14749 return SatShortFractTy;
14750 case BuiltinType::Fract:
14751 return SatFractTy;
14752 case BuiltinType::LongFract:
14753 return SatLongFractTy;
14754 case BuiltinType::UShortFract:
14755 return SatUnsignedShortFractTy;
14756 case BuiltinType::UFract:
14757 return SatUnsignedFractTy;
14758 case BuiltinType::ULongFract:
14759 return SatUnsignedLongFractTy;
14760 }
14761 }
14762
14763 LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
14764 if (LangOpts.OpenCL)
14765 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
14766
14767 if (LangOpts.CUDA)
14768 return getTargetInfo().getCUDABuiltinAddressSpace(AS);
14769
14770 return getLangASFromTargetAS(AS);
14771 }
14772
14773 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
14774 // doesn't include ASTContext.h
14775 template
14776 clang::LazyGenerationalUpdatePtr<
14777 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
14778 clang::LazyGenerationalUpdatePtr<
14779 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
14780 const clang::ASTContext &Ctx, Decl *Value);
14781
14782 unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
14783 assert(Ty->isFixedPointType());
14784
14785 const TargetInfo &Target = getTargetInfo();
14786 switch (Ty->castAs<BuiltinType>()->getKind()) {
14787 default:
14788 llvm_unreachable("Not a fixed point type!");
14789 case BuiltinType::ShortAccum:
14790 case BuiltinType::SatShortAccum:
14791 return Target.getShortAccumScale();
14792 case BuiltinType::Accum:
14793 case BuiltinType::SatAccum:
14794 return Target.getAccumScale();
14795 case BuiltinType::LongAccum:
14796 case BuiltinType::SatLongAccum:
14797 return Target.getLongAccumScale();
14798 case BuiltinType::UShortAccum:
14799 case BuiltinType::SatUShortAccum:
14800 return Target.getUnsignedShortAccumScale();
14801 case BuiltinType::UAccum:
14802 case BuiltinType::SatUAccum:
14803 return Target.getUnsignedAccumScale();
14804 case BuiltinType::ULongAccum:
14805 case BuiltinType::SatULongAccum:
14806 return Target.getUnsignedLongAccumScale();
14807 case BuiltinType::ShortFract:
14808 case BuiltinType::SatShortFract:
14809 return Target.getShortFractScale();
14810 case BuiltinType::Fract:
14811 case BuiltinType::SatFract:
14812 return Target.getFractScale();
14813 case BuiltinType::LongFract:
14814 case BuiltinType::SatLongFract:
14815 return Target.getLongFractScale();
14816 case BuiltinType::UShortFract:
14817 case BuiltinType::SatUShortFract:
14818 return Target.getUnsignedShortFractScale();
14819 case BuiltinType::UFract:
14820 case BuiltinType::SatUFract:
14821 return Target.getUnsignedFractScale();
14822 case BuiltinType::ULongFract:
14823 case BuiltinType::SatULongFract:
14824 return Target.getUnsignedLongFractScale();
14825 }
14826 }
14827
14828 unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
14829 assert(Ty->isFixedPointType());
14830
14831 const TargetInfo &Target = getTargetInfo();
14832 switch (Ty->castAs<BuiltinType>()->getKind()) {
14833 default:
14834 llvm_unreachable("Not a fixed point type!");
14835 case BuiltinType::ShortAccum:
14836 case BuiltinType::SatShortAccum:
14837 return Target.getShortAccumIBits();
14838 case BuiltinType::Accum:
14839 case BuiltinType::SatAccum:
14840 return Target.getAccumIBits();
14841 case BuiltinType::LongAccum:
14842 case BuiltinType::SatLongAccum:
14843 return Target.getLongAccumIBits();
14844 case BuiltinType::UShortAccum:
14845 case BuiltinType::SatUShortAccum:
14846 return Target.getUnsignedShortAccumIBits();
14847 case BuiltinType::UAccum:
14848 case BuiltinType::SatUAccum:
14849 return Target.getUnsignedAccumIBits();
14850 case BuiltinType::ULongAccum:
14851 case BuiltinType::SatULongAccum:
14852 return Target.getUnsignedLongAccumIBits();
14853 case BuiltinType::ShortFract:
14854 case BuiltinType::SatShortFract:
14855 case BuiltinType::Fract:
14856 case BuiltinType::SatFract:
14857 case BuiltinType::LongFract:
14858 case BuiltinType::SatLongFract:
14859 case BuiltinType::UShortFract:
14860 case BuiltinType::SatUShortFract:
14861 case BuiltinType::UFract:
14862 case BuiltinType::SatUFract:
14863 case BuiltinType::ULongFract:
14864 case BuiltinType::SatULongFract:
14865 return 0;
14866 }
14867 }
14868
14869 llvm::FixedPointSemantics
14870 ASTContext::getFixedPointSemantics(QualType Ty) const {
14871 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
14872 "Can only get the fixed point semantics for a "
14873 "fixed point or integer type.");
14874 if (Ty->isIntegerType())
14875 return llvm::FixedPointSemantics::GetIntegerSemantics(
14876 getIntWidth(Ty), Ty->isSignedIntegerType());
14877
14878 bool isSigned = Ty->isSignedFixedPointType();
14879 return llvm::FixedPointSemantics(
14880 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
14881 Ty->isSaturatedFixedPointType(),
14882 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
14883 }
14884
14885 llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
14886 assert(Ty->isFixedPointType());
14887 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
14888 }
14889
14890 llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
14891 assert(Ty->isFixedPointType());
14892 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
14893 }
14894
14895 QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
14896 assert(Ty->isUnsignedFixedPointType() &&
14897 "Expected unsigned fixed point type");
14898
14899 switch (Ty->castAs<BuiltinType>()->getKind()) {
14900 case BuiltinType::UShortAccum:
14901 return ShortAccumTy;
14902 case BuiltinType::UAccum:
14903 return AccumTy;
14904 case BuiltinType::ULongAccum:
14905 return LongAccumTy;
14906 case BuiltinType::SatUShortAccum:
14907 return SatShortAccumTy;
14908 case BuiltinType::SatUAccum:
14909 return SatAccumTy;
14910 case BuiltinType::SatULongAccum:
14911 return SatLongAccumTy;
14912 case BuiltinType::UShortFract:
14913 return ShortFractTy;
14914 case BuiltinType::UFract:
14915 return FractTy;
14916 case BuiltinType::ULongFract:
14917 return LongFractTy;
14918 case BuiltinType::SatUShortFract:
14919 return SatShortFractTy;
14920 case BuiltinType::SatUFract:
14921 return SatFractTy;
14922 case BuiltinType::SatULongFract:
14923 return SatLongFractTy;
14924 default:
14925 llvm_unreachable("Unexpected unsigned fixed point type");
14926 }
14927 }
14928
14929 // Given a list of FMV features, return a concatenated list of the
14930 // corresponding backend features (which may contain duplicates).
14931 static std::vector<std::string> getFMVBackendFeaturesFor(
14932 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) {
14933 std::vector<std::string> BackendFeats;
14934 llvm::AArch64::ExtensionSet FeatureBits;
14935 for (StringRef F : FMVFeatStrings)
14936 if (auto FMVExt = llvm::AArch64::parseFMVExtension(F))
14937 if (FMVExt->ID)
14938 FeatureBits.enable(*FMVExt->ID);
14939 FeatureBits.toLLVMFeatureList(BackendFeats);
14940 return BackendFeats;
14941 }
14942
14943 ParsedTargetAttr
14944 ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
14945 assert(TD != nullptr);
14946 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TD->getFeaturesStr());
14947
14948 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
14949 return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
14950 });
14951 return ParsedAttr;
14952 }
14953
14954 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
14955 const FunctionDecl *FD) const {
14956 if (FD)
14957 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
14958 else
14959 Target->initFeatureMap(FeatureMap, getDiagnostics(),
14960 Target->getTargetOpts().CPU,
14961 Target->getTargetOpts().Features);
14962 }
14963
14964 // Fills in the supplied string map with the set of target features for the
14965 // passed in function.
14966 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
14967 GlobalDecl GD) const {
14968 StringRef TargetCPU = Target->getTargetOpts().CPU;
14969 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
14970 if (const auto *TD = FD->getAttr<TargetAttr>()) {
14971 ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
14972
14973 // Make a copy of the features as passed on the command line into the
14974 // beginning of the additional features from the function to override.
14975 // AArch64 handles command line option features in parseTargetAttr().
14976 if (!Target->getTriple().isAArch64())
14977 ParsedAttr.Features.insert(
14978 ParsedAttr.Features.begin(),
14979 Target->getTargetOpts().FeaturesAsWritten.begin(),
14980 Target->getTargetOpts().FeaturesAsWritten.end());
14981
14982 if (ParsedAttr.CPU != "" && Target->isValidCPUName(ParsedAttr.CPU))
14983 TargetCPU = ParsedAttr.CPU;
14984
14985 // Now populate the feature map, first with the TargetCPU which is either
14986 // the default or a new one from the target attribute string. Then we'll use
14987 // the passed in features (FeaturesAsWritten) along with the new ones from
14988 // the attribute.
14989 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
14990 ParsedAttr.Features);
14991 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
14992 llvm::SmallVector<StringRef, 32> FeaturesTmp;
14993 Target->getCPUSpecificCPUDispatchFeatures(
14994 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
14995 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
14996 Features.insert(Features.begin(),
14997 Target->getTargetOpts().FeaturesAsWritten.begin(),
14998 Target->getTargetOpts().FeaturesAsWritten.end());
14999 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15000 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
15001 if (Target->getTriple().isAArch64()) {
15002 llvm::SmallVector<StringRef, 8> Feats;
15003 TC->getFeatures(Feats, GD.getMultiVersionIndex());
15004 std::vector<std::string> Features = getFMVBackendFeaturesFor(Feats);
15005 Features.insert(Features.begin(),
15006 Target->getTargetOpts().FeaturesAsWritten.begin(),
15007 Target->getTargetOpts().FeaturesAsWritten.end());
15008 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15009 } else if (Target->getTriple().isRISCV()) {
15010 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15011 std::vector<std::string> Features;
15012 if (VersionStr != "default") {
15013 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(VersionStr);
15014 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
15015 ParsedAttr.Features.end());
15016 }
15017 Features.insert(Features.begin(),
15018 Target->getTargetOpts().FeaturesAsWritten.begin(),
15019 Target->getTargetOpts().FeaturesAsWritten.end());
15020 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15021 } else {
15022 std::vector<std::string> Features;
15023 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15024 if (VersionStr.starts_with("arch="))
15025 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
15026 else if (VersionStr != "default")
15027 Features.push_back((StringRef{"+"} + VersionStr).str());
15028 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15029 }
15030 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
15031 std::vector<std::string> Features;
15032 if (Target->getTriple().isRISCV()) {
15033 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TV->getName());
15034 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
15035 ParsedAttr.Features.end());
15036 } else {
15037 assert(Target->getTriple().isAArch64());
15038 llvm::SmallVector<StringRef, 8> Feats;
15039 TV->getFeatures(Feats);
15040 Features = getFMVBackendFeaturesFor(Feats);
15041 }
15042 Features.insert(Features.begin(),
15043 Target->getTargetOpts().FeaturesAsWritten.begin(),
15044 Target->getTargetOpts().FeaturesAsWritten.end());
15045 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15046 } else {
15047 FeatureMap = Target->getTargetOpts().FeatureMap;
15048 }
15049 }
15050
15051 static SYCLKernelInfo BuildSYCLKernelInfo(ASTContext &Context,
15052 CanQualType KernelNameType,
15053 const FunctionDecl *FD) {
15054 // Host and device compilation may use different ABIs and different ABIs
15055 // may allocate name mangling discriminators differently. A discriminator
15056 // override is used to ensure consistent discriminator allocation across
15057 // host and device compilation.
15058 auto DeviceDiscriminatorOverrider =
15059 [](ASTContext &Ctx, const NamedDecl *ND) -> UnsignedOrNone {
15060 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
15061 if (RD->isLambda())
15062 return RD->getDeviceLambdaManglingNumber();
15063 return std::nullopt;
15064 };
15065 std::unique_ptr<MangleContext> MC{ItaniumMangleContext::create(
15066 Context, Context.getDiagnostics(), DeviceDiscriminatorOverrider)};
15067
15068 // Construct a mangled name for the SYCL kernel caller offload entry point.
15069 // FIXME: The Itanium typeinfo mangling (_ZTS<type>) is currently used to
15070 // name the SYCL kernel caller offload entry point function. This mangling
15071 // does not suffice to clearly identify symbols that correspond to SYCL
15072 // kernel caller functions, nor is this mangling natural for targets that
15073 // use a non-Itanium ABI.
15074 std::string Buffer;
15075 Buffer.reserve(128);
15076 llvm::raw_string_ostream Out(Buffer);
15077 MC->mangleCanonicalTypeName(KernelNameType, Out);
15078 std::string KernelName = Out.str();
15079
15080 return {KernelNameType, FD, KernelName};
15081 }
15082
15083 void ASTContext::registerSYCLEntryPointFunction(FunctionDecl *FD) {
15084 // If the function declaration to register is invalid or dependent, the
15085 // registration attempt is ignored.
15086 if (FD->isInvalidDecl() || FD->isTemplated())
15087 return;
15088
15089 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
15090 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
15091
15092 // Be tolerant of multiple registration attempts so long as each attempt
15093 // is for the same entity. Callers are obligated to detect and diagnose
15094 // conflicting kernel names prior to calling this function.
15095 CanQualType KernelNameType = getCanonicalType(SKEPAttr->getKernelName());
15096 auto IT = SYCLKernels.find(KernelNameType);
15097 assert((IT == SYCLKernels.end() ||
15098 declaresSameEntity(FD, IT->second.getKernelEntryPointDecl())) &&
15099 "SYCL kernel name conflict");
15100 (void)IT;
15101 SYCLKernels.insert(std::make_pair(
15102 KernelNameType, BuildSYCLKernelInfo(*this, KernelNameType, FD)));
15103 }
15104
15105 const SYCLKernelInfo &ASTContext::getSYCLKernelInfo(QualType T) const {
15106 CanQualType KernelNameType = getCanonicalType(T);
15107 return SYCLKernels.at(KernelNameType);
15108 }
15109
15110 const SYCLKernelInfo *ASTContext::findSYCLKernelInfo(QualType T) const {
15111 CanQualType KernelNameType = getCanonicalType(T);
15112 auto IT = SYCLKernels.find(KernelNameType);
15113 if (IT != SYCLKernels.end())
15114 return &IT->second;
15115 return nullptr;
15116 }
15117
15118 OMPTraitInfo &ASTContext::getNewOMPTraitInfo() {
15119 OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
15120 return *OMPTraitInfoVector.back();
15121 }
15122
15123 const StreamingDiagnostic &clang::
15124 operator<<(const StreamingDiagnostic &DB,
15125 const ASTContext::SectionInfo &Section) {
15126 if (Section.Decl)
15127 return DB << Section.Decl;
15128 return DB << "a prior #pragma section";
15129 }
15130
15131 bool ASTContext::mayExternalize(const Decl *D) const {
15132 bool IsInternalVar =
15133 isa<VarDecl>(D) &&
15134 basicGVALinkageForVariable(*this, cast<VarDecl>(D)) == GVA_Internal;
15135 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
15136 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
15137 (D->hasAttr<CUDAConstantAttr>() &&
15138 !D->getAttr<CUDAConstantAttr>()->isImplicit());
15139 // CUDA/HIP: managed variables need to be externalized since it is
15140 // a declaration in IR, therefore cannot have internal linkage. Kernels in
15141 // anonymous name space needs to be externalized to avoid duplicate symbols.
15142 return (IsInternalVar &&
15143 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
15144 (D->hasAttr<CUDAGlobalAttr>() &&
15145 basicGVALinkageForFunction(*this, cast<FunctionDecl>(D)) ==
15146 GVA_Internal);
15147 }
15148
15149 bool ASTContext::shouldExternalize(const Decl *D) const {
15150 return mayExternalize(D) &&
15151 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
15152 CUDADeviceVarODRUsedByHost.count(cast<VarDecl>(D)));
15153 }
15154
15155 StringRef ASTContext::getCUIDHash() const {
15156 if (!CUIDHash.empty())
15157 return CUIDHash;
15158 if (LangOpts.CUID.empty())
15159 return StringRef();
15160 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
15161 return CUIDHash;
15162 }
15163
15164 const CXXRecordDecl *
15165 ASTContext::baseForVTableAuthentication(const CXXRecordDecl *ThisClass) const {
15166 assert(ThisClass);
15167 assert(ThisClass->isPolymorphic());
15168 const CXXRecordDecl *PrimaryBase = ThisClass;
15169 while (1) {
15170 assert(PrimaryBase);
15171 assert(PrimaryBase->isPolymorphic());
15172 auto &Layout = getASTRecordLayout(PrimaryBase);
15173 auto Base = Layout.getPrimaryBase();
15174 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
15175 break;
15176 PrimaryBase = Base;
15177 }
15178 return PrimaryBase;
15179 }
15180
15181 bool ASTContext::useAbbreviatedThunkName(GlobalDecl VirtualMethodDecl,
15182 StringRef MangledName) {
15183 auto *Method = cast<CXXMethodDecl>(VirtualMethodDecl.getDecl());
15184 assert(Method->isVirtual());
15185 bool DefaultIncludesPointerAuth =
15186 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics;
15187
15188 if (!DefaultIncludesPointerAuth)
15189 return true;
15190
15191 auto Existing = ThunksToBeAbbreviated.find(VirtualMethodDecl);
15192 if (Existing != ThunksToBeAbbreviated.end())
15193 return Existing->second.contains(MangledName.str());
15194
15195 std::unique_ptr<MangleContext> Mangler(createMangleContext());
15196 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks;
15197 auto VtableContext = getVTableContext();
15198 if (const auto *ThunkInfos = VtableContext->getThunkInfo(VirtualMethodDecl)) {
15199 auto *Destructor = dyn_cast<CXXDestructorDecl>(Method);
15200 for (const auto &Thunk : *ThunkInfos) {
15201 SmallString<256> ElidedName;
15202 llvm::raw_svector_ostream ElidedNameStream(ElidedName);
15203 if (Destructor)
15204 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15205 Thunk, /* elideOverrideInfo */ true,
15206 ElidedNameStream);
15207 else
15208 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ true,
15209 ElidedNameStream);
15210 SmallString<256> MangledName;
15211 llvm::raw_svector_ostream mangledNameStream(MangledName);
15212 if (Destructor)
15213 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15214 Thunk, /* elideOverrideInfo */ false,
15215 mangledNameStream);
15216 else
15217 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ false,
15218 mangledNameStream);
15219
15220 Thunks[ElidedName].push_back(std::string(MangledName));
15221 }
15222 }
15223 llvm::StringSet<> SimplifiedThunkNames;
15224 for (auto &ThunkList : Thunks) {
15225 llvm::sort(ThunkList.second);
15226 SimplifiedThunkNames.insert(ThunkList.second[0]);
15227 }
15228 bool Result = SimplifiedThunkNames.contains(MangledName);
15229 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames);
15230 return Result;
15231 }